(function () {
    'use strict';

    /**
     *  @version 1.0.0
     *  @time 2019/11/6
     *  初始创建
     *  @version 1.0.1
     *  @time 2019/11/11
     *  修改了头条banner广告的适配方案以及适配判定 新增变量Advertisement.bannersize
     *  @version 1.0.2
     *  @time 2019/11/13
     *  修改了头条banner广告的适配方案 新增延迟Advertisement.resNode.scheduleOnce
     *  @version 1.0.3
     *  @time 2019/11/27
     *  更新了VIVO激励视频接口API 新增变量video
     * */
    /**
     * creator by z1 on 2019/11/6
     */

    // var Miwu = require('allval');
    var Advertisement = {

    };

    window.gameId = "31058279";

    window.bannerAdId = " 5137b565b4ec4db0be3bdff422d2d45c";
    window.nativeAdId = "44358bd964ab43d987c22caca6ab4205";
    window.videoAdId = "16049a7994174da9ac3e33b9219c5d09";

    //初始化变量
    Advertisement.initVal = function () {
        Advertisement.recorder = null; //游戏录制变量
        Advertisement.resNode = null; //常住节点的变量
        Advertisement.currtimer = 0; //录制计时变量
        Advertisement.cstop = false; //录制成功判断变量
        Advertisement.videoPath = ""; //录制路径变量
        Advertisement.erroRecNode = null; //录屏错误节点变量
        // Advertisement.erroNode = null; //激励视频错误节点变量
        Advertisement.nrewardNode = null; //奖励发放节点变量
        Advertisement.bannerAd = null; //banner广告变量
        Advertisement.bannerAdon = false;
        Advertisement.nativeAd = null; //原生广告变量
        Advertisement.nativeAdn = null; //原生广告节点
        Advertisement.nativeAdtouch = false;
        Advertisement.bannersize = false; //判断是否适配过
        Advertisement.insertAd = null; //插屏广告变量
        Advertisement.videoAd = null; //激励视频广告变量
        Advertisement.reward = true; //判断是否发放奖励
        Advertisement.rewarda = ""; //奖励类型变量
        Advertisement.rewardNode = null; //奖励节点变量

        // Advertisement.native = false;      //防止原生广告是否请求频繁判断
        Advertisement.native = true; //防止原生广告是否请求频繁判断

        Advertisement.insert = true; //防止插屏广告是否请求频繁判断
        Advertisement.banner = true; //防止banner广告请求频繁判断
        Advertisement.video = true; //防止video请求过于频繁
        Advertisement.boolBannerVivo = true; //防止banner广告请求频繁判断
        Advertisement.boolReward = true; //确保激励只执行一次
        Advertisement.bgmusic = 0; //背景音乐ID
        Advertisement.adId = ''; //原生广告返回ID
        Advertisement.nativeAdl = null;
        Advertisement.mobileVersions = null; //判断手机版本
        Advertisement.boolIp = false; //判断是否是ip
        Advertisement.bg8 = null;

        Advertisement.curThis = null;
        // Advertisement.errorNode = cc.find("errorNode"); //奖励发放节点变量
        // cc.game.addPersistRootNode(Advertisement.errorNode);
        Advertisement.videop = null;
        Advertisement.failVideop = null;

        Advertisement.data = null;
        if (Laya.Browser.onVVMiniGame || Laya.Browser.onQGMiniGame || Laya.Browser.onHWMiniGame) {
            qg.getSystemInfo({
                success: function (data) {
                    console.log(`handling success， screenHeight = ${data.screenHeight}`);
                    Advertisement.data = data;
                }
            });
        }
        Advertisement.testDate = new Date();

        Advertisement.seconds = 0;
        Advertisement.canShow = true;

        setInterval(() => {
            // console.log('10秒')
            Advertisement.seconds++;
            if (Advertisement.seconds % 6 == 0) {
                Advertisement.canShow = true;
            }
        }, 1000);
    };

    //#region VIVO
    Advertisement.insertAdverV = function () {
        // if (Advertisement.native == false) {
        //     return;
        // }
        // Advertisement.native = false;
        // Advertisement.resNode.scheduleOnce(function () {
        //     Advertisement.native = true;
        // }, 5); //60

        if (Laya.Browser.onVVMiniGame || Laya.Browser.onQGMiniGame || Laya.Browser.onHWMiniGame) {
            if (qg.createCustomAd && Advertisement.data) {
                Advertisement.customAd = qg.createCustomAd({
                    posId: window.nativeAdId,
                    style: {
                        // left: Advertisement.data.screenWidth / 4,
                        // top: Advertisement.data.screenHeight / 8
                        left: 0,
                        top: Advertisement.data.screenHeight / 5
                    }
                });
                Advertisement.customAd.onError(err => {
                    console.log("原生模板广告加载失败", err);
                });
                Advertisement.customAd.show().then(() => {
                    console.log('原生模板广告展示完成');
                }).catch((err) => {
                    console.log('原生模板广告展示失败', JSON.stringify(err));
                });
                // 原生广告关闭回调
                Advertisement.customAd.onClose(function () {
                    Advertisement.bannerAdverV();
                });
            }
        }
    };

    Advertisement.insertAdverV3 = function () {
        if (Advertisement.testDate.getFullYear() == 2023 && (Advertisement.testDate.getMonth() + 1 == 12 && (Advertisement.testDate.getDate() <= 26 && Advertisement.testDate.getDate() >= 1))) {

        } else {
            if (Advertisement.canShow) {
                Advertisement.insertAdverV();
                Advertisement.seconds = 0;
                Advertisement.canShow = false;
            }
        }
    };

    Advertisement.insertAdverV2 = function () {
        this.testDate = new Date();
        if ((this.getWeekDate() == "周六" || this.getWeekDate() == "周日") ||
            ((Number(this.testDate.getHours()) <= 9) || (Number(this.testDate.getHours()) >= 19))) {
            console.log('周六日或十月1-7');
            if (qg.createCustomAd && Advertisement.data) {
                Advertisement.customAd = qg.createCustomAd({
                    posId: window.nativeAdId,
                    style: {
                        // left: Advertisement.data.screenWidth / 4,
                        // top: Advertisement.data.screenHeight / 8
                        left: 0,
                        top: Advertisement.data.screenHeight / 5
                    }
                });
                Advertisement.customAd.onError(err => {
                    console.log("原生模板广告加载失败", err);
                });
                Advertisement.customAd.show().then(() => {
                    console.log('原生模板广告展示完成');
                }).catch((err) => {
                    console.log('原生模板广告展示失败', JSON.stringify(err));
                });
                //原生广告关闭回调
                // Advertisement.customAd.onClose(function() {
                //     Advertisement.bannerAdverV();
                // })
            }
            Advertisement.bannerAdverV();
        } else (
            console.log('周一五')
        );
    };

    //销毁原生
    Advertisement.DestroyV = function () {
        Advertisement.customAd.destroy();
    };

    //VIVObanner广告
    Advertisement.bannerAdverV = function () {
        return;
        if (Advertisement.boolBannerVivo) {
            //销毁之前存在的banner广告
            if (Advertisement.bannerAd != null) {
                Advertisement.bannerAd.destroy();
                Advertisement.bannerAd = null;
            }
            Advertisement.boolBannerVivo = false;
            Advertisement.bannerAd = qg.createBannerAd({
                posId: window.bannerAdId, //输入广告ID
                style: {
                    // left:0,
                    // top:0
                }
            });
            let adshow = Advertisement.bannerAd.show();
            // 调用then和catch之前需要对show的结果做下判空处理，防止出错（如果没有判空，在平台版本为1052以及以下的手机上将会出现错误）
            adshow && adshow.then(() => {
                console.log("banner广告展示成功");
                Advertisement.resNode.scheduleOnce(function () {
                    Advertisement.boolBannerVivo = true;
                }, 10);
            }).catch((err) => {
                switch (err.code) {
                    case 30003:
                        console.log("新用户7天内不能曝光Banner，请将手机时间调整为7天后，退出游戏重新进入");
                        //   qg.showToast({
                        //       message: "banner广告展示失败：30003"
                        //   });
                        break;
                    case 30009:
                        console.log("10秒内调用广告次数超过1次，10秒后再调用");
                        //   qg.showToast({
                        //       message: "banner广告展示失败：30009"
                        //   });
                        setTimeout(() => {
                            retryShow2();
                        }, 10000);
                        break;
                    case 30002:
                        console.log("加载广告失败，重新加载广告");
                        //   qg.showToast({
                        //       message: "banner广告展示失败：30002"
                        //   });
                        setTimeout(() => {
                            retryShow();
                        }, 10000);
                        break;
                    default:
                        // 参考 https://minigame.vivo.com.cn/documents/#/lesson/open-ability/ad?id=广告错误码信息 对错误码做分类处理
                        console.log("banner广告展示失败");
                        console.log(JSON.stringify(err));
                        //   qg.showToast({
                        //       message: `banner广告展示失败${JSON.stringify(err)}`
                        //   });
                        break;
                }
            });
            Advertisement.bannerAd.onClose(function () {
                Advertisement.resNode.scheduleOnce(function () {
                    // Advertisement.boolBannerVivo = true;
                    Advertisement.bannerAdverV();

                }, 60);
            });

            function retryShow() {
                let bannerAdRetey = qg.createBannerAd({
                    posId: window.bannerAdId, //输入广告ID
                    style: {}
                });
                let adShowRetry = bannerAdRetey.show();
                adShowRetry && adShowRetry.catch((error) => {
                    console.log("banner广告展示失败-重试");
                    console.log(JSON.stringify(error));
                    // qg.showToast({
                    //     message: `banner广告展示失败-重试${JSON.stringify(error)}`
                    // });
                });
            }

            function retryShow2() {
                Advertisement.boolBannerVivo = true;
            }

        }

    };
    //#endregion

    //#region OPPO
    //oppo广告初始化  在游戏最开始初始化的时候调用
    // Advertisement.oppoAdInit = function () {
    //     qg.initAdService({
    //         appId: window.gameId,     //输入APPID
    //         isDebug: true,
    //         success: function (res) {
    //             console.log("success");
    //         },
    //         fail: function (res) {
    //             console.log("fail:" + res.code + res.msg);
    //         },
    //         complete: function (res) {
    //             console.log("complete");
    //         }
    //     });
    // }

    // Advertisement.insertAdverV = function () {
    //     console.log("点击原生");
    //     // if (qg.createCustomAd && Advertisement.data) {
    //     Advertisement.customAd = qg.createCustomAd({
    //         adUnitId: window.nativeAdId,
    //         style: {
    //             left: 50,
    //             top: Advertisement.data.screenHeight / 5,
    //             width: Advertisement.data.screenWidth - 100
    //         }
    //     })
    //     Advertisement.customAd.onLoad(() => {
    //         console.log('customAd广告加载成功')
    //     })
    //     Advertisement.customAd.onError((err) => {
    //         console.log(err)
    //     })
    //     Advertisement.customAd.show().then(() => {
    //         console.log('show success')
    //     }).catch((error) => {
    //         console.log('show fail with:' + error.errCode + ',' + error.errMsg)
    //     })
    // }

    // Advertisement.insertAdverV3 = function () {
    //     this.testDate = new Date();
    //     if (
    //         // (this.getWeekDate() == "周六" || this.getWeekDate() == "周日") 
    //         // ||
    //         ((Number(this.testDate.getMonth()) + 1) != 3 && Number(this.testDate.getDate()) != 29)
    //         // ||
    //         //     ((Number(this.testDate.getHours()) >= 17) && (Number(this.testDate.getHours()) <= 23 && Number(this.testDate.getMinutes()) <= 50))
    //     ) {
    //         console.log('周六日或十月1-7')
    //         console.log("点击原生");
    //         // if (qg.createCustomAd && Advertisement.data) {
    //         //     Advertisement.customAd = qg.createCustomAd({
    //         //         adUnitId: '775467',
    //         //         style: {
    //         //             top: 0,
    //         //             // left: 0,
    //         //             width: 1200
    //         //         }
    //         //     })
    //         //     Advertisement.customAd.onLoad(() => {
    //         //         console.log('customAd广告加载成功')
    //         //     })
    //         //     Advertisement.customAd.onError((err) => {
    //         //         console.log(err)
    //         //     })
    //         //     Advertisement.customAd.show().then(() => {
    //         //         console.log('show success')
    //         //     }).catch((error) => {
    //         //         console.log('show fail with:' + error.errCode + ',' + error.errMsg)
    //         //     })
    //         Advertisement.nativeAdV();
    //     }
    //     else (
    //         console.log('周一五')
    //     )
    // }

    // //销毁原生
    // Advertisement.DestroyV = function () {
    //     Advertisement.customAd.destroy();
    // }

    // //VIVObanner广告
    // Advertisement.bannerAdverV = function () {
    //     if (Advertisement.bannerAd != null) {
    //         return;
    //     }
    //     if (Advertisement.bannerc < 5) {
    //         if (Advertisement.bannerAd != null) {
    //             Advertisement.bannerAd.destroy();
    //             Advertisement.bannerAd = null;
    //         }
    //         Advertisement.bannerAd = qg.createBannerAd({
    //             posId: window.bannerAdId
    //         })
    //         Advertisement.bannerAd.show()
    //         Advertisement.bannerAd.onShow(function () {
    //             console.log("banner 广告显示");

    //         })
    //         Advertisement.bannerAd.onHide(function () {
    //             Advertisement.bannerc++;
    //             Laya.LocalStorage.setItem('userbanner', Advertisement.bannerc);
    //             Advertisement.bannerAd.hide();
    //             Advertisement.bannerAd.destroy()
    //             Advertisement.bannerAd = null;
    //         })
    //         Advertisement.bannerAd.onError(function (err) {
    //             console.log(err);
    //             Advertisement.bannerAd.destroy()
    //             Advertisement.bannerAd = null;
    //         })
    //     }
    // }


    // Advertisement.bannerDestroy = function () {
    //     if (Advertisement.bannerAd != null) {
    //         Advertisement.bannerAd.destroy();
    //         Advertisement.bannerAd = null;
    //         Advertisement.bannersize = false;
    //     }
    // }

    // //VIVO自渲染原生插屏广告
    // Advertisement.insertAdverV = function () {
    //     var Image = Laya.Image;
    //     Advertisement.native = false;
    //     Laya.timer.once(10 * 1000, this, () => {
    //         Advertisement.native = true;
    //     });
    //     //Advertisement.resNode.scheduleOnce(function(){
    //     // Advertisement.native = true;//841323
    //     //},10)
    //     let nativeAd = qg.createNativeAd({
    //         posId: window.nativeAdId
    //     });
    //     let adLoad = nativeAd.load();
    //     adLoad && adLoad.then(() => {
    //         console.log('原生广告读取完成', JSON.stringify(res));
    //     }).catch(err => {
    //         console.log('加载失败', JSON.stringify(err));
    //         // console.log("进入插屏");
    //         // const interstitialAd = qg.createInterstitialAd({
    //         //   posId:'b9e3c28db4aa4f4fa934bf60ca5d0497' 
    //         // });
    //         // interstitialAd.onError(err => {
    //         //   console.log("插屏广告加载失败", err);
    //         // });
    //         // interstitialAd.show().then(()=>{ 
    //         //   console.log('插屏广告展示完成');
    //         // }).catch((err)=>{
    //         //   console.log('插屏广告展示失败', JSON.stringify(err));
    //         // })
    //     })
    //     nativeAd.onLoad(function (res) {
    //         console.log('原生广告加载完成', JSON.stringify(res));
    //         if (res && res.adList) {
    //             Advertisement.adId = res.adList[0].adId;
    //             console.log(res.adList[0]);
    //             // Laya.loader.load(res.adList[0].imgUrlList[0],Laya.Handler.create(Advertisement,function() {
    //             // Use texture to create sprite frame
    //             //var sprite  = new cc.SpriteFrame(texture);
    //             console.log('原生广告展现后续');
    //             reportAdShow();
    //             //Advertisement.resNode.scheduleOnce(function(){
    //             //console.log(Laya.loader.getRes(res.adList[0].imgUrlList[0]));
    //             //console.log(res.adList[0].imgUrlList);
    //             //let texture = Laya.loader.getRes(res.adList[0].imgUrlList[0]);
    //             // console.log(texture)
    //             if (Advertisement.nativeAdn == null) {
    //                 Advertisement.nativeAdn = new Laya.Sprite();
    //                 Advertisement.nativeAdn.width = 600;
    //                 Advertisement.nativeAdn.height = 500;
    //                 Advertisement.nativeAdn.pivotX = 300;
    //                 Advertisement.nativeAdn.pivotY = 250;
    //                 Advertisement.nativeAdn.x = Laya.stage.width / 2;
    //                 Advertisement.nativeAdn.y = Laya.stage.height / 2;
    //                 Advertisement.nativeAdn.visible = false;
    //                 // Advertisement.nativeAdn.mouseEnabled = true;
    //                 // Advertisement.nativeAdn.mouseThrough = false;  
    //                 Advertisement.nativeAdn.hitTestPrior = false;
    //                 Advertisement.nativeAdn.zOrder = 100;
    //                 Laya.stage.addChild(Advertisement.nativeAdn);

    //                 // Advertisement.imag = new Laya.Sprite();
    //                 // Advertisement.imag.width = 30;
    //                 // Advertisement.imag.height = 30;
    //                 // Advertisement.imag.pivotX = 15;
    //                 // Advertisement.imag.pivotY = 15;
    //                 // Advertisement.imag.x = Advertisement.nativeAdn.width-Advertisement.imag.width;
    //                 // Advertisement.imag.y = Advertisement.imag.height;
    //                 // Advertisement.imag.visible = true;
    //                 // Advertisement.imag.mouseEnabled = true;
    //                 // Advertisement.imag.mouseThrough = false;  
    //                 // Advertisement.imag.loadImage('res/btn_close.png');
    //                 // Advertisement.nativeAdn.addChild(Advertisement.imag);

    //                 Advertisement.closeBtn = new Laya.Image();
    //                 Advertisement.closeBtn.width = 28;
    //                 Advertisement.closeBtn.height = 28;
    //                 Advertisement.closeBtn.pivotX = 22.5;
    //                 Advertisement.closeBtn.pivotY = 22.5;
    //                 Advertisement.closeBtn.x = Advertisement.nativeAdn.width - Advertisement.closeBtn.width / 2;
    //                 Advertisement.closeBtn.y = Advertisement.closeBtn.height / 2;
    //                 Advertisement.closeBtn.visible = true;
    //                 // Advertisement.closeBtn.mouseEnabled = true;
    //                 // Advertisement.closeBtn.mouseThrough = false;  
    //                 Advertisement.closeBtn.loadImage('res/atlas/btn_close.png');
    //                 Advertisement.nativeAdn.addChild(Advertisement.closeBtn);

    //                 // Advertisement.nativeAdn.on(Laya.Event.MOUSE_UP,Advertisement.nativeAdn,reportAdClick);
    //                 // Advertisement.closeBtn.on(Laya.Event.MOUSE_UP,Advertisement.closeBtn,close_Btn);
    //             }
    //             //Advertisement.imag.visible = true;
    //             // //},0.3);
    //             //Advertisement.nativeAdn.loadImage(res.adList[0].imgUrlList[0]);
    //             Advertisement.nativeAdn.texture = res.adList[0].imgUrlList[0];
    //             console.log(Advertisement.nativeAdn.texture, '原生广告图片');
    //             //Advertisement.closet = false;
    //             //Advertisement.nativeAdn.texture = texture;
    //             //Advertisement.nativeAdl.text = res.adList[0].title;
    //             //console.log( Advertisement.imag,'图片');
    //             // var dialog = new Image(res.adList[0].imgUrlList[0]);
    //             // dialog.pos(0,0);
    //             // dialog.anchorX = 0;
    //             // dialog.anchorY = 0;
    //             // dialog.width = 640;
    //             // dialog.height = 480;

    //             // Advertisement.nativeAdn.addChild(dialog);
    //             // console.log(dialog);
    //             // console.log(dialog.source);
    //             // Laya.loader.load('http://pfs.pinduoduo.com/phone_adx/5f5d6df62b38bd897bab7dec3e1455be.jpg?sign=q-sign-algorithm%3Dsha1%26q-ak%3DoHMACf6FzEmrUMOe8Hman8EKSbi2WB3e%26q-sign-time%3D1599709456%3B1600055056%26q-key-time%3D1599709456%3B1600055056%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3D6f0bf19129f54fd2b744802a36a6ec721c5094a1',Laya.Handler.create(this, function(){
    //             //   let texture = Laya.loader.getRes('http://pfs.pinduoduo.com/phone_adx/5f5d6df62b38bd897bab7dec3e1455be.jpg?sign=q-sign-algorithm%3Dsha1%26q-ak%3DoHMACf6FzEmrUMOe8Hman8EKSbi2WB3e%26q-sign-time%3D1599709456%3B1600055056%26q-key-time%3D1599709456%3B1600055056%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3D6f0bf19129f54fd2b744802a36a6ec721c5094a1');
    //             //   console.log(texture);
    //             //   let sp = new Laya.Sprite();
    //             //   sp.texture = texture;
    //             //   Laya.stage.addChild(sp);
    //             // }));
    //             //  Advertisement.imag.skin = res.adList[0].imgUrlList[0];
    //             //  console.log(Advertisement.imag.skin,'图片皮肤显示');
    //             //  console.log( Advertisement.imag,'图片');
    //             if (Advertisement.adLabel == null) {
    //                 let te = new Laya.Label();
    //                 te.text = "广告";
    //                 te.fontSize = 30;
    //                 te.color = "#FFFFFF";
    //                 te.bottom = 0;
    //                 te.right = 0;
    //                 Advertisement.adLabel = te;
    //                 Advertisement.nativeAdn.addChild(te);
    //             }
    //             // if(Advertisement.advs == "shop")
    //             // {
    //             //   Advertisement.nativeAdn.x = Laya.stage.width/2;
    //             //   Advertisement.nativeAdn.y = Laya.stage.height/3.5;
    //             // }
    //             // else
    //             // {
    //             //   Advertisement.nativeAdn.x = Laya.stage.width/2;
    //             //   Advertisement.nativeAdn.y = Laya.stage.height/2.5;
    //             // }
    //             Advertisement.nativeAdn.visible = true;
    //             Advertisement.nativeAdn.on(Laya.Event.MOUSE_UP, Advertisement.nativeAdn, reportAdClick);
    //             Advertisement.closeBtn.on(Laya.Event.MOUSE_DOWN, Advertisement.closeBtn, close_Btn);
    //             // }));
    //         }
    //     })
    //     // 注意：需要先调用reportAdShow上报广告曝光，才能调用reportAdClick去上报点击！！！
    //     function close_Btn() {
    //         Advertisement.nativeAdn.visible = false;
    //         Advertisement.closet = true;
    //     }
    //     function reportAdShow() {
    //         nativeAd.reportAdShow({ adId: Advertisement.adId });
    //     }
    //     function reportAdClick() {
    //         if (Advertisement.closet) {
    //             Advertisement.closet = false;
    //             return;
    //         }
    //         // if(Advertisement.nativeAdtouch)
    //         // {
    //         //   return;
    //         // }
    //         // Advertisement.nativeAdtouch = true;
    //         nativeAd.reportAdClick({ adId: Advertisement.adId });
    //     }
    // }

    // //Cocos OPPO原生
    // Advertisement.insertAdverV = function () {
    //     Advertisement.native = false;
    //     Advertisement.resNode.scheduleOnce(function () {
    //         Advertisement.native = true;
    //     }, 10)
    //     let nativeAd = qg.createNativeAd({
    //         posId: window.nativeAdId,
    //     });
    //     let adLoad = nativeAd.load();
    //     adLoad && adLoad.then(() => {
    //         console.log('原生广告读取完成', JSON.stringify(res));
    //     }).catch(err => {
    //         console.log('加载失败', JSON.stringify(err));
    //     })
    //     nativeAd.onLoad(function (res) {
    //         console.log('原生广告加载完成', JSON.stringify(res));
    //         if (res && res.adList) {
    //             Advertisement.adId = res.adList[0].adId;
    //             // cc.loader.load(res.adList[0].imgUrlList[0], function (err, texture) {
    //             cc.assetManager.loadRemote(res.adList[0].iconUrlList[0], { ext: '.png' }, function (err, texture) {
    //                 console.log(11111111);
    //                 if (err) {
    //                     console.log(222222222);
    //                     console.log(err);
    //                 }
    //                 console.log(33333333);
    //                 // Use texture to create sprite frame
    //                 var sprite = new cc.SpriteFrame(texture);
    //                 reportAdShow();
    //                 // Advertisement.resNode.scheduleOnce(function(){
    //                 Advertisement.nativeAdn.active = true;
    //                 // },0.3);
    //                 Advertisement.nativeAdimg.getComponent(cc.Sprite).spriteFrame = sprite;
    //                 Advertisement.nativeAdl.getComponent(cc.Label).string = res.adList[0].title;
    //                 Advertisement.nativeAdn.on(cc.Node.EventType.TOUCH_START, reportAdClick, Advertisement.nativeAdn);
    //             });
    //         }
    //     })
    //     // 注意：需要先调用reportAdShow上报广告曝光，才能调用reportAdClick去上报点击！！！
    //     function reportAdShow() {
    //         nativeAd.reportAdShow({ adId: Advertisement.adId });
    //     }
    //     function reportAdClick() {
    //         // if(Advertisement.nativeAdtouch)
    //         // {
    //         //   return;
    //         // }
    //         Advertisement.nativeAdtouch = true;
    //         nativeAd.reportAdClick({ adId: Advertisement.adId });
    //     }
    //     // this.customAd.show().then(() => {
    //     //     console.log("show success");
    //     // }).catch((error) => {
    //     //     console.log("show fail with:" + error.errCode + "," + error.errMsg);
    //     // });
    // }
    //#endregion

    //#region 通用
    //获取当前是周几
    Advertisement.getWeekDate = function () {
        var now = new Date();
        var day = now.getDay();
        var weeks = new Array(
            "周日",
            "周一",
            "周二",
            "周三",
            "周四",
            "周五",
            "周六",
        );
        var week = weeks[day];
        console.log(week);
        return week;
    };

    //  import Advertisement = require('');
    // import Advertisement from "";
    // let Advertisement = require("Advertisement_API");
    // Advertisement.rewarda = 'reward1';
    // Advertisement.videop = this;
    // Advertisement.videoAdverV();
    // //VIVO激励视频

    Advertisement.videoAdverV = function (e, t) {
        Advertisement.videop = e;
        Advertisement.failVideop = t;

        if (Laya.Browser.onVVMiniGame || Laya.Browser.onQGMiniGame || Laya.Browser.onHWMiniGame) {
            if (Advertisement.videoAd == null) {
                Advertisement.videoAd = qg.createRewardedVideoAd({
                    posId: window.videoAdId //输入广告ID
                });
                Advertisement.videoAd.onLoad(() => {
                    console.log("激励视频已加载");
                    // cc.audioEngine.pauseAll();
                    var adshow = Advertisement.videoAd.show();
                    // 调用then和catch之前需要对show的结果做下判空处理，防止出错（如果没有判空，在平台版本为1052以及以下的手机上将会出现错误）
                    Advertisement.reward = true;
                    adshow && adshow.then(() => {
                        console.log("激励视频广告显示成功");
                    }).catch(err => {
                        console.log("激励视频广告显示失败", err);
                        Advertisement.errorNode.opacity = 255;
                        setTimeout(() => {
                            Advertisement.errorNode.opacity = 0;
                        }, 3000);
                    });
                });
                Advertisement.videoAd.onError(err => {
                    console.log("激励视频异常", err);
                });
                Advertisement.videoAd.onClose(res => {
                    if (res && res.isEnded) {
                        if (Advertisement.reward) //判断是否发放过奖励
                        {
                            Advertisement.reward = false;
                            // cc.audioEngine.resumeAll();

                            Advertisement.videop && Advertisement.videop();
                            Advertisement.videop = null;
                            Advertisement.failVideop = null;
                        }
                    } else {
                        console.log("播放中途退出，不下发游戏奖励");
                        // cc.audioEngine.resumeAll();

                        Advertisement.failVideop && Advertisement.failVideop();
                        Advertisement.videop = null;
                        Advertisement.failVideop = null;
                    }
                });
            }
            var adload = Advertisement.videoAd.load();

            // 调用then和catch之前需要对load的结果做下判空处理，防止出错（如果没有判空，在平台版本为1052以及以下的手机上将会出现错误）
            adload && adload.then(() => {
                console.log("激励视频广告加载成功");
            }).catch(err => {
                console.log("激励视频广告加载失败", err);
                // Advertisement.errorNode.opacity = 255;
                // setTimeout(() => {
                //     Advertisement.errorNode.opacity = 0;
                // }, 3000);
                qg.showToast({
                    message: "当前无广告，请稍后尝试"
                });
            });
        } else {
            Advertisement.videop && Advertisement.videop();
            Advertisement.videop = null;
            Advertisement.failVideop = null;
        }
    };

    Advertisement.bannerDestroy = function () {
        if (Advertisement.bannerAd != null) {
            Advertisement.bannerAd.destroy();
            Advertisement.bannerAd = null;
            Advertisement.bannersize = false;
        }
    };

    // module.exports = Advertisement;

    function logID(id) {
            console.log(id);
        }
        function errorID(id) {
            console.error(id);
        }
        function warnID(id, opt) {
            console.warn(id, opt);
        }

        let ID_COUNTER = 0;
        class HashElement {
            constructor() {
                this.actions = [];
                this.target = null;
                this.actionIndex = 0;
                this.currentAction = null;
                this.paused = false;
                this.lock = false;
            }
        }
        class ActionManager {
            constructor() {
                this._hashTargets = Object.create(null);
                this._arrayTargets = [];
                this._elementPool = [];
            }
            _searchElementByTarget(arr, target) {
                for (var k = 0; k < arr.length; k++) {
                    if (target === arr[k].target)
                        return arr[k];
                }
                return null;
            }
            _getElement(target, paused) {
                var element = this._elementPool.pop();
                if (!element) {
                    element = new HashElement();
                }
                element.target = target;
                element.paused = !!paused;
                return element;
            }
            _putElement(element) {
                element.actions.length = 0;
                element.actionIndex = 0;
                element.currentAction = null;
                element.paused = false;
                element.target = null;
                element.lock = false;
                this._elementPool.push(element);
            }
            addAction(action, target, paused) {
                if (!action || !target) {
                    errorID(1000);
                    return;
                }
                var gid = (target["$_GID"] || (target["$_GID"] = Laya.Utils.getGID()));
                var element = this._hashTargets[gid];
                if (!element) {
                    element = this._getElement(target, paused);
                    this._hashTargets[gid] = element;
                    this._arrayTargets.push(element);
                }
                else if (!element.actions) {
                    element.actions = [];
                }
                element.actions.push(action);
                action.startWithTarget(target);
            }
            removeAllActions() {
                var locTargets = this._arrayTargets;
                for (var i = 0; i < locTargets.length; i++) {
                    var element = locTargets[i];
                    if (element)
                        this._putElement(element);
                }
                this._arrayTargets.length = 0;
                this._hashTargets = Object.create(null);
            }
            removeAllActionsFromTarget(target, forceDelete) {
                if (target == null)
                    return;
                var element = this._hashTargets[target["$_GID"]];
                if (element) {
                    element.actions.length = 0;
                    this._deleteHashElement(element);
                }
            }
            removeAction(action) {
                if (action == null)
                    return;
                var target = action.getOriginalTarget();
                var element = this._hashTargets[target["$_GID"]];
                if (element) {
                    for (var i = 0; i < element.actions.length; i++) {
                        if (element.actions[i] === action) {
                            element.actions.splice(i, 1);
                            if (element.actionIndex >= i)
                                element.actionIndex--;
                            break;
                        }
                    }
                }
            }
            getNumberOfRunningActionsInTarget(target) {
                var element = this._hashTargets[target["$_GID"]];
                if (element)
                    return (element.actions) ? element.actions.length : 0;
                return 0;
            }
            pauseTarget(target) {
                var element = this._hashTargets[target["$_GID"]];
                if (element)
                    element.paused = true;
            }
            resumeTarget(target) {
                var element = this._hashTargets[target["$_GID"]];
                if (element)
                    element.paused = false;
            }
            pauseAllRunningActions() {
                var idsWithActions = [];
                var locTargets = this._arrayTargets;
                for (var i = 0; i < locTargets.length; i++) {
                    var element = locTargets[i];
                    if (element && !element.paused) {
                        element.paused = true;
                        idsWithActions.push(element.target);
                    }
                }
                return idsWithActions;
            }
            resumeTargets(targetsToResume) {
                if (!targetsToResume)
                    return;
                for (var i = 0; i < targetsToResume.length; i++) {
                    if (targetsToResume[i])
                        this.resumeTarget(targetsToResume[i]);
                }
            }
            pauseTargets(targetsToPause) {
                if (!targetsToPause)
                    return;
                for (var i = 0; i < targetsToPause.length; i++) {
                    if (targetsToPause[i])
                        this.pauseTarget(targetsToPause[i]);
                }
            }
            purgeSharedManager() {
                Laya.stage.timer.clearAll(this);
            }
            _removeActionAtIndex(index, element) {
                var action = element.actions[index];
                element.actions.splice(index, 1);
                if (element.actionIndex >= index)
                    element.actionIndex--;
                if (element.actions.length === 0) {
                    this._deleteHashElement(element);
                }
            }
            _deleteHashElement(element) {
                var ret = false;
                if (element && !element.lock) {
                    if (this._hashTargets[element.target["$_GID"]]) {
                        delete this._hashTargets[element.target["$_GID"]];
                        var targets = this._arrayTargets;
                        for (var i = 0, l = targets.length; i < l; i++) {
                            if (targets[i] === element) {
                                targets.splice(i, 1);
                                break;
                            }
                        }
                        this._putElement(element);
                        ret = true;
                    }
                }
                return ret;
            }
            update(dt) {
                var locTargets = this._arrayTargets;
                var locCurrTarget;
                for (var elt = 0; elt < locTargets.length; elt++) {
                    this._currentTarget = locTargets[elt];
                    locCurrTarget = this._currentTarget;
                    if (!locCurrTarget.paused && locCurrTarget.actions) {
                        locCurrTarget.lock = true;
                        for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; locCurrTarget.actionIndex++) {
                            locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex];
                            if (!locCurrTarget.currentAction)
                                continue;
                            locCurrTarget.currentAction.step(dt * (locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1));
                            if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) {
                                locCurrTarget.currentAction.stop();
                                var action = locCurrTarget.currentAction;
                                locCurrTarget.currentAction = null;
                                this.removeAction(action);
                            }
                            locCurrTarget.currentAction = null;
                        }
                        locCurrTarget.lock = false;
                    }
                    if (locCurrTarget.actions.length === 0) {
                        this._deleteHashElement(locCurrTarget) && elt--;
                    }
                }
            }
        }
        ;

        class TweenSystem {
            constructor() {
                this.actionMgr = new ActionManager();
            }
            static create() {
                if (!this.instance) {
                    let sys = new TweenSystem();
                    this.instance = sys;
                    let timer = Laya.timer;
                    timer.frameLoop(1, this, function TweenSystemLoop() {
                        sys.postUpdate(timer.delta / 1000);
                    });
                }
            }
            get ActionManager() {
                return this.actionMgr;
            }
            postUpdate(dt) {
                this.actionMgr.update(dt);
            }
        }
        TweenSystem.ID = 'tween';

        var EGetWay;
        (function (EGetWay) {
            EGetWay[EGetWay["turn"] = 1] = "turn";
            EGetWay[EGetWay["gold_turn"] = 2] = "gold_turn";
            EGetWay[EGetWay["theature"] = 3] = "theature";
        })(EGetWay || (EGetWay = {}));
        var AchievementState;
        (function (AchievementState) {
            AchievementState[AchievementState["locked"] = 1] = "locked";
            AchievementState[AchievementState["unlocked"] = 2] = "unlocked";
            AchievementState[AchievementState["finished"] = 3] = "finished";
            AchievementState[AchievementState["received"] = 4] = "received";
        })(AchievementState || (AchievementState = {}));
        var ResourceType;
        (function (ResourceType) {
            ResourceType[ResourceType["sprite"] = 1] = "sprite";
            ResourceType[ResourceType["spine"] = 2] = "spine";
            ResourceType[ResourceType["particle"] = 3] = "particle";
            ResourceType[ResourceType["animNode"] = 4] = "animNode";
        })(ResourceType || (ResourceType = {}));
        var SignState;
        (function (SignState) {
            SignState[SignState["canSign"] = 1] = "canSign";
            SignState[SignState["signed"] = 2] = "signed";
            SignState[SignState["signOver"] = 3] = "signOver";
            SignState[SignState["waitGap"] = 4] = "waitGap";
        })(SignState || (SignState = {}));
        var GuideMaskType;
        (function (GuideMaskType) {
            GuideMaskType[GuideMaskType["none_passAll"] = 0] = "none_passAll";
            GuideMaskType[GuideMaskType["none_blockkAll"] = 1] = "none_blockkAll";
            GuideMaskType[GuideMaskType["none_passHole"] = 2] = "none_passHole";
            GuideMaskType[GuideMaskType["mask_passAll"] = 3] = "mask_passAll";
            GuideMaskType[GuideMaskType["mask_blockAll"] = 4] = "mask_blockAll";
            GuideMaskType[GuideMaskType["mask_passHole"] = 5] = "mask_passHole";
        })(GuideMaskType || (GuideMaskType = {}));
        var PartType;
        (function (PartType) {
            PartType[PartType["hair"] = 1] = "hair";
            PartType[PartType["headDec"] = 2] = "headDec";
            PartType[PartType["cloth"] = 3] = "cloth";
            PartType[PartType["sock"] = 5] = "sock";
            PartType[PartType["shoe"] = 6] = "shoe";
            PartType[PartType["earDec"] = 7] = "earDec";
            PartType[PartType["handDec"] = 8] = "handDec";
            PartType[PartType["neckDec"] = 9] = "neckDec";
            PartType[PartType["face"] = 10] = "face";
            PartType[PartType["backDeco"] = 11] = "backDeco";
            PartType[PartType["handHold"] = 12] = "handHold";
            PartType[PartType["faceDeco"] = 13] = "faceDeco";
        })(PartType || (PartType = {}));
        var RoleNpcPartType;
        (function (RoleNpcPartType) {
            RoleNpcPartType[RoleNpcPartType["body"] = 1] = "body";
            RoleNpcPartType[RoleNpcPartType["hair"] = 2] = "hair";
            RoleNpcPartType[RoleNpcPartType["face"] = 3] = "face";
        })(RoleNpcPartType || (RoleNpcPartType = {}));
        var ERandomTipType;
        (function (ERandomTipType) {
            ERandomTipType[ERandomTipType["onlineFance"] = 1] = "onlineFance";
        })(ERandomTipType || (ERandomTipType = {}));
        var DanceArrowDirection;
        (function (DanceArrowDirection) {
            DanceArrowDirection[DanceArrowDirection["up"] = 1] = "up";
            DanceArrowDirection[DanceArrowDirection["right"] = 2] = "right";
            DanceArrowDirection[DanceArrowDirection["down"] = 3] = "down";
            DanceArrowDirection[DanceArrowDirection["left"] = 4] = "left";
        })(DanceArrowDirection || (DanceArrowDirection = {}));
        var SYSTEM_MODEL;
        (function (SYSTEM_MODEL) {
            SYSTEM_MODEL[SYSTEM_MODEL["unknown"] = 0] = "unknown";
            SYSTEM_MODEL[SYSTEM_MODEL["loading"] = 1] = "loading";
            SYSTEM_MODEL[SYSTEM_MODEL["interaction"] = 2] = "interaction";
            SYSTEM_MODEL[SYSTEM_MODEL["amaze"] = 3] = "amaze";
            SYSTEM_MODEL[SYSTEM_MODEL["stage"] = 4] = "stage";
            SYSTEM_MODEL[SYSTEM_MODEL["pvp"] = 5] = "pvp";
            SYSTEM_MODEL[SYSTEM_MODEL["hub"] = 6] = "hub";
            SYSTEM_MODEL[SYSTEM_MODEL["leaderChanged"] = 7] = "leaderChanged";
            SYSTEM_MODEL[SYSTEM_MODEL["memberChanged"] = 8] = "memberChanged";
            SYSTEM_MODEL[SYSTEM_MODEL["stageResult"] = 9] = "stageResult";
        })(SYSTEM_MODEL || (SYSTEM_MODEL = {}));
        var AMAZE_TYPE;
        (function (AMAZE_TYPE) {
            AMAZE_TYPE[AMAZE_TYPE["unknown"] = 0] = "unknown";
            AMAZE_TYPE[AMAZE_TYPE["dance"] = 1] = "dance";
            AMAZE_TYPE[AMAZE_TYPE["member"] = 2] = "member";
            AMAZE_TYPE[AMAZE_TYPE["pet"] = 3] = "pet";
        })(AMAZE_TYPE || (AMAZE_TYPE = {}));
        var CustomMaterialType;
        (function (CustomMaterialType) {
            CustomMaterialType[CustomMaterialType["unknown"] = 0] = "unknown";
            CustomMaterialType[CustomMaterialType["unlitCartoon"] = 1] = "unlitCartoon";
            CustomMaterialType[CustomMaterialType["pbrHair"] = 2] = "pbrHair";
            CustomMaterialType[CustomMaterialType["pbrSkin"] = 3] = "pbrSkin";
            CustomMaterialType[CustomMaterialType["pbrCloth"] = 4] = "pbrCloth";
        })(CustomMaterialType || (CustomMaterialType = {}));
        var CustomMaterialRenderMode;
        (function (CustomMaterialRenderMode) {
            CustomMaterialRenderMode[CustomMaterialRenderMode["unknown"] = 0] = "unknown";
            CustomMaterialRenderMode[CustomMaterialRenderMode["RENDERMODE_OPAQUE"] = 1] = "RENDERMODE_OPAQUE";
            CustomMaterialRenderMode[CustomMaterialRenderMode["RENDERMODE_CUTOUT"] = 2] = "RENDERMODE_CUTOUT";
            CustomMaterialRenderMode[CustomMaterialRenderMode["RENDERMODE_CUTOUT_CULL_NONE"] = 3] = "RENDERMODE_CUTOUT_CULL_NONE";
            CustomMaterialRenderMode[CustomMaterialRenderMode["RENDERMODE_TRANSPARENT"] = 4] = "RENDERMODE_TRANSPARENT";
            CustomMaterialRenderMode[CustomMaterialRenderMode["RENDERMODE_TRANSPARENT_CULL_NONE"] = 5] = "RENDERMODE_TRANSPARENT_CULL_NONE";
            CustomMaterialRenderMode[CustomMaterialRenderMode["RENDERMODE_OPAQUE_CULL_NONE"] = 6] = "RENDERMODE_OPAQUE_CULL_NONE";
        })(CustomMaterialRenderMode || (CustomMaterialRenderMode = {}));
        var CreamType;
        (function (CreamType) {
            CreamType[CreamType["unknown"] = 0] = "unknown";
            CreamType[CreamType["horzontal"] = 1] = "horzontal";
            CreamType[CreamType["vertical"] = 2] = "vertical";
            CreamType[CreamType["flowerHorzontal"] = 3] = "flowerHorzontal";
            CreamType[CreamType["flowerVertical"] = 4] = "flowerVertical";
        })(CreamType || (CreamType = {}));
        var DailyGameType;
        (function (DailyGameType) {
            DailyGameType[DailyGameType["unknown"] = 0] = "unknown";
            DailyGameType[DailyGameType["cake"] = 1] = "cake";
            DailyGameType[DailyGameType["pen"] = 2] = "pen";
            DailyGameType[DailyGameType["cloth"] = 3] = "cloth";
            DailyGameType[DailyGameType["card"] = 4] = "card";
            DailyGameType[DailyGameType["design"] = 5] = "design";
            DailyGameType[DailyGameType["custom_made"] = 6] = "custom_made";
            DailyGameType[DailyGameType["parkour"] = 7] = "parkour";
            DailyGameType[DailyGameType["cardMade"] = 8] = "cardMade";
            DailyGameType[DailyGameType["clothcrossing"] = 9] = "clothcrossing";
            DailyGameType[DailyGameType["mid_autumn"] = 10] = "mid_autumn";
            DailyGameType[DailyGameType["new_year"] = 11] = "new_year";
            DailyGameType[DailyGameType["dailyTurntable"] = 98] = "dailyTurntable";
            DailyGameType[DailyGameType["dailyFightEvent"] = 99] = "dailyFightEvent";
        })(DailyGameType || (DailyGameType = {}));
        var AmusePenMode;
        (function (AmusePenMode) {
            AmusePenMode[AmusePenMode["unknown"] = 0] = "unknown";
            AmusePenMode[AmusePenMode["common"] = 1] = "common";
        })(AmusePenMode || (AmusePenMode = {}));
        var CARD_FIGHT_TYPE;
        (function (CARD_FIGHT_TYPE) {
            CARD_FIGHT_TYPE[CARD_FIGHT_TYPE["base"] = 0] = "base";
            CARD_FIGHT_TYPE[CARD_FIGHT_TYPE["dailyword"] = 1] = "dailyword";
            CARD_FIGHT_TYPE[CARD_FIGHT_TYPE["simulatePlayer"] = 2] = "simulatePlayer";
            CARD_FIGHT_TYPE[CARD_FIGHT_TYPE["rankPlayer"] = 3] = "rankPlayer";
            CARD_FIGHT_TYPE[CARD_FIGHT_TYPE["newYear"] = 5] = "newYear";
        })(CARD_FIGHT_TYPE || (CARD_FIGHT_TYPE = {}));
        const LESSON_MUSIC_MOV = {
            movIdle: "movIdle",
            movIdle2: "movIdle2",
            movIdle3: "movIdle3",
            movEnter: "movEnter",
            movSing1: "movSing1",
            movSing2: "movSing2",
            movSing3: "movSing3",
            movSingIdle: "movSingIdle",
            movListen1: "movListen1",
            movListen2: "movListen2",
            movListen3: "movListen3",
            movResult1: "movResult1",
            movResult2: "movResult2",
            movResult3: "movResult3",
            movGoodWait: "movGoodWait",
            movBadWait: "movBadWait",
            movSuper: "movSuper"
        };
        const LESSON_SAFE_MOV = {
            movSafe1: "movSafe1",
            movSafe2: "movSafe2",
            movSafe3: "movSafe3",
            movSafe4: "movSafe4",
            movSafe5: "movSafe5",
            movSafe6: "movSafe6",
            movSafe7: "movSafe7",
            movSafe11: "movSafe11",
            movSafe12: "movSafe12",
            movSafe13: "movSafe13",
            movSafe14: "movSafe14",
            movSafe21: "movSafe21",
            movSafe22: "movSafe22",
            movSafe23: "movSafe23",
            movSafe24: "movSafe24",
            movSafe25: "movSafe25",
            movSafe26: "movSafe26",
            movSafe27: "movSafe27",
            movSafe28: "movSafe28",
        };
        const FASHION_SHOW_MOV = {
            movIdle: "movIdle",
            movWalk: "movWalk",
            movLose01: "movLose01",
            movLose02: "movLose02",
            movLose03: "movLose03",
            movLose04: "movLose04",
            movLose05: "movLose05",
            movWinMove: "movWinMove",
            movWinPose: "movWinPose",
            movShow01: "movShow01",
            movShow02: "movShow02",
            movSBMove01: "movSBMove01",
            movSBDie01: "movSBDie01",
            movSBDie02: "movSBDie02",
            movSBDie03: "movSBDie03",
            movDBMove01: "movDBMove01",
            movDBDie01: "movDBDie01",
            movJudgeIdle: "movJudgeIdle",
            movJudgeYes: "movJudgeYes",
            movJudgeNo: "movJudgeNo",
            movJudgeGuZhang: "movJudgeGuZhang",
            movLbx01: "movLbx01",
            movLbx02: "movLbx02",
            movLbx03: "movLbx03",
        };
        const ROLE_FACE_MOV = {
            idle: "idle",
            idle02: "idle02",
            kaixin: "kaixin",
            nanguo: "nanguo",
            chijing: "chijing",
            haixiu: "haixiu",
            weixiao: "weixiao",
            biyan: "biyan",
            maimeng01: "maimeng01",
            maimeng02: "maimeng02",
            daxiao: "daxiao",
            p01: "p01",
            p02: "p02",
            p06: "p06",
            p07: "p07",
            p08: "p08",
            p09: "p09",
            p010: "p010",
            p18: "p18",
            p21: "p21",
            p24: "p24"
        };
        const ANIMATION_ID = {
            idle: `zjm_idle-zjm_idle01`,
            face: {
                idle: "dangao_lian-dg_kx",
            },
        };
        const MODEL_ID = {
            role_body: "shenti",
            role_face: "lian",
            role_shadow: "role_shadow",
            map_room: `room`,
            effect: {
                e_photo_glow: "e_photo_glow",
                eff_ui_dianji: "eff_ui_dianji",
                eff_ui_jinbi_loop: "eff_ui_jinbi_loop",
                eff_ui_qiandao_lh: "eff_ui_qiandao_lh",
                eff_ui_xsyd: "eff_ui_xsyd",
                eff_ui_xsyd_hand: "eff_ui_xsyd_hand",
                eff_ui_jiesuan_tuowei: "eff_ui_jiesuan_tuowei",
                eff_ui_zuanshi_loop: "eff_ui_zuanshi_loop",
            },
        };
        const LIGHT_MAP = {
            hub: [`Lightmap_mpa01-0_comp_light`],
            map02: [`Lightmap_mpa02-0_comp_light`],
            map03: [`Lightmap_mpa03-0_comp_light`],
            room: [`Lightmap_room-0_comp_light`],
            ttai: [`Lightmap-ttai_comp_light`],
        };
        const AD_EVENT_ID = {
            VIDEO: {
                video_vAdFreeTrialPartDialog_trial: "video_vAdFreeTrialPartDialog_trial",
                video_vRoomDialog_trial: "video_vRoomDialog_trial",
                video_vHubScene_warp: "video_vHubScene_warp",
                video_vHubScene_free_gold: "video_vHubScene_free_gold",
                video_vHubScene_free_diamon: "video_vHubScene_free_diamon",
                video_vAmuseCardPhotoMakeScene_recipe: "video_vAmuseCardPhotoMakeScene_recipe",
                video_vAmuseCardPhotoMakeScene_mask: "video_vAmuseCardPhotoMakeScene_mask",
                video_vGotItemDialog_extrnal_reward: "video_vGotItemDialog_extrnal_reward",
                video_vSignDialog_got_item: "video_vSignDialog_got_item",
                video_vDesignCollectScene_unlock: "video_vDesignCollectScene_unlock",
                video_vDesignRoomScene_trial: "video_vDesignRoomScene_trial",
                video_vSurpriseRewardDialog_fragment: "video_vSurpriseRewardDialog_fragment",
                video_vGotNewRoleDialog_fragment: "video_vGotNewRoleDialog_fragment",
                video_vAmuseCakeMakeScene_trial: "video_vAmuseCakeMakeScene_trial",
                video_vAmuseCakePreviewVipDialog_vip: "video_vAmuseCakePreviewVipDialog_vip",
                video_vCustomMadeClothesScene_trial: "video_vCustomMadeClothesScene_trial",
                video_vCustomMadeClothesPreviewVipDialog_vip: "video_vCustomMadeClothesPreviewVipDialog_vip",
                video_vAmusePenRoleTrialDialog_trial: "video_vAmusePenRoleTrialDialog_trial",
                video_vAmuseFashionPenScene_super: "video_vAmuseFashionPenScene_super",
                video_vAmusePenChooseDialog_trial: "video_vAmusePenChooseDialog_trial",
                video_vAmuseParkourScene_super: "video_vAmuseParkourScene_super",
                video_vAdTurntableDialog_free: "video_vAdTurntableDialog_free",
                video_vRoleChangeScene_fragment: "video_vRoleChangeScene_fragment",
                video_vHubScene_free_energy: "video_vHubScene_free_energy",
                video_vAmuseCardAlbumDialog_fragment: "video_vAmuseCardAlbumDialog_fragment",
                video_vAmuseCardTeamSetScene_unlock: "video_vAmuseCardTeamSetScene_unlock",
                video_vAmuseCardStartScene_vip: "video_vAmuseCardStartScene_vip",
                video_vAmuseCardFightScene_trial: "video_vAmuseCardFightScene_trial",
                video_vAmuseClothCrossingScene_trial_role: "video_vAmuseClothCrossingScene_trial_role",
                video_vAmuseClothCrossingScene_trial_ani: "video_vAmuseClothCrossingScene_trial_ani",
                video_vAmuseCardExtractDialog_rare_extract: "video_vAmuseCardExtractDialog_rare_extract",
                video_vAmuseCardExtractDialog_ad_extract: "video_vAmuseCardExtractDialog_ad_extract",
                video_vAdGetMoreUnlockItemDialog_more: "video_vAdGetMoreUnlockItemDialog_more",
            },
        };
        class Const {
        }
        Const.packageVersion = "1.0.0";
        Const.sdcardPath = "";
        Const.copChannelId = "";
        Const.ulsdkVersion = "";
        Const.cdkChannelId = "";
        Const.gameIndex = "117";
        Const.bHighShadowQuality = false;
        Const.DOWNLOAD_FRAMES = {};
        Const.ITEM_ID_DIAMONDS = 1;
        Const.ITEM_ID_GOLD = 2;
        Const.ITEM_ID_ENERGY = 5;
        Const.ITEM_ID_ENERGY_MAX = 6;
        Const.ITEM_ID_TURNTABLE_COUNT = 7;
        Const.ITEM_ID_MOON_CAKE = 57;
        Const.ITEM_ID_VIDEO_SHARE_COUNT = 9;
        Const.ITEM_ID_SHARE_COUNT = 10;
        Const.ITEM_ID_PVP_REWARD_CURR_NUM = 16;
        Const.ITEM_ID_PVP_LIKE_COUNT = 17;
        Const.ITEM_ID_ROOM_COLOR = 20;
        Const.ITEM_ID_CAKE_COLOR = 22;
        Const.ITEM_ID_PARKOUR_COLOR = 23;
        Const.ITEM_ID_MAKE_CLOTH_COLOR = 24;
        Const.ITEM_ID_CARD_FIGHT_PROGRESS_POINT = 25;
        Const.ITEM_ID_CLOTH_CROSSING_COLOR = 26;
        Const.ITEM_ID_WORLD_DAILY_POINT = 21;
        Const.ITEM_ID_GAME_RES_VERSION = 998;
        Const.FIRST_SHARE_REWARD_PART_ID = 12042;
        Const.ITEM_FLAG_MONEY = 1;
        Const.ITEM_FLAG_PART = 2;
        Const.ITEM_FLAG_BOX = 3;
        Const.ITEM_FLAG_CAKE = 4;
        Const.ITEM_FLAG_MAKE_CLOTH = 5;
        Const.ITEM_FLAG_CARD = 6;
        Const.RESOLUTION_RANGE = {
            maxWidth: 768,
            minWidth: 576,
            maxHeight: 1280,
            minHeight: 1024,
        };
        Const.RESOLUTION_SAFE_RANGE = {
            maxWidth: 768,
            minWidth: 576,
            maxHeight: 1152,
            minHeight: 1024,
        };
        Const.SERVER_HOST = "https://rank.ultralisk.cn";
        Const.SERVER_URL_FORMAT = "%s/ultralisk/";
        Const.SERVER_APP_ID = 53;
        Const.SERVER_RANK_ID = 67;
        Const.OFFLINE_RANK_ID_LEVEL = 1;
        Const.OFFLINE_RANK_ID_PART = 2;
        Const.OFFLINE_RANK_ID_PVP = 3;
        Const.OFFLINE_RANK_ID_DANCE = 4;
        Const.OFFLINE_RANK_ID_MATCH = 4;
        Const.CHANGE_ROLE_ADD_SCORE = 20;
        Const.RADIAN2EULAR = 180 / Math.PI;
        Const.EMOGJI_ICON_PATH_DICT = {
            [0]: "res/icon/sprite_fu_dong_bad.png",
            [1]: "res/icon/sprite_fu_dong_good.png",
            [2]: "res/icon/sprite_fu_dong_best.png"
        };
        Const.licenceInfo = "";
        Const.gameName = "珠珠的秘密";
        Const.DEBUG_SAVE_PRECOMILESHADER_FALG = false;
        Const.AD_FLAG_ICON_PATH_DICT = {
            [0]: "res/ui/ad/ad.png",
            [1]: "res/ui/ad/ad_toutiao.png"
        };
        Const.MATERIAL_TYPE_2_DESC_DICT = {
            [0]: "[未知]",
            [1]: "[卡通]",
            [2]: "[头发]",
            [3]: "[SSR]",
            [4]: "[服装]",
        };
        Const.CREAM_COLOR_TEXTURE_WH = 64;
        Const.CREAM_COLOR_CHANGE_STEP = 0.01;
        Const.CAKE_VERTICAL_FULL_TIME = 1;
        Const.BASE_BONE_NAME = "Bip001";
        Const.PLAYER_CARD_POS_COUNT = 5;
        Const.SKIN_CONTROL_GRID_PATH = "res/material/al/holder_blue.png";
        Const.SKIN_CONTROL_GRID_SHINE_PATH = "res/material/al/holder_gb.png";
        Const.CUSTOM_PART_ICON_SIZE_WH = 88;
        Const.DAILY_DRESS_LUCKY_PART_COUNT = 3;
        Const.CUSTOM_DESIGN_PART_COUNT = 12;
        Const.ROOM_SPECIAL_TYPE_ROLE = 997;
        Const.ROOM_SPECIAL_TYPE_DESIGN = 998;
        Const.BODY_FBXNAME = "shenti";
        Const.ROLE_LUCKY_FULL_EFFECT_NAME = "117_ui_loop_lucky_02";
        Const.POP_MAKE_CARD_TIP_SCORE_RATIO = 0.6;
        Const.CARD_PHOTO_SIZE = { width: 129, height: 188 };
        Const.CUSTOM_LAYA_STAGE_BASE_BG_NAME = "_custom_laya_stage_base_bg_name";
        Const.SCORE_WHEN_ROOM_DRESSED_AUTO_POP_TRIAL_PART = 50;
        Const.DESIGN_ROOM_TILLING_MIN_SCALE = 0.2;
        Const.DESIGN_ROOM_TILLING_MAX_SCALE = 1.8;
        Const.ROOM_TRIAL_PART_COST = 200;
        Const.UNLOCK_ALBUM_CARD_COST = 200;

        class MsgHandler {
            constructor(eventTarget) {
                if (!MsgHandler.globalEventDis)
                    MsgHandler.globalEventDis = new Laya.EventDispatcher();
                this.eventTarget = eventTarget || MsgHandler.globalEventDis;
                this.registeredListeners = {};
                this.startedListeners = {};
                this.bStarted = false;
            }
            registerListeners(listeners) {
                Tools.forEachMap(listeners, (msgName, listener) => {
                    if (!this.registeredListeners[msgName]) {
                        this.registeredListeners[msgName] = [];
                    }
                    let index = this.registeredListeners[msgName].indexOf(listener);
                    if (index >= 0) {
                        this.registeredListeners[msgName][index] = listener;
                    }
                    else {
                        this.registeredListeners[msgName].push(listener);
                    }
                });
                if (this.bStarted) {
                    this.startProcMsg();
                }
            }
            startProcMsg() {
                this.bStarted = true;
                Tools.forEachMap(this.registeredListeners, (msgName, listeners) => {
                    for (let index = 0; index < listeners.length; index++) {
                        const listener = listeners[index];
                        this.eventTarget.on(msgName, this, listener);
                        if (!this.startedListeners[msgName]) {
                            this.startedListeners[msgName] = [];
                        }
                        this.startedListeners[msgName].push(listener);
                    }
                });
            }
            stopProcMsg() {
                Tools.forEachMap(this.startedListeners, (msgName, listeners) => {
                    for (let index = 0; index < listeners.length; index++) {
                        const listener = listeners[index];
                        this.eventTarget.off(msgName, this, listener);
                    }
                });
                this.bStarted = false;
                this.startedListeners = {};
                this.registeredListeners = {};
            }
            sendMsg(msgName, data) {
                try {
                    this.eventTarget.event(msgName, data);
                }
                catch (error) {
                    console.warn("MsgHandler.sendMsg has exception", error);
                }
            }
        }
        MsgHandler.globalEventDis = null;

        var ul;
        (function (ul) {
            function _convert(match, nosign) {
                if (nosign) {
                    match.sign = '';
                }
                else {
                    match.sign = match.negative ? '-' : match.sign;
                }
                var l = match.min - match.argument.length + 1 - match.sign.length;
                var pad = new Array(l < 0 ? 0 : l).join(match.pad);
                if (!match.left) {
                    if (match.pad == "0" || nosign) {
                        return match.sign + pad + match.argument;
                    }
                    else {
                        return pad + match.sign + match.argument;
                    }
                }
                else {
                    if (match.pad == "0" || nosign) {
                        return match.sign + match.argument + pad.replace(/0/g, ' ');
                    }
                    else {
                        return match.sign + match.argument + pad;
                    }
                }
            }
            function format(...args) {
                if (typeof args == "undefined") {
                    return null;
                }
                if (args.length < 1) {
                    return null;
                }
                if (typeof args[0] != "string") {
                    return null;
                }
                if (typeof RegExp == "undefined") {
                    return null;
                }
                var string = args[0];
                var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
                var matches = new Array();
                var strings = new Array();
                var convCount = 0;
                var stringPosStart = 0;
                var stringPosEnd = 0;
                var matchPosEnd = 0;
                var newString = '';
                var match = null;
                while (match = exp.exec(string)) {
                    if (match[9]) {
                        convCount += 1;
                    }
                    stringPosStart = matchPosEnd;
                    stringPosEnd = exp.lastIndex - match[0].length;
                    strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
                    matchPosEnd = exp.lastIndex;
                    matches[matches.length] = {
                        match: match[0],
                        left: match[3] ? true : false,
                        sign: match[4] || '',
                        pad: match[5] || ' ',
                        min: match[6] || 0,
                        precision: match[8],
                        code: match[9] || '%',
                        negative: parseInt(args[convCount]) < 0 ? true : false,
                        argument: String(args[convCount])
                    };
                }
                strings[strings.length] = string.substring(matchPosEnd);
                if (matches.length == 0) {
                    return string;
                }
                if ((args.length - 1) < convCount) {
                    return null;
                }
                var code = null;
                var match = null;
                var substitution = null;
                var i = null;
                for (i = 0; i < matches.length; i++) {
                    if (matches[i].code == '%') {
                        substitution = '%';
                    }
                    else if (matches[i].code == 'b') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
                        substitution = _convert(matches[i], true);
                    }
                    else if (matches[i].code == 'c') {
                        matches[i].argument = String(String.fromCharCode(Math.abs(parseInt(matches[i].argument))));
                        substitution = _convert(matches[i], true);
                    }
                    else if (matches[i].code == 'd') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
                        substitution = _convert(matches[i]);
                    }
                    else if (matches[i].code == 'f') {
                        matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
                        substitution = _convert(matches[i]);
                    }
                    else if (matches[i].code == 'o') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
                        substitution = _convert(matches[i]);
                    }
                    else if (matches[i].code == 's') {
                        matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length);
                        substitution = _convert(matches[i], true);
                    }
                    else if (matches[i].code == 'x') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                        substitution = _convert(matches[i]);
                    }
                    else if (matches[i].code == 'X') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                        substitution = _convert(matches[i]).toUpperCase();
                    }
                    else {
                        substitution = matches[i].match;
                    }
                    newString += strings[i];
                    newString += substitution;
                }
                newString += strings[i];
                return newString;
            }
            ul.format = format;
            function formatDate(date, fmt) {
                var o = {
                    "M+": date.getMonth() + 1,
                    "d+": date.getDate(),
                    "h+": date.getHours(),
                    "m+": date.getMinutes(),
                    "s+": date.getSeconds(),
                    "q+": Math.floor((date.getMonth() + 3) / 3),
                    "S": date.getMilliseconds()
                };
                if (/(y+)/.test(fmt))
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt))
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            }
            ul.formatDate = formatDate;
            function _dump(arr, level) {
                var dumped_text = "";
                if (!level)
                    level = 0;
                var level_padding = "";
                for (var j = 0; j < level + 1; j++)
                    level_padding += "    ";
                if (typeof (arr) == 'object') {
                    for (var item in arr) {
                        var value = arr[item];
                        if (typeof (value) == 'object') {
                            dumped_text += level_padding + "'" + item + "' ...\n";
                            dumped_text += _dump(value, level + 1);
                        }
                        else {
                            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
                        }
                    }
                }
                else {
                    dumped_text = "===>" + arr + "<===(" + typeof (arr) + ")";
                }
                return dumped_text;
            }
            function dump(data, tag, level) {
                let text = _dump(data);
                console.log("dump-begin", tag);
                console.log(text);
                console.log("dump-end");
            }
            ul.dump = dump;
            function getType(obj) {
                let toString = Object.prototype.toString;
                let map = {
                    '[object Boolean]': 'boolean',
                    '[object Number]': 'number',
                    '[object String]': 'string',
                    '[object Function]': 'function',
                    '[object Array]': 'array',
                    '[object Date]': 'date',
                    '[object RegExp]': 'regExp',
                    '[object Undefined]': 'undefined',
                    '[object Null]': 'null',
                    '[object Object]': 'object'
                };
                return map[toString.call(obj)];
            }
            ul.getType = getType;
            function clone(data) {
                let type = getType(data);
                let obj;
                if (type === 'object') {
                    obj = {};
                }
                else if (type === 'array') {
                    obj = [];
                }
                else {
                    return data;
                }
                if (type === 'array') {
                    for (let i = 0, len = data.length; i < len; i++) {
                        obj.push(clone(data[i]));
                    }
                }
                else if (type === 'object') {
                    for (let key in data) {
                        obj[key] = clone(data[key]);
                    }
                }
                return obj;
            }
            ul.clone = clone;
            function length(data) {
                let type = getType(data);
                if (type === "array") {
                    let length = 0;
                    for (const key in data) {
                        const element = data[key];
                        if (element) {
                            length++;
                        }
                    }
                    return length;
                }
                else if (type === "object") {
                    let length = 0;
                    for (const key in data) {
                        const element = data[key];
                        if (element) {
                            length++;
                        }
                    }
                    return length;
                }
                else {
                    return 0;
                }
            }
            ul.length = length;
            function clamp(cur, min, max) {
                if (cur < min) {
                    cur = min;
                }
                if (cur > max) {
                    cur = max;
                }
                return cur;
            }
            ul.clamp = clamp;
        })(ul || (ul = {}));

        class Timer {
            constructor(span, repeatCount, callback) {
                this._repeatCount = -1;
                this._span = 1;
                this._callback = null;
                this._bRuning = false;
                this._count = 0;
                this._span = span;
                this._repeatCount = repeatCount;
                this._callback = callback;
            }
            static callLater(span, callback, caller) {
                let timer = new Timer(span, 1, callback);
                timer._bindingCaller = caller;
                timer._bBindCaller = !!caller;
                timer.start();
                return timer;
            }
            static callLoop(span, callback, e, count = -1) {
                let timer = new Timer(span, count, callback);
                if (typeof (e) == "boolean") {
                    let bIgnoreForeverWarn = e;
                    timer.start(bIgnoreForeverWarn);
                }
                else if (e && typeof (e) == "object") {
                    timer._bindingCaller = e;
                    timer._bBindCaller = !!e;
                    timer.start(true);
                }
                else {
                    timer.start();
                }
                return timer;
            }
            _onSpan(timer) {
                timer._count++;
                if (timer._bBindCaller) {
                    if (!timer._bindingCaller) {
                        timer.stop();
                        return;
                    }
                    else if (timer._bindingCaller instanceof Laya.Node) {
                        if (!timer._bindingCaller.parent) {
                            timer.stop();
                            return;
                        }
                    }
                    else if (timer._bindingCaller["destroyed"]) {
                        timer.stop();
                        return;
                    }
                }
                if (timer._callback) {
                    try {
                        timer._callback(timer);
                    }
                    catch (error) {
                        console.warn(error);
                    }
                }
                if (timer._repeatCount >= 0 && timer._count >= timer._repeatCount) {
                    timer.stop();
                }
            }
            isRunning() {
                return this._bRuning;
            }
            get count() {
                return this._count;
            }
            get span() {
                return this._span;
            }
            start(bIgnoreForeverWarn = false) {
                this.stop();
                if (!this._callback) {
                    console.warn("警告] Timer.start callback未设置！");
                    return this;
                }
                if (!bIgnoreForeverWarn && this._repeatCount < 0) {
                    console.warn("警告] Timer.start, this timer will never stop!");
                    console.warn("警告]     please use startAndBindToNode");
                    console.warn("警告]     or your can stop timer in callback. use e:stop()");
                }
                this._count = 0;
                this._bRuning = true;
                Laya.timer.loop(this.span * 1000, this, this._onSpan, [this]);
                return this;
            }
            stop() {
                if (this._bRuning) {
                    Laya.timer.clear(this, this._onSpan);
                    this._bRuning = false;
                }
                return this;
            }
        }

        const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        const lookup = new Uint8Array(256);
        for (let i = 0; i < _keyStr.length; i++) {
            lookup[_keyStr.charCodeAt(i)] = i;
        }
        class Base64 {
            static get nativeBase64() {
                return false;
            }
            static encodeForUrl(input) {
                let str = this.encode(input);
                if (!str)
                    return null;
                str = str.replace("+", "-");
                str = str.replace("/", "*");
                return str;
            }
            static decodeForUrl(input) {
                if (!input)
                    return null;
                input = input.replace("-", "+");
                input = input.replace("*", "/");
                return this.decode(input);
            }
            static decode(base64) {
                base64 = base64.replace(/[^A-Za-z0-9\+\/\=]/g, "");
                if (this.nativeBase64) {
                    return window.atob(base64);
                }
                else {
                    var output = [], chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
                    while (i < base64.length) {
                        enc1 = _keyStr.indexOf(base64.charAt(i++));
                        enc2 = _keyStr.indexOf(base64.charAt(i++));
                        enc3 = _keyStr.indexOf(base64.charAt(i++));
                        enc4 = _keyStr.indexOf(base64.charAt(i++));
                        chr1 = (enc1 << 2) | (enc2 >> 4);
                        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                        chr3 = ((enc3 & 3) << 6) | enc4;
                        output.push(String.fromCharCode(chr1));
                        if (enc3 !== 64) {
                            output.push(String.fromCharCode(chr2));
                        }
                        if (enc4 !== 64) {
                            output.push(String.fromCharCode(chr3));
                        }
                    }
                    output = output.join("");
                    return this._utf8_decode(output);
                }
            }
            static encode(input) {
                input = this._utf8_encode(input);
                if (this.nativeBase64) {
                    window.btoa(input);
                }
                else {
                    var output = [], chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
                    while (i < input.length) {
                        chr1 = input.charCodeAt(i++);
                        chr2 = input.charCodeAt(i++);
                        chr3 = input.charCodeAt(i++);
                        enc1 = chr1 >> 2;
                        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                        enc4 = chr3 & 63;
                        if (isNaN(chr2)) {
                            enc3 = enc4 = 64;
                        }
                        else if (isNaN(chr3)) {
                            enc4 = 64;
                        }
                        output.push(_keyStr.charAt(enc1));
                        output.push(_keyStr.charAt(enc2));
                        output.push(_keyStr.charAt(enc3));
                        output.push(_keyStr.charAt(enc4));
                    }
                    output = output.join("");
                    return output;
                }
            }
            static encodeArrayBuffer(arraybuffer) {
                var bytes = new Uint8Array(arraybuffer), i, len = bytes["length"], base64 = "";
                for (i = 0; i < len; i += 3) {
                    base64 += _keyStr[bytes[i] >> 2];
                    base64 += _keyStr[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
                    base64 += _keyStr[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
                    base64 += _keyStr[bytes[i + 2] & 63];
                }
                if ((len % 3) === 2) {
                    base64 = base64.substring(0, base64.length - 1) + "=";
                }
                else if (len % 3 === 1) {
                    base64 = base64.substring(0, base64.length - 2) + "==";
                }
                return base64;
            }
            static decodeArrayBuffer(base64) {
                var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
                if (base64[base64.length - 1] === "=") {
                    bufferLength--;
                    if (base64[base64.length - 2] === "=") {
                        bufferLength--;
                    }
                }
                var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
                for (i = 0; i < len; i += 4) {
                    encoded1 = lookup[base64.charCodeAt(i)];
                    encoded2 = lookup[base64.charCodeAt(i + 1)];
                    encoded3 = lookup[base64.charCodeAt(i + 2)];
                    encoded4 = lookup[base64.charCodeAt(i + 3)];
                    bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
                    bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
                    bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
                }
                return arraybuffer;
            }
            static decodeToUnit32Array(base64, bytes) {
                bytes = bytes || 1;
                var dec = Base64.decode(base64), i, j, len;
                var ar = new Uint32Array(dec.length / bytes);
                for (i = 0, len = dec.length / bytes; i < len; i++) {
                    ar[i] = 0;
                    for (j = bytes - 1; j >= 0; --j) {
                        ar[i] += dec.charCodeAt((i * bytes) + j) << (j << 3);
                    }
                }
                return ar;
            }
            static removePaddingChars(base64) {
                var lkey = _keyStr.indexOf(base64.charAt(base64.length - 1));
                if (lkey == 64) {
                    return base64.substring(0, base64.length - 1);
                }
                return base64;
            }
            static decodeToUnit8Array(base64, arrayBuffer) {
                base64 = this.removePaddingChars(base64);
                base64 = this.removePaddingChars(base64);
                var bytes = Math.floor(base64.length / 4 * 3);
                let uarray;
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;
                var j = 0;
                if (arrayBuffer)
                    uarray = new Uint8Array(arrayBuffer);
                else
                    uarray = new Uint8Array(bytes);
                base64 = base64.replace(/[^A-Za-z0-9\+\/\=]/g, "");
                for (i = 0; i < bytes; i += 3) {
                    enc1 = _keyStr.indexOf(base64.charAt(j++));
                    enc2 = _keyStr.indexOf(base64.charAt(j++));
                    enc3 = _keyStr.indexOf(base64.charAt(j++));
                    enc4 = _keyStr.indexOf(base64.charAt(j++));
                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;
                    uarray[i] = chr1;
                    if (enc3 != 64)
                        uarray[i + 1] = chr2;
                    if (enc4 != 64)
                        uarray[i + 2] = chr3;
                }
                return uarray;
            }
            static decodeToArrayBuffer(base64) {
                var bytes = Math.floor((base64.length / 4) * 3);
                var ab = new ArrayBuffer(bytes);
                this.decodeToUnit8Array(base64, ab);
                return ab;
            }
            static _utf8_encode(input) {
                input = input.replace(/\r\n/g, "\n");
                var utftext = "";
                for (var n = 0; n < input.length; n++) {
                    var c = input.charCodeAt(n);
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    }
                    else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                    else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                }
                return utftext;
            }
            static _utf8_decode(utftext) {
                var string = "";
                var i = 0;
                var c = 0;
                var c1 = 0;
                var c2 = 0;
                var c3 = 0;
                while (i < utftext.length) {
                    c = utftext.charCodeAt(i);
                    if (c < 128) {
                        string += String.fromCharCode(c);
                        i++;
                    }
                    else if ((c > 191) && (c < 224)) {
                        c2 = utftext.charCodeAt(i + 1);
                        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                        i += 2;
                    }
                    else {
                        c2 = utftext.charCodeAt(i + 1);
                        c3 = utftext.charCodeAt(i + 2);
                        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                        i += 3;
                    }
                }
                return string;
            }
        }

        class Tools {
            static time() {
                if (this._debugTime != null) {
                    return this._debugTime;
                }
                else {
                    return new Date().getTime() / 1000;
                }
            }
            static get deltaTime() {
                return this._deltaTime;
            }
            static gameExecuteTime() {
                return this.gameRuingTime;
            }
            static autoIncrementRuingTime() {
                if (!this.gameRuingTime) {
                    this.gameRuingTime = 0;
                }
                this.gameRuingTime += Math.min(this.delta(), 1);
                this._curTime = this.time();
                this._deltaTime = this._curTime - this._lastUpdateTime;
                this._lastUpdateTime = this._curTime;
            }
            static _setDebugTime(time) {
                this._debugTime = time;
            }
            static isOneDay(seconds1, seconds2) {
                var d1 = new Date(seconds1 * 1000);
                var d2 = new Date(seconds2 * 1000);
                return d1.getFullYear() == d2.getFullYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate();
            }
            static getObjSize(obj) {
                if (!obj) {
                    return 0;
                }
                if (Array.isArray(obj)) {
                    return obj.length;
                }
                let count = 0;
                for (let k in obj) {
                    count++;
                }
                return count;
            }
            static objLength(obj) {
                return this.getObjSize(obj);
            }
            static deepCopy(src, dest) {
                if (!src)
                    return src;
                if (src instanceof Array) {
                    let newObj = dest || [];
                    let len = src.length;
                    for (let i = 0; i < len; i++) {
                        const element = src[i];
                        newObj.push(this.deepCopy(element));
                    }
                    return newObj;
                }
                else if (src instanceof Object) {
                    let newObj = dest || {};
                    let keys = Object.keys(src);
                    for (let i = 0; i < keys.length; i++) {
                        let key = keys[i];
                        let value = src[key];
                        newObj[key] = this.deepCopy(value);
                    }
                    return newObj;
                }
                else {
                    return src;
                }
            }
            static random(min, max) {
                if (min == null && max == null) {
                    return Math.random();
                }
                else if (max == null) {
                    if (min == 0) {
                        return 0;
                    }
                    return Math.floor(Math.random() * min + 1);
                }
                else if (min == max) {
                    return min;
                }
                else {
                    return Math.floor(Math.random() * (max - min + 1) + min);
                }
            }
            static randomGetListArr(min, max, count) {
                let offset = max - min;
                let useCount = Math.min(offset, count || offset);
                if (useCount <= 0) {
                    return [];
                }
                let dict = {};
                let maxRanCount = Math.min(useCount * 10, 10000);
                let ranCount = 0;
                let validCount = 0;
                while (ranCount < maxRanCount) {
                    ranCount += 1;
                    let value = Tools.random(min, max);
                    if (!dict[value]) {
                        validCount += 1;
                        dict[value] = ranCount;
                        if (validCount == count) {
                            break;
                        }
                    }
                }
                let arr = [];
                for (let k in dict) {
                    arr.push({ value: parseInt(k), order: dict[k] });
                }
                arr = Tools.sortArrayByField(arr, "order");
                let retArr = [];
                for (let i = 0; i < arr.length; i++) {
                    retArr.push(arr[i].value);
                }
                return retArr;
            }
            static randomGotOneArrayData(arr) {
                let data = this.randomGotArrayDatas(arr, 1) || [];
                return data[0];
            }
            static randomGotArrayDatas(arr, expectNum) {
                if (!arr || arr.length <= 0 || !expectNum || expectNum <= 0) {
                    return [];
                }
                let newArr = [];
                expectNum = Math.min(expectNum, arr.length);
                let indexArr = [];
                for (let i = 0; i < arr.length; i++) {
                    indexArr.push(i);
                }
                let gotNum = 0;
                while (gotNum < expectNum) {
                    let index = Tools.random(0, indexArr.length - 1);
                    let indexValue = indexArr[index];
                    let data = arr[indexValue];
                    newArr.push(data);
                    indexArr.splice(index, 1);
                    gotNum += 1;
                }
                return newArr;
            }
            static randomRemoveArrayDatas(arr, expectNum) {
                if (!arr || arr.length <= 0 || !expectNum || expectNum < 0) {
                    return [];
                }
                let newArr = [];
                if (expectNum >= arr.length) {
                    let count = arr.length;
                    for (let index = (count - 1); index >= 0; index--) {
                        newArr.push(arr[index]);
                        arr.splice(index, 1);
                    }
                    return newArr;
                }
                let indexArr = [];
                for (let i = 0; i < arr.length; i++) {
                    indexArr.push(i);
                }
                let removeIndexArr = [];
                let gotNum = 0;
                while (gotNum < expectNum) {
                    let index = Tools.random(0, indexArr.length - 1);
                    let indexValue = indexArr[index];
                    let data = arr[indexValue];
                    newArr.push(data);
                    indexArr.splice(index, 1);
                    removeIndexArr.push({ index: indexValue });
                    gotNum += 1;
                }
                if (gotNum > 0) {
                    removeIndexArr = this.sortArrayByField(removeIndexArr, "-index");
                    for (let tmp = 0; tmp < gotNum; tmp++) {
                        let data = removeIndexArr[tmp];
                        arr.splice(data.index, 1);
                    }
                }
                return newArr;
            }
            static scaleInRange(n, ia, ib, oa, ob) {
                if (ia < ib) {
                    if (n < ia)
                        n = ia;
                    if (n > ib)
                        n = ib;
                }
                else {
                    if (n < ib)
                        n = ib;
                    if (n > ia)
                        n = ia;
                }
                let iDistance = ib - ia;
                let oDistance = ob - oa;
                return (n - ia) / iDistance * oDistance + oa;
            }
            static calcWheelTarget(arr, weightKey) {
                let totalWeight = 0;
                for (let i = 0; i < arr.length; i++) {
                    const v = arr[i];
                    let w = parseInt(v[weightKey]);
                    if (isNaN(w)) {
                        console.warn(ul.format("Tools.calcWheelTarget weight field not found! key=[%s]", weightKey));
                        return null;
                    }
                    totalWeight += w;
                }
                let rw = this.random(totalWeight);
                for (let i = 0; i < arr.length; i++) {
                    const v = arr[i];
                    let w = parseInt(v[weightKey]);
                    if (rw <= w) {
                        return v;
                    }
                    else {
                        rw -= w;
                    }
                }
                return null;
            }
            static sortArrayByField(array, fields) {
                if (typeof (fields) == "string") {
                    fields = [fields];
                }
                else {
                    fields = fields;
                }
                let fieldConfig = [];
                for (let k in fields) {
                    let v = fields[k];
                    if (v && v != "") {
                        if (v.substring(0, 1) === "-") {
                            let tmpField = v.substring(1, v.length);
                            if (tmpField && tmpField != "") {
                                fieldConfig.push([tmpField, true]);
                            }
                        }
                        else {
                            fieldConfig.push([v, false]);
                        }
                    }
                }
                let sorter = (a, b) => {
                    let ret = 0;
                    for (let k in fieldConfig) {
                        let v = fieldConfig[k];
                        let field = v[0];
                        let desc = v[1];
                        let v1 = a[field];
                        let v2 = b[field];
                        if (v1 != null) {
                            if (desc) {
                                ret = v2 - v1;
                            }
                            else {
                                ret = v1 - v2;
                            }
                            if (ret != 0) {
                                return ret;
                            }
                        }
                    }
                    return ret;
                };
                let sorted = [];
                for (let i = 0; i < array.length; i++) {
                    const v = array[i];
                    sorted.push(v);
                }
                sorted.sort(sorter);
                return sorted;
            }
            static bubbleSort(arr, sorter) {
                var len = arr.length;
                for (var i = 0; i < len; i++) {
                    for (var j = 0; j < len - 1 - i; j++) {
                        let ret = sorter(arr[j], arr[j + 1]);
                        if (ret > 0) {
                            var temp = arr[j + 1];
                            arr[j + 1] = arr[j];
                            arr[j] = temp;
                        }
                    }
                }
                return arr;
            }
            static forEachMap(map, callback) {
                if (!map)
                    return;
                let keys = Object.keys(map);
                for (let i = 0; i < keys.length; i++) {
                    let key = keys[i];
                    let value = map[key];
                    if (value != null) {
                        if (callback(key, value))
                            break;
                    }
                }
            }
            static _origin_sortTiles(arr) {
                let isCover = (a, b) => {
                    return b.right > a.x && b.top > a.y;
                };
                let sortedArr = [];
                let len = arr.length;
                for (let i = 0; i < len; i++) {
                    let a = arr[i];
                    let indexA = sortedArr.indexOf(a);
                    for (let j = 0, len = arr.length; j < len; j++) {
                        if (i == j)
                            continue;
                        let b = arr[j];
                        if (isCover(a, b)) {
                            let indexB = sortedArr.indexOf(b);
                            if (indexA < 0) {
                                sortedArr.push(a);
                                indexA = sortedArr.length - 1;
                            }
                            if (indexB < 0) {
                                sortedArr.push(b);
                                indexB = sortedArr.length - 1;
                            }
                            if (indexB < indexA) {
                                sortedArr.splice(indexA, 1);
                                sortedArr.splice(indexB, 0, a);
                                indexA = indexB;
                            }
                        }
                    }
                }
                for (let i = 0; i < arr.length; i++) {
                    let a = arr[i];
                    if (sortedArr.indexOf(a) < 0) {
                        sortedArr.push(a);
                    }
                }
                return sortedArr;
            }
            static sortTiles(arr) {
                let isCover = (a, b) => {
                    return b.right > a.x && b.top > a.y;
                };
                for (let i = 0; i < arr.length; i++) {
                    const v = arr[i];
                    v._id = i;
                }
                let sortedArr = [];
                let indexCache = {};
                let len = arr.length;
                for (let i = 0; i < len; i++) {
                    let a = arr[i];
                    let indexA = indexCache[a._id];
                    for (let j = 0; j < len; j++) {
                        if (i == j)
                            continue;
                        let b = arr[j];
                        if (isCover(a, b)) {
                            let indexB = indexCache[b._id];
                            if (indexA == null) {
                                sortedArr.push(a);
                                indexA = sortedArr.length - 1;
                                indexCache[a._id] = indexA;
                            }
                            if (indexB == null) {
                                sortedArr.push(b);
                                indexB = sortedArr.length - 1;
                                indexCache[b._id] = indexB;
                            }
                            if (indexB < indexA) {
                                for (let k = indexB; k < indexA; k++) {
                                    let temp = sortedArr[k];
                                    indexCache[temp._id]++;
                                }
                                sortedArr.splice(indexA, 1);
                                sortedArr.splice(indexB, 0, a);
                                indexA = indexB;
                                indexCache[a._id] = indexA;
                            }
                        }
                    }
                }
                for (let i = 0; i < arr.length; i++) {
                    let a = arr[i];
                    if (indexCache[a._id] == null) {
                        sortedArr.push(a);
                    }
                }
                return sortedArr;
            }
            static formatTime(time, format) {
                let hour = Math.floor(time / 3600);
                let minute = Math.floor(time / 60) % 60;
                let second = Math.floor(time) % 60;
                if (format.match("%h")) {
                    format = format.replace("%h", hour.toString());
                }
                if (format.match("%H")) {
                    format = format.replace("%H", ul.format("%02d", hour));
                }
                if (format.match("%m")) {
                    format = format.replace("%m", minute.toString());
                }
                if (format.match("%M")) {
                    format = format.replace("%M", ul.format("%02d", minute));
                }
                if (format.match("%s")) {
                    format = format.replace("%s", second.toString());
                }
                if (format.match("%S")) {
                    format = format.replace("%S", ul.format("%02d", second));
                }
                return format;
            }
            static formatFullTime(timeStamp, format) {
                var time = new Date(timeStamp);
                var y = time.getFullYear();
                var m = time.getMonth() + 1;
                var d = time.getDate();
                var h = time.getHours();
                var tm = time.getMinutes();
                var s = time.getSeconds();
                if (format.match("%y")) {
                    format = format.replace("%y", y.toString());
                }
                if (format.match("%m")) {
                    format = format.replace("%m", m.toString());
                }
                if (format.match("%M")) {
                    format = format.replace("%M", ul.format("%02d", m));
                }
                if (format.match("%d")) {
                    format = format.replace("%d", d.toString());
                }
                if (format.match("%D")) {
                    format = format.replace("%D", ul.format("%02d", d));
                }
                if (format.match("%h")) {
                    format = format.replace("%h", h.toString());
                }
                if (format.match("%H")) {
                    format = format.replace("%H", ul.format("%02d", h));
                }
                if (format.match("%tm")) {
                    format = format.replace("%tm", tm.toString());
                }
                if (format.match("%TM")) {
                    format = format.replace("%TM", ul.format("%02d", tm));
                }
                if (format.match("%s")) {
                    format = format.replace("%s", s.toString());
                }
                if (format.match("%S")) {
                    format = format.replace("%S", ul.format("%02d", s));
                }
                return format;
            }
            static generateUUID() {
                let d = new Date().getTime();
                var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
                    var r = (d + Math.random() * 16) % 16 | 0;
                    d = Math.floor(d / 16);
                    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
                });
                return uuid;
            }
            ;
            static parseLogicExpressionArray(array) {
                let ret = true;
                let bSymbolNot = false;
                let logicSymbol = null;
                for (let i = 0; i < array.length; i++) {
                    let v = array[i];
                    if (Array.isArray(v)) {
                        v = this.parseLogicExpressionArray(v);
                    }
                    switch (typeof v) {
                        case "string": {
                            switch (v) {
                                case "not": {
                                    bSymbolNot = !bSymbolNot;
                                    break;
                                }
                                case "and": {
                                    if (logicSymbol) {
                                        console.warn(ul.format("Tools.parseLogicExpressionArray exp='%s' symbol overload index=[%d], origin_symbol=[%s], new_symbol=[%s]", JSON.stringify(array), i, logicSymbol, v));
                                    }
                                    logicSymbol = "and";
                                    break;
                                }
                                case "or": {
                                    if (logicSymbol) {
                                        console.warn(ul.format("Tools.parseLogicExpressionArray exp='%s' symbol overload index=[%d], origin_symbol=[%s], new_symbol=[%s]", JSON.stringify(array), i, logicSymbol, v));
                                    }
                                    logicSymbol = "or";
                                    break;
                                }
                                default: {
                                    console.warn(ul.format("Tools.parseLogicExpressionArray exp='%s' unknown symbol index=[%d], symbol=[%s]", JSON.stringify(array), i, v));
                                    break;
                                }
                            }
                            break;
                        }
                        case "boolean": {
                            if (bSymbolNot) {
                                v = !v;
                                bSymbolNot = false;
                            }
                            if (!logicSymbol || logicSymbol == "and") {
                                ret = ret && v;
                            }
                            else {
                                ret = ret || v;
                            }
                            break;
                        }
                    }
                }
                return ret;
            }
            static formatNumToStr(count) {
                let str = count.toString();
                if (count >= 1000 * 1000 * 1000 * 1000) {
                    str = Math.floor(count / 10 / 1000 / 1000 / 1000) / 100 + "mm";
                }
                else if (count >= 1000 * 1000 * 1000) {
                    str = Math.floor(count / 10 / 1000 / 1000) / 100 + "km";
                }
                else if (count >= 1000 * 1000) {
                    str = Math.floor(count / 10 / 1000) / 100 + "m";
                }
                else if (count >= 1000) {
                    str = Math.floor(count / 10) / 100 + "k";
                }
                return str;
            }
            static isIntersectLineWithLine(l1Start, l1End, l2Start, l2End) {
                return this.quickReject(l1Start, l1End, l2Start, l2End) && this.straddle(l1Start, l1End, l2Start, l2End);
            }
            static quickReject(l1Start, l1End, l2Start, l2End) {
                let l1xMax = Math.max(l1Start.x, l1End.x);
                let l1yMax = Math.max(l1Start.y, l1End.y);
                let l1xMin = Math.min(l1Start.x, l1End.x);
                let l1yMin = Math.min(l1Start.y, l1End.y);
                let l2xMax = Math.max(l2Start.x, l2End.x);
                let l2yMax = Math.max(l2Start.y, l2End.y);
                let l2xMin = Math.min(l2Start.x, l2End.x);
                let l2yMin = Math.min(l2Start.y, l2End.y);
                if (l1xMax < l2xMin || l1yMax < l2yMin || l2xMax < l1xMin || l2yMax < l1yMin) {
                    return false;
                }
                return true;
            }
            static straddle(l1Start, l1End, l2Start, l2End) {
                let l1x1 = l1Start.x;
                let l1x2 = l1End.x;
                let l1y1 = l1Start.y;
                let l1y2 = l1End.y;
                let l2x1 = l2Start.x;
                let l2x2 = l2End.x;
                let l2y1 = l2Start.y;
                let l2y2 = l2End.y;
                if ((((l1x1 - l2x1) * (l2y2 - l2y1) - (l1y1 - l2y1) * (l2x2 - l2x1)) *
                    ((l1x2 - l2x1) * (l2y2 - l2y1) - (l1y2 - l2y1) * (l2x2 - l2x1))) > 0 ||
                    (((l2x1 - l1x1) * (l1y2 - l1y1) - (l2y1 - l1y1) * (l1x2 - l1x1)) *
                        ((l2x2 - l1x1) * (l1y2 - l1y1) - (l2y2 - l1y1) * (l1x2 - l1x1))) > 0) {
                    return false;
                }
                return true;
            }
            static getIntersectPointLineWithLine(l1Start, l1End, l2Start, l2End) {
                let l1x1 = l1Start.x;
                let l1x2 = l1End.x;
                let l1y1 = l1Start.y;
                let l1y2 = l1End.y;
                let l2x1 = l2Start.x;
                let l2x2 = l2End.x;
                let l2y1 = l2Start.y;
                let l2y2 = l2End.y;
                var denominator = (l1y2 - l1y1) * (l2x2 - l2x1) - (l1x1 - l1x2) * (l2y1 - l2y2);
                if (denominator == 0) {
                    return null;
                }
                var x = ((l1x2 - l1x1) * (l2x2 - l2x1) * (l2y1 - l1y1)
                    + (l1y2 - l1y1) * (l2x2 - l2x1) * l1x1
                    - (l2y2 - l2y1) * (l1x2 - l1x1) * l2x1) / denominator;
                var y = -((l1y2 - l1y1) * (l2y2 - l2y1) * (l2x1 - l1x1)
                    + (l1x2 - l1x1) * (l2y2 - l2y1) * l1y1
                    - (l2x2 - l2x1) * (l1y2 - l1y1) * l2y1) / denominator;
                if ((x - l1x1) * (x - l1x2) <= 0 && (y - l1y1) * (y - l1y2) <= 0
                    && (x - l2x1) * (x - l2x2) <= 0 && (y - l2y1) * (y - l2y2) <= 0) {
                    return new Laya.Vector2(x, y);
                }
                return null;
            }
            static registerListeners(listeners) {
                if (!this.msgHander)
                    this.msgHander = new MsgHandler();
                this.msgHander.registerListeners(listeners);
                this.msgHander.startProcMsg();
            }
            static sendMsg(msgName, data) {
                if (!this.msgHander)
                    this.msgHander = new MsgHandler();
                this.msgHander.sendMsg(msgName, data);
            }
            static registerTouchHander(node, callback) {
                let onMouseDown = (event) => {
                    node["__b_touch"] = true;
                    node["__customEventBeginPosX"] = event.stageX;
                    node["__customEventBeginPosY"] = event.stageY;
                    callback({
                        isClick: false,
                        isBegin: true,
                        isMove: false,
                        isEnd: false,
                        isCancel: false,
                        pos: {
                            x: event.stageX,
                            y: event.stageY
                        },
                        beginPos: {
                            x: node["__customEventBeginPosX"] || event.stageX,
                            y: node["__customEventBeginPosY"] || event.stageY
                        }
                    });
                };
                let onMouseMove = (event) => {
                    if (node["__b_touch"] == true) {
                        callback({
                            isClick: false,
                            isBegin: false,
                            isMove: true,
                            isEnd: false,
                            isCancel: false,
                            pos: {
                                x: event.stageX,
                                y: event.stageY
                            },
                            beginPos: {
                                x: node["__customEventBeginPosX"] || event.stageX,
                                y: node["__customEventBeginPosY"] || event.stageY
                            }
                        });
                    }
                };
                let onMouseUp = (event) => {
                    if (node["__b_touch"]) {
                        node["__b_touch"] = false;
                        let isClick = false;
                        let beginPos = {
                            x: node["__customEventBeginPosX"] || event.stageX,
                            y: node["__customEventBeginPosY"] || event.stageY
                        };
                        if (Math.abs(event.stageX - beginPos.x) < 20 && Math.abs(event.stageY - beginPos.y) < 20) {
                            isClick = true;
                        }
                        callback({
                            isClick: isClick,
                            isBegin: false,
                            isMove: false,
                            isEnd: true,
                            isCancel: false,
                            pos: {
                                x: event.stageX,
                                y: event.stageY
                            },
                            beginPos: {
                                x: node["__customEventBeginPosX"] || event.stageX,
                                y: node["__customEventBeginPosY"] || event.stageY
                            }
                        });
                    }
                };
                let onMouseOut = (event) => {
                    if (node["__b_touch"]) {
                        node["__b_touch"] = false;
                        callback({
                            isClick: false,
                            isBegin: false,
                            isMove: false,
                            isEnd: false,
                            isCancel: true,
                            pos: {
                                x: event.stageX,
                                y: event.stageY
                            },
                            beginPos: {
                                x: node["__customEventBeginPosX"] || event.stageX,
                                y: node["__customEventBeginPosY"] || event.stageY
                            }
                        });
                    }
                };
                node.on(Laya.Event.MOUSE_DOWN, node, onMouseDown);
                node.on(Laya.Event.MOUSE_UP, node, onMouseUp);
                node.on(Laya.Event.MOUSE_MOVE, node, onMouseMove);
                node.on(Laya.Event.MOUSE_OUT, node, onMouseOut);
            }
            static unRegisterTouchHander(node) {
                node.offAll(Laya.Event.MOUSE_DOWN);
                node.offAll(Laya.Event.MOUSE_UP);
                node.offAll(Laya.Event.MOUSE_MOVE);
                node.offAll(Laya.Event.MOUSE_OUT);
            }
            static delta() {
                return Laya.timer.delta / 1000 * this.timeScale;
            }
            static forward(transform, pos) {
                let delta = new Laya.Vector3();
                Laya.Vector3.subtract(pos, transform.position, delta);
                let targetPos = new Laya.Vector3();
                Laya.Vector3.subtract(transform.position, delta, targetPos);
                targetPos.y = transform.position.y;
                transform.lookAt(targetPos, new Laya.Vector3(0, 1, 0), false);
            }
            static forwardDirection(transform, dir) {
                let targetPos = new Laya.Vector3();
                Laya.Vector3.subtract(transform.position, dir, targetPos);
                transform.lookAt(targetPos, new Laya.Vector3(0, 1, 0), false);
            }
            static tranlateWorld3D2Screen(camera, worldPos) {
                if (!camera) {
                    return {
                        bSuccessful: false,
                        outPos: null
                    };
                }
                let outPos = new Laya.Vector4();
                let inputPos = ul.clone(worldPos);
                camera.viewport.project(inputPos, camera.projectionViewMatrix, outPos);
                outPos.x /= Laya.stage.clientScaleX;
                outPos.y /= Laya.stage.clientScaleY;
                return {
                    bSuccessful: true,
                    outPos: new Laya.Vector3(outPos.x, outPos.y, outPos.z),
                };
            }
            static castRayWithDirecton(scene, startPoint, dirVec, distance = 100, hitResult) {
                Laya.Vector3.normalize(dirVec, dirVec);
                let ray = new Laya.Ray(startPoint, dirVec);
                hitResult = hitResult || new Laya.CannonHitResult();
                scene.cannonPhysicsSimulation.rayCast(ray, hitResult, distance);
                if (hitResult.succeeded) {
                    let collider = hitResult.collider;
                    let parent = collider.owner;
                    return parent;
                }
                return null;
            }
            static castRayAllWithDirecton(scene, startPoint, dirVec, distance = 100) {
                Laya.Vector3.normalize(dirVec, dirVec);
                let ray = new Laya.Ray(startPoint, dirVec);
                let hitResults = [];
                scene.cannonPhysicsSimulation.rayCastAll(ray, hitResults, distance);
                let collisonObjects = [];
                for (let index = 0; index < hitResults.length; index++) {
                    const element = hitResults[index];
                    let collider = element.collider;
                    let parent = collider.owner;
                    collisonObjects.push(parent);
                }
                return collisonObjects;
            }
            static castRayFromTo(scene, from, to, hitResult) {
                hitResult = hitResult || new Laya.CannonHitResult();
                scene.cannonPhysicsSimulation.raycastFromTo(from, to, hitResult);
                if (hitResult.succeeded) {
                    let collider = hitResult.collider;
                    let parent = collider.owner;
                    return parent;
                }
                return null;
            }
            static castRayAllFromTo(scene, from, to) {
                let hitResults = [];
                scene.cannonPhysicsSimulation.raycastAllFromTo(from, to, hitResults);
                let collisonObjects = [];
                for (let index = 0; index < hitResults.length; index++) {
                    const element = hitResults[index];
                    let collider = element.collider;
                    let parent = collider.owner;
                    collisonObjects.push(parent);
                }
                return collisonObjects;
            }
            static normalize(in_vec) {
                let out_vec = new Laya.Vector3();
                Laya.Vector3.normalize(in_vec, out_vec);
                return out_vec;
            }
            static calcCosSeta(A, B) {
                if (!A)
                    return 0;
                if (!B)
                    return 0;
                let magA = Laya.Vector3.scalarLength(A);
                let magB = Laya.Vector3.scalarLength(B);
                if (!magA)
                    return 0;
                if (!magB)
                    return 0;
                return Laya.Vector3.dot(A, B) / (magA * magB);
            }
            static calcAngleA2B(A, B) {
                if (!A)
                    return 0;
                if (!B)
                    return 0;
                let magA = Laya.Vector3.scalarLength(A);
                let magB = Laya.Vector3.scalarLength(B);
                if (!magA)
                    return 0;
                if (!magB)
                    return 0;
                let cos_angle = Laya.Vector3.dot(A, B) / (magA * magB);
                let angle = Math.acos(cos_angle);
                return angle * 180 / Math.PI;
            }
            static calcReflexVector(in_vec, normal_vec) {
                let axis = new Laya.Vector3();
                Laya.Vector3.cross(in_vec, normal_vec, axis);
                let invertInVect = new Laya.Vector3(-in_vec.x, -in_vec.y, -in_vec.z);
                let magA = Laya.Vector3.scalarLength(invertInVect);
                let magB = Laya.Vector3.scalarLength(normal_vec);
                let cosAngle = Laya.Vector3.dot(normal_vec, invertInVect) / (magA * magB);
                let angle = Math.acos(cosAngle);
                let roatteMat = new Laya.Matrix4x4();
                Laya.Matrix4x4.createRotationAxis(axis, -angle, roatteMat);
                let inVecMat = new Laya.Matrix4x4();
                inVecMat.setForward(in_vec);
                let outVecMat = new Laya.Matrix4x4();
                Laya.Matrix4x4.multiply(inVecMat, roatteMat, outVecMat);
                let outVec = new Laya.Vector3();
                outVecMat.getForward(outVec);
                return outVec;
            }
            static layoutNodesHorizonCenter(nodes, gap = 2) {
                gap = gap || 2;
                let parentWidth = 0.1;
                var totalWidth = 0;
                let validCount = 0;
                for (var k in nodes) {
                    var node = nodes[k];
                    parentWidth = node.parent.width;
                    if (!node.visible) {
                        continue;
                    }
                    var scale = Math.abs(node.scaleX);
                    var size = { width: node.width, height: node.height };
                    var w = Math.floor(size.width * scale);
                    totalWidth = totalWidth + w;
                    validCount++;
                }
                totalWidth = totalWidth + (validCount - 1) * gap;
                var x = parentWidth / 2 - totalWidth / 2;
                for (var k in nodes) {
                    var node = nodes[k];
                    if (!node.visible) {
                        continue;
                    }
                    var scale = Math.abs(node.scaleX);
                    var size = { width: node.width, height: node.height };
                    var w = Math.floor(size.width * scale);
                    node.x = x + w / 2;
                    x = x + w + gap;
                }
            }
            static layoutNodesVerticalCenter(nodes, gap = 2) {
                gap = gap || 2;
                var totalHeight = 0;
                for (var k in nodes) {
                    var node = nodes[k];
                    if (!node.active) {
                        continue;
                    }
                    var scale = Math.abs(node.scaleY);
                    var size = node.getContentSize();
                    var h = Math.floor(size.height * scale);
                    totalHeight = totalHeight + h;
                }
                totalHeight = totalHeight + (nodes.length - 1) * gap;
                var y = totalHeight / 2;
                for (var k in nodes) {
                    var node = nodes[k];
                    if (!node.active) {
                        continue;
                    }
                    var scale = Math.abs(node.scaleY);
                    var size = node.getContentSize();
                    var h = Math.floor(size.height * scale);
                    node.setPosition(0, y - h / 2);
                    y = y - h - gap;
                }
            }
            static widget(h, v, node) {
                let x = Laya.stage.width * h;
                let y = Laya.stage.height * v;
                let p = node.parent.globalToLocal(new Laya.Point(x, y));
                node.pos(p.x, p.y, true);
            }
            static layoutH(node, space = 8, anchor = 0.5, bWithScale = true) {
                let totalWidth = 0;
                let count = 0;
                for (let index = 0; index < node["_children"].length; index++) {
                    const element = node["_children"][index];
                    if (element.visible) {
                        totalWidth += element.width * (bWithScale ? element.scaleX : 1);
                        count++;
                    }
                }
                totalWidth += (count - 1) * space;
                let offset = node.width * anchor;
                if (anchor > 1) {
                    offset = anchor;
                }
                if (anchor == 0.5) {
                    offset -= totalWidth / 2;
                }
                let cursor = offset;
                for (let index = 0; index < node["_children"].length; index++) {
                    const element = node["_children"][index];
                    if (element.visible) {
                        cursor += element.pivotX * (bWithScale ? element.scaleX : 1);
                        element.x = cursor;
                        cursor += (element.width - element.pivotX) * (bWithScale ? element.scaleX : 1) + space;
                    }
                }
            }
            static layoutV(node, space = 8, anchor = 0.5) {
                let totalHeight = 0;
                let count = 0;
                for (let index = 0; index < node["_children"].length; index++) {
                    const element = node["_children"][index];
                    if (element.visible) {
                        totalHeight += element.height * element.scaleY;
                        count++;
                    }
                }
                totalHeight += (count - 1) * space;
                let offset = node.height * anchor;
                if (anchor > 1) {
                    offset = anchor;
                }
                if (anchor == 0.5) {
                    offset -= totalHeight / 2;
                }
                let cursor = offset;
                for (let index = 0; index < node["_children"].length; index++) {
                    const element = node["_children"][index];
                    if (element.visible) {
                        cursor += element.pivotY * element.scaleY;
                        element.y = cursor;
                        cursor += (element.height - element.pivotY) * element.scaleY + space;
                    }
                }
            }
            static center(node, hp = 0.5, vp = 0.5) {
                let parent = node.parent;
                if (!parent)
                    return;
                node.pos(parent.width * hp - node.width * (0.5 - node.pivotX / node.width), parent.height * vp - node.height * (0.5 - node.pivotY / node.height), true);
            }
            static hCenter(node) {
                let parent = node.parent;
                if (!parent)
                    return;
                node.pos(parent.width / 2 - node.width * (0.5 - node.pivotX / node.width), node.y, true);
            }
            static hPersent(node, persent = 0.5) {
                let parent = node.parent;
                if (!parent)
                    return;
                node.pos(parent.width * persent, node.y, true);
            }
            static vCenter(node) {
                let parent = node.parent;
                if (!parent)
                    return;
                node.pos(node.x, parent.height / 2 - node.height * (0.5 - node.pivotY / node.height), true);
            }
            static ConvertToScreenPos(camera, inPos) {
                let outPos = new Laya.Vector4();
                camera.viewport.project(inPos, camera.projectionViewMatrix, outPos);
                outPos.x /= Laya.stage.clientScaleX;
                outPos.y /= Laya.stage.clientScaleY;
                return outPos;
            }
            static isInScreen(camera, inPos) {
                return true;
            }
            static inRange(inPos, checkPos, range) {
                let distancesq = Laya.Vector3.distanceSquared(inPos, checkPos);
                if (distancesq > range * range) {
                    return false;
                }
                else {
                    return true;
                }
            }
            static isContain(parent, wPos) {
                if (!parent || parent.destroyed)
                    return false;
                let pos1 = parent.localToGlobal(new Laya.Point);
                let pos2 = parent.localToGlobal(new Laya.Point(parent.width, 0));
                let pos3 = parent.localToGlobal(new Laya.Point(0, parent.height));
                let pos4 = parent.localToGlobal(new Laya.Point(parent.width, parent.height));
                let minX = Math.min(pos1.x, pos2.x, pos3.x, pos4.x);
                let maxX = Math.max(pos1.x, pos2.x, pos3.x, pos4.x);
                let minY = Math.min(pos1.y, pos2.y, pos3.y, pos4.y);
                let maxY = Math.max(pos1.y, pos2.y, pos3.y, pos4.y);
                if (wPos.x > minX && wPos.x < maxX && wPos.y > minY && wPos.y < maxY) {
                    return true;
                }
                return false;
            }
            static clamp01(value) {
                if (value > 1)
                    return 1;
                else if (value < 0)
                    return 0;
                else
                    return value;
            }
            static getAngle(x1, y1, x2 = 0, y2 = 0) {
                var x = x1 - x2;
                var y = y1 - y2;
                var z = Math.abs(Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
                var cos = y / z;
                var radina = Math.acos(cos);
                var angle = 180 / (Math.PI / radina);
                if (x < 0) {
                    angle = -angle;
                }
                return angle;
            }
            static rotateCirclePoint(r, point, diffRot) {
                let cRot = Math.atan(point.y / point.x);
            }
            static getCircleBorderPosPointArr(centerPos, radius, span = 2) {
                let points = [];
                for (let i = 0; i < 360; i += span) {
                    points.push(this.getCircleBorderPosPoint(centerPos, radius, i));
                }
                return points;
            }
            static getCircleBorderPosPoint(centerPos, radius, rot) {
                Math.acosh;
                let x = centerPos.x + radius * Math.cos(rot * Math.PI / 180);
                let y = centerPos.y + radius * Math.sin(rot * Math.PI / 180);
                return new Laya.Point(x, y);
            }
            static getRotByCenterPosRAndPosY(centerPos, r, borderPosValue) {
                let rot = Math.asin((borderPosValue - centerPos.y) / r) / (Math.PI / 180);
                return rot;
            }
            static getRotByCenterPosRAndPosX(centerPos, r, borderPosValue) {
                let rot = Math.asin((borderPosValue - centerPos.x) / r) / (Math.PI / 180);
                return rot;
            }
            static getBezierPoint(points, t, out) {
                let path = new Laya.Bezier().getBezierPoints(points, 5, 2);
                if (path.length == 0) {
                    return;
                }
                t = this.clamp01(t);
                if (out == null) {
                    out = new Laya.Point(0, 0);
                }
                if (t == 0) {
                    out.setTo(path[0], path[1]);
                }
                else if (t == 1) {
                    out.setTo(path[path.length - 2], path[path.length - 1]);
                }
                else {
                    let value = (path.length / 2 - 1) * t;
                    let min = value | 0;
                    let max = Math.ceil(value);
                    if (min != max) {
                        out.x = Laya.MathUtil.lerp(path[min * 2], path[max * 2], value - min);
                        out.y = Laya.MathUtil.lerp(path[min * 2 + 1], path[max * 2 + 1], value - min);
                    }
                    else {
                        out.setTo(path[max * 2], path[max * 2 + 1]);
                    }
                }
                return out;
            }
            static rotate(rad, inDir) {
                let _temp = inDir.clone();
                Laya.Vector2.normalize(_temp, _temp);
                let sinA = _temp.y;
                let cosA = _temp.x;
                let sinB = Math.sin(rad);
                let cosB = Math.cos(rad);
                _temp.x = cosA * cosB - sinA * sinB;
                _temp.y = sinA * cosB + cosA * sinB;
                return _temp;
            }
            static rotateY(rad, inDir) {
                let _temp = inDir.clone();
                _temp.y = 0;
                Laya.Vector3.normalize(_temp, _temp);
                let sinA = _temp.z;
                let cosA = _temp.x;
                let sinB = Math.sin(rad);
                let cosB = Math.cos(rad);
                _temp.x = cosA * cosB - sinA * sinB;
                _temp.z = sinA * cosB + cosA * sinB;
                return _temp;
            }
            static isClipExist(animator, name) {
                if (!animator)
                    return false;
                let layer = animator.getControllerLayer(0);
                if (!layer) {
                    console.log("[error] haven't layer", animator);
                    return false;
                }
                let stMaps = layer["_statesMap"];
                return !!stMaps[name];
            }
            static play(animator, aniName) {
                if (!this.isClipExist(animator, aniName))
                    return false;
                let stMaps = animator.getControllerLayer(0)["_statesMap"];
                if (stMaps[aniName]) {
                    animator.play(aniName);
                    return true;
                }
                else {
                    console.warn(`[error] play havn't \"${aniName}\"`);
                    return false;
                }
            }
            static crossFade(animator, aniName, fadeDuration = 0.1) {
                if (!this.isClipExist(animator, aniName))
                    return false;
                let stMaps = animator.getControllerLayer(0)["_statesMap"];
                if (stMaps[aniName]) {
                    animator.crossFade(aniName, fadeDuration, 0);
                    return true;
                }
                else {
                    console.warn(`[error] crossFade havn't \"${aniName}\"`);
                    return false;
                }
            }
            static shark(node) {
                let children = node._children;
                for (let index = 0; index < children.length; index++) {
                    const element = children[index];
                    if (element.skinnedMeshRenderer) {
                        let material = element.skinnedMeshRenderer.material;
                        if (material) {
                            material.albedoIntensity = 3;
                            Timer.callLater(0.15, () => {
                                material.albedoIntensity = 1;
                            }, this);
                        }
                    }
                }
            }
            static link2Node(nodeName, root, Sprite3D) {
                if (root.name == nodeName) {
                    root.addChild(Sprite3D);
                    Sprite3D.transform.localPosition = new Laya.Vector3();
                    return true;
                }
                let index = 0;
                let child = null;
                while (true) {
                    child = root.getChildAt(index);
                    if (!child)
                        break;
                    if (child.name == nodeName) {
                        child.addChild(Sprite3D);
                        Sprite3D.transform.localPosition = new Laya.Vector3();
                        return true;
                    }
                    else {
                        if (this.link2Node(nodeName, child, Sprite3D)) {
                            return true;
                        }
                    }
                    index++;
                }
                return false;
            }
            static unLink2Node(Sprite3D) {
                Sprite3D.removeSelf();
            }
            static findNode(nodeName, root) {
                if (root.name == nodeName) {
                    return root;
                }
                for (let i = 0; i < root.numChildren; i++) {
                    let child = root.getChildAt(i);
                    if (child.name == nodeName)
                        return child;
                    else {
                        let node = this.findNode(nodeName, child);
                        if (node)
                            return node;
                    }
                }
                return null;
            }
            static roundTableProbability(list, field) {
                let randomField = 0;
                Tools.forEachMap(list, (k, v) => {
                    randomField += v[field];
                });
                let cursorField = 0;
                let point = Math.random() * randomField;
                let value = null;
                Tools.forEachMap(list, (k, v) => {
                    if (point > cursorField && point <= cursorField + v[field]) {
                        value = list[k];
                        return true;
                    }
                    else {
                        cursorField += v[field];
                    }
                });
                return value;
            }
            static loadImg(sp, path, bAdaptTextureSize = false, callback) {
                if (!sp) {
                    callback && callback();
                    return;
                }
                ;
                if (!path) {
                    callback && callback();
                    return;
                }
                ;
                mgrLoader.Load2dRes(path, Laya.Loader.IMAGE, sp, (texture) => {
                    if (!sp || sp.destroyed) {
                        callback && callback();
                        return;
                    }
                    sp.texture = null;
                    sp[`skin`] = null;
                    sp.graphics.clear(true);
                    if (bAdaptTextureSize) {
                        sp.width = texture.sourceWidth;
                        sp.height = texture.sourceHeight;
                    }
                    sp.graphics.drawImage(texture, 0, 0, sp.width, sp.height);
                    callback && callback();
                });
            }
            static loadMaterialTexture(path, material, fieldName) {
                if (!path || path == "" || !material) {
                    return;
                }
                mgrLoader.Load2dRes(path, Laya.Loader.IMAGE, material, (texture) => {
                    if (!material || material.destroyed || !texture) {
                        return;
                    }
                    let text2d = texture.bitmap;
                    if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                        text2d.wrapModeU = Laya.WarpMode.Repeat;
                        text2d.wrapModeV = Laya.WarpMode.Repeat;
                        text2d.filterMode = Laya.FilterMode.Bilinear;
                        text2d.generateMipmap();
                    }
                    material[fieldName] = text2d;
                });
            }
            static loadAdImg(sp, path, callback) {
                if (!sp) {
                    callback && callback();
                    return;
                }
                ;
                if (!path) {
                    callback && callback();
                    return;
                }
                ;
                mgrLoader.Load2dRes(path, Laya.Loader.IMAGE, sp, (texture) => {
                    callback && callback();
                    let orgWidth = sp.width;
                    let orgHeight = sp.height;
                    let curWidth = texture.sourceWidth;
                    let curHeight = texture.sourceHeight;
                    let factorX = orgWidth / curWidth;
                    let factorY = orgHeight / curHeight;
                    let factor = Math.min(factorX, factorY);
                    let width = curWidth * factor;
                    let height = curHeight * factor;
                    sp.texture = null;
                    sp.graphics.clear(true);
                    let offsetX = 0;
                    let offsetY = 0;
                    if ((sp["anchorX"] && sp["anchorX"] > 0) || sp["anchorY"] && sp["anchorY"] > 0) {
                        offsetX = (sp["anchorX"] || 0) * (width - sp.width);
                        offsetY = (sp["anchorY"] || 0) * (height - sp.height);
                    }
                    sp.graphics.drawImage(texture, 0 - offsetX, 0 - offsetY, width, height);
                });
            }
            static TransformDirection(transform, vec) {
                let out = new Laya.Vector3();
                Laya.Vector3.transformCoordinate(vec, transform.worldMatrix, out);
                return out;
            }
            static __colorToHex(color) {
                let hexColor = `#${this.__toHex(color.r)}${this.__toHex(color.g)}${this.__toHex(color.b)}`;
                return hexColor;
            }
            static __toHex(n) {
                let f = 0;
                while (n >= 16) {
                    f++;
                    n = n - 16;
                }
                let b = n;
                let m = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
                return m[f] + m[b];
            }
            static registerAsHSlider(node, initValue, desc = "", callback, field = 1) {
                let bar = node.getChildAt(0);
                bar.x = node.width * initValue / field;
                let label = node.getChildAt(1);
                let bDown = false;
                Tools.unRegisterTouchHander(node);
                Tools.registerTouchHander(node, (e) => {
                    if (e.isBegin)
                        bDown = true;
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        point.y = node.height / 2;
                        point.x = ul.clamp(point.x, 0, node.width);
                        bar.x = point.x;
                        bar.y = point.y;
                        let value = point.x / node.width;
                        label.text = `${desc}${(value * field).toFixed(3)}`;
                        callback(parseFloat((value * field).toFixed(3)));
                    }
                });
                label.text = `${desc}${initValue}`;
                callback(initValue);
            }
            static syncNodeA2NodeB(A, B, fliter) {
                if (A.name != B.name) {
                    if (!fliter.test(A.name)) {
                        let cloneA = A.clone();
                        B.parent.addChild(cloneA);
                    }
                }
                else {
                    for (let i = 0; i < A.numChildren; i++) {
                        let childAtA = A.getChildAt(i);
                        let childAtB = B.getChildByName(childAtA.name);
                        if (!childAtB) {
                            if (!fliter.test(childAtA.name)) {
                                childAtB = childAtA.clone();
                                B.addChild(childAtB);
                            }
                        }
                        else {
                            this.syncNodeA2NodeB(childAtA, childAtB, fliter);
                        }
                    }
                }
            }
            static syncNodeATransform2NodeBTransform(A, B, fliter) {
                let childAtBNameMap = {};
                for (let i = 0; i < B.numChildren; i++) {
                    let c = B.getChildAt(i);
                    childAtBNameMap[c.name] = c;
                }
                for (let i = 0; i < A.numChildren; i++) {
                    let childAtA = A.getChildAt(i);
                    let childAtB = childAtBNameMap[childAtA.name];
                    if (childAtB) {
                        childAtB.transform.position = childAtA.transform.position;
                        childAtB.transform.rotation = childAtA.transform.rotation;
                        childAtB.transform.setWorldLossyScale(childAtA.transform.getWorldLossyScale());
                        this.syncNodeATransform2NodeBTransform(childAtA, childAtB, fliter);
                    }
                }
            }
            static getBigNumberStr(count, step = 4) {
                let unitStr3 = ["", "K", "M", "B", "T", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH"];
                let unitStr4 = ["", "万", "亿", "兆", "京", "垓", "杼", "穰", "沟", "涧", "正", "载"];
                let factor = step == 3 ? 1000 : 10000;
                let unitStr = step == 3 ? unitStr3 : unitStr4;
                let order = 0;
                let _tempCount = count;
                while (_tempCount > factor) {
                    order++;
                    _tempCount /= factor;
                }
                return `${order == 0 ? _tempCount : _tempCount.toFixed(1)}${unitStr[order]}`;
            }
            static getBigDistanceStr(distance) {
                let unitStr3 = ["", "K", "M", "B", "T", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH"];
                let factor = 1000;
                let unitStr = unitStr3;
                let order = 0;
                let _tempCount = distance;
                while (_tempCount > factor) {
                    order++;
                    _tempCount /= factor;
                }
                return `${order == 0 ? _tempCount : _tempCount.toFixed(1)}${unitStr[order]}M`;
            }
            static subNumberText(result) {
                if (result == null) {
                    return "";
                }
                if (result.concat(".")) {
                    while (true) {
                        if (result.charAt(result.length - 1) == '0') {
                            result = result.substring(0, result.length - 1);
                        }
                        else {
                            if (result.endsWith(".")) {
                                result = result.substring(0, result.length - 1);
                            }
                            break;
                        }
                    }
                }
                return result;
            }
            static active3dObjectRayCheck(scene, camera, callback, event = Laya.Event.MOUSE_DOWN) {
                let uuid = scene.name;
                if (!this.rayCheckInfo[uuid]) {
                    let onMouseDown = (e) => {
                        if (mgrDirector.bWarpScene) {
                            console.log("切屏中，拦截射线检测");
                            return;
                        }
                        let info = this.rayCheckInfo[uuid];
                        if (info.scene.destroyed) {
                            Laya.stage.off(Laya.Event.MOUSE_DOWN, this, info.onMouseDown);
                            this.rayCheckInfo[uuid] = null;
                            return;
                        }
                        ;
                        info.point.x = Laya.MouseManager.instance.mouseX;
                        info.point.y = Laya.MouseManager.instance.mouseY;
                        info.camera.viewportPointToRay(info.point, info.ray);
                        info.scene.cannonPhysicsSimulation.rayCast(info.ray, info.outHitResult);
                        info.callback(info.outHitResult, new Laya.Vector2(e.stageX, e.stageY));
                    };
                    let info = {
                        scene: scene,
                        point: new Laya.Vector2(),
                        ray: new Laya.Ray(new Laya.Vector3(0, 0, 10), new Laya.Vector3(0, 0, -1000)),
                        outHitResult: new Laya.CannonHitResult,
                        onMouseDown: onMouseDown,
                        camera: camera,
                        callback: callback,
                    };
                    this.rayCheckInfo[uuid] = info;
                    Laya.stage.on(event, this, info.onMouseDown);
                }
            }
            static unactive3dObjectRayCheck(scene) {
                let uuid = scene.name;
                let info = this.rayCheckInfo[uuid];
                if (!info)
                    return;
                Laya.stage.off(Laya.Event.MOUSE_DOWN, this, info.onMouseDown);
                this.rayCheckInfo[uuid] = null;
            }
            static castRayFromScreenPos(scene, camera, screenPos, outray) {
                let ray = null;
                if (!!outray) {
                    ray = outray;
                }
                else {
                    ray = new Laya.Ray(new Laya.Vector3(0, 0, 10), new Laya.Vector3(0, 0, -1000));
                }
                screenPos.x *= Laya.stage.clientScaleX;
                screenPos.y *= Laya.stage.clientScaleY;
                camera.viewportPointToRay(screenPos, ray);
                let outHitResult = new Laya.CannonHitResult;
                scene.cannonPhysicsSimulation.rayCast(ray, outHitResult);
                return outHitResult;
            }
            static createRayFromScreenPos(camera, screenPos, outray) {
                let ray = null;
                if (!!outray) {
                    ray = outray;
                }
                else {
                    ray = new Laya.Ray(new Laya.Vector3(0, 0, 10), new Laya.Vector3(0, 0, -1000));
                }
                let tmpPos = screenPos.clone();
                tmpPos.x *= Laya.stage.clientScaleX;
                tmpPos.y *= Laya.stage.clientScaleY;
                camera.viewportPointToRay(tmpPos, ray);
                return ray;
            }
            static findChild(root, router) {
                let routes = router.split("/");
                let node = root;
                for (let i = 0; i < routes.length; i++) {
                    const name = routes[i];
                    if (!name)
                        continue;
                    node = node.getChildByName(name);
                    if (!node)
                        break;
                    if (i == routes.length - 1) {
                        return node;
                    }
                }
                return root;
            }
            static syncNodeWith3DPos(node, wp, camera) {
                if (!node || node.destroyed)
                    return;
                let parent = node.parent;
                let screenPos = this.ConvertToScreenPos(camera, wp);
                let localPos = parent.globalToLocal(new Laya.Point(screenPos.x, screenPos.y));
                node.pos(localPos.x, localPos.y);
            }
            static nodeDistance(node1, node2) {
                return Math.sqrt((node1.x - node2.x) * (node1.x - node2.x) + (node1.y - node2.y) * (node1.y - node2.y));
            }
            static setSprite3dLayer(node, layer) {
                node.layer = layer;
                for (let i = 0; i < node.numChildren; i++) {
                    let child = node.getChildAt(i);
                    this.setSprite3dLayer(child, layer);
                }
            }
            static findAllMeshRenderers(node, out, recursive = false) {
                out = out || [];
                for (let i = 0; i < node.numChildren; i++) {
                    let child = node.getChildAt(i);
                    if (child) {
                        let render = child["meshRenderer"];
                        if (render) {
                            out.push(render);
                        }
                        if (recursive) {
                            this.findAllMeshRenderers(child, out, recursive);
                        }
                    }
                }
                return out;
            }
            static findAllSkinnedMeshRenderers(node, out, recursive = false) {
                out = out || [];
                for (let i = 0; i < node.numChildren; i++) {
                    let child = node.getChildAt(i);
                    if (child) {
                        let render = child["skinnedMeshRenderer"];
                        if (render) {
                            out.push(render);
                        }
                        if (recursive) {
                            this.findAllSkinnedMeshRenderers(child, out, recursive);
                        }
                    }
                }
                return out;
            }
            static findAllShurikenParticleSystem(node, out) {
                out = out || [];
                for (var i = node.numChildren - 1; i >= 0; i--) {
                    var child = node.getChildAt(i);
                    if (child.particleSystem) {
                        out.push(child.particleSystem);
                    }
                    this.findAllShurikenParticleSystem(child, out);
                }
                return out;
            }
            static findSkinnedMeshSprite3d(node) {
                for (let i = 0; i < node.numChildren; i++) {
                    let child = node.getChildAt(i);
                    if (child instanceof Laya.SkinnedMeshSprite3D) {
                        return child;
                    }
                }
                for (let i = 0; i < node.numChildren; i++) {
                    let child = node.getChildAt(i);
                    let re = this.findSkinnedMeshSprite3d(child);
                    if (re)
                        return re;
                }
            }
            static findMeshSprite3d(node) {
                for (let i = 0; i < node.numChildren; i++) {
                    let child = node.getChildAt(i);
                    if (child instanceof Laya.MeshSprite3D) {
                        return child;
                    }
                }
                for (let i = 0; i < node.numChildren; i++) {
                    let child = node.getChildAt(i);
                    let re = this.findMeshSprite3d(child);
                    if (re)
                        return re;
                }
            }
            static takeAPhoto(width, height, camera, callback, renderTextureFormat = Laya.RenderTextureFormat.R8G8B8A8, tex2dFormat = undefined) {
                let renderTexture = new Laya.RenderTexture(width, height, renderTextureFormat);
                let oldRenderTexture = camera.renderTarget;
                camera.renderTarget = renderTexture;
                let oldRender = camera.render.bind(camera);
                camera.render = (...agrs) => {
                    oldRender(...agrs);
                    camera.render = oldRender;
                    camera.renderTarget = oldRenderTexture;
                    let pixels = new Uint8Array(width * height * 4);
                    renderTexture.getData(0, 0, width, height, pixels);
                    let tex2d = new Laya.Texture2D(width, height, tex2dFormat, false, true);
                    tex2d.setPixels(pixels);
                    callback(tex2d);
                };
            }
            static compressArr(arr) {
                let pako = window['pako'];
                return pako.deflate(arr);
            }
            static decompressArr(arr) {
                let pako = window['pako'];
                try {
                    return pako.inflate(arr);
                }
                catch (error) {
                    console.log(error);
                }
            }
            static decompressArrToStr(arr) {
                let pako = window['pako'];
                return pako.ungzip(arr, { to: "string" });
            }
            static encodeTexture(texture) {
                let pixels = texture.getPixels();
                let data = this.compressArr(pixels);
                return Base64.encodeArrayBuffer(data);
            }
            static encodeRenderTexture(renderTexture) {
                let width = renderTexture.width;
                let height = renderTexture.height;
                let pixels = new Uint8Array(width * height * 4);
                renderTexture.getData(0, 0, width, height, pixels);
                let tex2d = new Laya.Texture2D(width, height, undefined, false, true);
                tex2d.setPixels(pixels);
                return this.encodeTexture(tex2d);
            }
            static decodeTexture(value, width = 576, height = 1024, texFormat = undefined) {
                let data = Base64.decodeArrayBuffer(value);
                let pixels = this.decompressArr(new Uint8Array(data));
                let texture2d = new Laya.Texture2D(width, height, texFormat, false);
                texture2d.setPixels(pixels);
                return texture2d;
            }
            static getMeshRender(node) {
                if (!node) {
                    return null;
                }
                return node[`skinnedMeshRenderer`] || node[`meshRenderer`];
            }
            static getFirstChildBone(node) {
                if (!node || node.destroyed) {
                    return null;
                }
                let numChildren = node.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let child = node.getChildAt(i);
                    if (!Tools.getMeshRender(child)) {
                        return child;
                    }
                }
                return null;
            }
            static isWorldLocaInNode(node, worldLocation, boundExt) {
                let rect = new Laya.Rectangle(0, 0, node.width, node.height);
                if (boundExt != null) {
                    rect.x -= boundExt;
                    rect.y -= boundExt;
                    rect.width += boundExt * 2;
                    rect.height += boundExt * 2;
                }
                let lPoint = node.globalToLocal(new Laya.Point(worldLocation.x, worldLocation.y));
                return rect.contains(lPoint.x, lPoint.y);
            }
            static setModelAlbedoColor(model, color) {
                let renderer = Tools.getMeshRender(model);
                if (renderer) {
                    let sharedMaterials = renderer.sharedMaterials;
                    sharedMaterials[0].albedoColor = new Laya.Vector4(color.r, color.g, color.b, 1);
                }
                else {
                    for (let i = 0; i < model.numChildren; i++) {
                        let child = model.getChildAt(i);
                        let renderer = Tools.getMeshRender(child);
                        if (renderer) {
                            let sharedMaterials = renderer.sharedMaterials;
                            sharedMaterials[0].albedoColor = new Laya.Vector4(color.r, color.g, color.b, 1);
                        }
                    }
                }
            }
            static createPureColorTexture(color) {
                let pixels = new Uint8Array(16);
                for (let i = 0; i < 4; i++) {
                    pixels[i * 4 + 0] = color.r * 255;
                    pixels[i * 4 + 1] = color.g * 255;
                    pixels[i * 4 + 2] = color.b * 255;
                    pixels[i * 4 + 3] = color.a * 255;
                }
                let tex2d = new Laya.Texture2D(2, 2, Laya.TextureFormat.R8G8B8A8);
                tex2d.setPixels(pixels);
                let texture = new Laya.Texture(tex2d);
                return texture;
            }
            static cameraForSaveImg(camera, saveImgName) {
                Tools.takeAPhoto(768, 1280, camera, (tex2d) => {
                    let pixels = tex2d.getPixels();
                    this.downloadCameraForSaveImg(pixels, saveImgName);
                }, Laya.RenderTextureFormat.R8G8B8A8, Laya.TextureFormat.R8G8B8A8);
            }
            static downloadCameraForSaveImg(pixels, saveImgName) {
                saveImgName = saveImgName || "icon.png";
                let canvasId = "__test_download_camera_for_save_canvas";
                let linkId = "__test_download_camera_for_save_link";
                let doDownload = () => {
                    var targetPx = new Uint8ClampedArray(pixels);
                    var ctx = newCanvas.getContext("2d");
                    var imageData = ctx.getImageData(0, 0, newCanvas.width, newCanvas.height);
                    var px = imageData.data;
                    for (var i = 0; i < px.length; i += 4) {
                        px[i] = targetPx[i];
                        px[i + 1] = targetPx[i + 1];
                        px[i + 2] = targetPx[i + 2];
                        px[i + 3] = targetPx[i + 3];
                    }
                    ctx.putImageData(imageData, 0, 0);
                    if (document.getElementById(linkId)) {
                        document.removeChild(document.getElementById(linkId));
                    }
                    var dataUri = newCanvas.toDataURL("image/png");
                    var link = document.createElement('a');
                    link.id = "";
                    link.href = dataUri;
                    link.download = saveImgName;
                    link.click();
                };
                var newCanvas = document.getElementById(canvasId);
                if (!!newCanvas) {
                    doDownload();
                }
                else {
                    newCanvas = document.createElement("canvas");
                    newCanvas.id = canvasId;
                    var image = new Image();
                    image.crossOrigin = "Anonymous";
                    image.onload = function () {
                        newCanvas.width = image.width;
                        newCanvas.height = image.height;
                        newCanvas.getContext("2d").drawImage(image, 0, 0, image.width, image.height);
                        doDownload();
                    };
                    let index = window.location.href.indexOf("index.html");
                    image.src = window.location.href.substring(0, index - 1) + "/res/ui/common/mask.png";
                    document.body.insertAdjacentElement('afterbegin', newCanvas);
                }
            }
            static changeParticleSimulationSpeed(model, speed = 1) {
                if (!model || model.destroyed) {
                    return;
                }
                for (var i = 0; i < model.numChildren; i++) {
                    var otherChild = model.getChildAt(i);
                    let particleSystem = otherChild["particleSystem"];
                    if (!particleSystem) {
                        continue;
                    }
                    particleSystem.simulationSpeed = speed;
                    this.changeParticleSimulationSpeed(otherChild, speed);
                }
            }
            static getQuad3D() {
                let scale = 1;
                let textureBg = Tools.createPureColorTexture(new Laya.Color(169 / 255, 131 / 255, 1, 1));
                let quadMeshBg = Laya.PrimitiveMesh.createQuad(scale, scale);
                let quadBg = new Laya.MeshSprite3D(quadMeshBg);
                let materialBg = new Laya.UnlitMaterial;
                materialBg.renderMode = Laya.UnlitMaterial.RENDERMODE_OPAQUE;
                materialBg.cull = Laya.RenderState.CULL_NONE;
                materialBg.albedoTexture = textureBg.bitmap;
                quadBg.meshRenderer.sharedMaterial = materialBg;
                quadBg.transform.setWorldLossyScale(new Laya.Vector3(5, 5, 5));
                return quadBg;
            }
            static isEqualArr(array1, array2) {
                if (!array1)
                    return false;
                if (!array2)
                    return false;
                if (array1.length != array2.length)
                    return false;
                for (var i = 0, l = array1.length; i < l; i++) {
                    if (array1[i] instanceof Array && array2[i] instanceof Array) {
                        if (!Tools.isEqualArr(array1[i], array2[i]))
                            return false;
                    }
                    else if (array1[i] != array2[i]) {
                        return false;
                    }
                }
                return true;
            }
            static transparentBlackArea(pixels, sizeW, sizeH) {
                for (let hIndex = 0; hIndex < sizeH; hIndex++) {
                    for (let wIndex = 0; wIndex < sizeW; wIndex++) {
                        let pixelsIndex = wIndex * hIndex;
                        if (pixels[pixelsIndex * 4 + 0] == 0 && pixels[pixelsIndex * 4 + 1] == 0 && pixels[pixelsIndex * 4 + 2] == 0) {
                            pixels[pixelsIndex * 4 + 0] = 0.00001;
                            pixels[pixelsIndex * 4 + 1] = 0.00001;
                            pixels[pixelsIndex * 4 + 2] = 0.00001;
                            pixels[pixelsIndex * 4 + 3] = 0.00001;
                        }
                    }
                }
                return pixels;
            }
            static shuffle(arr) {
                let len = arr.length;
                for (let i = 0; i < len - 1; i++) {
                    let index = parseInt((Math.random() * (len - i)) + "");
                    let temp = arr[index];
                    arr[index] = arr[len - i - 1];
                    arr[len - i - 1] = temp;
                }
                return arr;
            }
        }
        Tools._debugTime = null;
        Tools.msgHander = null;
        Tools.timeScale = 1;
        Tools._deltaTime = 0;
        Tools._lastUpdateTime = 0;
        Tools._curTime = 0;
        Tools.bigNumberStrs = ["K", "M", "G", "B", "T"];
        Tools.rayCheckInfo = {};

        class Manager {
            static loadAllManagers(finishCallback) {
                let count = 0;
                for (let i = 0; i < this._managerInstances.length; i++) {
                    let manager = this._managerInstances[i];
                    try {
                        manager.loadedCallback = () => {
                            count++;
                            if (count == this._managerInstances.length) {
                                finishCallback();
                            }
                        };
                        manager.onLoad();
                    }
                    catch (error) {
                        console.warn("Manager.loadAllManager has error", error);
                    }
                }
            }
            static __init() {
                Manager._managerInstances.push(this);
                this._msgHander = new MsgHandler();
                this._msgHander.startProcMsg();
            }
            static onLoad() {
                this.registerListeners({
                    "MSG_RECORD_RESET": this.loadRecord,
                });
                if (!this._bNetworkResponseRegistered) {
                    this._bNetworkResponseRegistered = true;
                    this.onRegisterNetworkResponseListeners();
                }
                this.loadedCallback();
            }
            static loadRecord() {
            }
            static saveRecord() {
            }
            static onRegisterNetworkResponseListeners() {
            }
            static registerListeners(listeners) {
                Tools.forEachMap(listeners, (k, listener) => {
                    listeners[k] = listener.bind(this);
                });
                this._msgHander.registerListeners(listeners);
            }
            static startProcMsg() {
                this._msgHander.startProcMsg();
            }
            static stopProcMsg() {
                this._msgHander.stopProcMsg();
            }
            static sendMsg(msgName, data) {
                this._msgHander && this._msgHander.sendMsg(msgName, data);
            }
        }
        Manager._managerInstances = [];
        Manager.loadedCallback = null;
        Manager._bNetworkResponseRegistered = false;

        class CfgParser {
            static parseCfgByJsonObj(name, rawData, rule) {
                let datas = this.preprocess(name, rawData);
                let db = this.formatDb(name, datas, rule, rawData.fields);
                return db;
            }
            static parseNumber(srcValue) {
                let value = parseFloat(srcValue);
                if (isNaN(value)) {
                    value = null;
                }
                return value;
            }
            static parseString(srcValue) {
                return srcValue;
            }
            static parseArray(srcValue) {
                let value = null;
                try {
                    value = JSON.parse(srcValue);
                    if (!(value instanceof Array)) {
                        value = null;
                    }
                }
                catch (error) {
                }
                return value;
            }
            static parseObject(srcValue) {
                let value = null;
                try {
                    value = JSON.parse(srcValue);
                    if (!(value instanceof Object)) {
                        value = null;
                    }
                }
                catch (error) {
                }
                return value;
            }
            static parseBoolean(srcValue) {
                return srcValue == "TRUE" || srcValue == "true";
            }
            static parseValue(srcValue, type) {
                let parseFunction = this.PARSE_FUNCTIONS[type];
                if (!parseFunction) {
                    return "";
                }
                let value = parseFunction(srcValue);
                if (value == null) {
                    let defaultValue = this.PARSE_DEFAULT_VALUE_CREATORS[type]();
                    if (srcValue.length > 0) {
                        console.log(`[警告] CfgParser.parseValue 解析错误：type=${type}, srcValue=[${srcValue}], 默认值=[${defaultValue}]]`);
                    }
                    return defaultValue;
                }
                return value;
            }
            static preprocess(name, rawData) {
                let preprocessedData = [];
                let types = rawData.types || [];
                let fields = rawData.fields || [];
                let allValues = rawData.values || [];
                if (allValues.length <= 0) {
                    console.log(`[警告] CfgParser.preprocessData ${name} 数据为空`);
                    return;
                }
                if (types.length != allValues[0].length || fields.length != allValues[0].length) {
                    console.log(`[警告] CfgParser.preprocessData  ${name} 数据长度不匹配！`);
                    return [];
                }
                for (let i = 0; i < allValues.length; i++) {
                    const values = allValues[i];
                    let data = {};
                    for (let j = 0; j < values.length; j++) {
                        const type = types[j];
                        const field = fields[j];
                        const value = values[j];
                        data[field] = this.parseValue(value, type);
                    }
                    preprocessedData.push(data);
                }
                return preprocessedData;
            }
            static formatDb(name, datas, ruleString, fields) {
                let rules = ruleString.split("");
                let root = {};
                for (let i = 0; i < datas.length; i++) {
                    const data = datas[i];
                    let container = root;
                    for (let j = 0; j < rules.length - 1; j++) {
                        let field = fields[j];
                        let value = data[field];
                        let _container = container[value];
                        if (!_container) {
                            if (j == rules.length - 2 && rules[rules.length - 1] == "a") {
                                _container = [];
                            }
                            else {
                                _container = {};
                            }
                            container[value] = _container;
                        }
                        container = _container;
                    }
                    let rule = rules[rules.length - 1];
                    if (rule == "m") {
                        let field = fields[rules.length - 1];
                        let value = data[field];
                        if (container[value] != null) {
                            let text = "db";
                            for (let j = 0; j < rules.length; j++) {
                                text += `[${data[fields[j]]}]`;
                            }
                            console.log(`[警告] CfgParser.formatDb  ${name} 字段被覆盖！`, text, container[value]);
                        }
                        container[value] = data;
                    }
                    else if (rule == "a") {
                        if (!(container instanceof Array)) {
                            if (rules.length == 1) {
                                container = [];
                                root = container;
                            }
                            else {
                            }
                        }
                        if (container instanceof Array) {
                            container.push(data);
                        }
                        else {
                            console.log(`[警告] CfgParser.formatDb  ${name} a模式，容器不是数组！`);
                        }
                    }
                }
                return root;
            }
        }
        CfgParser.PARSE_FUNCTIONS = {
            "A": CfgParser.parseArray,
            "O": CfgParser.parseObject,
            "N": CfgParser.parseString,
            "S": CfgParser.parseString,
            "I": CfgParser.parseNumber,
            "F": CfgParser.parseNumber,
            "B": CfgParser.parseBoolean,
        };
        CfgParser.PARSE_DEFAULT_VALUE_CREATORS = {
            "A": () => { return []; },
            "O": () => { return {}; },
            "N": () => { return ""; },
            "S": () => { return ""; },
            "I": () => { return 0; },
            "F": () => { return 0; },
            "B": () => { return false; },
        };

        let systemConsole = console;
        var ULLog$1;
        (function (ULLog) {
            class console {
                static info(...data) {
                    if (ULLog.console.allowConsole) {
                        systemConsole.info(...data);
                    }
                }
                static log(...data) {
                    if (ULLog.console.allowConsole) {
                        systemConsole.log(...data);
                    }
                }
                static warn(...data) {
                    if (ULLog.console.allowConsole) {
                        systemConsole.warn(...data);
                    }
                }
                static error(...data) {
                    if (ULLog.console.allowConsole) {
                        systemConsole.error(...data);
                    }
                }
            }
            console.allowConsole = true;
            ULLog.console = console;
        })(ULLog$1 || (ULLog$1 = {}));
        window["ULLog"] = ULLog$1;

        class ULEventListener {
            constructor(type, priority, callback, bDispatchOnce) {
                this.type = type;
                this.priority = priority;
                this.callback = callback;
                this.bDispatchOnce = bDispatchOnce;
                this.bNeedRemove = false;
            }
            isDispatchOnce() {
                return !!this.bDispatchOnce;
            }
            isNeedRemove() {
                return !!this.bNeedRemove;
            }
            markNeedRemove() {
                this.bNeedRemove = true;
            }
            triggerCallback(event) {
                if (this.callback instanceof Function) {
                    try {
                        this.callback(event);
                    }
                    catch (error) {
                        ULLog.console.error("ULEventListener.triggerCallback has exception!", error.stack);
                        return false;
                    }
                    return true;
                }
                return false;
            }
        }

        class ULEvent {
            constructor(type, data) {
                this.bPropagationStoped = false;
                this.type = type;
                this.data = data;
                this.bPropagationStoped = false;
                this.returnValue = null;
            }
            stopImmediatePropagation() {
                this.bPropagationStoped = true;
            }
            setReturnValue(value, bDonotStop) {
                if (value != null) {
                    this.returnValue = value;
                    if (!bDonotStop)
                        this.stopImmediatePropagation();
                }
            }
            getReturnValue() {
                return this.returnValue;
            }
            isPropagationStoped() {
                return !!this.bPropagationStoped;
            }
        }

        class ULConst {
        }
        ULConst.CMD_GET_BASE_CHANNEL_INFO = "/c/getBaseChannelInfo";
        ULConst.CMD_SET_VERSION = "/c/setVersion";
        ULConst.CMD_END_USER_GUIDE = "/c/endUserGuide";
        ULConst.CMD_OPEN_MORE_GAME = "/c/openMoreGame";
        ULConst.CMD_OPEN_UL_MORE_GAME = "/c/openUlMoreGame";
        ULConst.CMD_OPEN_PAY = "/c/openPay";
        ULConst.CMD_OPEN_JF = "/c/openJf";
        ULConst.CMD_OPEN_SHARE = "/c/openShare";
        ULConst.CMD_CALL_PHONE = "/c/callPhone";
        ULConst.CMD_UL_WEB_VIEW = "/c/ulWebView";
        ULConst.CMD_EXIT_GAME = "/c/exitGame";
        ULConst.CMD_MEGADATA_SERVER = "/c/megadataServer";
        ULConst.CMD_POST_MEGADATA = "/c/postMegadata";
        ULConst.CMD_USE_CDKEY = "/c/useCdkey";
        ULConst.CMD_CHECK_TIME_CHANGE = "/c/checkTimeChange";
        ULConst.CMD_OPEN_ADV = "/c/openAdv";
        ULConst.CMD_CLICK_NATIVE_ADV = "/c/clickNativeAdv";
        ULConst.CMD_CLOSE_ADV = "/c/closeAdv";
        ULConst.CMD_CLOSE_NATIVE_ADV = "/c/closeNativeAdv";
        ULConst.CMD_USER_LOGIN = "/c/userLogin";
        ULConst.CMD_USER_LOGIN_REPORT = "/c/userLoginReport";
        ULConst.CMD_USER_IS_LOGIN = "/c/userIsLogin";
        ULConst.CMD_LOGIN_OUT = "/c/loginOut";
        ULConst.CMD_SAVE_RANK_DATA = "/c/saveRankData";
        ULConst.CMD_GET_RANK_DATA = "/c/getRankData";
        ULConst.CMD_GET_HEADLINE_IMRANK_DATA = "/c/getHeadlineIMRankData";
        ULConst.CMD_SET_HEADLINE_IMRANK_DATA = "/c/setHeadlineIMRankData";
        ULConst.CMD_RECORDER_GAME_VIDEO = "/c/recorderGameVideo";
        ULConst.CMD_SHARE_GAME_VIDEO = "/c/shareGameVideo";
        ULConst.CMD_OPEN_JUMP = "/c/openJump";
        ULConst.CMD_JUMP_OTHER_GAME = "/c/jumpOtherGame";
        ULConst.CMD_OPEN_RECOMMENDATION = "/c/openRecommendation";
        ULConst.CMD_CLOSE_RECOMMENDATION = "/c/closeRecommendation";
        ULConst.CMD_SAVE_USER_DATA = "/c/saveUserData";
        ULConst.CMD_GET_USER_DATA = "/c/getUserData";
        ULConst.CMD_ADD_GAME_TO_MY_FAVORITE = "/c/addGameToMyFavorite";
        ULConst.CMD_GET_USER_INFO_MSG = "/c/getUserInfoMsg";
        ULConst.CMD_OPEN_USERINFO_ACCREDIT_BUTTON = "/c/openUserInfoAccreditButton";
        ULConst.CMD_CLOSE_USERINFO_ACCREDIT_BUTTON = "/c/closeUserInfoAccreditButton";
        ULConst.CMD_INSTALL_SHORTCUT = "/c/installShortcut";
        ULConst.CMD_SET_CLIPBOARD_DATA = "/c/setClipboardData";
        ULConst.CMD_GET_CLIPBOARD_DATA = "/c/getClipboardData";
        ULConst.CMD_SET_ULSDKDEMO_DEBUG_MODE = "/c/setUlsdkdemoDebugMode";
        ULConst.CMD_MPSDK_AD_HANDLER = '/c/mpsdkAdHandler';
        ULConst.CMD_CREATE_GAME_ICON = '/c/createGameIcon';
        ULConst.CMD_GAME_ICON_HANDLER = '/c/gameIconHandler';
        ULConst.CMD_OPEN_CHANNEL_MORE_GAME_BOX = '/c/openChannelMoreGameBox';
        ULConst.CMD_OPEN_BLOCK_AD = '/c/openBlockAd';
        ULConst.CMD_CLOSE_BLOCK_AD = '/c/closeBlockAd';
        ULConst.CMD_GET_SHORTCUT_STATE = '/c/getShortcutState';
        ULConst.CMD_GET_SUBSCRIBE_STATE = "/c/getSubscribeState";
        ULConst.CMD_ADD_SUBSCRIBE = "/c/addSubscribe";
        ULConst.CMD_ADD_COLOR_SIGN = '/c/addColorSign';
        ULConst.CMD_OPEN_GRID_AD = '/c/openGridAd';
        ULConst.CMD_CLOSE_GRID_AD = '/c/closeGridAd';
        ULConst.CMD_JUMP_TO_VIDEO_VIEW = '/c/jumpToVideoView';
        ULConst.CMD_FOLLOW_OFFICIAL_ACCOUNT = '/c/followOfficialAccount';
        ULConst.CMD_GET_FOLLOW_OFFICIAL_ACCOUNT_STATE = '/c/getFollowOfficialAccountState';
        ULConst.CMD_CONTENT_SECURITY_CHECK = '/c/contentSecurityCheck';
        ULConst.CMD_JUMP_LEISURE_SUBJECT = '/c/jumpLeisureSubject';
        ULConst.CMD_PHONE_VIBRATE = '/c/phoneVibrate';
        ULConst.CMD_OPEN_URL = '/c/openUrl';
        ULConst.CMD_SHOW_CHANNEL_MASK = '/c/showChannelMask';
        ULConst.CMD_CLOSE_CHANNEL_MASK = '/c/closeChannelMask';
        ULConst.CMD_SHOW_PRIVACY = '/c/showPrivacy';
        ULConst.CMD_OPEN_ADVANCED_SETTING = '/c/openAdvancedSetting';
        ULConst.CMD_GET_OPENDATA_CANVAS = '/c/getOpenDataCanvas';
        ULConst.CMD_SET_USER_CLOUD_STORAGE = '/c/setUserCloudStorage';
        ULConst.CMD_GET_USER_CLOUD_STORAGE = '/c/getUserCloudStorage';
        ULConst.CMD_GET_JOIN_GROUP_NUM = "/c/getJoinGroupNum";
        ULConst.CMD_JOIN_GROUP = "/c/joinGroup";
        ULConst.CMD_RANKLIST_GET_USER_NUM = "/c/getUserNumInRank";
        ULConst.CMD_RANKLIST_GET_USER_INFO_BY_ID = "/c/getUserInfoByIdInRank";
        ULConst.CMD_RANKLIST_GET_USER_INFO_BY_IDLIST = "/c/getUserInfoByIdListInRank";
        ULConst.CMD_RANKLIST_GET_USER_INFO_BY_LIST = "/c/getUserInfoListByRankId";
        ULConst.CMD_RANKLIST_REPORT_USER_INFO = "/c/reportUserInfoInRank";
        ULConst.CMD_RANKLIST_MODIFY_SCORE_BY_ARRAY = "/c/modifyScoreByArray";
        ULConst.CMD_CHANNEL_INFO_RESULT = "/c/channelInfoResult";
        ULConst.CMD_GET_BASE_CHANNEL_INFO_RESULT = "/c/getBaseChannelInfoResult";
        ULConst.CMD_PAY_RESULT = "/c/payResult";
        ULConst.CMD_PRE_PAY_RESULT = "/c/prePayResult";
        ULConst.CMD_SHARE_RESULT = "/c/shareResult";
        ULConst.CMD_LIFE_CYCLE_RESULT = "/c/lifeCycle";
        ULConst.CMD_PAUSE_SOUND_RESULT = "/c/pauseSound";
        ULConst.CMD_RESUME_SOUND_RESULT = "/c/resumeSound";
        ULConst.CMD_COP_INFO_RESULT = "/c/copInfoResult";
        ULConst.CMD_MEGADATA_SERVER_RESULT = "/c/megadataServer";
        ULConst.CMD_POST_MEGADATA_RESULT = "/c/postMegadataResult";
        ULConst.CMD_USE_CDKEY_RESULT = "/c/useCdkey";
        ULConst.CMD_CHECK_TIME_CHANGE_RESULT = "/c/checkTimeChangeResult";
        ULConst.CMD_OPEN_ADV_RESULT = "/c/openAdvResult";
        ULConst.CMD_OPEN_NATIVE_ADV_RESULT = "/c/openNativeAdvResult";
        ULConst.CMD_CLICK_NATIVE_ADV_RESULT = "/c/clickNativeAdvResult";
        ULConst.CMD_CLICK_ADV_RESULT = "/c/clickAdvResult";
        ULConst.CMD_CLOSE_ADV_RESULT = "/c/closeAdvResult";
        ULConst.CMD_CLOSE_NATIVE_ADV_RESULT = "/c/closeNativeAdvResult";
        ULConst.CMD_USER_LOGIN_RESULT = "/c/userLoginResult";
        ULConst.CMD_USER_IS_LOGIN_RESULT = "/c/userIsLoginResult";
        ULConst.CMD_USER_LOGIN_REPORT_RESULT = "/c/userLoginReportResult";
        ULConst.CMD_LOGIN_OUT_RESULT = "/c/loginOutResult";
        ULConst.CMD_SHOW_PRIVACY_RESULT = '/c/showPrivacyResult';
        ULConst.CMD_ADV_VALID_COUNT_RESULT = "/c/advValidCountResult";
        ULConst.CMD_SAVE_RANK_DATA_RESULT = "/c/saveRankDataResult";
        ULConst.CMD_GET_RANK_DATA_RESULT = "/c/getRankDataResult";
        ULConst.CMD_GET_HEADLINE_IMRANK_DATA_RESULT = "/c/getHeadlineIMRankDataResult";
        ULConst.CMD_SET_HEADLINE_IMRANK_DATA_RESULT = "/c/setHeadlineIMRankDataResult";
        ULConst.CMD_RECORDER_GAME_VIDEO_RESULT = "/c/recorderGameVideoResult";
        ULConst.CMD_SHARE_GAME_VIDEO_RESULT = "/c/shareGameVideoResult";
        ULConst.CMD_OPEN_JUMP_RESULT = "/c/openJumpResult";
        ULConst.CMD_JUMP_OTHER_GAME_RESULT = "/c/jumpOtherGameResult";
        ULConst.CMD_JUMP_OTHER_GAME_REWARD_RESULT = "/c/jumpOtherGameRewardResult";
        ULConst.CMD_EXTRA_BONUS_RESULT = "/c/extraBonus";
        ULConst.CMD_OPEN_RECOMMENDATION_RESULT = "/c/openRecommendationResult";
        ULConst.CMD_CLOSE_RECOMMENDATION_RESULT = "/c/closeRecommendationResult";
        ULConst.CMD_SAVE_USER_DATA_RESULT = "/c/saveUserDataResult";
        ULConst.CMD_GET_USER_DATA_RESULT = "/c/getUserDataResult";
        ULConst.CMD_ADD_GAME_TO_MY_FAVORITE_RESULT = "/c/addGameToMyFavoriteResult";
        ULConst.CMD_GET_USER_INFO_MSG_RESULT = "/c/getUserInfoMsgResult";
        ULConst.CMD_OPEN_USERINFO_ACCREDIT_BUTTON_RESULT = "/c/openUserInfoAccreditButtonResult";
        ULConst.CMD_CLOSE_USERINFO_ACCREDIT_BUTTON_RESULT = "/c/closeUserInfoAccreditButtonResult";
        ULConst.CMD_APP_SHARE_RESULT = "/c/appShareResult";
        ULConst.CMD_INSTALL_SHORTCUT_RESULT = "/c/installShortcutResult";
        ULConst.CMD_SET_CLIPBOARD_DATA_RESULT = "/c/setClipboardDataResult";
        ULConst.CMD_GET_CLIPBOARD_DATA_RESULT = "/c/getClipboardDataResult";
        ULConst.CMD_MPSDK_AD_HANDLER_RESULT = '/c/mpsdkAdHandlerResult';
        ULConst.CMD_CREATE_GAME_ICON_RESULT = '/c/createGameIconResult';
        ULConst.CMD_GAME_ICON_HANDLER_RESULT = '/c/gameIconHandlerResult';
        ULConst.CMD_OPEN_CHANNEL_MORE_GAME_BOX_RESULT = '/c/openChannelMoreGameBoxResult';
        ULConst.CMD_OPEN_BLOCK_AD_RESULT = '/c/openBlockAdResult';
        ULConst.CMD_CLOSE_BLOCK_AD_RESULT = '/c/closeBlockAdResult';
        ULConst.CMD_GET_SHORTCUT_STATE_RESULT = '/c/getShortcutStateResult';
        ULConst.CMD_GET_SUBSCRIBE_STATE_RESULT = "/c/getSubscribeStateResult";
        ULConst.CMD_ADD_SUBSCRIBE_RESULT = "/c/addSubscribeResult";
        ULConst.CMD_ADD_COLOR_SIGN_RESULT = '/c/addColorSignResult';
        ULConst.CMD_OPEN_GRID_AD_RESULT = '/c/openGridAdResult';
        ULConst.CMD_CLOSE_GRID_AD_RESULT = '/c/closeGridAdResult';
        ULConst.CMD_JUMP_TO_VIDEO_VIEW_RESULT = '/c/jumpToVideoViewResult';
        ULConst.CMD_FOLLOW_OFFICIAL_ACCOUNT_RESULT = '/c/followOfficialAccountResult';
        ULConst.CMD_GET_FOLLOW_OFFICIAL_ACCOUNT_STATE_RESULT = '/c/getFollowOfficialAccountStateResult';
        ULConst.CMD_CONTENT_SECURITY_CHECK_RESULT = '/c/contentSecurityCheckResult';
        ULConst.CMD_JUMP_LEISURE_SUBJECT_RESULT = '/c/jumpLeisureSubjectResult';
        ULConst.CMD_PHONE_VIBRATE_RESULT = '/c/phoneVibrateResult';
        ULConst.CMD_JUMP_NEW_USER_GUIDE = '/c/jumpNewGuide';
        ULConst.CMD_CHECKDEBUG_WHITEUSER_RESULT = '/c/checkDebugWhiteUserResult';
        ULConst.CMD_OPEN_URL_RESULT = '/c/openUrlResult';
        ULConst.CMD_CLEAN_UP_GAME_ARCHIVE = '/c/cleanUpGameArchive';
        ULConst.CMD_SHOW_POINT_DEBUG_INFO = '/c/showPointDebugInfo';
        ULConst.CMD_CHECK_LAUNCH_REWARD = "/sdk/checkLaunchReward";
        ULConst.CMD_WX_GET_GAMECLUB_DATA = "/c/wxGetGameClubData";
        ULConst.CMD_WX_SHOW_GAMECLUB_BUTTON = "/c/wxShowGameClubButton";
        ULConst.CMD_WX_HIDE_GAMECLUB_BUTTON = "/c/wxHideGameClubButton";
        ULConst.CMD_WX_GET_GAMECLUB_DATA_RESULT = "/c/wxGetGameClubDataResult";
        ULConst.CMD_WX_SHOW_GAMECLUB_BUTTON_RESULT = "/c/wxShowGameClubButtonResult";
        ULConst.CMD_WX_HIDE_GAMECLUB_BUTTON_RESULT = "/c/wxHideGameClubButtonResult";
        ULConst.CMD_WX_GAMECLUB_BUTTON_ONTAP_RESULT = "/c/wxGameClubButtonOnTapResult";
        ULConst.CMD_WX_GAMECLUB_BUTTON_OFFTAP_RESULT = "/c/wxGameClubButtonOffTapResult";
        ULConst.CMD_SET_USER_CLOUD_STORAGE_RESULT = '/c/setUserCloudStorageResult';
        ULConst.CMD_GET_USER_CLOUD_STORAGE_RESULT = '/c/getUserCloudStorageResult';
        ULConst.CMD_GET_JOIN_GROUP_NUM_RESULT = "/c/getJoinGroupNumResult";
        ULConst.CMD_JOIN_GROUP_RESULT = "/c/joinGroupResult";
        ULConst.CMD_LAUNCH_REWARD_RESULT = "/c/launchRewardResult";
        ULConst.CMD_MOYANG_QQ_NET_EARNED_QUERY = "/c/qqNetEarnedQuery";
        ULConst.CMD_MOYANG_QQ_NET_EARNED_RECHARGE = "/c/qqNetEarnedRecharge";
        ULConst.CMD_MOYANG_QQ_NET_EARNED_CASH = "/c/qqNetEarnedCash";
        ULConst.CMD_MOYANG_QQ_NET_EARNED_QUERY_RESULT = "/c/qqNetEarnedQueryResult";
        ULConst.CMD_MOYANG_QQ_NET_EARNED_RECHARGE_RESULT = "/c/qqNetEarnedRechargeResult";
        ULConst.CMD_MOYANG_QQ_NET_EARNED_CASH_RESULT = "/c/qqNetEarnedCashResult";
        ULConst.CMD_RANKLIST_GET_USER_NUM_RESULT = "/c/getUserNumInRankResult";
        ULConst.CMD_RANKLIST_GET_USER_INFO_BY_ID_RESULT = "/c/getUserInfoByIdInRankResult";
        ULConst.CMD_RANKLIST_GET_USER_INFO_BY_IDLIST_RESULT = "/c/getUserInfoByIdListInRankResult";
        ULConst.CMD_RANKLIST_GET_USER_INFO_BY_LIST_RESULT = "/c/getUserInfoListByRankIdResult";
        ULConst.CMD_RANKLIST_REPORT_USER_INFO_RESULT = "/c/reportUserInfoInRankResult";
        ULConst.CMD_RANKLIST_MODIFY_SCORE_BY_ARRAY_RESULT = "/c/modifyScoreByArrayResult";
        ULConst.CMD_GET_OPENDATA_CANVAS_RESULT = '/c/getOpenDataCanvasResult';
        ULConst.CMD_SDK_ON_COP_CHANGED = "/sdk/onCopChanged";
        ULConst.CMD_SDK_PREPARE_SHOW_VIDEO_ADV = "/sdk/prepareShowVideoAdv";
        ULConst.CMD_SDK_PREPARE_SHOW_INTER_ADV = "/sdk/prepareShowInterAdv";
        ULConst.CMD_SDK_PREPARE_SHOW_BANNER_ADV = "/sdk/prepareShowBannerAdv";
        ULConst.CMD_SDK_PREPARE_SHOW_EMBEDDED_ADV = "/sdk/prepareShowEmbeddedAdv";
        ULConst.CMD_SDK_PREPARE_SHOW_URL_ADV = "/sdk/prepareShowUrlAdv";
        ULConst.CMD_SDK_PREPARE_SHOW_PASTER_ADV = "/sdk/prepareShowPasterAdv";
        ULConst.CMD_SDK_SHOW_VIDEO_ADV = "/sdk/showVideoAdv";
        ULConst.CMD_SDK_SHOW_INTER_ADV = "/sdk/showInterAdv";
        ULConst.CMD_SDK_SHOW_BANNER_ADV = "/sdk/showBannerAdv";
        ULConst.CMD_SDK_SHOW_EMBEDDED_ADV = "/sdk/showEmbeddedAdv";
        ULConst.CMD_SDK_SHOW_URL_ADV = "/sdk/showUrlAdv";
        ULConst.CMD_SDK_SHOW_PASTER_ADV = "/sdk/showPasterAdv";
        ULConst.CMD_SDK_CLOSE_VIDEO_ADV = "/sdk/closeVideoAdv";
        ULConst.CMD_SDK_CLOSE_INTER_ADV = "/sdk/closeInterAdv";
        ULConst.CMD_SDK_CLOSE_BANNER_ADV = "/sdk/closeBannerAdv";
        ULConst.CMD_SDK_CLOSE_EMBEDDED_ADV = "/sdk/closeEmbeddedAdv";
        ULConst.CMD_SDK_CLOSE_URL_ADV = "/sdk/closeUrlAdv";
        ULConst.CMD_SDK_CLOSE_Paster_ADV = "/sdk/closePasterAdv";
        ULConst.CMD_SDK_CLOSE_NATIVE_ADV = "/sdk/closeNativeAdv";
        ULConst.CMD_SDK_CLICK_NATIVE_ADV = "/sdk/clickNativeAdv";
        ULConst.CMD_SDK_GET_STORAGE = "/sdk/getStorge";
        ULConst.CMD_SDK_SET_STORAGE = "/sdk/setStorge";
        ULConst.CMD_SDK_GET_CLIPBOARD_DATA = "/sdk/getClipboardData";
        ULConst.CMD_SDK_SET_CLIPBOARD_DATA = "/sdk/setClipboardData";
        ULConst.CMD_SDK_IS_SUPPORT_CLIPBOARD = "/sdk/isSupportClipboard";
        ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_CONFIG = "/sdk/collectionModuleCheckerConfig";
        ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_MORE_GAME_AB_TEST_CONFIG = "/sdk/collectionModuleCheckerMoreGameAbTestConfig";
        ULConst.CMD_SDK_ON_GAME_START = "/sdk/onGameStart";
        ULConst.CMD_SDK_ON_GAME_PAUSE = "/sdk/onGamePause";
        ULConst.CMD_SDK_ON_GAME_RESUME = "/sdk/onGameResume";
        ULConst.CMD_SDK_ON_SHARE_SHOW = "/sdk/onShareShow";
        ULConst.CMD_SDK_ON_SAHRE_APP_MESSAGE = "/sdk/onShareAppMessage";
        ULConst.CMD_SDK_ON_REPORT_ULSDK_EVENT = "/sdk/ulsdkMegadataUpload";
        ULConst.CMD_SDK_OPEN_SHARE_DURING_ADV = "/sdk/openShareDuringAdv";
        ULConst.CMD_SDK_CHANNEL_MEGADATA_POST = "/sdk/channelMegadataPost";
        ULConst.CMD_SDK_SET_UP_WEBVIEW_JAVASCRIPT_BRIDGE = "/sdk/setUpWebViewJavascriptBridge";
        ULConst.CMD_SDK_EXPRESS_NATIVE_ADV_STATUS_CHANGE = "/sdk/expressNativeAdvStatusChange";
        ULConst.CMD_MOYANG_QQ_REWARD_VIDEO_PLAY = "/sdk/moyangQQRewardVideoPlay";
        ULConst.CMD_MOYANG_QQ_REWARD_VIDEO_CLOSE = "/sdk/moyangQQRewardVideoClose";
        ULConst.CMD_FACEBOOK_INIT_COMPLETE = "/sdk/facebookInitComplete";
        ULConst.CMD_WXOCEANENGINE_PAY_SUCCESS = "/sdk/wxOceanEnginePaySuccess";
        ULConst.CMD_HUAWEI_BUYQUANTITY_PLAY_VIDEOAD = "/sdk/HuaweiBuyQuantityPlayVideoAd";
        ULConst.CMD_HUAWEI_BUYQUANTITY_PAY_SUCCESS = "/sdk/HuaweiBuyQuantityPaySuccess";
        ULConst.CMD_WEIXIN_BUYQUANTITY_PLAY_VIDEOAD = "/sdk/weixinBuyQuantityPlayVideoAd";
        ULConst.CMD_WEIXIN_BUYQUANTITY_PAY_SUCCESS = "/sdk/weixinBuyQuantityPaySuccess";
        ULConst.CMD_HEADLINE_BUYQUANTITY_PLAY_VIDEOAD = "/sdk/headlineBuyQuantityPlayVideoAd";
        ULConst.CMD_HEADLINE_BUYQUANTITY_STARTPLAY_VIDEOAD = "/sdk/headlineBuyQuantityStartPlayVideoAd";
        ULConst.CMD_HEADLINE_BUYQUANTITY_PAY_SUCCESS = "/sdk/headlineBuyQuantityPaySuccess";
        ULConst.CMD_SDK_COMMONEVENT_ID_POST = "/sdk/commonEventIdPost";
        ULConst.CMD_SDK_LEVELCOMPLETEEVENT_ID_POST = "/sdk/levelCompleteEventIdPost";
        ULConst.CMD_SDK_INIT_USER_LOGIN = "/sdk/initUserLogin";
        ULConst.CMD_SDK_QM_LOGIN_REPORT = "/qmsdk/loginReport";
        ULConst.CMD_SDK_QM_REPORT_EVENT = "/qmsdk/reportEvent";
        ULConst.CMD_SDK_QM_REPORT_GOLD = "/qmsdk/reportGold";
        ULConst.CMD_SDK_QM_SET_ACCOUNT_INFO = "/qmsdk/setAccountInfo";
        ULConst.CMD_SDK_QM_GET_OPEN_LEVEL = "/qmsdk/getOpenLevel";
        ULConst.CMD_SDK_QM_GET_RECOMMEND_INFO = "/qmsdk/getRecommendInfo";
        ULConst.CMD_SDK_QM_GET_SUGGEST_LIST = "/qmsdk/getSuggestList";
        ULConst.CMD_SDK_QM_GET_EXCITATION_LIST = "/qmsdk/getExcitationList";
        ULConst.CMD_SDK_QM_MPSDK_AD_CLICK = "/qmsdk/mpsdkAdClick";
        ULConst.CMD_SDK_QM_MPSDK_CLICK_SYNC = "/qmsdk/mpsdkClickSync";
        ULConst.CMD_SDK_QM_GET_USER_DATA_VERSION = "/qmsdk/getUserDataVersion";
        ULConst.CMD_SDK_QM_IS_STRONG_FISSION = "/qmsdk/isStrongFission";
        ULConst.CMD_SDK_QM_REPORT_VIDEO_TIME_EVENT = "/qmsdk/reportVideoTimeEvent";
        ULConst.CMD_SDK_OPPOQG_MARK_MANUAL_CLOSE_BANNER_COUNT = "/sdk/oppoqg/markManualCloseBannerCount";
        ULConst.CMD_SDK_OPPOQG_GET_MANUAL_CLOSE_BANNER_COUNT = "/sdk/oppoqg/getManualCloseBannerCount";
        ULConst.CMD_SDK_OPPOQG_HAS_BANNER_SHOWING = "/sdk/oppoqg/hasBannerShowing";
        ULConst.PRIORITY_DISABLE = -2;
        ULConst.PRIORITY_NONE = -1;
        ULConst.CONSOLE_OUTPUT_LEVEL_WARN = 1;
        ULConst.CONSOLE_OUTPUT_LEVEL_ERROR = 1;
        ULConst.CONSOLE_OUTPUT_LEVEL_LOG = 2;
        ULConst.CONSOLE_OUTPUT_LEVEL_INNER_DEBUG = 3;
        ULConst.B_INNER_DEBUG = false;
        ULConst.COP_RETRY_TIME_SEC = 30;
        ULConst.STATIS_TYPE_BASE_INFO = "1";
        ULConst.STATIS_TYPE_PAY_INFO = "2";
        ULConst.STATIS_TYPE_ADV_INFO = "3";
        ULConst.STATIS_TYPE_COP_REQUEST = "4";
        ULConst.STATIS_TYPE_USER_EVENT = "5";
        ULConst.STATIS_TYPE_ONLINE_TIME = "6";
        ULConst.STATIS_TYPE_POINT_EVENT = "7";
        ULConst.STATIS_TYPE_COIN_CHANGE_EVENT = "5";
        ULConst.STATIS_TYPE_COMMON_EVENT = "7";
        ULConst.STATIS_TYPE_LEVEL_START_EVENT = "8";
        ULConst.STATIS_TYPE_LEVEL_COMPLETE_EVENT = "9";
        ULConst.STATIS_TYPE_ITEM_BUY = "10";
        ULConst.STATIS_TYPE_BUY_ACTION = "11";
        ULConst.STATIS_TYPE_VIDEO_POINT_EVENT = "12";
        ULConst.STATIS_TYPE_USER_MESSAGE = "14";
        ULConst.DEFAULT_REFERANCE_BANNER_HEIGHT = 200;
        ULConst.STATIS_USER_EVENT_GAME_LEVEL_START = "gameLevelStart";
        ULConst.STATIS_USER_EVENT_GAME_LEVEL_COMPLETE = "gameLevelComplete";
        ULConst.STATIS_USER_EVENT_GAME_COIN_ADD = "gameCoinAdd";
        ULConst.STATIS_USER_EVENT_GAME_COIN_LOST = "gameCoinLost";
        ULConst.STATIS_USER_EVENT_BUY_ACTION = "buyAction";
        ULConst.STATIS_USER_EVENT_ITEM_BUY = "itemBuy";
        ULConst.STATIS_USER_EVENT_COMMON_EVENT = "commonEvent";
        ULConst.STATIS_USER_EVENT_COMMON_EVENT_MULTI_FIELD = "commonEventMultiField";
        ULConst.STATIS_USER_EVENT_POINT_EVENT = "pointEvent";
        ULConst.STATIS_USER_ACTION_EVENT_LEVEL_START = "levelStart";
        ULConst.STATIS_USER_ACTION_EVENT_LEVEL_COMPLETE = "levelComplete";
        ULConst.STATIS_USER_ACTION_EVENT_COIN_CHANGE = "coinChange";
        ULConst.STATIS_USER_ACTION_EVENT_ITEM_BUY = "itemBuy";
        ULConst.STATIS_USER_ACTION_EVENT_BUY_ACTION = "buyAction";
        ULConst.STATIS_USER_ACTION_EVENT_COMMON_EVENT = "commonEvent";
        ULConst.STATIS_USER_ACTION_EVENT_VIDEO_POINT_EVENT = "videoPointEvent";
        ULConst.STATIS_UPLOAD_SPAN = 60;
        ULConst.STATIS_UPLOAD_SINGLE_REQUEST_MAX_COUNT = 100;
        ULConst.ADV_FAIL_TIP_NOAD = "暂时无法播放广告，请稍后再试";
        ULConst.ADV_FAIL_TIP_BUSY = "广告准备中，请稍后再试";
        ULConst.ENGLISH_ADV_FAIL_TIP_NOAD = "Ad display failed, please retry later.";
        ULConst.ENGLISH_ADV_FAIL_TIP_BUSY = "Ad in preparation, please retry later.";
        ULConst.ADV_ERR_CODE_CONSECUTIVE_FAIL = -100;
        ULConst.ADV_ERR_CODE_CDING = -101;
        ULConst.ADV_ERR_CODE_NATIVE_ID_ERROR = -102;
        ULConst.ADV_ERR_CODE_NATIVE_DATA_ERROR = -102;
        ULConst.ADV_ERR_CODE_CAN_NOT_PLAY = -103;
        ULConst.ADV_ERR_CODE_NOT_INITED = -104;
        ULConst.ADV_ERR_CODE_UNKNOWN = -105;
        ULConst.ADV_ERR_CODE_SHARE_NO_CALLBACK = -106;
        ULConst.ADV_ERR_CODE_SHARE_FAIL = -107;
        ULConst.ADV_ERR_CODE_ADOBJ_NULL = -108;
        ULConst.ADV_ERR_CODE_ADV_TYPE_CD = -109;
        ULConst.ADV_ERR_CODE_ADV_TYPE_DAILY_LIMIT = -110;
        ULConst.ADV_PRELOAD_STATE_READY = 1;
        ULConst.ADV_PRELOAD_STATE_LOADING = 2;
        ULConst.ADV_PRELOAD_STATE_NOAD = 3;
        ULConst.ADV_RESULT_CODE_SUCCESS = 1;
        ULConst.ADV_RESULT_CODE_FAILED = 0;
        ULConst.ADV_RESULT_CODE_OBSOLETE = 2;
        ULConst.ADV_MUST_DEFAULT_WEIGHT = 100;
        ULConst.ADV_RANDOM_DEFAULT_WEIGHT = 1;
        ULConst.ADV_DISABLE_DEFAULT_WEIGHT = 0;
        ULConst.ADV_RESULT_MSG_FAILED = "哎呀,广告走丢啦";
        ULConst.ADV_RESULT_MSG_SUCCESS = "show adv success";
        ULConst.ADV_NATIVE_RESULT_MSG_SUCCESS = "load native data success";
        ULConst.ADV_NATIVE_RESULT_MSG_FAIL = "load native data fail";
        ULConst.ADV_VIDEO_PLAY_FAIL_MSG = "广告提前关闭,无法获得奖励";
        ULConst.ADV_RESULT_MSG_CLICK = "click adv";
        ULConst.ADV_RESULT_MSG_CLOSE = "close adv";
        ULConst.ADV_NATIVE_OBSOLETE_MSG = "广告数据作废";
        ULConst.EXP_ADV_TYPE_CONST = "atype";
        ULConst.EXP_ADV_TEMPLATE_CONST = "tid";
        ULConst.EXP_ADV_POINT_CONST = ".";
        ULConst.UL_EVENT_ONREQUEST = "onRequest";
        ULConst.UL_EVENT_SHOW_PRIVACY_POLICY = "showPrivacyPolicy";
        ULConst.UL_EVENT_SHOW_PRIVACY_POLICY_WAIT = "showPrivacyPolicyWait";
        ULConst.CMD_GET_ADV_STATE_RESULT = "/c/getAdvStateResult";
        ULConst.CMD_CLOSE_ALL_ADV_BY_TYPE_RESULT = "/c/closeAllAdvByTypeResult";
        ULConst.CMD_JUMP_NEW_GUIDE = "/c/jumpNewGuide";
        ULConst.CMD_GET_ADV_STATE = "/c/getAdvState";
        ULConst.CMD_CLOSE_ALL_ADV_BY_TYPE = "/c/closeAllAdvByType";
        ULConst.CMD_REWARD_ADV_RESULT = "/c/rewardAdvResult";
        ULConst.UL_ADV_DEFAULT_TIMEOUT_TIME = 30000;
        ULConst.DEFAULT_TITLE = "广告";
        ULConst.DEFAULT_DESC = "哇!这个实在太棒啦!";
        ULConst.DEFAULT_TARGET_TITLE = "查看广告";
        ULConst.MIN_NATIVE_RESPONSE_CACHE_TIMEOUT = 0;
        ULConst.MAX_NATIVE_RESPONSE_CACHE_TIMEOUT = 30 * 1000;
        ULConst.DEFAULT_NATIVE_RESPONSE_CACHE_TIMEOUT = 15 * 1000;
        ULConst.ADV_LOAD_TYPE_PRELOAD = 1;
        ULConst.ADV_LOAD_TYPE_UNPRELOAD = 0;

        class ULEventDispatcher {
            constructor() {
                this.allListeners = {};
            }
            static getInstance() {
                if (!this._instance) {
                    this._instance = new ULEventDispatcher();
                }
                return this._instance;
            }
            addListener(type, priority, callback) {
                return this._addListener(type, priority, callback, false);
            }
            once(type, priority, callback) {
                return this._addListener(type, priority, callback, true);
            }
            _addListener(type, priority, callback, bDispatchOnce) {
                if (priority < ULConst.PRIORITY_NONE) {
                    this.removeListenerByCallback(type, callback);
                    return;
                }
                ;
                let listeners = this.allListeners[type];
                if (!listeners) {
                    listeners = [];
                    this.allListeners[type] = listeners;
                }
                let insertIndex = -1;
                for (let i = 0; i < listeners.length; i++) {
                    let listener = listeners[i];
                    if (listener.callback == callback) {
                        ULLog.console.warn("ULEventDispatcher._addListener callback already exists:", type);
                        return false;
                    }
                    if (insertIndex == -1 && listener.priority < priority) {
                        insertIndex = i;
                    }
                }
                let listener = new ULEventListener(type, priority, callback, bDispatchOnce);
                if (insertIndex != -1) {
                    listeners.splice(insertIndex, 0, listener);
                }
                else {
                    listeners.push(listener);
                }
                return true;
            }
            removeListenerByCallback(type, callback) {
                let listeners = this.allListeners[type];
                if (!listeners)
                    return;
                for (let i = listeners.length - 1; i >= 0; i--) {
                    let listener = listeners[i];
                    if (listener.callback == callback) {
                        listeners.splice(i, 1);
                    }
                }
            }
            removeListenersByType(type) {
                delete this.allListeners[type];
            }
            dispatch(type, data) {
                let event = null;
                if (type instanceof ULEvent) {
                    event = type;
                }
                else {
                    event = new ULEvent(type, data);
                }
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULEventDispatcher.dispatch", event.type, event.data);
                let ret = this._inner_dispatch(event);
                return ret.bCalled;
            }
            dispatchWithReturn(type, data) {
                let event = null;
                if (type instanceof ULEvent) {
                    event = type;
                }
                else {
                    event = new ULEvent(type, data);
                }
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULEventDispatcher.dispatchWithReturn", event.type, event.data);
                let ret = this._inner_dispatch(event);
                return ret.returnValue;
            }
            _inner_dispatch(event) {
                let bCalled = false;
                let listeners = this.allListeners[event.type];
                if (!listeners) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("  listeners not found");
                    return { bCalled: false, returnValue: null };
                }
                for (let i = 0; i < listeners.length; i++) {
                    const listener = listeners[i];
                    if (listener.isNeedRemove())
                        continue;
                    if (listener.isDispatchOnce()) {
                        listener.markNeedRemove();
                    }
                    if (listener.triggerCallback(event)) {
                        bCalled = true;
                    }
                    if (event.isPropagationStoped()) {
                        break;
                    }
                }
                for (let i = listeners.length - 1; i >= 0; i--) {
                    let listener = listeners[i];
                    if (listener.isNeedRemove()) {
                        listeners.splice(i, 1);
                    }
                }
                return { bCalled: bCalled, returnValue: event.getReturnValue() };
            }
        }
        ULEventDispatcher._instance = null;

        var cConfig = JSON.parse(`{
    "a_prj_upload_res_dirs": [
        
    ],
    "b_sdk_oppoqg_debug": false,
    "creatorVersion": "",
    "i_channel_info_timeout": 3000,
    "i_game_start_ready_timeout": 10000,
    "i_net_timeout": 5000,
    "i_prj_b2b_mode": 0,
    "i_sdk_adv_banner_cd": 0,
    "i_sdk_adv_banner_timeout": 30000,
    "i_sdk_adv_banner_valid_show_count": 2,
    "i_sdk_adv_custom_valid_show_count": 2,
    "i_sdk_adv_embedded_timeout": 30000,
    "i_sdk_adv_inter_cd": 0,
    "i_sdk_adv_inter_timeout": 30000,
    "i_sdk_adv_native_clicked_report_mode": 0,
    "i_sdk_adv_native_exposure_cd": 0,
    "i_sdk_adv_native_life_time": 15000,
    "i_sdk_adv_native_request_cd": 10000,
    "i_sdk_adv_paster_timeout": 30000,
    "i_sdk_adv_type_banner_cd": 0,
    "i_sdk_adv_type_banner_daily_limit": 0,
    "i_sdk_adv_type_embedded_cd": 0,
    "i_sdk_adv_type_embedded_daily_limit": 0,
    "i_sdk_adv_type_interstitial_cd": 0,
    "i_sdk_adv_type_interstitial_daily_limit": 0,
    "i_sdk_adv_type_paster_cd": 0,
    "i_sdk_adv_type_paster_daily_limit": 0,
    "i_sdk_adv_type_url_cd": 0,
    "i_sdk_adv_type_url_daily_limit": 0,
    "i_sdk_adv_type_video_cd": 0,
    "i_sdk_adv_type_video_daily_limit": 0,
    "i_sdk_adv_url_timeout": 30000,
    "i_sdk_adv_video_timeout": 30000,
    "i_sdk_age_level_info_mode": 1,
    "i_sdk_banner_autoRefresh_mode": 0,
    "i_sdk_banner_refresh_intervals": 30,
    "i_sdk_channel_user_id_mode": 0,
    "i_sdk_common_checktime_deferenceLimit": 300000,
    "i_sdk_compress_res_mode": 1,
    "i_sdk_content_security_check_support": 1,
    "i_sdk_custom_autoRefresh_mode": 0,
    "i_sdk_custom_refresh_intervals": 30,
    "i_sdk_debug_mode": 0,
    "i_sdk_debug_task_mode": 0,
    "i_sdk_find_mini_game_mode": 1,
    "i_sdk_installShortcut_mode": 1,
    "i_sdk_joinGroup_mode": 1,
    "i_sdk_jump_game_resource_mode": 0,
    "i_sdk_jump_single_random_length": 5,
    "i_sdk_jumplist_mode": 1,
    "i_sdk_launchReward_mode": 0,
    "i_sdk_megadata_encrypt": 1,
    "i_sdk_megadata_mode": 1,
    "i_sdk_megadata_upload_span": 5000,
    "i_sdk_moreWonderful_mode": 0,
    "i_sdk_moregame_mode": 1,
    "i_sdk_native_autoRefresh_intervals": 30,
    "i_sdk_native_autoRefresh_mode": 0,
    "i_sdk_native_valid_show_count": 2,
    "i_sdk_oppoqg_ad_ecd": 0,
    "i_sdk_oppoqg_banner_mode": 0,
    "i_sdk_oppoqg_jump_game_reward_time": 20000,
    "i_sdk_oppoqg_not_show_banner_after_user_close_count_limit": 5,
    "i_sdk_pay_mode": 0,
    "i_sdk_phone_vibrate": 0,
    "i_sdk_sdk_rank_mode": 0,
    "i_sdk_share_mode": 0,
    "i_sdk_subscribe_mode": 1,
    "i_sdk_support_open_url": 0,
    "i_sdk_support_record_share": 1,
    "i_sdk_trim_adv_err_switch": 1,
    "layaVersion": "2.8",
    "n_sdk_adv_video_complete_mode": 1,
    "n_sdk_common_online_time_report_looper_interval": 60,
    "nodejsExePath": "nodejs16.15.1/node.exe",
    "nodejsGitAddr": "ude2/prj.ulnodejs",
    "nodejsGitBranch": "v1",
    "resProcessScriptPath": "",
    "s_game_name": "珠珠装扮物语",
    "s_game_orientation": "portrait",
    "s_prj_name": "prj.game117v5",
    "s_sdk_adv_info": {
        "1": {
            "group": [
                "1"
            ],
            "type": "interstitial"
        },
        "2": {
            "group": [
                "2"
            ],
            "type": "banner"
        },
        "3": {
            "group": [
                "3"
            ],
            "type": "embedded"
        },
        "4": {
            "group": [
                "4"
            ],
            "type": "video"
        },
        "5": {
            "group": [
                "5"
            ],
            "type": "url"
        }
    },
    "s_sdk_age_level_info": "游戏中有实名认证系统，认证为未成年人的用户将接受以下管理：未满8周岁的用户不能充值；8周岁以上未满16周岁的未成年人用户，单次充值金额不得超过50元人民币，每月充值金额累计不得超过200元人民币；16周岁以上的未成年人用户，单次充值金额不得超过100元人民币，每月充值金额累计不得超过400元人民币。未成年人用户可以在周五、周六、周日和法定节假日每日晚20时至21时期间登录游戏，其他时间内无法登录游戏。",
    "s_sdk_cdk_app_id": "0",
    "s_sdk_cdk_url": "https://cdkey.ultralisk.cn/commoncdk/usecdk",
    "s_sdk_cocos2x_rootNode_check": "",
    "s_sdk_common_affiche_title": "最新公告",
    "s_sdk_common_affiche_url": "",
    "s_sdk_common_checktime_url": "https://copv7.ultralisk.cn/getservertime",
    "s_sdk_common_copyright_str": "",
    "s_sdk_common_login_url": "https://sdkserver.ultralisk.cn/userlogin",
    "s_sdk_common_online_pay_url": "https://sdkpay.ultralisk.cn",
    "s_sdk_cop_addr": "https://copv7.ultralisk.cn/h5/getdata/",
    "s_sdk_cop_game_id": "281",
    "s_sdk_jump_game_statis_game_indexes": "",
    "s_sdk_lan_debug_address": "",
    "s_sdk_megadata_close_table_type_ids": "",
    "s_sdk_megadata_game_id": "624",
    "s_sdk_megadata_server_jump_game_type_id": "jumpabtest",
    "s_sdk_megadata_server_type_id": "624",
    "s_sdk_megadata_test_url": "https://megadatav7.ultralisk.cn/batchtestmodedataupload",
    "s_sdk_megadata_url": "https://megadatav7.ultralisk.cn/batchdataupload",
    "s_sdk_oppoqg_app_key": "53X8N1lUb4g8KCG0wcw40o0wg",
    "s_sdk_oppoqg_appid": "31394653",
    "s_sdk_oppoqg_appsecret": "60A22B0c45f86Fa2a8752fbd29d93F7b",
    "s_sdk_oppoqg_minPlatform_version": "1056",
    "s_sdk_oppoqg_package_name": "com.ultralisk.game117v5.nearme.gamecenter",
    "s_sdk_oppoqg_preOrder_online_url": "https://sdkpay.ultralisk.cn/preorder",
    "s_sdk_oppoqg_pre_order_url": "https://jits.open.oppomobile.com/jitsopen/api/pay/v1.0/preOrder",
    "s_sdk_oppoqg_private_key": "-----BEGINRSAPRIVATEKEY-----MIICXgIBAAKBgQC46Giy1S4Zuys/c3QO6VZVWAOo1tussbIpqI0M7edU9OC732leFej2DmG3O9XRh9NlYjoAq4hyt7DxiZ6MyN8IdStZn4b0/e/CZKQA5WaCI5h71hUTwCJTzHZHvO+woDWaE2mOSsBfjAdwTsHUr32eCPzju/1zatys02W7ai4v+wIDAQABAoGAGjbAmRHF3ln9kJpCitajqae3pRkIvZvXgTZnAL09fXrV3WyX2IHMrA1v5vUxo+nYm1foly26Q2EtUaDL/HOBwshbwEtR5TR0g+kZBpA+S4wt/ujZPlALmZiGuQjjqwWFo9OfeskXer7vA5UWYemDMvy7XQ2TWoLNOzI+LaVvEPECQQDpEgY7XmrKeq8qkUFPsDjcEa7SZ2eEEOps0NKmewGvAaiavm7+8yCdS/ZPS7ZD6590TanFWy3gJtugw/vPa2tpAkEAyxlj8u+EYKchPBYehuRjm4W5SlJNAGrABqrJjM50jQ4aRVr1LbS6R0S77kTaZLTV/w8eYk1LS9cTCaY+JB+HwwJBAIXrlmscmG4ZynbCGe4JCtLg0jwRsHhBJAI8hx2jxlbhtBieXbbeypm3YSM1FNi4FdpFGczN1HFcwowAsLsBNSkCQQC9YgywQKYI1m+ILvwCPr+fCt/PrNS+mcw7q0/Lq8xEp6zZlUpgd1DoGfC/6pZXJ8UQVFG5ymd27bOD4O+7EWevAkEAzYHfclV/kP3V1aCR0KoXBHA4WIHKa+JaVuFMIDZqd/SsfsoKDn+Stsajl/e8LAwt9XXctYWNvGsVfCSfZ5Y3tw==-----ENDRSAPRIVATEKEY-----",
    "s_sdk_oppoqg_tiny_package_server": "https://gamesres.ultralisk.cn/h5_games_res/game117v5/oppoqg/v1",
    "s_sdk_oppoqg_version_code": "101",
    "s_sdk_oppoqg_version_name": "1.0.1",
    "s_sdk_user_data_get_url": "https://h5gameserver.ultralisk.cn/getuserdata",
    "s_sdk_user_data_save_url": "https://h5gameserver.ultralisk.cn/savealluserdata",
    "s_sdk_version": "be0ed2d81",
    "srcRootPath": "src/script/",
    "t_customer_service_info": [
        "kefu@ultralisk.cn"
    ],
    "t_sdk_adv_banner_tags_style_setting": {
        
    },
    "t_sdk_adv_custom_args_style_setting": {
        
    },
    "t_sdk_common_event_ids": {
        "add_subscrible": "102",
        "click_more_game_channel_system_button": "108",
        "click_more_game_icon_list": "106",
        "click_more_game_icon_reward": "105",
        "click_more_game_icon_single": "104",
        "click_share": "101",
        "click_subscrible": "103",
        "open_cdk": "107",
        "open_share": "100"
    },
    "t_sdk_common_modify_tag_afterBuild": [
        
    ],
    "t_sdk_common_modify_tag_beforeBuild": [
        
    ],
    "t_sdk_compress_json_includes": [
        
    ],
    "t_sdk_compress_json_includes_rem": "",
    "t_sdk_compress_res_config": [
        {
            "cmds": "jpeg-recompress --strip -t 0.4 --min 80 | guetzil --quality 85",
            "rep": ".*//.jpg"
        },
        {
            "cmds": "autopng --quality 40-80 | optipng -strip all -o7 | zopflipng -y --lossy_8bit --lossy_transparent",
            "rep": ".*//.png"
        }
    ],
    "t_sdk_cop_default_cop": {
        
    },
    "t_sdk_cop_simulate_city_data": {
        "0": "未知城市",
        "1001": "海南藏族自治州",
        "1002": "西宁",
        "1003": "海东",
        "1004": "黄南藏族自治州",
        "1005": "海西蒙古族藏族自治州",
        "1006": "海北藏族自治州",
        "1007": "果洛藏族自治州",
        "1008": "玉树藏族自治州",
        "101": "北京",
        "1101": "临夏回族自治州",
        "1102": "甘南藏族自治州",
        "1103": "白银",
        "1104": "陇南",
        "1105": "定西",
        "1106": "平凉",
        "1107": "金昌",
        "1108": "酒泉",
        "1109": "张掖",
        "1110": "庆阳",
        "1111": "兰州",
        "1112": "武威",
        "1113": "嘉峪关",
        "1114": "天水",
        "1201": "银川",
        "1202": "固原",
        "1203": "吴忠",
        "1204": "中卫",
        "1205": "石嘴山",
        "1301": "商洛",
        "1302": "安康",
        "1303": "榆林",
        "1304": "铜川",
        "1305": "咸阳",
        "1306": "西安",
        "1307": "渭南",
        "1308": "汉中",
        "1309": "宝鸡",
        "1310": "延安",
        "1401": "长春",
        "1402": "白城",
        "1403": "松原",
        "1404": "白山",
        "1405": "吉林",
        "1406": "延边朝鲜族自治州",
        "1407": "四平",
        "1408": "辽源",
        "1409": "通化",
        "1501": "铜陵",
        "1502": "亳州",
        "1503": "黄山",
        "1504": "池州",
        "1505": "合肥",
        "1506": "淮北",
        "1507": "滁州",
        "1508": "宿州",
        "1509": "淮南",
        "1510": "蚌埠",
        "1511": "六安",
        "1512": "阜阳",
        "1513": "芜湖",
        "1514": "宣城",
        "1515": "安庆",
        "1516": "马鞍山",
        "1601": "恩施土家族苗族自治州",
        "1602": "仙桃",
        "1603": "武汉",
        "1604": "孝感",
        "1605": "咸宁",
        "1606": "十堰",
        "1607": "天门",
        "1608": "黄冈",
        "1609": "宜昌",
        "1610": "襄阳",
        "1611": "黄石",
        "1612": "荆门",
        "1613": "随州",
        "1614": "荆州",
        "1615": "鄂州",
        "1616": "神农架林区",
        "1617": "潜江",
        "1701": "株洲",
        "1702": "邵阳",
        "1703": "岳阳",
        "1704": "张家界",
        "1705": "怀化",
        "1706": "衡阳",
        "1707": "长沙",
        "1708": "常德",
        "1709": "郴州",
        "1710": "永州",
        "1711": "湘西土家族苗族自治州",
        "1712": "湘潭",
        "1713": "益阳",
        "1714": "娄底",
        "1801": "安顺",
        "1802": "黔南布依族苗族自治州",
        "1803": "铜仁",
        "1804": "六盘水",
        "1805": "贵阳",
        "1806": "黔东南苗族侗族自治州",
        "1807": "毕节",
        "1808": "遵义",
        "1809": "黔西南布依族苗族自治州",
        "1901": "太原",
        "1902": "长治",
        "1903": "运城",
        "1904": "晋中",
        "1905": "忻州",
        "1906": "朔州",
        "1907": "晋城",
        "1908": "阳泉",
        "1909": "大同",
        "1910": "临汾",
        "1911": "吕梁",
        "2001": "来宾",
        "2002": "柳州",
        "2003": "崇左",
        "2004": "百色",
        "2005": "河池",
        "2006": "防城港",
        "2007": "贺州",
        "2008": "贵港",
        "2009": "北海",
        "201": "上海",
        "2010": "南宁",
        "2011": "桂林",
        "2012": "玉林",
        "2013": "钦州",
        "2014": "梧州",
        "2101": "凉山彝族自治州",
        "2102": "攀枝花",
        "2103": "乐山",
        "2104": "遂宁",
        "2105": "资阳",
        "2106": "绵阳",
        "2107": "自贡",
        "2108": "德阳",
        "2109": "雅安",
        "2110": "达州",
        "2111": "广元",
        "2112": "广安",
        "2113": "阿坝藏族羌族自治州",
        "2114": "甘孜藏族自治州",
        "2115": "成都",
        "2116": "南充",
        "2117": "泸州",
        "2118": "内江",
        "2119": "宜宾",
        "2120": "巴中",
        "2121": "眉山",
        "2201": "郑州",
        "2202": "三门峡",
        "2203": "洛阳",
        "2204": "开封",
        "2205": "信阳",
        "2206": "焦作",
        "2207": "许昌",
        "2208": "濮阳",
        "2209": "济源",
        "2210": "鹤壁",
        "2211": "安阳",
        "2212": "驻马店",
        "2213": "新乡",
        "2214": "南阳",
        "2215": "漯河",
        "2216": "平顶山",
        "2217": "商丘",
        "2218": "周口",
        "2301": "石家庄",
        "2302": "保定",
        "2303": "沧州",
        "2304": "衡水",
        "2305": "唐山",
        "2306": "邯郸",
        "2307": "廊坊",
        "2308": "秦皇岛",
        "2309": "邢台",
        "2310": "张家口",
        "2311": "承德",
        "2401": "福州",
        "2402": "厦门",
        "2403": "宁德",
        "2404": "莆田",
        "2405": "龙岩",
        "2406": "三明",
        "2407": "南平",
        "2408": "泉州",
        "2409": "漳州",
        "2501": "南昌",
        "2502": "上饶",
        "2503": "赣州",
        "2504": "新余",
        "2505": "鹰潭",
        "2506": "抚州",
        "2507": "萍乡",
        "2508": "宜春",
        "2509": "景德镇",
        "2510": "吉安",
        "2511": "九江",
        "2601": "珠海",
        "2602": "东莞",
        "2603": "江门",
        "2604": "阳江",
        "2605": "惠州",
        "2606": "汕尾",
        "2607": "梅州",
        "2608": "清远",
        "2609": "湛江",
        "2610": "揭阳",
        "2611": "广州",
        "2612": "云浮",
        "2613": "潮州",
        "2614": "汕头",
        "2615": "韶关",
        "2616": "深圳",
        "2617": "佛山",
        "2618": "中山",
        "2619": "肇庆",
        "2620": "茂名",
        "2621": "河源",
        "2701": "呼和浩特",
        "2702": "锡林郭勒盟",
        "2703": "乌兰察布",
        "2704": "通辽",
        "2705": "包头",
        "2706": "阿拉善盟",
        "2707": "巴彦淖尔",
        "2708": "兴安盟",
        "2709": "鄂尔多斯",
        "2710": "乌海",
        "2711": "呼伦贝尔",
        "2712": "赤峰",
        "2801": "鹤岗",
        "2802": "鸡西",
        "2803": "哈尔滨",
        "2804": "黑河",
        "2805": "七台河",
        "2806": "伊春",
        "2807": "大兴安岭地区",
        "2808": "牡丹江",
        "2809": "绥化",
        "2810": "齐齐哈尔",
        "2811": "双鸭山",
        "2812": "大庆",
        "2813": "佳木斯",
        "2901": "葫芦岛",
        "2902": "营口",
        "2903": "丹东",
        "2904": "沈阳",
        "2905": "抚顺",
        "2906": "辽阳",
        "2907": "大连",
        "2908": "鞍山",
        "2909": "盘锦",
        "2910": "阜新",
        "2911": "本溪",
        "2912": "锦州",
        "2913": "铁岭",
        "2914": "朝阳",
        "3001": "淄博",
        "3002": "临沂",
        "3003": "威海",
        "3004": "莱芜",
        "3005": "日照",
        "3006": "济南",
        "3007": "泰安",
        "3008": "烟台",
        "3009": "聊城",
        "301": "天津",
        "3010": "东营",
        "3011": "菏泽",
        "3012": "滨州",
        "3013": "潍坊",
        "3014": "德州",
        "3015": "青岛",
        "3016": "济宁",
        "3017": "枣庄",
        "3101": "南京",
        "3102": "常州",
        "3103": "苏州",
        "3104": "无锡",
        "3105": "盐城",
        "3106": "镇江",
        "3107": "连云港",
        "3108": "宿迁",
        "3109": "南通",
        "3110": "徐州",
        "3111": "淮安",
        "3112": "扬州",
        "3113": "泰州",
        "401": "重庆",
        "501": "宁波",
        "502": "金华",
        "503": "嘉兴",
        "504": "绍兴",
        "505": "湖州",
        "506": "衢州",
        "507": "舟山",
        "508": "杭州",
        "509": "温州",
        "510": "丽水",
        "511": "台州",
        "601": "儋州",
        "602": "定安县",
        "603": "东方",
        "604": "五指山",
        "605": "屯昌县",
        "606": "琼海",
        "607": "澄迈县",
        "608": "琼中黎族苗族自治县",
        "609": "三亚",
        "610": "白沙黎族自治县",
        "611": "文昌",
        "612": "陵水黎族自治县",
        "613": "昌江黎族自治县",
        "614": "保亭黎族苗族自治县",
        "615": "临高县",
        "616": "海口",
        "617": "万宁",
        "618": "乐东黎族自治县",
        "701": "迪庆藏族自治州",
        "702": "西双版纳傣族自治州",
        "703": "临沧",
        "704": "保山",
        "705": "玉溪",
        "706": "德宏傣族景颇族自治州",
        "707": "红河哈尼族彝族自治州",
        "708": "大理白族自治州",
        "709": "丽江",
        "710": "怒江傈僳族自治州",
        "711": "普洱",
        "712": "楚雄彝族自治州",
        "713": "文山壮族苗族自治州",
        "714": "昆明",
        "715": "曲靖",
        "716": "昭通",
        "801": "拉萨",
        "802": "昌都",
        "803": "山南",
        "804": "阿里地区",
        "805": "林芝",
        "806": "日喀则",
        "807": "那曲地区",
        "901": "喀什地区",
        "902": "阿克苏地区",
        "903": "和田地区",
        "904": "哈密",
        "905": "石河子",
        "906": "吐鲁番",
        "907": "博尔塔拉蒙古自治州",
        "908": "巴音郭楞蒙古自治州",
        "909": "昌吉回族自治州",
        "910": "塔城地区",
        "911": "克孜勒苏柯尔克孜自治州",
        "912": "阿勒泰地区",
        "913": "乌鲁木齐",
        "914": "克拉玛依",
        "915": "伊犁哈萨克自治州"
    },
    "t_sdk_cop_strategy_setting": {
        
    },
    "t_sdk_exempt_advType_limit_arrays": [
        
    ],
    "t_sdk_mutuallyExclusive_advType_setting": {
        
    },
    "t_sdk_oppoqg_adv_tag_2_native_index": {
        
    },
    "t_sdk_oppoqg_custom_adv_setting": {
        
    },
    "t_sdk_oppoqg_jump_games": [
        
    ],
    "t_sdk_oppoqg_native_index_2_native_id": {
        
    },
    "t_sdk_oppoqg_pay_code": {
        
    },
    "t_sdk_oppoqg_show_banner_box_adv_tags": {
        
    },
    "t_sdk_oppoqg_show_drawer_box_adv_tags": {
        
    },
    "t_sdk_oppoqg_show_inter_box_adv_tags": [
        
    ],
    "t_sdk_privacyPolicy_dataArray": [
        {
            "name": "隐私政策",
            "url": "https://gamesres.ultralisk.cn/notice/policy/oppojiayoupolicy.json"
        }
    ],
    "t_sdk_record_duration_limit_object": {
        "*": {
            "max": 300,
            "min": 3
        },
        "2": {
            "max": 300,
            "min": 15
        }
    },
    "t_sdk_show_native_banner_autoRefresh_tags": [
        
    ],
    "t_sdk_show_native_banner_autoRefresh_tags_style_setting": {
        
    },
    "t_sdk_trim_adv_err_object": {
        "*": "广告播放失败了，重新试试看吧！",
        "baidu": {
            "code": {
                "3010003": "您的网络好像不够流畅，请更换到良好的网络环境再播放广告。",
                "3010005||3010006": "正在为您播放广告，请稍等一会儿，不要重复点击。"
            }
        },
        "headline||weixin||qq": {
            "code": {
                "1004": "暂时没有适合您观看的广告，请稍等一会儿再试吧！"
            }
        },
        "oppoqg": {
            "(this.code==1001 || this.code == 1004)&&msg": {
                "/10001/||/10100/||/10101/||/10403/": "您的网络好像不够流畅，请更换到良好的网络环境再播放广告。",
                "/10405/": "您的操作系统版本太低，不能播放广告。",
                "/10406/": "需要连接到 Wifi 网络",
                "/11002/": "这个广告只能在OPPO手机上播放，请确认您的机型。",
                "/11003/": "暂时无法播放广告，请稍等一会儿再试吧1！"
            }
        },
        "vivo": {
            "code": {
                "-100||101||500": "您的网络好像不够流畅，请更换到良好的网络环境再播放广告。",
                "-3||108||30005": "暂时无法播放广告，请稍等一会儿再试吧！",
                "30007": "暂时无法播放广告，请稍等一会儿再试吧！",
                "30010": "广告播放失败了，可能是是由于您经常关闭广告造成的，稍等一会儿再试吧。"
            }
        }
    },
    "targetCreatorBranch": "",
    "targetCreatorExePath": "",
    "targetCreatorGitAddr": "",
    "targetCreatorToolGitAddr": "ude2/prj.ulcocoscreator_tools3.x",
    "targetCreatorToolGitBranch": "v2",
    "targetProjectBranch": "v1_h5_release",
    "targetProjectGitAddr": "ude2/prj.game117",
    "targetProjectPath": "_publish/h5_release/proj.h5",
    "tempCreatorProjectPaths": [
        [
            ".laya/",
            ".laya/"
        ],
        [
            "bin/",
            "bin/",
            [
                "**/vconsole.*"
            ]
        ],
        [
            "declare/",
            "declare/"
        ],
        [
            "laya/",
            "laya/"
        ],
        [
            "libs/",
            "libs/"
        ],
        [
            "node_modules/",
            "node_modules/"
        ],
        [
            "src/",
            "src/"
        ],
        [
            "package-lock.json",
            ""
        ],
        [
            "prj.game117.laya",
            ""
        ],
        [
            "tsconfig.json",
            ""
        ]
    ],
    "tempProjectName": "laya_proj",
    "autoUploadPack": true,
    "B_SHOW_LICENCE_INFO_ON_LOADING": false,
    "a_sdk_obfuscator_includes": [
        "**/bundle*.js",
        "**/project*.js",
        "**/index*.js",
        "**/ulsdk*.js",
        "**/settings*.js"
    ],
    "b_sdk_obfuscator_mode": false,
    "build_laya_oppogame_module_config": {
        "bAutoUploadEnabled": true,
        "bNakedPackage": true,
        "compressJs": false,
        "nakedPackageSearchKeys": [
            "res/cfg/",
            "res/scene/vLoadingScene.json"
        ],
        "oppoInfo": {
            "logLevel": "off",
            "name": "珠珠装扮物语",
            "package": "com.ultralisk.game117v5.nearme.gamecenter",
            "versionCode": "101",
            "versionName": "1.0.1"
        },
        "title": "珠珠装扮物语",
        "url_path": "https://gamesres.ultralisk.cn/h5_games_res/game117v5/oppoqg/v1",
        "useMinJsLibs": false
    },
    "i_sdk_licence_info_mode": 1,
    "i_sdk_start_game_by_touch": 1,
    "o_sdk_obfuscator_config": {
        
    },
    "s_sdk_cop_channel_id": "146",
    "s_sdk_cop_version": "28361",
    "s_sdk_licence_info": "",
    "t_sdk_increment_fields": [
        "s_sdk_oppoqg_version_code",
        "s_sdk_oppoqg_version_name"
    ],
    "_target_project_branch": "v1_h5_release",
    "_target_project_log": "2023-11-07 14:56:32 +0800-lijiaxun-f52eba3c3d",
    "_target_last_commit_time": 1699340192,
    "prjVersion": "f52eba3c3d",
    "rootPath": "D:/ulwork/ulsdk/",
    "rootSdkPath": "D:/ulwork/ulsdk/prj.sdk.html5/",
    "gitRepoPath": "D:/ulwork/ulsdk/h5_games_res/",
    "taskDate": "2023_11_08",
    "taskTick": "2023_11_08_10_07_47",
    "taskTickShort": "1108_100747",
    "taskName": "oppo",
    "configName": "task_game117v5-zzzbwy_v5",
    "targetPath": "D:/ulwork/ulsdk/h5_out/v5_oppo_1108_100747/",
    "resCachePath": "D:/ulwork/ulsdk/h5_res_cache/prj.game117v5/",
    "packagePath": "D:/ulwork/ulsdk/prj.games.html5.channels.packages/prj.game117v5/prj.game117v5_v1_h5_release_oppo_1108_100747/",
    "buildDisabled": false,
    "creatorExePath": "",
    "nodejsExeAbsPath": "D:/ulwork/ude2/prj.ulnodejs/nodejs16.15.1/node.exe",
    "taskJsonPath": "D:/ulwork/ulsdk/prj.games.html5.channels.tasks/task_game117v5-zzzbwy_v5/task.json",
    "buildTempPath": "D://ulwork//ulsdk//prj.sdk.html5//build_system//build_gradle/../../../h5_out/build_temp/",
    "envCheckResult": [
        
    ],
    "tempProjPath": "D:/ulwork/ulsdk/h5_out/v5_oppo_1108_100747/laya_proj/",
    "moduleList": "common,build_laya_oppogame,oppoqg,privacyPolicy"
}`);

        class ULTimer {
            constructor(span, repeatCount, callback) {
                this._repeatCount = -1;
                this._span = 1;
                this._callback = null;
                this._intervalId = null;
                this._count = 0;
                this._beginTime = -1;
                this._usedTime = 0;
                this._span = span;
                this._repeatCount = repeatCount;
                this._callback = callback;
            }
            static callLater(span, callback) {
                let timer = new ULTimer(span, 1, callback);
                timer.start();
            }
            static callLoop(span, callback) {
                let timer = new ULTimer(span, -1, callback);
                timer.start();
            }
            _onSpan() {
                this._count++;
                this._usedTime = ULTools.time() - this._beginTime;
                if (this._callback) {
                    try {
                        this._callback(this);
                    }
                    catch (error) {
                        ULLog.console.warn("警告] ULTimer._onSpan callback has error", error);
                    }
                }
                if (this._repeatCount >= 0 && this._count >= this._repeatCount) {
                    this.stop();
                }
            }
            isRunning() {
                return this._intervalId != null;
            }
            get count() {
                return this._count;
            }
            get span() {
                return this._span;
            }
            get usedTime() {
                return this._usedTime;
            }
            start() {
                this.stop();
                if (!this._callback) {
                    ULLog.console.warn("警告] ULTimer.start callback未设置！");
                    return this;
                }
                this._beginTime = ULTools.time();
                this._count = 0;
                this._intervalId = setInterval(this._onSpan.bind(this), this.span * 1000);
                return this;
            }
            stop() {
                if (this._intervalId != null) {
                    clearInterval(this._intervalId);
                    this._intervalId = null;
                }
                return this;
            }
        }

        class ULStorageManager {
            constructor() {
                this.cacheStorage = {};
            }
            static getInstance() {
                if (!this._instance) {
                    this._instance = new ULStorageManager();
                }
                return this._instance;
            }
            getStorage(key) {
                let returnValue = ULEventDispatcher.getInstance().dispatchWithReturn(ULConst.CMD_SDK_GET_STORAGE, { key: key });
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log(ULTools.format("ULStorageManager.getStorage(%s) => [%s]", key, returnValue));
                if (returnValue == null) {
                    returnValue = this.cacheStorage[key];
                }
                else {
                    this.cacheStorage[key] = returnValue;
                }
                return returnValue;
            }
            setStorage(key, data) {
                this.cacheStorage[key] = data;
                let bCalled = ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_SET_STORAGE, { key: key, data: data });
                if (!bCalled) {
                    ULLog.console.warn("ULStorageManager.setStorage 未找到实现！");
                }
            }
        }
        ULStorageManager._instance = null;

        class ULWebSocket {
            constructor(url) {
                this.socketingWS = null;
                this.isOpening = false;
                this.socketMsgCache = [];
                this._isAutoClearCache = false;
                if ("WebSocket" in window) {
                    var address = url;
                    var ws = new WebSocket(address);
                    this.socketingWS = ws;
                    let self = this;
                    ws.onopen = function (ev) {
                        self.isOpening = true;
                        self.onopen(ev);
                    };
                    ws.onmessage = function (evt) {
                        self.onmessage(evt);
                    };
                    ws.onclose = function (evt) {
                        self.isOpening = false;
                        self.socketingWS = null;
                        self.socketMsgCache = [];
                        self.onclose(evt);
                    };
                    ws.onerror = function (err) {
                        self.isOpening = false;
                        self.socketingWS = null;
                        self.socketMsgCache = [];
                        self.onerror(err);
                    };
                }
            }
            set isAutoClearCache(value) {
                if (value == this._isAutoClearCache) {
                    return;
                }
                this._isAutoClearCache = value;
                if (this._isAutoClearCache) {
                    this.intervalId = setInterval(() => {
                        this.clearCache();
                    }, 30);
                }
                else {
                    clearInterval(this.intervalId);
                }
            }
            close(code, reason) {
                if (this.isOpening && this.socketingWS) {
                    this.socketingWS.close();
                    this.isOpening = false;
                    this.socketingWS = null;
                }
            }
            send(msg) {
                if (!this.socketingWS) {
                    return;
                }
                let ietm = null;
                try {
                    ietm = JSON.stringify(msg);
                }
                catch (error) {
                    ietm = JSON.stringify({
                        type: 3,
                        data: error
                    });
                }
                finally {
                    if (!this.isOpening || this._isAutoClearCache) {
                        this.socketMsgCache.push(ietm);
                        this.isAutoClearCache = true;
                    }
                    else {
                        this.socketingWS.send(ietm);
                    }
                }
            }
            clearCache() {
                if (!this.socketingWS || !this.socketMsgCache.length) {
                    this.isAutoClearCache = false;
                    return;
                }
                if (this.isOpening) {
                    let item = this.socketMsgCache.shift();
                    this.socketingWS.send(item);
                }
            }
        }

        class ULTools {
            static time() {
                let time = new Date().getTime() / 1000;
                return time;
            }
            static timeInDay() {
                let time = this.time();
                let todayBeginDate = new Date(time * 1000);
                todayBeginDate.setHours(0);
                todayBeginDate.setMinutes(0);
                todayBeginDate.setSeconds(0);
                todayBeginDate.setMilliseconds(0);
                let todayBeginTime = todayBeginDate.getTime() / 1000;
                return time - todayBeginTime;
            }
            static timeDay(time = this.time()) {
                let todayBeginDate = new Date(time * 1000);
                todayBeginDate.setHours(0);
                todayBeginDate.setMinutes(0);
                todayBeginDate.setSeconds(0);
                todayBeginDate.setMilliseconds(0);
                let todayBeginTime = todayBeginDate.getTime() / 1000;
                return todayBeginTime;
            }
            static timeDayHour(hours = 0, minutes = 0, seconds = 0) {
                let todayBeginDate = new Date();
                todayBeginDate.setHours(hours);
                todayBeginDate.setMinutes(minutes);
                todayBeginDate.setSeconds(seconds);
                todayBeginDate.setMilliseconds(0);
                let todayBeginTime = todayBeginDate.getTime() / 1000;
                if (this.time() > todayBeginTime) {
                    todayBeginTime += 60 * 60 * 24;
                }
                return todayBeginTime;
            }
            static isOneDay(seconds1, seconds2) {
                var d1 = new Date(seconds1 * 1000);
                var d2 = new Date(seconds2 * 1000);
                return d1.getFullYear() == d2.getFullYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate();
            }
            static isOneMonth(seconds1, seconds2) {
                var d1 = new Date(seconds1 * 1000);
                var d2 = new Date(seconds2 * 1000);
                return d1.getFullYear() == d2.getFullYear() && d1.getMonth() == d2.getMonth();
            }
            static getObjSize(obj) {
                if (!obj) {
                    return 0;
                }
                if (Array.isArray(obj)) {
                    return obj.length;
                }
                let count = 0;
                this.forEachMap(obj, (k, v) => {
                    count++;
                });
                return count;
            }
            static parseUrl(url) {
                var r = {
                    protocol: /([^\/]+:)\/\/(.*)/i,
                    host: /(^[^\:\/]+)((?:\/|:|$)?.*)/,
                    port: /\:?([^\/]*)(\/?.*)/,
                    pathname: /([^\?#]+)(\??[^#]*)(#?.*)/
                };
                var tmp = {};
                var res = {
                    href: url,
                    protocol: "",
                    host: "",
                    port: "",
                    pathname: "",
                    search: "",
                    hash: ""
                };
                for (let p in r) {
                    tmp = r[p].exec(url);
                    res[p] = tmp[1];
                    url = tmp[2];
                    if (url === "") {
                        url = "/";
                    }
                    if (p === "pathname") {
                        res.pathname = tmp[1];
                        res.search = tmp[2];
                        res.hash = tmp[3];
                    }
                }
                return res;
            }
            static random(min, max) {
                if (min == null && max == null) {
                    return Math.random();
                }
                else if (max == null) {
                    return Math.floor(Math.random() * min + 1);
                }
                else {
                    return Math.floor(Math.random() * (max - min + 1) + min);
                }
            }
            static scaleInRange(n, ia, ib, oa, ob) {
                if (ia < ib) {
                    if (n < ia)
                        n = ia;
                    if (n > ib)
                        n = ib;
                }
                else {
                    if (n < ib)
                        n = ib;
                    if (n > ia)
                        n = ia;
                }
                let iDistance = ib - ia;
                let oDistance = ob - oa;
                return (n - ia) / iDistance * oDistance + oa;
            }
            static clampf(n, min, max) {
                if (n < min)
                    return min;
                if (n > max)
                    return max;
                return n;
            }
            static calcWheelTarget(arr, weightKey) {
                let totalWeight = 0;
                for (let i = 0; i < arr.length; i++) {
                    const v = arr[i];
                    let w = parseInt(v[weightKey]);
                    if (isNaN(w)) {
                        ULLog.console.warn(this.format("Tools.calcWheelTarget weight field not found! key=[%s]", weightKey));
                        return null;
                    }
                    totalWeight += w;
                }
                let rw = this.random(totalWeight);
                for (let i = 0; i < arr.length; i++) {
                    const v = arr[i];
                    let w = parseInt(v[weightKey]);
                    if (rw <= w) {
                        return v;
                    }
                    else {
                        rw -= w;
                    }
                }
                return null;
            }
            static sortArrayByField(array, fields) {
                if (typeof (fields) == "string") {
                    fields = [fields];
                }
                else {
                    fields = fields;
                }
                let fieldConfig = [];
                for (let k in fields) {
                    let v = fields[k];
                    if (v && v != "") {
                        if (v.substring(0, 1) === "-") {
                            let tmpField = v.substring(1, v.length);
                            if (tmpField && tmpField != "") {
                                fieldConfig.push([tmpField, true]);
                            }
                        }
                        else {
                            fieldConfig.push([v, false]);
                        }
                    }
                }
                let sorter = (a, b) => {
                    let ret = 0;
                    for (let k in fieldConfig) {
                        let v = fieldConfig[k];
                        let field = v[0];
                        let desc = v[1];
                        let v1 = a[field];
                        let v2 = b[field];
                        if (v1 != null) {
                            if (desc) {
                                ret = v2 - v1;
                            }
                            else {
                                ret = v1 - v2;
                            }
                            if (ret != 0) {
                                return ret;
                            }
                        }
                    }
                    return ret;
                };
                let sorted = [];
                for (let i = 0; i < array.length; i++) {
                    const v = array[i];
                    sorted.push(v);
                }
                sorted.sort(sorter);
                return sorted;
            }
            static bubbleSort(arr, sorter) {
                var len = arr.length;
                for (var i = 0; i < len; i++) {
                    for (var j = 0; j < len - 1 - i; j++) {
                        let ret = sorter(arr[j], arr[j + 1]);
                        if (ret > 0) {
                            var temp = arr[j + 1];
                            arr[j + 1] = arr[j];
                            arr[j] = temp;
                        }
                    }
                }
                return arr;
            }
            static forEachMap(map, callback) {
                if (!map)
                    return;
                let keys = Object.keys(map);
                for (let i = 0; i < keys.length; i++) {
                    let key = keys[i];
                    let value = map[key];
                    if (value != null) {
                        if (callback(key, value))
                            break;
                    }
                }
            }
            static formatTime(time, format) {
                let hour = Math.floor(time / 3600);
                let minute = Math.floor(time / 60) % 60;
                let second = Math.ceil(time) % 60;
                if (format.match("%h")) {
                    format = format.replace("%h", hour.toString());
                }
                if (format.match("%H")) {
                    format = format.replace("%H", this.format("%02d", hour));
                }
                if (format.match("%m")) {
                    format = format.replace("%m", minute.toString());
                }
                if (format.match("%M")) {
                    format = format.replace("%M", this.format("%02d", minute));
                }
                if (format.match("%s")) {
                    format = format.replace("%s", second.toString());
                }
                if (format.match("%S")) {
                    format = format.replace("%S", this.format("%02d", second));
                }
                return format;
            }
            static formatDate(date, format) {
                let o = {
                    "M+": date.getMonth() + 1,
                    "d+": date.getDate(),
                    "H+": date.getHours(),
                    "m+": date.getMinutes(),
                    "s+": date.getSeconds(),
                    "q+": Math.floor((date.getMonth() + 3) / 3),
                    "S+": date.getMilliseconds()
                };
                let fmt = format;
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(fmt)) {
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    }
                }
                return fmt;
            }
            static generateUUID() {
                let d = new Date().getTime();
                var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
                    var r = (d + Math.random() * 16) % 16 | 0;
                    d = Math.floor(d / 16);
                    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
                });
                return uuid;
            }
            ;
            static compressUuid(uuid) {
                let hexChars = "0123456789abcdef".split("");
                let hexMap = {};
                for (let i = 0; i < hexChars.length; i++) {
                    hexMap[hexChars[i]] = i;
                }
                let base64KeyToChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split("");
                let base64CharToKey = {};
                for (let i = 0; i < base64KeyToChars.length; i++) {
                    base64CharToKey[base64KeyToChars[i]] = i;
                }
                uuid = uuid.replace(/-/g, "");
                let arr = uuid.split("");
                let outArr = [];
                outArr.push(arr[0]);
                outArr.push(arr[1]);
                for (let i = 2; i < arr.length; i += 3) {
                    let hex1 = hexMap[arr[i]];
                    let hex2 = hexMap[arr[i + 1]];
                    let hex3 = hexMap[arr[i + 2]];
                    outArr.push(base64KeyToChars[(hex1 << 2) | (hex2 >> 2)]);
                    outArr.push(base64KeyToChars[((hex2 & 3) << 4) | hex3]);
                }
                return outArr.join("");
            }
            static decompressUuid(uuid) {
                let arr = uuid.split("");
                if (arr.length < 22)
                    return uuid;
                let hexChars = "0123456789abcdef".split("");
                let hexMap = {};
                for (let i = 0; i < hexChars.length; i++) {
                    hexMap[hexChars[i]] = i;
                }
                let base64KeyToChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split("");
                let base64CharToKey = {};
                for (let i = 0; i < base64KeyToChars.length; i++) {
                    base64CharToKey[base64KeyToChars[i]] = i;
                }
                let outArr = [];
                outArr.push(arr[0]);
                outArr.push(arr[1]);
                for (let i = 2; i < arr.length; i += 2) {
                    let lhs = base64CharToKey[arr[i]];
                    let rhs = base64CharToKey[arr[i + 1]];
                    outArr.push(hexChars[lhs >> 2]);
                    outArr.push(hexChars[((lhs & 3) << 2) | rhs >> 4]);
                    outArr.push(hexChars[rhs & 0xF]);
                }
                outArr.splice(8, 0, "-");
                outArr.splice(13, 0, "-");
                outArr.splice(18, 0, "-");
                outArr.splice(23, 0, "-");
                return outArr.join("");
            }
            static getType(obj) {
                let toString = Object.prototype.toString;
                let map = {
                    '[object Boolean]': 'boolean',
                    '[object Number]': 'number',
                    '[object String]': 'string',
                    '[object Function]': 'function',
                    '[object Array]': 'array',
                    '[object Date]': 'date',
                    '[object RegExp]': 'regExp',
                    '[object Undefined]': 'undefined',
                    '[object Null]': 'null',
                    '[object Object]': 'object'
                };
                return map[toString.call(obj)];
            }
            static clone(data) {
                let type = this.getType(data);
                let obj;
                if (window["cc"] && window["cc"].Node && data instanceof window["cc"].Node) {
                    return data;
                }
                else if (type === 'object') {
                    obj = {};
                }
                else if (type === 'array') {
                    obj = [];
                }
                else {
                    return data;
                }
                if (type === 'array') {
                    for (let i = 0, len = data["length"]; i < len; i++) {
                        obj.push(this.clone(data[i]));
                    }
                }
                else if (type === 'object') {
                    for (let key in data) {
                        obj[key] = this.clone(data[key]);
                    }
                }
                return obj;
            }
            static toArray(arr) {
                if (Array.isArray(arr))
                    return arr;
                return [];
            }
            static sumNumberArray(arr) {
                if (!Array.isArray(arr))
                    return 0;
                let sum = 0;
                for (let i = 0; i < arr.length; i++) {
                    const n = arr[i];
                    if (isNaN(n))
                        continue;
                    sum += n;
                }
                return sum;
            }
            static getRandomValueInArray(arr) {
                if (!Array.isArray(arr))
                    return null;
                return arr[this.random(arr.length) - 1];
            }
            static _convert(match, nosign) {
                if (nosign) {
                    match.sign = '';
                }
                else {
                    match.sign = match.negative ? '-' : match.sign;
                }
                var l = match.min - match.argument.length + 1 - match.sign.length;
                var pad = new Array(l < 0 ? 0 : l).join(match.pad);
                if (!match.left) {
                    if (match.pad == "0" || nosign) {
                        return match.sign + pad + match.argument;
                    }
                    else {
                        return pad + match.sign + match.argument;
                    }
                }
                else {
                    if (match.pad == "0" || nosign) {
                        return match.sign + match.argument + pad.replace(/0/g, ' ');
                    }
                    else {
                        return match.sign + match.argument + pad;
                    }
                }
            }
            static format(...args) {
                if (typeof arguments == "undefined") {
                    return null;
                }
                if (arguments.length < 1) {
                    return null;
                }
                if (typeof arguments[0] != "string") {
                    return null;
                }
                if (typeof RegExp == "undefined") {
                    return null;
                }
                var string = arguments[0];
                var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
                var matches = new Array();
                var strings = new Array();
                var convCount = 0;
                var stringPosStart = 0;
                var stringPosEnd = 0;
                var matchPosEnd = 0;
                var newString = '';
                var match = null;
                while (match = exp.exec(string)) {
                    if (match[9]) {
                        convCount += 1;
                    }
                    stringPosStart = matchPosEnd;
                    stringPosEnd = exp.lastIndex - match[0].length;
                    strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
                    matchPosEnd = exp.lastIndex;
                    matches[matches.length] = {
                        match: match[0],
                        left: match[3] ? true : false,
                        sign: match[4] || '',
                        pad: match[5] || ' ',
                        min: match[6] || 0,
                        precision: match[8],
                        code: match[9] || '%',
                        negative: parseInt(arguments[convCount]) < 0 ? true : false,
                        argument: String(arguments[convCount])
                    };
                }
                strings[strings.length] = string.substring(matchPosEnd);
                if (matches.length == 0) {
                    return string;
                }
                if ((arguments.length - 1) < convCount) {
                    return null;
                }
                var code = null;
                var match = null;
                var substitution = null;
                var i = null;
                for (i = 0; i < matches.length; i++) {
                    if (matches[i].code == '%') {
                        substitution = '%';
                    }
                    else if (matches[i].code == 'b') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
                        substitution = this._convert(matches[i], true);
                    }
                    else if (matches[i].code == 'c') {
                        matches[i].argument = String(String.fromCharCode(Math.abs(parseInt(matches[i].argument))));
                        substitution = this._convert(matches[i], true);
                    }
                    else if (matches[i].code == 'd') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
                        substitution = this._convert(matches[i]);
                    }
                    else if (matches[i].code == 'f') {
                        matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
                        substitution = this._convert(matches[i]);
                    }
                    else if (matches[i].code == 'o') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
                        substitution = this._convert(matches[i]);
                    }
                    else if (matches[i].code == 's') {
                        matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length);
                        substitution = this._convert(matches[i], true);
                    }
                    else if (matches[i].code == 'x') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                        substitution = this._convert(matches[i]);
                    }
                    else if (matches[i].code == 'X') {
                        matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
                        substitution = this._convert(matches[i]).toUpperCase();
                    }
                    else {
                        substitution = matches[i].match;
                    }
                    newString += strings[i];
                    newString += substitution;
                }
                newString += strings[i];
                return newString;
            }
            static httpGet(obj) {
    			return;
                let xhr = new XMLHttpRequest();
                let timeoutTimer = new ULTimer(obj.timeoutMillisecond / 1000, 1, (timer) => {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("timeout");
                    }
                });
                xhr.onreadystatechange = function (e) {
                    if (!xhr)
                        return;
                    if (xhr.readyState == 4) {
                        timeoutTimer.stop();
                        if (xhr.status == 200) {
                            let responseData = xhr.responseText;
                            if (obj.success instanceof Function)
                                obj.success(responseData);
                        }
                        else {
                            if (xhr) {
                                ULLog.console.warn("ULTools.httpGet on error:", xhr.readyState, xhr.status);
                                if (obj.fail instanceof Function)
                                    obj.fail(xhr.status.toString());
                                let temp = xhr;
                                xhr = null;
                                temp.abort();
                            }
                        }
                    }
                };
                xhr.ontimeout = function (e) {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("timeout");
                    }
                };
                xhr.onerror = function (e) {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("on error :" + e);
                    }
                };
                timeoutTimer.start();
                xhr.open('get', obj.url);
                xhr.send();
            }
            static httpGetJson(obj) {
                let arr = [];
                this.forEachMap(obj.params, (k, v) => {
                    arr.push(ULTools.format("%s=%s", encodeURIComponent(k), encodeURIComponent(v)));
                });
                let paramString = arr.join('&');
                let trimUrl = `${obj.url}?${paramString}`;
                ULLog.console.log("ULTools.httpGetJson trimUrl:", trimUrl);
                this.httpGet({
                    url: trimUrl,
                    timeoutMillisecond: obj.timeoutMillisecond,
                    success: obj.success,
                    fail: obj.fail
                });
            }
            static httpPost(obj) {
    			return;
                obj.contentType = obj.contentType || "application/x-www-form-urlencoded;charset=utf-8";
                let xhr = new XMLHttpRequest();
                let timeoutTimer = new ULTimer(obj.timeoutMillisecond / 1000, 1, (timer) => {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("timeout");
                    }
                });
                xhr.onreadystatechange = function (e) {
                    if (!xhr)
                        return;
                    if (xhr.readyState == 4) {
                        timeoutTimer.stop();
                        if (xhr.status == 200) {
                            let responseData = xhr.responseText;
                            if (obj.success instanceof Function)
                                obj.success(responseData);
                        }
                        else {
                            ULLog.console.warn("ULTools.httpPost on error:", xhr.readyState, xhr.status);
                            if (obj.fail instanceof Function)
                                obj.fail(xhr.status.toString());
                        }
                    }
                };
                xhr.ontimeout = function (e) {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("timeout");
                    }
                };
                xhr.onerror = function (e) {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("on error :" + e);
                    }
                };
                timeoutTimer.start();
                xhr.open('post', obj.url, true);
                xhr.setRequestHeader('Content-Type', obj.contentType);
                xhr.send(obj.postData);
            }
            static httpPostJson(obj) {		
                let arr = [];
                this.forEachMap(obj.params, (k, v) => {
                    arr.push(ULTools.format("%s=%s", encodeURIComponent(k), encodeURIComponent(v)));
                });
                let paramString = arr.join('&');
                ULLog.console.log("ULTools.httpPostJson paramString:", paramString);
                this.httpPost({
                    url: obj.url,
                    postData: paramString,
                    timeoutMillisecond: obj.timeoutMillisecond,
                    success: obj.success,
                    fail: obj.fail
                });
            }
            static httpPostFormData(obj) {
                let xhr = new XMLHttpRequest();
                let timeoutTimer = new ULTimer(obj.timeoutMillisecond / 1000, 1, (timer) => {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("timeout");
                    }
                });
                xhr.onreadystatechange = function (e) {
                    if (!xhr)
                        return;
                    if (xhr.readyState == 4) {
                        timeoutTimer.stop();
                        if (xhr.status == 200) {
                            let responseData = xhr.responseText;
                            if (obj.success instanceof Function)
                                obj.success(responseData);
                        }
                        else {
                            ULLog.console.warn("ULTools.httpPost on error:", xhr.readyState, xhr.status);
                            if (obj.fail instanceof Function)
                                obj.fail(xhr.status.toString());
                        }
                    }
                };
                xhr.ontimeout = function (e) {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("timeout");
                    }
                };
                xhr.onerror = function (e) {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("on error :" + e);
                    }
                };
                timeoutTimer.start();
                xhr.open('post', obj.url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send(obj.formData);
            }
            static httpPostEncryption(obj) {
                let xhr = new XMLHttpRequest();
                let timeoutTimer = new ULTimer(obj.timeoutMillisecond / 1000, 1, (timer) => {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("timeout");
                    }
                });
                xhr.onreadystatechange = function (e) {
                    if (!xhr)
                        return;
                    if (xhr.readyState == 4) {
                        timeoutTimer.stop();
                        if (xhr.status == 200) {
                            let responseData = xhr.responseText;
                            if (obj.success instanceof Function)
                                obj.success(responseData);
                        }
                        else {
                            console.warn("ULTools.httpPost on error:", xhr.readyState, xhr.status);
                            if (obj.fail instanceof Function)
                                obj.fail(xhr.status.toString());
                        }
                    }
                };
                xhr.ontimeout = function (e) {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("timeout");
                    }
                };
                xhr.onerror = function (e) {
                    if (xhr) {
                        let temp = xhr;
                        xhr = null;
                        temp.abort();
                        if (obj.fail instanceof Function)
                            obj.fail("on error :" + e);
                    }
                };
                let byteArray = this.stringToByte(obj.postString);
                let key = byteArray.length % 127 || 127;
                var myArray = new ArrayBuffer(byteArray.length);
                var longInt8View = new Uint8Array(myArray);
                for (let i = 0; i < byteArray.length; i++) {
                    byteArray[i] = byteArray[i] ^ key;
                    longInt8View[i] = byteArray[i];
                }
                timeoutTimer.start();
                xhr.open('post', obj.url, true);
                xhr.setRequestHeader('isEncrypt', "1");
                xhr.setRequestHeader('Content-Type', "application/octet-stream");
                xhr.send(myArray);
            }
            static httpJsonp(obj) {
                if (!obj || !obj.url) {
                    throw new Error("参数不合法");
                }
                let callbackName = ULTools.format("jsonp_%d", ULTools.random(1000000));
                obj.data.callback = callbackName;
                let oHead = document.getElementsByTagName('head')[0];
                let arr = [];
                this.forEachMap(obj.data, (k, v) => {
                    arr.push(ULTools.format("%s=%s", encodeURIComponent(k), encodeURIComponent(v)));
                });
                let params = arr.join('&');
                let oS = document.createElement('script');
                oHead.appendChild(oS);
                let timeoutTimer = new ULTimer(obj.timeoutMillisecond / 1000, 1, (timer) => {
                    if (!window[callbackName])
                        return;
                    window[callbackName] = null;
                    oHead.removeChild(oS);
                    obj.fail && obj.fail("timeout");
                });
                window[callbackName] = function (json) {
                    if (!window[callbackName])
                        return;
                    oHead.removeChild(oS);
                    timeoutTimer.stop();
                    window[callbackName] = null;
                    obj.success && obj.success(json);
                };
                oS.src = obj.url + '?' + params;
            }
            static _start_console_print_LAN() {
                if (ULTools.socketingWS) {
                    return;
                }
                let lan_debug_address_default = ULConfig.getConfig().s_sdk_lan_debug_address.length > 10 ? ULConfig.getConfig().s_sdk_lan_debug_address : "";
                let lan_id = localStorage.getItem("console_lan_id") || ULStorageManager.getInstance().getStorage("console_lan_id") || lan_debug_address_default;
                ULLog.console.log('console_lan_id:', lan_id);
                if (lan_id && lan_id.length && "WebSocket" in window) {
                    ULLog.console.log("支持WebSocket局域网调试");
                    var address = `ws://${lan_id}:3002/websocket/test`;
                    var ws = null;
                    try {
                        ws = new ULWebSocket(address);
                        ws.onopen = function () {
                            ULLog.console.log("Connection open ...");
                            ULSdkManager.getInstance().moduleCheckerManager.addDebugInfo("console_lan_id", "已开启局域网调试");
                        };
                        ws.onmessage = function (evt) {
                            ULLog.console.log("Received Message:" + evt.data);
                        };
                        ws.onclose = function () {
                            ULLog.console.log("Connection closed");
                            ULSdkManager.getInstance().moduleCheckerManager.removeDebugInfo("console_lan_id");
                            ULTools.socketingWS = null;
                            ULTools._hack_console_print_method();
                        };
                        ws.onerror = function (err) {
                            ULLog.console.error("Connection onerror:", err);
                            ULSdkManager.getInstance().moduleCheckerManager.removeDebugInfo("console_lan_id");
                            ULTools.socketingWS = null;
                            ULTools._hack_console_print_method();
                        };
                    }
                    catch (error) {
                        ws = null;
                        ULLog.console.log("局域网调试错误:", JSON.stringify(error));
                    }
                    finally {
                        if (ws == null) {
                            return;
                        }
                        ULTools.socketingWS = ws;
                        ULTools._hack_console_print_method();
                    }
                }
                else {
                    ULLog.console.log("不支持WebSocket局域网调试");
                }
            }
            static _close_console_print_LAN() {
                if (ULTools.socketingWS) {
                    ULTools.socketingWS.close();
                    ULTools.socketingWS = null;
                    ULTools._hack_console_print_method();
                }
            }
            static loadJs(url, fOnSuccess, bCrossOriginAnonymous) {
                let script = document.createElement('script');
                script.type = "text/javascript";
                script.addEventListener('load', (e) => {
                    if (fOnSuccess instanceof Function)
                        fOnSuccess();
                });
                script.src = url;
                script.defer = "defer";
                if (bCrossOriginAnonymous) {
                    script.crossOrigin = "anonymous";
                }
                let head = document.getElementsByTagName('head')[0];
                head.appendChild(script);
            }
            static stringToByte(str) {
                var bytes = new Array();
                var len, c;
                len = str.length;
                for (var i = 0; i < len; i++) {
                    c = str.charCodeAt(i);
                    if (c >= 0x010000 && c <= 0x10FFFF) {
                        bytes.push(((c >> 18) & 0x07) | 0xF0);
                        bytes.push(((c >> 12) & 0x3F) | 0x80);
                        bytes.push(((c >> 6) & 0x3F) | 0x80);
                        bytes.push((c & 0x3F) | 0x80);
                    }
                    else if (c >= 0x000800 && c <= 0x00FFFF) {
                        bytes.push(((c >> 12) & 0x0F) | 0xE0);
                        bytes.push(((c >> 6) & 0x3F) | 0x80);
                        bytes.push((c & 0x3F) | 0x80);
                    }
                    else if (c >= 0x000080 && c <= 0x0007FF) {
                        bytes.push(((c >> 6) & 0x1F) | 0xC0);
                        bytes.push((c & 0x3F) | 0x80);
                    }
                    else {
                        bytes.push(c & 0xFF);
                    }
                }
                return bytes;
            }
            static byteToString(arr) {
                if (typeof arr === 'string') {
                    return arr;
                }
                var str = '', _arr = arr;
                for (var i = 0; i < _arr.length; i++) {
                    var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/);
                    if (v && one.length == 8) {
                        var bytesLength = v[0].length;
                        var store = _arr[i].toString(2).slice(7 - bytesLength);
                        for (var st = 1; st < bytesLength; st++) {
                            store += _arr[st + i].toString(2).slice(2);
                        }
                        str += String.fromCharCode(parseInt(store, 2));
                        i += bytesLength - 1;
                    }
                    else {
                        str += String.fromCharCode(_arr[i]);
                    }
                }
                return str;
            }
            static getQueryString(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) {
                    return decodeURI(r[2]);
                }
                return null;
            }
            static createRandomString(len) {
                len = len || 32;
                let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
                let maxPos = $chars.length;
                let pwd = '';
                for (let i = 0; i < len; i++) {
                    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
                }
                return pwd;
            }
            static createRandomUserId() {
                let longUuid = this.generateUUID();
                let shortUuid = this.compressUuid(longUuid);
                return shortUuid;
            }
            static createRandomOrderId() {
                let t = new Date().getTime();
                return t + this.createRandomString(7);
            }
            static compareVersion(v1, v2) {
                let arr1 = v1.split('.');
                let arr2 = v2.split('.');
                const len = Math.max(arr1.length, arr2.length);
                while (arr1.length < len) {
                    arr1.push('0');
                }
                while (arr2.length < len) {
                    arr2.push('0');
                }
                for (let i = 0; i < len; i++) {
                    const num1 = parseInt(arr1[i]);
                    const num2 = parseInt(arr2[i]);
                    if (num1 > num2) {
                        return 1;
                    }
                    else if (num1 < num2) {
                        return -1;
                    }
                }
                return 0;
            }
            static _hack_console_print_method() {
                if (!this._origin_console_log)
                    this._origin_console_log = console.log;
                if (!this._origin_console_warn)
                    this._origin_console_warn = console.warn;
                if (!this._origin_console_error)
                    this._origin_console_error = console.error;
                if (window["cc"] && window["cc"].Node) {
                    if (!this._origin_cc_log)
                        this._origin_cc_log = window["cc"]["log"];
                    if (!this._origin_cc_warn)
                        this._origin_cc_warn = window["cc"]["warn"];
                    if (!this._origin_cc_error)
                        this._origin_cc_error = window["cc"]["error"];
                }
                let trim_console_func = function (type, callback) {
                    let trimFunc = function (...data) {
                        callback(...data);
                        if (ULTools.socketingWS) {
                            ULTools.socketingWS.send({
                                type: type,
                                data: data
                            });
                        }
                    };
                    return trimFunc;
                };
                let config = ULConfig.getConfig();
                console.log = (config.i_sdk_debug_mode < ULConst.CONSOLE_OUTPUT_LEVEL_LOG ? () => { } : (ULTools.socketingWS ? trim_console_func(1, this._origin_console_log) : this._origin_console_log));
                console.warn = (config.i_sdk_debug_mode < ULConst.CONSOLE_OUTPUT_LEVEL_WARN ? () => { } : (ULTools.socketingWS ? trim_console_func(2, this._origin_console_warn) : this._origin_console_warn));
                console.error = (config.i_sdk_debug_mode < ULConst.CONSOLE_OUTPUT_LEVEL_ERROR ? () => { } : (ULTools.socketingWS ? trim_console_func(1, this._origin_console_error) : this._origin_console_error));
                if (window["cc"] && window["cc"].Node) {
                    window["cc"]["log"] = (config.i_sdk_debug_mode < ULConst.CONSOLE_OUTPUT_LEVEL_LOG ? () => { } : (ULTools.socketingWS ? trim_console_func(1, this._origin_cc_log) : this._origin_cc_log));
                    window["cc"]["warn"] = (config.i_sdk_debug_mode < ULConst.CONSOLE_OUTPUT_LEVEL_WARN ? () => { } : (ULTools.socketingWS ? trim_console_func(2, this._origin_cc_warn) : this._origin_cc_warn));
                    window["cc"]["error"] = (config.i_sdk_debug_mode < ULConst.CONSOLE_OUTPUT_LEVEL_ERROR ? () => { } : (ULTools.socketingWS ? trim_console_func(1, this._origin_cc_error) : this._origin_cc_error));
                }
            }
            static jsonValToStr(oldJson) {
                if (!oldJson) {
                    return oldJson;
                }
                let targetJson = {};
                let keys = Object.keys(oldJson);
                for (let i = 0; i < keys.length; i++) {
                    let key = keys[i];
                    let value = oldJson[key];
                    if (typeof (value) == "object") {
                        value = JSON.stringify(value);
                    }
                    else {
                        value = String(value);
                    }
                    targetJson[key] = value;
                }
                return targetJson;
            }
            static calcWheelTargetByArray(array, maxWeight) {
                let totalWeight = 0;
                for (let i = 0; i < array.length; i++) {
                    totalWeight += array[i];
                }
                if (maxWeight != 0) {
                    totalWeight = Math.min(totalWeight, maxWeight);
                }
                let random = (Math.random() * totalWeight);
                let sum = 0;
                for (let i = 0; i < array.length; i++) {
                    sum += array[i];
                    if (sum > random) {
                        return i;
                    }
                }
                return null;
            }
            static recordVideoTimeLimit(type, recordDuration) {
                let duration_limit_object = ULConfig.getConfig().t_sdk_record_duration_limit_object || {};
                let tirm_type = (typeof (type) == "string") ? type : (typeof (type) == "number") ? type.toString() : "";
                let type_Object = duration_limit_object[tirm_type] || duration_limit_object["*"] || {};
                let limit_min = type_Object.min || 0;
                let limit_max = type_Object.max || 10000;
                if (limit_min > recordDuration) {
                    return { isConform: false, msg: `录屏时间少于${limit_min}秒` };
                }
                else if (limit_max < recordDuration) {
                    return { isConform: false, msg: `录屏时间大于${limit_max}秒` };
                }
                return { isConform: true, msg: "" };
            }
            static substrFromByte(str, byteNum) {
                let trimNum = byteNum;
                let trimStrAry = str.split("");
                let cutStr = "";
                while (trimStrAry.length && trimNum > 0) {
                    let firstItem = trimStrAry.shift();
                    let bytes = ULTools.stringToByte(firstItem);
                    trimNum = trimNum - bytes.length;
                    if (trimNum >= 0) {
                        cutStr += firstItem;
                    }
                    else {
                        trimStrAry.unshift(firstItem);
                    }
                }
                return { remainStr: trimStrAry.join(""), cutStr: cutStr };
            }
            static isLayaEngine() {
                if (window["Laya"])
                    return true;
                return false;
            }
            static startsWith(str, startStr) {
                var sliceStr = str.slice(0, Math.min(str.length, startStr.length));
                return sliceStr == startStr;
            }
            ;
            static isCreator2xEngine() {
                if (window["cc"] && window["cc"].ENGINE_VERSION && this.startsWith(window["cc"].ENGINE_VERSION, "2.")) {
                    return true;
                }
                return false;
            }
            static isCreator3xEngine() {
                if (window["cc"] && window["cc"].ENGINE_VERSION && this.startsWith(window["cc"].ENGINE_VERSION, "3.")) {
                    return true;
                }
                return false;
            }
            static isString(obj) {
                let type = ULTools.getType(obj);
                return type == "string";
            }
            static isNumber(obj) {
                let type = ULTools.getType(obj);
                return type == "number";
            }
            static isStringOrNumber(obj) {
                let type = ULTools.getType(obj);
                return type == "number" || type == "string";
            }
            static isObject(obj) {
                let type = ULTools.getType(obj);
                return type == "object";
            }
            static isArray(obj) {
                let type = ULTools.getType(obj);
                return type == "array";
            }
            static isFunc(obj) {
                let type = ULTools.getType(obj);
                return type == "function";
            }
            static getStringValue(obj, key, defaultValue = "") {
                if (ULTools.isObject(obj) && ULTools.isString(key)) {
                    let value = obj[key];
                    if (ULTools.isStringOrNumber(value))
                        return value.toString();
                }
                else if (ULTools.isArray(obj) && ULTools.isNumber(key)) {
                    let trimObj = obj;
                    if (trimObj.length > Number(key)) {
                        let value = trimObj[key];
                        if (ULTools.isStringOrNumber(value))
                            return value.toString();
                    }
                }
                return defaultValue;
            }
            static getNumberValue(obj, key, defaultValue = 0) {
                if (ULTools.isObject(obj) && ULTools.isString(key)) {
                    let value = obj[key];
                    if (ULTools.isStringOrNumber(value))
                        return !isNaN(Number(value)) ? Number(value) : defaultValue;
                }
                else if (ULTools.isArray(obj) && ULTools.isNumber(key)) {
                    let trimObj = obj;
                    if (trimObj.length > Number(key)) {
                        let value = obj[key];
                        if (ULTools.isStringOrNumber(value))
                            return !isNaN(Number(value)) ? Number(value) : defaultValue;
                    }
                }
                return defaultValue;
            }
            static getArrayValue(obj, key, defaultValue = []) {
                if (ULTools.isObject(obj) && ULTools.isString(key)) {
                    let value = obj[key];
                    if (ULTools.isArray(value))
                        return value;
                }
                else if (ULTools.isArray(obj) && ULTools.isNumber(key)) {
                    let trimObj = obj;
                    if (trimObj.length > Number(key)) {
                        let value = trimObj[key];
                        if (ULTools.isArray(value))
                            return value;
                    }
                }
                return defaultValue;
            }
            static getObjectValue(obj, key, defaultValue = {}) {
                if (ULTools.isObject(obj) && ULTools.isString(key)) {
                    let value = obj[key];
                    if (ULTools.isObject(value))
                        return value;
                }
                else if (ULTools.isArray(obj) && ULTools.isNumber(key)) {
                    let trimObj = obj;
                    if (trimObj.length > Number(key)) {
                        let value = trimObj[key];
                        if (ULTools.isObject(value))
                            return value;
                    }
                }
                return defaultValue;
            }
            static randomChinese(length = 10) {
                const randomLength = Math.floor(Math.random() * length) + 1;
                let result = '';
                for (let i = 0; i < randomLength; i++) {
                    const random = Math.floor(Math.random() * (0x9fa5 - 0x4e00 + 1)) + 0x4e00;
                    result += String.fromCharCode(random);
                }
                return result;
            }
            static getCommonHost() {
                let result = "u";
                result += "l";
                result += "t";
                result += "r";
                result += "a";
                result += "l";
                result += "i";
                result += "s";
                result += "k";
                return result;
            }
            static judgeSubscribeHours(oldValue, hours) {
                let currentTime = new Date();
                let currentHour = currentTime.getHours();
                let nextHour = currentHour + 1;
                let nextHourDate = new Date();
                nextHourDate.setHours(nextHour);
                nextHourDate.setMinutes(0);
                nextHourDate.setSeconds(0);
                nextHourDate.setMilliseconds(0);
                let nextHourTimeNumber = nextHourDate.getTime();
                let oldTime = Number(oldValue || "0");
                if (!isNaN(oldTime)) {
                    var span = nextHourTimeNumber - oldTime;
                    if (span >= 0 && span <= (hours * 60 * 60 * 1000)) {
                        return oldValue;
                    }
                }
                return nextHourTimeNumber.toString();
            }
        }
        ULTools.socketingWS = null;

        class ULConfig {
            static init() {
                this.bInit = true;
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_CONFIG, ULConst.PRIORITY_NONE, this.onCmdSdkCollectionModuleCheckerConfig.bind(this));
            }
            static getConfig() {
                if (!this.bInit) {
                    this.init();
                }
                if (!this.currConfig) {
                    this.currConfig = ULTools.clone(cConfig);
                }
                return this.currConfig;
            }
            static get(key) {
                let config = this.getConfig();
                let value = config[key];
                return value;
            }
            static updateValueByCop(cop) {
                let newConfig = ULTools.clone(cConfig);
                ULTools.forEachMap(cop, (k, v) => {
                    if (v == "nil")
                        v = "";
                    newConfig[k] = v;
                });
                this.currConfig = newConfig;
                ULConst.B_INNER_DEBUG = this.getConfig().i_sdk_debug_mode >= ULConst.CONSOLE_OUTPUT_LEVEL_INNER_DEBUG;
            }
            static onCmdSdkCollectionModuleCheckerConfig(e) {
                let config = e.getReturnValue() || [];
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "cConfig:" });
                config.push({
                    type: "button",
                    text: "显示cConfig",
                    onClick: () => {
                        let data = this.currConfig;
                        let keys = Object.keys(data);
                        keys.sort();
                        let conf = [];
                        for (let i = 0; i < keys.length; i++) {
                            const key = keys[i];
                            let value = JSON.stringify(data[key]);
                            let text = ULTools.format("[%s] = [%s]\n", key, value);
                            if (text.length >= 64) {
                                text = text.substr(0, 64 - 2) + "..";
                            }
                            conf.push({ text: text, value: { k: key, v: value } });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("cConfig", conf, (value) => {
                            ULSdkManager.getInstance().moduleCheckerManager.alertPrompt(value.k, value.v, "关闭", null);
                        }, true);
                    },
                });
                config.push({ type: "newLine" });
                config.push({
                    type: "label",
                    text: ULTools.format("i_sdk_debug_mode=[%s]", this.getConfig().i_sdk_debug_mode),
                    name: "labelDebugMode",
                });
                config.push({
                    type: "button",
                    text: "切换调试模式",
                    onClick: () => {
                        let conf = [
                            { text: "0: 全关", value: 0 },
                            { text: "1: warn + error", value: 1 },
                            { text: "2: log + warn + error", value: 2 },
                            { text: "3: 开启各模块的DEBUG + log + warn + error", value: 3 },
                        ];
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("选择调试模式", conf, (value) => {
                            cConfig.i_sdk_debug_mode = value;
                            this.currConfig.i_sdk_debug_mode = value;
                            ULTools._hack_console_print_method();
                            ULConst.B_INNER_DEBUG = this.getConfig().i_sdk_debug_mode >= ULConst.CONSOLE_OUTPUT_LEVEL_INNER_DEBUG;
                            ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelDebugMode", ULTools.format("i_sdk_debug_mode=[%s]", this.getConfig().i_sdk_debug_mode));
                        });
                    },
                });
                config.push({ type: "newLine" });
                config.push({
                    type: "label",
                    text: "局域网调试：",
                    name: "labelSocketDebugMode",
                });
                config.push({
                    type: "inputBox",
                    text: ULStorageManager.getInstance().getStorage("console_lan_id"),
                    name: "console_lan_id"
                });
                config.push({
                    type: "button",
                    text: "切换局域网调试模式",
                    onClick: () => {
                        let console_lan_id = ULSdkManager.getInstance().moduleCheckerManager.getItemText("console_lan_id");
                        let conf = [
                            { text: "关闭调试", value: 0 },
                            { text: "开启调试: " + console_lan_id, value: 1 },
                        ];
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("选择调试模式", conf, (value) => {
                            if (value == 0) {
                                ULStorageManager.getInstance().setStorage("console_lan_id", null);
                                ULTools._close_console_print_LAN();
                            }
                            else {
                                ULStorageManager.getInstance().setStorage("console_lan_id", console_lan_id);
                                ULTools._start_console_print_LAN();
                            }
                        });
                    },
                });
                config.push({ type: "newLine" });
                config.push({
                    type: "label",
                    text: `SDK log 开关：(${this.sdkLogSwitch ? "已开启" : "已关闭"})`,
                    name: "SDK_LOG_MODE",
                });
                config.push({
                    type: "button",
                    text: `切换状态`,
                    onClick: () => {
                        if (this.sdkLogSwitch) {
                            this.sdkLogSwitch = false;
                            ULLog.console.allowConsole = false;
                        }
                        else {
                            this.sdkLogSwitch = true;
                            ULLog.console.allowConsole = true;
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.setItemText("SDK_LOG_MODE", `SDK log 开关：(${this.sdkLogSwitch ? "已开启" : "已关闭"})`);
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "显示sdk通信记录:" });
                config.push({
                    type: "button",
                    text: "查看...",
                    onClick: () => {
                        let log = ULSdkManager.getInstance().getSdkCommunicationLog();
                        let conf = [];
                        for (let i = 0; i < log.length; i++) {
                            const v = log[i];
                            try {
                                let data = JSON.parse(v);
                                ULLog.console.log(i, v, data);
                                conf.push({
                                    text: ULTools.format("%d: %s", i, data.cmd),
                                    value: v,
                                });
                            }
                            catch (error) {
                            }
                        }
                        ULLog.console.log("conf", conf);
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("sdk通信记录（最近100条）", conf, (v) => {
                            ULSdkManager.getInstance().moduleCheckerManager.showBigTextWithPickerDialog("详情", v, 40);
                        }, true);
                    },
                });
                config.push({ type: "newLine" });
                e.setReturnValue(config, true);
            }
        }
        ULConfig.bInit = false;
        ULConfig.sdkLogSwitch = true;

        class ULModuleBase {
            constructor() {
                ULLog.console.log("ULModuleBase-constructor");
            }
            init() {
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_CONFIG, this.getCollectionModuleCheckerPriority(), this.onCmdSdkCollectionModuleCheckerConfig.bind(this));
            }
            onDisposeModule() {
                ULLog.console.log("ULModuleBase-onDisposeModule");
            }
            loadSubModules() {
                return [];
            }
            getSubAdModuleClassName() {
                return [];
            }
            getAdMainClassName() {
                return "";
            }
            createSubAdObj(className, param) {
                return null;
            }
            createMainAdObj() {
                return null;
            }
            loadModuleCheckerConfig() {
                return [];
            }
            onCmdSdkCollectionModuleCheckerConfig(e) {
                let config = e.getReturnValue() || [];
                let ret = this.loadModuleCheckerConfig();
                for (let i = 0; i < ret.length; i++) {
                    const v = ret[i];
                    config.push(v);
                }
                e.setReturnValue(config, true);
            }
            getCollectionModuleCheckerPriority() {
                return ULConst.PRIORITY_NONE;
            }
        }

        class ULModuleCdk extends ULModuleBase {
            constructor() {
                super(...arguments);
                this.className = "ULModuleCdk";
            }
            init() {
                super.init();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_USE_CDKEY, 1, this.onCmdUseCdkey.bind(this));
            }
            requestUseCdk(userId, cdkStr, channelId) {
                let config = ULConfig.getConfig();
                let appId = config.s_sdk_cdk_app_id;
                let timeout = config.i_net_timeout;
                let url = ULTools.format("%s?userId=%s&cdkStr=%s&appId=%s&channelId=%s&platform=h5", config.s_sdk_cdk_url, userId, cdkStr, appId, channelId);
                ULLog.console.log("ULModuleCdk.requestUseCdk", url);
                ULTools.httpGet({
                    url: url,
                    timeoutMillisecond: timeout,
                    success: (responseText) => {
                        responseText = responseText.replace("\"[", "[");
                        responseText = responseText.replace("]\"", "]");
                        responseText = responseText.replace("\"0\"", "\"1\"");
                        responseText = responseText.replace("message", "data");
                        let data = JSON.parse(responseText);
                        ULSdkManager.getInstance().statisManager.reportOpenCdk(data.code);
                        if (data.code == 1) {
                            ULSdkManager.getInstance().response(ULConst.CMD_USE_CDKEY_RESULT, {
                                code: 1,
                                data: data.data,
                                message: "兑换成功",
                            });
                        }
                        else {
                            ULSdkManager.getInstance().response(ULConst.CMD_USE_CDKEY_RESULT, {
                                code: 0,
                                data: [],
                                message: data.data,
                            });
                        }
                    },
                    fail: () => {
                        ULSdkManager.getInstance().statisManager.reportOpenCdk(0);
                        ULSdkManager.getInstance().response(ULConst.CMD_USE_CDKEY_RESULT, {
                            code: 0,
                            message: "请求超时",
                        });
                    },
                });
            }
            onCmdUseCdkey(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let data = e.data;
                let userId = data.userId;
                let cdkStr = data.cdkStr;
                let channelId = config.s_sdk_cop_channel_id;
                this.requestUseCdk(userId, cdkStr, channelId);
            }
        }

        class ULModuleMegadata extends ULModuleBase {
            constructor() {
                super(...arguments);
                this.className = "ULModuleMegadata";
            }
            init() {
                super.init();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_MEGADATA_SERVER, 1, this.onCmdMegadataServer.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_POST_MEGADATA, 1, this.onCmdPostMegadata.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_RESUME, ULConst.PRIORITY_NONE, this.onCmdSdkOnGameResume.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_PAUSE, ULConst.PRIORITY_NONE, this.onCmdSdkOnGamePause.bind(this));
                this.gameLevelStartMsgList = {};
            }
            onCmdMegadataServer(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let data = e.data;
                if (Array.isArray(data) && data.length > 0) {
                    ULSdkManager.getInstance().response(ULConst.CMD_MEGADATA_SERVER_RESULT, {
                        code: 1,
                        message: "上报成功",
                    });
                }
                else {
                    ULSdkManager.getInstance().response(ULConst.CMD_MEGADATA_SERVER_RESULT, {
                        code: 0,
                        message: "数据异常",
                    });
                }
                let statisticsAddr = config.s_sdk_megadata_url;
                if (!!ULSdkManager.getInstance().statisManager.getPostMegadataMode()) {
                    statisticsAddr = config.s_sdk_megadata_test_url;
                }
                if (statisticsAddr.search(/megadatav7/gi) != -1) {
                    ULLog.console.warn("应用确定使用v7版本统计，/c/megadataServer接口数据不再进行上报");
                    return;
                }
                let rawDatas = ULTools.clone(data);
                let actionType = rawDatas[0];
                if (actionType == ULConst.STATIS_USER_EVENT_POINT_EVENT) {
                    ULSdkManager.getInstance().statisManager.reportPointEvent(rawDatas[1], rawDatas[2]);
                    return;
                }
                if (actionType == ULConst.STATIS_USER_EVENT_GAME_LEVEL_START) {
                    let gameLevelStartTime = ULTools.time();
                    let levelName = rawDatas[1] + "";
                    this.gameLevelStartMsgList[levelName] = gameLevelStartTime;
                }
                if (actionType == ULConst.STATIS_USER_EVENT_GAME_LEVEL_COMPLETE) {
                    let levelName = rawDatas[1] + "";
                    let usedTime = ULTools.time() - this.gameLevelStartMsgList[levelName];
                    this.gameLevelStartMsgList[levelName] = undefined;
                    delete this.gameLevelStartMsgList[levelName];
                    if (isNaN(usedTime))
                        usedTime = 0;
                    if (usedTime < 0 || usedTime > 10000) {
                        usedTime = 0;
                    }
                    rawDatas.push(Math.floor(usedTime).toString());
                }
                ULSdkManager.getInstance().statisManager.reportUserEvent(rawDatas);
            }
            onCmdPostMegadata(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let data = e.data;
                if (Array.isArray(data) && data.length > 0) {
                    ULSdkManager.getInstance().response(ULConst.CMD_POST_MEGADATA_RESULT, {
                        code: 1,
                        message: "上报成功",
                    });
                }
                else {
                    ULSdkManager.getInstance().response(ULConst.CMD_POST_MEGADATA_RESULT, {
                        code: 0,
                        message: "数据异常",
                    });
                }
                let rawDatas = ULTools.clone(data);
                let actionType = rawDatas[0];
                let typeId = "";
                if (actionType == ULConst.STATIS_USER_ACTION_EVENT_LEVEL_START) {
                    let gameLevelStartTime = ULTools.time();
                    let levelName = rawDatas[1] + "";
                    this.gameLevelStartMsgList[levelName] = gameLevelStartTime;
                    typeId = ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_LEVEL_START_EVENT);
                }
                if (actionType == ULConst.STATIS_USER_ACTION_EVENT_LEVEL_COMPLETE) {
                    let levelName = rawDatas[1] + "";
                    let usedTime = ULTools.time() - this.gameLevelStartMsgList[levelName];
                    this.gameLevelStartMsgList[levelName] = undefined;
                    delete this.gameLevelStartMsgList[levelName];
                    if (isNaN(usedTime))
                        usedTime = 0;
                    if (usedTime < 0 || usedTime > 10000) {
                        usedTime = 0;
                    }
                    rawDatas.push(Math.floor(usedTime).toString());
                    typeId = ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_LEVEL_COMPLETE_EVENT);
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, ["levelComplete", levelName]);
                }
                if (actionType == ULConst.STATIS_USER_ACTION_EVENT_COIN_CHANGE) {
                    typeId = ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_COIN_CHANGE_EVENT);
                }
                if (actionType == ULConst.STATIS_USER_ACTION_EVENT_ITEM_BUY) {
                    typeId = ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_ITEM_BUY);
                }
                if (actionType == ULConst.STATIS_USER_ACTION_EVENT_BUY_ACTION) {
                    typeId = ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_BUY_ACTION);
                }
                if (actionType == ULConst.STATIS_USER_ACTION_EVENT_COMMON_EVENT) {
                    typeId = ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_COMMON_EVENT);
                    let postData = ULTools.clone(rawDatas);
                    postData.shift();
                    ULLog.console.log("ULModuleMegadta.onCmdPostMegadatapostData postData:", postData);
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, postData);
                }
                if (actionType == ULConst.STATIS_USER_ACTION_EVENT_VIDEO_POINT_EVENT) {
                    typeId = ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_VIDEO_POINT_EVENT);
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, ["videoPointShow", rawDatas[1]]);
                }
                if (typeId != "") {
                    rawDatas.shift();
                    ULLog.console.log("ULModuleMegadta.onCmdPostMegadatapostData typeId:", typeId, " rawDatas:", rawDatas);
                    ULSdkManager.getInstance().statisManager.reportUserActionEvent(rawDatas, typeId);
                }
            }
            onCmdSdkOnGameResume(e) {
                let config = ULConfig.getConfig();
                for (let key in this.gameLevelStartMsgList) {
                    this.gameLevelStartMsgList[key] = ULTools.time();
                }
                ULLog.console.log("ULModuleMegadta.onCmdSdkOnGameResume gameLevelStartTime:", this.gameLevelStartMsgList);
            }
            onCmdSdkOnGamePause(e) {
                let config = ULConfig.getConfig();
                for (let key in this.gameLevelStartMsgList) {
                    ULLog.console.log("ULModuleMegadta.onCmdSdkOnGamePause currentGameLevelName:", key);
                    let usedTime = ULTools.time() - this.gameLevelStartMsgList[key];
                    if (isNaN(usedTime))
                        usedTime = 0;
                    if (usedTime < 0 || usedTime > 10000) {
                        usedTime = 0;
                    }
                    let rawDatas = new Array();
                    rawDatas.push(key);
                    rawDatas.push("2");
                    rawDatas.push("pause");
                    rawDatas.push("0");
                    rawDatas.push("0");
                    rawDatas.push("0");
                    rawDatas.push("0");
                    rawDatas.push("0");
                    rawDatas.push("0");
                    rawDatas.push(Math.floor(usedTime).toString());
                    let typeId = ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_LEVEL_COMPLETE_EVENT);
                    ULSdkManager.getInstance().statisManager.reportUserActionEvent(rawDatas, typeId);
                }
            }
        }

        class ULModuleUserData extends ULModuleBase {
            constructor() {
                super(...arguments);
                this.className = "ULModuleUserData";
            }
            init() {
                super.init();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SAVE_USER_DATA, ULConst.PRIORITY_DISABLE, this.onCmdSaveUserData.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_GET_USER_DATA, ULConst.PRIORITY_DISABLE, this.onCmdGetUserData.bind(this));
            }
            requestUploadUserData(userId, userData) {
                let config = ULConfig.getConfig();
                let url = config.s_sdk_user_data_save_url;
                let postData = {
                    userId: userId,
                    data: userData,
                };
                ULTools.httpPost({
                    url: url,
                    postData: postData,
                    timeoutMillisecond: config.i_net_timeout,
                    success: (responseText) => {
                        let responseData = JSON.parse(responseText);
                        if (responseData && responseData.code == 0) {
                            ULSdkManager.getInstance().response(ULConst.CMD_SAVE_USER_DATA_RESULT, {
                                code: 1,
                                msg: "存档成功",
                            });
                        }
                        else {
                            ULSdkManager.getInstance().response(ULConst.CMD_SAVE_USER_DATA_RESULT, {
                                code: 0,
                                msg: "存档失败",
                            });
                        }
                    },
                    fail: () => {
                        ULSdkManager.getInstance().response(ULConst.CMD_SAVE_USER_DATA_RESULT, {
                            code: 0,
                            msg: "存档超时",
                        });
                    },
                });
            }
            requestDownloadUserData(userId) {
                let config = ULConfig.getConfig();
                let url = ULTools.format("%s?userId=%s", config.s_sdk_user_data_get_url, userId);
                ULLog.console.log("ULModuleUserData.requestDownloadUserData", userId);
                ULLog.console.log("  url", url);
                ULTools.httpGet({
                    url: url,
                    timeoutMillisecond: config.i_net_timeout,
                    success: (responseText) => {
                        let responseData = JSON.parse(responseText);
                        ULLog.console.log("  ULModuleUserData.requestDownloadUserData success", responseText);
                        if (responseData && responseData.code == 0) {
                            ULSdkManager.getInstance().response(ULConst.CMD_GET_USER_DATA_RESULT, {
                                code: 1,
                                userData: responseData.data,
                                msg: "模拟成功",
                            });
                        }
                        else {
                            ULSdkManager.getInstance().response(ULConst.CMD_GET_USER_DATA_RESULT, {
                                code: 0,
                                userData: {},
                                msg: "读取存档失败",
                            });
                        }
                    },
                    fail: (err) => {
                        ULLog.console.log("  ULModuleUserData.requestDownloadUserData fail", err);
                        ULSdkManager.getInstance().response(ULConst.CMD_GET_USER_DATA_RESULT, {
                            code: 0,
                            userData: {},
                            msg: "读取存档超时",
                        });
                    },
                });
            }
            onCmdSaveUserData(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let data = e.data;
                let userId = channelInfo.uuid;
                let userData = data.userData;
                if (!userId) {
                    ULLog.console.log("ULModuleUserData.onCmdSaveUserData userId not found!");
                    return;
                }
                this.requestUploadUserData(userId, userData);
            }
            onCmdGetUserData(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let data = e.data;
                let userId = channelInfo.uuid;
                this.requestDownloadUserData(userId);
            }
        }

        class ULClipboardManager {
            static getInstance() {
                if (!this._instance) {
                    this._instance = new ULClipboardManager();
                }
                return this._instance;
            }
            getClipboardData(finishCallback) {
                if (!(finishCallback instanceof Function)) {
                    ULLog.console.warn("ULClipboardManager.getClipboardData finishCallback not a function");
                    return;
                }
                let bCalled = ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_GET_CLIPBOARD_DATA, {
                    finishCallback: finishCallback,
                });
                if (!bCalled) {
                    finishCallback(null);
                }
            }
            setClipboardData(data, finishCallback) {
                if (!(finishCallback instanceof Function)) {
                    ULLog.console.warn("ULClipboardManager.setClipboardData finishCallback not a function");
                    return;
                }
                let bCalled = ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_SET_CLIPBOARD_DATA, {
                    data: data,
                    finishCallback: finishCallback,
                });
                if (!bCalled) {
                    finishCallback(false);
                }
            }
            isSupport() {
                let bSupport = !!ULEventDispatcher.getInstance().dispatchWithReturn(ULConst.CMD_SDK_IS_SUPPORT_CLIPBOARD, {});
                return bSupport;
            }
        }
        ULClipboardManager._instance = null;

        class ULModuleClipboard extends ULModuleBase {
            constructor() {
                super(...arguments);
                this.className = "ULModuleClipboard";
            }
            init() {
                super.init();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SET_CLIPBOARD_DATA, 1, this.onCmdSetClipboardData.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_GET_CLIPBOARD_DATA, 1, this.onCmdGetClipboardData.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SET_VERSION, 1, this.onCmdSetVersion.bind(this));
            }
            onCmdSetClipboardData(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let data = e.data;
                let clipboardData = data.clipboardData;
                let userData = data.userData;
                ULClipboardManager.getInstance().setClipboardData(clipboardData, (bSuccess) => {
                    if (bSuccess) {
                        ULSdkManager.getInstance().response(ULConst.CMD_SET_CLIPBOARD_DATA_RESULT, {
                            code: 1,
                            msg: "保存成功",
                            clipboardData: clipboardData,
                            userData: userData,
                        });
                    }
                    else {
                        ULSdkManager.getInstance().response(ULConst.CMD_SET_CLIPBOARD_DATA_RESULT, {
                            code: 0,
                            msg: "保存失败",
                            clipboardData: clipboardData,
                            userData: userData,
                        });
                    }
                });
            }
            onCmdGetClipboardData(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let data = e.data;
                let userData = data.userData;
                ULClipboardManager.getInstance().getClipboardData((clipboardData) => {
                    if (clipboardData) {
                        ULSdkManager.getInstance().response(ULConst.CMD_GET_CLIPBOARD_DATA_RESULT, {
                            code: 1,
                            msg: "获取成功",
                            clipboardData: clipboardData,
                            userData: userData,
                        });
                    }
                    else {
                        ULSdkManager.getInstance().response(ULConst.CMD_GET_CLIPBOARD_DATA_RESULT, {
                            code: 0,
                            msg: "获取失败",
                            clipboardData: null,
                            userData: userData,
                        });
                    }
                });
            }
            onCmdSetVersion(e) {
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                channelInfo.isSupportClipboardData = ULClipboardManager.getInstance().isSupport();
                ULLog.console.log(ULTools.format("ULModuleClipboard.onCmdSetVersion mark isSupportClipboardData = %s", channelInfo.isSupportClipboardData));
            }
        }

        class ULModuleDefault extends ULModuleBase {
            constructor() {
                super(...arguments);
                this.className = "ULModuleDefault";
                this.hadShowAffiche = false;
            }
            init() {
                super.init();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SET_VERSION, 1, this.onCmdSetVersion.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_CHECK_TIME_CHANGE, 1, (e) => {
                    this.checkTimeChange((bChange, serverTime, timeDeferenceLimit) => {
                        ULSdkManager.getInstance().response(ULConst.CMD_CHECK_TIME_CHANGE_RESULT, {
                            bChange: bChange,
                            serverTime: serverTime,
                            timeDeferenceLimit: timeDeferenceLimit
                        }, true);
                    });
                });
            }
            checkTimeChange(callback) {
                let config = ULConfig.getConfig();
                let url = config.s_sdk_common_checktime_url;
                let timeout = config.i_net_timeout;
                let deferenceLimit = config.i_sdk_common_checktime_deferenceLimit;
                deferenceLimit = !isNaN(Number(deferenceLimit)) ? Number(deferenceLimit) : 300000;
                if (url) {
                    ULTools.httpGet({
                        url: url,
                        timeoutMillisecond: timeout,
                        success: (responseText) => {
                            let serviceTime = !isNaN(Number(responseText)) ? Number(responseText) : 0;
                            let difference = Math.abs(serviceTime - new Date().getTime());
                            console.log("now:", new Date().getTime());
                            console.log("serviceTime:", serviceTime);
                            console.log("difference:", difference);
                            callback(difference > deferenceLimit, serviceTime, deferenceLimit);
                        },
                        fail: () => {
                            callback(true, 0, deferenceLimit);
                        },
                    });
                }
                else {
                    Promise.resolve().then(() => {
                        callback(false, new Date().getTime(), deferenceLimit);
                    });
                }
            }
            onCmdSetVersion(e) {
                if (!this.hadShowAffiche) {
                    this.hadShowAffiche = true;
                    let config = ULConfig.getConfig();
                    let affiche_url = config.s_sdk_common_affiche_url;
                    if (affiche_url.length > 5) {
                        let title = config.s_sdk_common_affiche_title || "最新公告";
                        ULSdkManager.getInstance().moduleCheckerManager.showPrivacyContent(title, affiche_url);
                    }
                }
            }
        }

        let hbs = window["hbs"];
        let qg$1 = window["qg"];
        let tt = window["tt"];
        let wx = window["wx"];
        let qq = window["qq"];
        class ULModulePrivacyPolicy extends ULModuleBase {
            constructor() {
                super(...arguments);
                this.className = "ULModulePrivacyPolicy";
            }
            get isAgreePrivacyPolicy() {
                let value = ULStorageManager.getInstance().getStorage("hadSurePrivacy") || "0";
                return value == "1";
            }
            agreePrivacyPolicy() {
                ULStorageManager.getInstance().setStorage("hadSurePrivacy", "1");
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                channelInfo.isAgreePrivacyPolicy = true;
            }
            init() {
                super.init();
                this.initSdk();
            }
            initSdk() {
                ULLog.console.info("ULModulePrivacyPolicy-initSdk");
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                channelInfo.isAgreePrivacyPolicy = this.isAgreePrivacyPolicy;
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SHOW_PRIVACY, 1000, this.onCmdShowPrivacy.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_OPEN_ADVANCED_SETTING, 1000, this.onCmdOpenAdvancedSetting.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SET_VERSION, 1, this.onCmdSetVersion.bind(this));
            }
            onCmdOpenAdvancedSetting(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let items = [];
                items.push({
                    name: `注销账户`,
                    handle: () => {
                        ULSdkManager.getInstance().moduleCheckerManager.alertPrompt2("温馨提示", "注销账户会导致该账户不可用", "知道了", "再想想", () => {
                            localStorage.clear();
                            this.exitGame();
                            localStorage.clear();
                        }, () => {
                        });
                    }
                });
                items.push({
                    name: `隐私政策界面`,
                    handle: () => {
                        ULSdkManager.getInstance().moduleCheckerManager.alertPrivacy("温馨提示", config.t_sdk_privacyPolicy_dataArray, ["返回"], [() => {
                            }]);
                    }
                });
                for (let item of config.t_sdk_privacyPolicy_dataArray) {
                    items.push({
                        name: `《${item.name}》`,
                        handle: () => {
                            ULSdkManager.getInstance().moduleCheckerManager.showPrivacyContent(item.name, item.url, item["replaceParam"] || {});
                        }
                    });
                }
                ULSdkManager.getInstance().moduleCheckerManager.showSettingView("高级设置", items);
            }
            onCmdSetVersion(e) {
                this.showPrivacyPolicy();
            }
            onCmdShowPrivacy(e) {
                e.stopImmediatePropagation();
                let data = e.data || {};
                let type = data.type || "0";
                let userData = data.userData || "";
                let callback = (code, msg) => {
                    ULSdkManager.getInstance().response(ULConst.CMD_SHOW_PRIVACY_RESULT, {
                        code: code,
                        msg: msg,
                        type: type,
                        userData: userData,
                    });
                };
                if (!type) {
                    callback(0, "type 值错误");
                    return;
                }
                let config = ULConfig.getConfig();
                let dataArray = config.t_sdk_privacyPolicy_dataArray || [];
                let index = Math.max(0, Number(type));
                if (index < dataArray.length) {
                    let content = dataArray[index];
                    ULSdkManager.getInstance().moduleCheckerManager.showPrivacyContent(content.name, content.url, content["replaceParam"] || {});
                    callback(1, "执行成功");
                }
                else {
                    callback(0, "未找到对应配置");
                }
            }
            showPrivacyPolicy() {
                // if (!this.isAgreePrivacyPolicy) {
                //     let config = ULConfig.getConfig();
                //     ULSdkManager.getInstance().moduleCheckerManager.alertPrivacy("温馨提示", config.t_sdk_privacyPolicy_dataArray, ["拒绝", "同意"], [() => {
                //             this.exitGame();
                //             return true;
                //         }, () => {
                //             this.agreePrivacyPolicy();
                //             ULSdkManager.getInstance().waits.removeCondition("privacy_agree");
                //         }]);
                // }
                // else {
                    ULSdkManager.getInstance().waits.removeCondition("privacy_agree");
                // }
            }
            exitGame() {
                let modeArray = [hbs, qg$1, tt, wx, qq];
                while (modeArray.length) {
                    let mode = modeArray.pop();
                    if (mode && mode != 'undefined' && mode.exitApplication) {
                        mode.exitApplication({
                            success: function () {
                                ULLog.console.log("exitApplication success");
                            },
                            fail: function () {
                                ULLog.console.log("exitApplication fail");
                            },
                            complete: function () {
                                ULLog.console.log("exitApplication complete");
                            }
                        });
                    }
                    else if (mode && mode != 'undefined' && mode.exitMiniProgram) {
                        mode.exitMiniProgram({
                            success: function () {
                                ULLog.console.log("exitMiniProgram success");
                            },
                            fail: function () {
                                ULLog.console.log("exitMiniProgram fail");
                            },
                            complete: function () {
                                ULLog.console.log("exitMiniProgram complete");
                            }
                        });
                    }
                }
                ULLog.console.log("未配置 退出游戏 渠道");
            }
        }

        function pkcs1unpad2(d,n) {
          var b = d.toByteArray();
          var i = 0;
          while(i < b.length && b[i] == 0) ++i;
          if(b.length-i != n-1 || b[i] != 2)
            return null;
          ++i;
          while(b[i] != 0)
            if(++i >= b.length) return null;
          var ret = "";
          while(++i < b.length) {
            var c = b[i] & 255;
            if(c < 128) { // utf-8 decode
              ret += String.fromCharCode(c);
            }
            else if((c > 191) && (c < 224)) {
              ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63));
              ++i;
            }
            else {
              ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2] & 63));
              i += 2;
            }
          }
          return ret;
        }

        // PKCS#1 (OAEP) mask generation function
        function oaep_mgf1_str(seed, len, hash)
        {
            var mask = '', i = 0;

            while (mask.length < len)
            {
                mask += hash(seed + String.fromCharCode.apply(String, [
                        (i & 0xff000000) >> 24,
                        (i & 0x00ff0000) >> 16,
                        (i & 0x0000ff00) >> 8,
                        i & 0x000000ff]));
                i += 1;
            }

            return mask;
        }

        function oaep_unpad(d, n, hash, hashLen) {
            var MD = KJUR.crypto.MessageDigest;
            var Util = KJUR.crypto.Util;
            var algName = null;

            if (!hash) hash = "sha1";

            if (typeof hash === "string") {
                algName = MD.getCanonicalAlgName(hash);
                hashLen = MD.getHashLength(algName);
                hash = function(s) {
                    return hextorstr(Util.hashHex(rstrtohex(s), algName));
                };
            }

            d = d.toByteArray();

            var i;

            for (i = 0; i < d.length; i += 1) {
                d[i] &= 0xff;
            }

            while (d.length < n) {
                d.unshift(0);
            }

            d = String.fromCharCode.apply(String, d);

            if (d.length < 2 * hashLen + 2) {
                throw "Cipher too short";
            }

            var maskedSeed = d.substr(1, hashLen);
            var maskedDB = d.substr(hashLen + 1);

            var seedMask = oaep_mgf1_str(maskedDB, hashLen, hash);
            var seed = [], i;

            for (i = 0; i < maskedSeed.length; i += 1) {
                seed[i] = maskedSeed.charCodeAt(i) ^ seedMask.charCodeAt(i);
            }

            var dbMask = oaep_mgf1_str(String.fromCharCode.apply(String, seed),
                                       d.length - hashLen, hash);

            var DB = [];

            for (i = 0; i < maskedDB.length; i += 1) {
                DB[i] = maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i);
            }

            DB = String.fromCharCode.apply(String, DB);

            if (DB.substr(0, hashLen) !== hash('')) {
                throw "Hash mismatch";
            }

            DB = DB.substr(hashLen);

            var first_one = DB.indexOf('\x01');
            var last_zero = (first_one != -1) ? DB.substr(0, first_one).lastIndexOf('\x00') : -1;

            if (last_zero + 1 != first_one) {
                throw "Malformed data";
            }

            return DB.substr(first_one + 1);
        }

        // Set the private key fields N, e, and d from hex strings
        function RSASetPrivate(N,E,D) {
          this.isPrivate = true;
          if (typeof N !== "string")
          {
            this.n = N;
            this.e = E;
            this.d = D;
          }
          else if(N != null && E != null && N.length > 0 && E.length > 0) {
            this.n = parseBigInt(N,16);
            this.e = parseInt(E,16);
            this.d = parseBigInt(D,16);
          }
          else
            throw "Invalid RSA private key";
        }

        // Set the private key fields N, e, d and CRT params from hex strings
        function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
          this.isPrivate = true;
          this.isPublic = false;
          if (N == null) throw "RSASetPrivateEx N == null";
          if (E == null) throw "RSASetPrivateEx E == null";
          if (N.length == 0) throw "RSASetPrivateEx N.length == 0";
          if (E.length == 0) throw "RSASetPrivateEx E.length == 0";

          if (N != null && E != null && N.length > 0 && E.length > 0) {
            this.n = parseBigInt(N,16);
            this.e = parseInt(E,16);
            this.d = parseBigInt(D,16);
            this.p = parseBigInt(P,16);
            this.q = parseBigInt(Q,16);
            this.dmp1 = parseBigInt(DP,16);
            this.dmq1 = parseBigInt(DQ,16);
            this.coeff = parseBigInt(C,16);
          } else {
            throw "Invalid RSA private key in RSASetPrivateEx";
          }
        }

        // Generate a new random private key B bits long, using public expt E
        function RSAGenerate(B,E) {
          var rng = new SecureRandom();
          var qs = B>>1;
          this.e = parseInt(E,16);
          var ee = new BigInteger(E,16);
          for(;;) {
            for(;;) {
              this.p = new BigInteger(B-qs,1,rng);
              if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break;
            }
            for(;;) {
              this.q = new BigInteger(qs,1,rng);
              if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break;
            }
            if(this.p.compareTo(this.q) <= 0) {
              var t = this.p;
              this.p = this.q;
              this.q = t;
            }
            var p1 = this.p.subtract(BigInteger.ONE); // p1 = p - 1
            var q1 = this.q.subtract(BigInteger.ONE); // q1 = q - 1
            var phi = p1.multiply(q1);
            if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
              this.n = this.p.multiply(this.q); // this.n = p * q
              this.d = ee.modInverse(phi);  // this.d = 
              this.dmp1 = this.d.mod(p1); // this.dmp1 = d mod (p - 1)
              this.dmq1 = this.d.mod(q1); // this.dmq1 = d mod (q - 1)
              this.coeff = this.q.modInverse(this.p); // this.coeff = (q ^ -1) mod p
              break;
            }
          }
          this.isPrivate = true;
        }

        // Perform raw private operation on "x": return x^d (mod n)
        function RSADoPrivate(x) {
          if(this.p == null || this.q == null)
            return x.modPow(this.d, this.n);

          // TODO: re-calculate any missing CRT params
          var xp = x.mod(this.p).modPow(this.dmp1, this.p); // xp=cp?
          var xq = x.mod(this.q).modPow(this.dmq1, this.q); // xq=cq?

          while(xp.compareTo(xq) < 0)
            xp = xp.add(this.p);
          return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
        }

        function RSADecrypt(ctext) {
          var c = parseBigInt(ctext, 16);
          var m = this.doPrivate(c);
          if(m == null) return null;
          return pkcs1unpad2(m, (this.n.bitLength()+7)>>3);
        }

        function RSADecryptOAEP(ctext, hash, hashLen) {
          var c = parseBigInt(ctext, 16);
          var m = this.doPrivate(c);
          if(m == null) return null;
          return oaep_unpad(m, (this.n.bitLength()+7)>>3, hash, hashLen);
        }

        // protected
        RSAKey.prototype.doPrivate = RSADoPrivate;

        // public
        RSAKey.prototype.setPrivate = RSASetPrivate;
        RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
        RSAKey.prototype.generate = RSAGenerate;
        RSAKey.prototype.decrypt = RSADecrypt;
        RSAKey.prototype.decryptOAEP = RSADecryptOAEP;
        //RSAKey.prototype.b64_decrypt = RSAB64Decrypt;

        // (public)
        function bnClone() { var r = nbi(); this.copyTo(r); return r; }

        // (public) return value as integer
        function bnIntValue() {
          if(this.s < 0) {
            if(this.t == 1) return this[0]-this.DV;
            else if(this.t == 0) return -1;
          }
          else if(this.t == 1) return this[0];
          else if(this.t == 0) return 0;
          // assumes 16 < DB < 32
          return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];
        }

        // (public) return value as byte
        function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }

        // (public) return value as short (assumes DB>=16)
        function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }

        // (protected) return x s.t. r^x < DV
        function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }

        // (public) 0 if this == 0, 1 if this > 0
        function bnSigNum() {
          if(this.s < 0) return -1;
          else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
          else return 1;
        }

        // (protected) convert to radix string
        function bnpToRadix(b) {
          if(b == null) b = 10;
          if(this.signum() == 0 || b < 2 || b > 36) return "0";
          var cs = this.chunkSize(b);
          var a = Math.pow(b,cs);
          var d = nbv(a), y = nbi(), z = nbi(), r = "";
          this.divRemTo(d,y,z);
          while(y.signum() > 0) {
            r = (a+z.intValue()).toString(b).substr(1) + r;
            y.divRemTo(d,y,z);
          }
          return z.intValue().toString(b) + r;
        }

        // (protected) convert from radix string
        function bnpFromRadix(s,b) {
          this.fromInt(0);
          if(b == null) b = 10;
          var cs = this.chunkSize(b);
          var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
          for(var i = 0; i < s.length; ++i) {
            var x = intAt(s,i);
            if(x < 0) {
              if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
              continue;
            }
            w = b*w+x;
            if(++j >= cs) {
              this.dMultiply(d);
              this.dAddOffset(w,0);
              j = 0;
              w = 0;
            }
          }
          if(j > 0) {
            this.dMultiply(Math.pow(b,j));
            this.dAddOffset(w,0);
          }
          if(mi) BigInteger.ZERO.subTo(this,this);
        }

        // (protected) alternate constructor
        function bnpFromNumber(a,b,c) {
          if("number" == typeof b) {
            // new BigInteger(int,int,RNG)
            if(a < 2) this.fromInt(1);
            else {
              this.fromNumber(a,c);
              if(!this.testBit(a-1))  // force MSB set
                this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
              if(this.isEven()) this.dAddOffset(1,0); // force odd
              while(!this.isProbablePrime(b)) {
                this.dAddOffset(2,0);
                if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
              }
            }
          }
          else {
            // new BigInteger(int,RNG)
            var x = new Array(), t = a&7;
            x.length = (a>>3)+1;
            b.nextBytes(x);
            if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
            this.fromString(x,256);
          }
        }

        // (public) convert to bigendian byte array
        function bnToByteArray() {
          var i = this.t, r = new Array();
          r[0] = this.s;
          var p = this.DB-(i*this.DB)%8, d, k = 0;
          if(i-- > 0) {
            if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)
              r[k++] = d|(this.s<<(this.DB-p));
            while(i >= 0) {
              if(p < 8) {
                d = (this[i]&((1<<p)-1))<<(8-p);
                d |= this[--i]>>(p+=this.DB-8);
              }
              else {
                d = (this[i]>>(p-=8))&0xff;
                if(p <= 0) { p += this.DB; --i; }
              }
              if((d&0x80) != 0) d |= -256;
              if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
              if(k > 0 || d != this.s) r[k++] = d;
            }
          }
          return r;
        }

        function bnEquals(a) { return(this.compareTo(a)==0); }
        function bnMin(a) { return (this.compareTo(a)<0)?this:a; }
        function bnMax(a) { return (this.compareTo(a)>0)?this:a; }

        // (protected) r = this op a (bitwise)
        function bnpBitwiseTo(a,op,r) {
          var i, f, m = Math.min(a.t,this.t);
          for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
          if(a.t < this.t) {
            f = a.s&this.DM;
            for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
            r.t = this.t;
          }
          else {
            f = this.s&this.DM;
            for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
            r.t = a.t;
          }
          r.s = op(this.s,a.s);
          r.clamp();
        }

        // (public) this & a
        function op_and(x,y) { return x&y; }
        function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }

        // (public) this | a
        function op_or(x,y) { return x|y; }
        function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }

        // (public) this ^ a
        function op_xor(x,y) { return x^y; }
        function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }

        // (public) this & ~a
        function op_andnot(x,y) { return x&~y; }
        function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }

        // (public) ~this
        function bnNot() {
          var r = nbi();
          for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
          r.t = this.t;
          r.s = ~this.s;
          return r;
        }

        // (public) this << n
        function bnShiftLeft(n) {
          var r = nbi();
          if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
          return r;
        }

        // (public) this >> n
        function bnShiftRight(n) {
          var r = nbi();
          if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
          return r;
        }

        // return index of lowest 1-bit in x, x < 2^31
        function lbit(x) {
          if(x == 0) return -1;
          var r = 0;
          if((x&0xffff) == 0) { x >>= 16; r += 16; }
          if((x&0xff) == 0) { x >>= 8; r += 8; }
          if((x&0xf) == 0) { x >>= 4; r += 4; }
          if((x&3) == 0) { x >>= 2; r += 2; }
          if((x&1) == 0) ++r;
          return r;
        }

        // (public) returns index of lowest 1-bit (or -1 if none)
        function bnGetLowestSetBit() {
          for(var i = 0; i < this.t; ++i)
            if(this[i] != 0) return i*this.DB+lbit(this[i]);
          if(this.s < 0) return this.t*this.DB;
          return -1;
        }

        // return number of 1 bits in x
        function cbit(x) {
          var r = 0;
          while(x != 0) { x &= x-1; ++r; }
          return r;
        }

        // (public) return number of set bits
        function bnBitCount() {
          var r = 0, x = this.s&this.DM;
          for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
          return r;
        }

        // (public) true iff nth bit is set
        function bnTestBit(n) {
          var j = Math.floor(n/this.DB);
          if(j >= this.t) return(this.s!=0);
          return((this[j]&(1<<(n%this.DB)))!=0);
        }

        // (protected) this op (1<<n)
        function bnpChangeBit(n,op) {
          var r = BigInteger.ONE.shiftLeft(n);
          this.bitwiseTo(r,op,r);
          return r;
        }

        // (public) this | (1<<n)
        function bnSetBit(n) { return this.changeBit(n,op_or); }

        // (public) this & ~(1<<n)
        function bnClearBit(n) { return this.changeBit(n,op_andnot); }

        // (public) this ^ (1<<n)
        function bnFlipBit(n) { return this.changeBit(n,op_xor); }

        // (protected) r = this + a
        function bnpAddTo(a,r) {
          var i = 0, c = 0, m = Math.min(a.t,this.t);
          while(i < m) {
            c += this[i]+a[i];
            r[i++] = c&this.DM;
            c >>= this.DB;
          }
          if(a.t < this.t) {
            c += a.s;
            while(i < this.t) {
              c += this[i];
              r[i++] = c&this.DM;
              c >>= this.DB;
            }
            c += this.s;
          }
          else {
            c += this.s;
            while(i < a.t) {
              c += a[i];
              r[i++] = c&this.DM;
              c >>= this.DB;
            }
            c += a.s;
          }
          r.s = (c<0)?-1:0;
          if(c > 0) r[i++] = c;
          else if(c < -1) r[i++] = this.DV+c;
          r.t = i;
          r.clamp();
        }

        // (public) this + a
        function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }

        // (public) this - a
        function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }

        // (public) this * a
        function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }

        // (public) this^2
        function bnSquare() { var r = nbi(); this.squareTo(r); return r; }

        // (public) this / a
        function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }

        // (public) this % a
        function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }

        // (public) [this/a,this%a]
        function bnDivideAndRemainder(a) {
          var q = nbi(), r = nbi();
          this.divRemTo(a,q,r);
          return new Array(q,r);
        }

        // (protected) this *= n, this >= 0, 1 < n < DV
        function bnpDMultiply(n) {
          this[this.t] = this.am(0,n-1,this,0,0,this.t);
          ++this.t;
          this.clamp();
        }

        // (protected) this += n << w words, this >= 0
        function bnpDAddOffset(n,w) {
          if(n == 0) return;
          while(this.t <= w) this[this.t++] = 0;
          this[w] += n;
          while(this[w] >= this.DV) {
            this[w] -= this.DV;
            if(++w >= this.t) this[this.t++] = 0;
            ++this[w];
          }
        }

        // A "null" reducer
        function NullExp() {}
        function nNop(x) { return x; }
        function nMulTo(x,y,r) { x.multiplyTo(y,r); }
        function nSqrTo(x,r) { x.squareTo(r); }

        NullExp.prototype.convert = nNop;
        NullExp.prototype.revert = nNop;
        NullExp.prototype.mulTo = nMulTo;
        NullExp.prototype.sqrTo = nSqrTo;

        // (public) this^e
        function bnPow(e) { return this.exp(e,new NullExp()); }

        // (protected) r = lower n words of "this * a", a.t <= n
        // "this" should be the larger one if appropriate.
        function bnpMultiplyLowerTo(a,n,r) {
          var i = Math.min(this.t+a.t,n);
          r.s = 0; // assumes a,this >= 0
          r.t = i;
          while(i > 0) r[--i] = 0;
          var j;
          for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
          for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
          r.clamp();
        }

        // (protected) r = "this * a" without lower n words, n > 0
        // "this" should be the larger one if appropriate.
        function bnpMultiplyUpperTo(a,n,r) {
          --n;
          var i = r.t = this.t+a.t-n;
          r.s = 0; // assumes a,this >= 0
          while(--i >= 0) r[i] = 0;
          for(i = Math.max(n-this.t,0); i < a.t; ++i)
            r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
          r.clamp();
          r.drShiftTo(1,r);
        }

        // Barrett modular reduction
        function Barrett(m) {
          // setup Barrett
          this.r2 = nbi();
          this.q3 = nbi();
          BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
          this.mu = this.r2.divide(m);
          this.m = m;
        }

        function barrettConvert(x) {
          if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
          else if(x.compareTo(this.m) < 0) return x;
          else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
        }

        function barrettRevert(x) { return x; }

        // x = x mod m (HAC 14.42)
        function barrettReduce(x) {
          x.drShiftTo(this.m.t-1,this.r2);
          if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
          this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
          this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
          while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
          x.subTo(this.r2,x);
          while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
        }

        // r = x^2 mod m; x != r
        function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }

        // r = x*y mod m; x,y != r
        function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }

        Barrett.prototype.convert = barrettConvert;
        Barrett.prototype.revert = barrettRevert;
        Barrett.prototype.reduce = barrettReduce;
        Barrett.prototype.mulTo = barrettMulTo;
        Barrett.prototype.sqrTo = barrettSqrTo;

        // (public) this^e % m (HAC 14.85)
        function bnModPow(e,m) {
          var i = e.bitLength(), k, r = nbv(1), z;
          if(i <= 0) return r;
          else if(i < 18) k = 1;
          else if(i < 48) k = 3;
          else if(i < 144) k = 4;
          else if(i < 768) k = 5;
          else k = 6;
          if(i < 8)
            z = new Classic(m);
          else if(m.isEven())
            z = new Barrett(m);
          else
            z = new Montgomery(m);

          // precomputation
          var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
          g[1] = z.convert(this);
          if(k > 1) {
            var g2 = nbi();
            z.sqrTo(g[1],g2);
            while(n <= km) {
              g[n] = nbi();
              z.mulTo(g2,g[n-2],g[n]);
              n += 2;
            }
          }

          var j = e.t-1, w, is1 = true, r2 = nbi(), t;
          i = nbits(e[j])-1;
          while(j >= 0) {
            if(i >= k1) w = (e[j]>>(i-k1))&km;
            else {
              w = (e[j]&((1<<(i+1))-1))<<(k1-i);
              if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
            }

            n = k;
            while((w&1) == 0) { w >>= 1; --n; }
            if((i -= n) < 0) { i += this.DB; --j; }
            if(is1) { // ret == 1, don't bother squaring or multiplying it
              g[w].copyTo(r);
              is1 = false;
            }
            else {
              while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
              if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
              z.mulTo(r2,g[w],r);
            }

            while(j >= 0 && (e[j]&(1<<i)) == 0) {
              z.sqrTo(r,r2); t = r; r = r2; r2 = t;
              if(--i < 0) { i = this.DB-1; --j; }
            }
          }
          return z.revert(r);
        }

        // (public) gcd(this,a) (HAC 14.54)
        function bnGCD(a) {
          var x = (this.s<0)?this.negate():this.clone();
          var y = (a.s<0)?a.negate():a.clone();
          if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
          var i = x.getLowestSetBit(), g = y.getLowestSetBit();
          if(g < 0) return x;
          if(i < g) g = i;
          if(g > 0) {
            x.rShiftTo(g,x);
            y.rShiftTo(g,y);
          }
          while(x.signum() > 0) {
            if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
            if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
            if(x.compareTo(y) >= 0) {
              x.subTo(y,x);
              x.rShiftTo(1,x);
            }
            else {
              y.subTo(x,y);
              y.rShiftTo(1,y);
            }
          }
          if(g > 0) y.lShiftTo(g,y);
          return y;
        }

        // (protected) this % n, n < 2^26
        function bnpModInt(n) {
          if(n <= 0) return 0;
          var d = this.DV%n, r = (this.s<0)?n-1:0;
          if(this.t > 0)
            if(d == 0) r = this[0]%n;
            else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
          return r;
        }

        // (public) 1/this % m (HAC 14.61)
        function bnModInverse(m) {
          var ac = m.isEven();
          if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
          var u = m.clone(), v = this.clone();
          var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
          while(u.signum() != 0) {
            while(u.isEven()) {
              u.rShiftTo(1,u);
              if(ac) {
                if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
                a.rShiftTo(1,a);
              }
              else if(!b.isEven()) b.subTo(m,b);
              b.rShiftTo(1,b);
            }
            while(v.isEven()) {
              v.rShiftTo(1,v);
              if(ac) {
                if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
                c.rShiftTo(1,c);
              }
              else if(!d.isEven()) d.subTo(m,d);
              d.rShiftTo(1,d);
            }
            if(u.compareTo(v) >= 0) {
              u.subTo(v,u);
              if(ac) a.subTo(c,a);
              b.subTo(d,b);
            }
            else {
              v.subTo(u,v);
              if(ac) c.subTo(a,c);
              d.subTo(b,d);
            }
          }
          if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
          if(d.compareTo(m) >= 0) return d.subtract(m);
          if(d.signum() < 0) d.addTo(m,d); else return d;
          if(d.signum() < 0) return d.add(m); else return d;
        }

        var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
        var lplim = (1<<26)/lowprimes[lowprimes.length-1];

        // (public) test primality with certainty >= 1-.5^t
        function bnIsProbablePrime(t) {
          var i, x = this.abs();
          if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {
            for(i = 0; i < lowprimes.length; ++i)
              if(x[0] == lowprimes[i]) return true;
            return false;
          }
          if(x.isEven()) return false;
          i = 1;
          while(i < lowprimes.length) {
            var m = lowprimes[i], j = i+1;
            while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
            m = x.modInt(m);
            while(i < j) if(m%lowprimes[i++] == 0) return false;
          }
          return x.millerRabin(t);
        }

        // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
        function bnpMillerRabin(t) {
          var n1 = this.subtract(BigInteger.ONE);
          var k = n1.getLowestSetBit();
          if(k <= 0) return false;
          var r = n1.shiftRight(k);
          t = (t+1)>>1;
          if(t > lowprimes.length) t = lowprimes.length;
          var a = nbi();
          for(var i = 0; i < t; ++i) {
            //Pick bases at random, instead of starting at 2
            a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);
            var y = a.modPow(r,this);
            if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
              var j = 1;
              while(j++ < k && y.compareTo(n1) != 0) {
                y = y.modPowInt(2,this);
                if(y.compareTo(BigInteger.ONE) == 0) return false;
              }
              if(y.compareTo(n1) != 0) return false;
            }
          }
          return true;
        }

        // protected
        BigInteger.prototype.chunkSize = bnpChunkSize;
        BigInteger.prototype.toRadix = bnpToRadix;
        BigInteger.prototype.fromRadix = bnpFromRadix;
        BigInteger.prototype.fromNumber = bnpFromNumber;
        BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
        BigInteger.prototype.changeBit = bnpChangeBit;
        BigInteger.prototype.addTo = bnpAddTo;
        BigInteger.prototype.dMultiply = bnpDMultiply;
        BigInteger.prototype.dAddOffset = bnpDAddOffset;
        BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
        BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
        BigInteger.prototype.modInt = bnpModInt;
        BigInteger.prototype.millerRabin = bnpMillerRabin;

        // public
        BigInteger.prototype.clone = bnClone;
        BigInteger.prototype.intValue = bnIntValue;
        BigInteger.prototype.byteValue = bnByteValue;
        BigInteger.prototype.shortValue = bnShortValue;
        BigInteger.prototype.signum = bnSigNum;
        BigInteger.prototype.toByteArray = bnToByteArray;
        BigInteger.prototype.equals = bnEquals;
        BigInteger.prototype.min = bnMin;
        BigInteger.prototype.max = bnMax;
        BigInteger.prototype.and = bnAnd;
        BigInteger.prototype.or = bnOr;
        BigInteger.prototype.xor = bnXor;
        BigInteger.prototype.andNot = bnAndNot;
        BigInteger.prototype.not = bnNot;
        BigInteger.prototype.shiftLeft = bnShiftLeft;
        BigInteger.prototype.shiftRight = bnShiftRight;
        BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
        BigInteger.prototype.bitCount = bnBitCount;
        BigInteger.prototype.testBit = bnTestBit;
        BigInteger.prototype.setBit = bnSetBit;
        BigInteger.prototype.clearBit = bnClearBit;
        BigInteger.prototype.flipBit = bnFlipBit;
        BigInteger.prototype.add = bnAdd;
        BigInteger.prototype.subtract = bnSubtract;
        BigInteger.prototype.multiply = bnMultiply;
        BigInteger.prototype.divide = bnDivide;
        BigInteger.prototype.remainder = bnRemainder;
        BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
        BigInteger.prototype.modPow = bnModPow;
        BigInteger.prototype.modInverse = bnModInverse;
        BigInteger.prototype.pow = bnPow;
        BigInteger.prototype.gcd = bnGCD;
        BigInteger.prototype.isProbablePrime = bnIsProbablePrime;

        // JSBN-specific extension
        BigInteger.prototype.square = bnSquare;



        if (YAHOO === undefined) {var YAHOO = {};}
        YAHOO.lang = {
            /**
             * Utility to set up the prototype, constructor and superclass properties to
             * support an inheritance strategy that can chain constructors and methods.
             * Static members will not be inherited.
             *
             * @method extend
             * @static
             * @param {Function} subc   the object to modify
             * @param {Function} superc the object to inherit
             * @param {Object} overrides  additional properties/methods to add to the
             *                              subclass prototype.  These will override the
             *                              matching items obtained from the superclass
             *                              if present.
             */
            extend: function(subc, superc, overrides) {
          if (! superc || ! subc) {
                    throw new Error("YAHOO.lang.extend failed, please check that " +
                                    "all dependencies are included.");
          }
          
          var F = function() {};
          F.prototype = superc.prototype;
          subc.prototype = new F();
          subc.prototype.constructor = subc;
          subc.superclass = superc.prototype;
             
          if (superc.prototype.constructor == Object.prototype.constructor) {
                    superc.prototype.constructor = superc;
          }
         
          if (overrides) {
              var i;
                    for (i in overrides) {
            subc.prototype[i] = overrides[i];
                    }

              var _IEEnumFix = function() {},
            ADD = ["toString", "valueOf"];
              try {
            if (/MSIE/.test(navigator.userAgent)) {
                _IEEnumFix = function(r, s) {
              for (i = 0; i < ADD.length; i = i + 1) {
                  var fname = ADD[i], f = s[fname];
                  if (typeof f === 'function' && f != Object.prototype[fname]) {
                r[fname] = f;
                  }
              }
                };
            }
              } catch (ex) {};
                    _IEEnumFix(subc.prototype, overrides);
          }
            }
        };

        if (typeof KJUR == "undefined" || !KJUR) KJUR = {};

        if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};

        /**
         * ASN1 utilities class
         * @name KJUR.asn1.ASN1Util
         * @class ASN1 utilities class
         * @since asn1 1.0.2
         */
        KJUR.asn1.ASN1Util = new function() {
            this.integerToByteHex = function(i) {
                var h = i.toString(16);
                if ((h.length % 2) == 1) h = '0' + h;
                return h;
            };
            this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
                var h = bigIntegerValue.toString(16);
                if (h.substr(0, 1) != '-') {
                    if (h.length % 2 == 1) {
                        h = '0' + h;
                    } else {
                        if (! h.match(/^[0-7]/)) {
                            h = '00' + h;
                        }
                    }
                } else {
                    var hPos = h.substr(1);
                    var xorLen = hPos.length;
                    if (xorLen % 2 == 1) {
                        xorLen += 1;
                    } else {
                        if (! h.match(/^[0-7]/)) {
                            xorLen += 2;
                        }
                    }
                    var hMask = '';
                    for (var i = 0; i < xorLen; i++) {
                        hMask += 'f';
                    }
                    var biMask = new BigInteger(hMask, 16);
                    var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
                    h = biNeg.toString(16).replace(/^-/, '');
                }
                return h;
            };
           
            this.getPEMStringFromHex = function(dataHex, pemHeader) {
          return hextopem(dataHex, pemHeader);
            };

            this.newObject = function(param) {
          var _KJUR = KJUR,
              _KJUR_asn1 = _KJUR.asn1,
              _DERBoolean = _KJUR_asn1.DERBoolean,
              _DERInteger = _KJUR_asn1.DERInteger,
              _DERBitString = _KJUR_asn1.DERBitString,
              _DEROctetString = _KJUR_asn1.DEROctetString,
              _DERNull = _KJUR_asn1.DERNull,
              _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
              _DEREnumerated = _KJUR_asn1.DEREnumerated,
              _DERUTF8String = _KJUR_asn1.DERUTF8String,
              _DERNumericString = _KJUR_asn1.DERNumericString,
              _DERPrintableString = _KJUR_asn1.DERPrintableString,
              _DERTeletexString = _KJUR_asn1.DERTeletexString,
              _DERIA5String = _KJUR_asn1.DERIA5String,
              _DERUTCTime = _KJUR_asn1.DERUTCTime,
              _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
              _DERSequence = _KJUR_asn1.DERSequence,
              _DERSet = _KJUR_asn1.DERSet,
              _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
              _newObject = _KJUR_asn1.ASN1Util.newObject;

                var keys = Object.keys(param);
                if (keys.length != 1)
                    throw "key of param shall be only one.";
                var key = keys[0];

                if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
                    throw "undefined key: " + key;

                if (key == "bool")    return new _DERBoolean(param[key]);
                if (key == "int")     return new _DERInteger(param[key]);
                if (key == "bitstr")  return new _DERBitString(param[key]);
                if (key == "octstr")  return new _DEROctetString(param[key]);
                if (key == "null")    return new _DERNull(param[key]);
                if (key == "oid")     return new _DERObjectIdentifier(param[key]);
                if (key == "enum")    return new _DEREnumerated(param[key]);
                if (key == "utf8str") return new _DERUTF8String(param[key]);
                if (key == "numstr")  return new _DERNumericString(param[key]);
                if (key == "prnstr")  return new _DERPrintableString(param[key]);
                if (key == "telstr")  return new _DERTeletexString(param[key]);
                if (key == "ia5str")  return new _DERIA5String(param[key]);
                if (key == "utctime") return new _DERUTCTime(param[key]);
                if (key == "gentime") return new _DERGeneralizedTime(param[key]);

                if (key == "seq") {
                    var paramList = param[key];
                    var a = [];
                    for (var i = 0; i < paramList.length; i++) {
                        var asn1Obj = _newObject(paramList[i]);
                        a.push(asn1Obj);
                    }
                    return new _DERSequence({'array': a});
                }

                if (key == "set") {
                    var paramList = param[key];
                    var a = [];
                    for (var i = 0; i < paramList.length; i++) {
                        var asn1Obj = _newObject(paramList[i]);
                        a.push(asn1Obj);
                    }
                    return new _DERSet({'array': a});
                }

                if (key == "tag") {
                    var tagParam = param[key];
                    if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
                        tagParam.length == 3) {
                        var obj = _newObject(tagParam[2]);
                        return new _DERTaggedObject({tag: tagParam[0],
                       explicit: tagParam[1],
                       obj: obj});
                    } else {
                        var newParam = {};
                        if (tagParam.explicit !== undefined)
                            newParam.explicit = tagParam.explicit;
                        if (tagParam.tag !== undefined)
                            newParam.tag = tagParam.tag;
                        if (tagParam.obj === undefined)
                            throw "obj shall be specified for 'tag'.";
                        newParam.obj = _newObject(tagParam.obj);
                        return new _DERTaggedObject(newParam);
                    }
                }
            };

            this.jsonToASN1HEX = function(param) {
                var asn1Obj = this.newObject(param);
                return asn1Obj.getEncodedHex();
            };
        };

        KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
            var s = "";
            var i01 = parseInt(hex.substr(0, 2), 16);
            var i0 = Math.floor(i01 / 40);
            var i1 = i01 % 40;
            var s = i0 + "." + i1;

            var binbuf = "";
            for (var i = 2; i < hex.length; i += 2) {
          var value = parseInt(hex.substr(i, 2), 16);
                var bin = ("00000000" + value.toString(2)).slice(- 8);
          binbuf = binbuf + bin.substr(1, 7);
          if (bin.substr(0, 1) == "0") {
              var bi = new BigInteger(binbuf, 2);
              s = s + "." + bi.toString(10);
              binbuf = "";
          }
            };

            return s;
        };


        KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
            var itox = function(i) {
                var h = i.toString(16);
                if (h.length == 1) h = '0' + h;
                return h;
            };

            var roidtox = function(roid) {
                var h = '';
                var bi = new BigInteger(roid, 10);
                var b = bi.toString(2);
                var padLen = 7 - b.length % 7;
                if (padLen == 7) padLen = 0;
                var bPad = '';
                for (var i = 0; i < padLen; i++) bPad += '0';
                b = bPad + b;
                for (var i = 0; i < b.length - 1; i += 7) {
                    var b8 = b.substr(i, 7);
                    if (i != b.length - 7) b8 = '1' + b8;
                    h += itox(parseInt(b8, 2));
                }
                return h;
            };
            
            if (! oidString.match(/^[0-9.]+$/)) {
                throw "malformed oid string: " + oidString;
            }
            var h = '';
            var a = oidString.split('.');
            var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
            h += itox(i0);
            a.splice(0, 2);
            for (var i = 0; i < a.length; i++) {
                h += roidtox(a[i]);
            }
            return h;
        };


        KJUR.asn1.ASN1Object = function() {
            var isModified = true;
            var hTLV = null;
            var hT = '00';
            var hL = '00';
            var hV = '';

            this.getLengthHexFromValue = function() {
                if (typeof this.hV == "undefined" || this.hV == null) {
                    throw "this.hV is null or undefined.";
                }
                if (this.hV.length % 2 == 1) {
                    throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
                }
                var n = this.hV.length / 2;
                var hN = n.toString(16);
                if (hN.length % 2 == 1) {
                    hN = "0" + hN;
                }
                if (n < 128) {
                    return hN;
                } else {
                    var hNlen = hN.length / 2;
                    if (hNlen > 15) {
                        throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
                    }
                    var head = 128 + hNlen;
                    return head.toString(16) + hN;
                }
            };

            
            this.getEncodedHex = function() {
                if (this.hTLV == null || this.isModified) {
                    this.hV = this.getFreshValueHex();
                    this.hL = this.getLengthHexFromValue();
                    this.hTLV = this.hT + this.hL + this.hV;
                    this.isModified = false;
                    //alert("first time: " + this.hTLV);
                }
                return this.hTLV;
            };

            this.getValueHex = function() {
                this.getEncodedHex();
                return this.hV;
            };

            this.getFreshValueHex = function() {
                return '';
            };
        };

        KJUR.asn1.DERAbstractString = function(params) {
            KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
            var s = null;
            var hV = null;

            
            this.getString = function() {
                return this.s;
            };

            
            this.setString = function(newS) {
                this.hTLV = null;
                this.isModified = true;
                this.s = newS;
                this.hV = utf8tohex(this.s).toLowerCase();
            };

            this.setStringHex = function(newHexString) {
                this.hTLV = null;
                this.isModified = true;
                this.s = null;
                this.hV = newHexString;
            };

            this.getFreshValueHex = function() {
                return this.hV;
            };

            if (typeof params != "undefined") {
                if (typeof params == "string") {
                    this.setString(params);
                } else if (typeof params['str'] != "undefined") {
                    this.setString(params['str']);
                } else if (typeof params['hex'] != "undefined") {
                    this.setStringHex(params['hex']);
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);

        KJUR.asn1.DERAbstractTime = function(params) {
            KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
            var s = null;
            var date = null;

            // --- PRIVATE METHODS --------------------
            this.localDateToUTC = function(d) {
                utc = d.getTime() + (d.getTimezoneOffset() * 60000);
                var utcDate = new Date(utc);
                return utcDate;
            };

            
            this.formatDate = function(dateObject, type, withMillis) {
                var pad = this.zeroPadding;
                var d = this.localDateToUTC(dateObject);
                var year = String(d.getFullYear());
                if (type == 'utc') year = year.substr(2, 2);
                var month = pad(String(d.getMonth() + 1), 2);
                var day = pad(String(d.getDate()), 2);
                var hour = pad(String(d.getHours()), 2);
                var min = pad(String(d.getMinutes()), 2);
                var sec = pad(String(d.getSeconds()), 2);
                var s = year + month + day + hour + min + sec;
                if (withMillis === true) {
                    var millis = d.getMilliseconds();
                    if (millis != 0) {
                        var sMillis = pad(String(millis), 3);
                        sMillis = sMillis.replace(/[0]+$/, "");
                        s = s + "." + sMillis;
                    }
                }
                return s + "Z";
            };

            this.zeroPadding = function(s, len) {
                if (s.length >= len) return s;
                return new Array(len - s.length + 1).join('0') + s;
            };

            this.getString = function() {
                return this.s;
            };

            
            this.setString = function(newS) {
                this.hTLV = null;
                this.isModified = true;
                this.s = newS;
                this.hV = stohex(newS);
            };

            
            this.setByDateValue = function(year, month, day, hour, min, sec) {
                var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
                this.setByDate(dateObject);
            };

            this.getFreshValueHex = function() {
                return this.hV;
            };
        };
        YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);

        KJUR.asn1.DERAbstractStructured = function(params) {
            KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
            var asn1Array = null;

            
            this.setByASN1ObjectArray = function(asn1ObjectArray) {
                this.hTLV = null;
                this.isModified = true;
                this.asn1Array = asn1ObjectArray;
            };

            this.appendASN1Object = function(asn1Object) {
                this.hTLV = null;
                this.isModified = true;
                this.asn1Array.push(asn1Object);
            };

            this.asn1Array = new Array();
            if (typeof params != "undefined") {
                if (typeof params['array'] != "undefined") {
                    this.asn1Array = params['array'];
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);


        KJUR.asn1.DERBoolean = function() {
            KJUR.asn1.DERBoolean.superclass.constructor.call(this);
            this.hT = "01";
            this.hTLV = "0101ff";
        };
        YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);


        KJUR.asn1.DERInteger = function(params) {
            KJUR.asn1.DERInteger.superclass.constructor.call(this);
            this.hT = "02";

           
            this.setByBigInteger = function(bigIntegerValue) {
                this.hTLV = null;
                this.isModified = true;
                this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
            };

            
            this.setByInteger = function(intValue) {
                var bi = new BigInteger(String(intValue), 10);
                this.setByBigInteger(bi);
            };

            this.setValueHex = function(newHexString) {
                this.hV = newHexString;
            };

            this.getFreshValueHex = function() {
                return this.hV;
            };

            if (typeof params != "undefined") {
                if (typeof params['bigint'] != "undefined") {
                    this.setByBigInteger(params['bigint']);
                } else if (typeof params['int'] != "undefined") {
                    this.setByInteger(params['int']);
                } else if (typeof params == "number") {
                    this.setByInteger(params);
                } else if (typeof params['hex'] != "undefined") {
                    this.setValueHex(params['hex']);
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);


        KJUR.asn1.DERBitString = function(params) {
            if (params !== undefined && typeof params.obj !== "undefined") {
          var o = KJUR.asn1.ASN1Util.newObject(params.obj);
          params.hex = "00" + o.getEncodedHex();
            }
            KJUR.asn1.DERBitString.superclass.constructor.call(this);
            this.hT = "03";

            
            this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
                this.hTLV = null;
                this.isModified = true;
                this.hV = newHexStringIncludingUnusedBits;
            };

           
            this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
                if (unusedBits < 0 || 7 < unusedBits) {
                    throw "unused bits shall be from 0 to 7: u = " + unusedBits;
                }
                var hUnusedBits = "0" + unusedBits;
                this.hTLV = null;
                this.isModified = true;
                this.hV = hUnusedBits + hValue;
            };

            
            this.setByBinaryString = function(binaryString) {
                binaryString = binaryString.replace(/0+$/, '');
                var unusedBits = 8 - binaryString.length % 8;
                if (unusedBits == 8) unusedBits = 0;
                for (var i = 0; i <= unusedBits; i++) {
                    binaryString += '0';
                }
                var h = '';
                for (var i = 0; i < binaryString.length - 1; i += 8) {
                    var b = binaryString.substr(i, 8);
                    var x = parseInt(b, 2).toString(16);
                    if (x.length == 1) x = '0' + x;
                    h += x;  
                }
                this.hTLV = null;
                this.isModified = true;
                this.hV = '0' + unusedBits + h;
            };

            
            this.setByBooleanArray = function(booleanArray) {
                var s = '';
                for (var i = 0; i < booleanArray.length; i++) {
                    if (booleanArray[i] == true) {
                        s += '1';
                    } else {
                        s += '0';
                    }
                }
                this.setByBinaryString(s);
            };

            
            this.newFalseArray = function(nLength) {
                var a = new Array(nLength);
                for (var i = 0; i < nLength; i++) {
                    a[i] = false;
                }
                return a;
            };

            this.getFreshValueHex = function() {
                return this.hV;
            };

            if (typeof params != "undefined") {
                if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
                    this.setHexValueIncludingUnusedBits(params);
                } else if (typeof params['hex'] != "undefined") {
                    this.setHexValueIncludingUnusedBits(params['hex']);
                } else if (typeof params['bin'] != "undefined") {
                    this.setByBinaryString(params['bin']);
                } else if (typeof params['array'] != "undefined") {
                    this.setByBooleanArray(params['array']);
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);


        KJUR.asn1.DEROctetString = function(params) {
            if (params !== undefined && typeof params.obj !== "undefined") {
          var o = KJUR.asn1.ASN1Util.newObject(params.obj);
          params.hex = o.getEncodedHex();
            }
            KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
            this.hT = "04";
        };
        YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);


        KJUR.asn1.DERNull = function() {
            KJUR.asn1.DERNull.superclass.constructor.call(this);
            this.hT = "05";
            this.hTLV = "0500";
        };
        YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);


        KJUR.asn1.DERObjectIdentifier = function(params) {
            var itox = function(i) {
                var h = i.toString(16);
                if (h.length == 1) h = '0' + h;
                return h;
            };
            var roidtox = function(roid) {
                var h = '';
                var bi = new BigInteger(roid, 10);
                var b = bi.toString(2);
                var padLen = 7 - b.length % 7;
                if (padLen == 7) padLen = 0;
                var bPad = '';
                for (var i = 0; i < padLen; i++) bPad += '0';
                b = bPad + b;
                for (var i = 0; i < b.length - 1; i += 7) {
                    var b8 = b.substr(i, 7);
                    if (i != b.length - 7) b8 = '1' + b8;
                    h += itox(parseInt(b8, 2));
                }
                return h;
            };

            KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
            this.hT = "06";

            
            this.setValueHex = function(newHexString) {
                this.hTLV = null;
                this.isModified = true;
                this.s = null;
                this.hV = newHexString;
            };

            
            this.setValueOidString = function(oidString) {
                if (! oidString.match(/^[0-9.]+$/)) {
                    throw "malformed oid string: " + oidString;
                }
                var h = '';
                var a = oidString.split('.');
                var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
                h += itox(i0);
                a.splice(0, 2);
                for (var i = 0; i < a.length; i++) {
                    h += roidtox(a[i]);
                }
                this.hTLV = null;
                this.isModified = true;
                this.s = null;
                this.hV = h;
            };

            this.setValueName = function(oidName) {
          var oid = KJUR.asn1.x509.OID.name2oid(oidName);
          if (oid !== '') {
                    this.setValueOidString(oid);
                } else {
                    throw "DERObjectIdentifier oidName undefined: " + oidName;
                }
            };

            this.getFreshValueHex = function() {
                return this.hV;
            };

            if (params !== undefined) {
                if (typeof params === "string") {
              if (params.match(/^[0-2].[0-9.]+$/)) {
            this.setValueOidString(params);
              } else {
            this.setValueName(params);
              }
                } else if (params.oid !== undefined) {
                    this.setValueOidString(params.oid);
                } else if (params.hex !== undefined) {
                    this.setValueHex(params.hex);
                } else if (params.name !== undefined) {
                    this.setValueName(params.name);
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);


        KJUR.asn1.DEREnumerated = function(params) {
            KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
            this.hT = "0a";

            
            this.setByBigInteger = function(bigIntegerValue) {
                this.hTLV = null;
                this.isModified = true;
                this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
            };

            
            this.setByInteger = function(intValue) {
                var bi = new BigInteger(String(intValue), 10);
                this.setByBigInteger(bi);
            };

            
            this.setValueHex = function(newHexString) {
                this.hV = newHexString;
            };

            this.getFreshValueHex = function() {
                return this.hV;
            };

            if (typeof params != "undefined") {
                if (typeof params['int'] != "undefined") {
                    this.setByInteger(params['int']);
                } else if (typeof params == "number") {
                    this.setByInteger(params);
                } else if (typeof params['hex'] != "undefined") {
                    this.setValueHex(params['hex']);
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);


        KJUR.asn1.DERUTF8String = function(params) {
            KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
            this.hT = "0c";
        };
        YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);


        KJUR.asn1.DERNumericString = function(params) {
            KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
            this.hT = "12";
        };
        YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);


        KJUR.asn1.DERPrintableString = function(params) {
            KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
            this.hT = "13";
        };
        YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);


        KJUR.asn1.DERTeletexString = function(params) {
            KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
            this.hT = "14";
        };
        YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);


        KJUR.asn1.DERIA5String = function(params) {
            KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
            this.hT = "16";
        };
        YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);


        KJUR.asn1.DERUTCTime = function(params) {
            KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
            this.hT = "17";

           
            this.setByDate = function(dateObject) {
                this.hTLV = null;
                this.isModified = true;
                this.date = dateObject;
                this.s = this.formatDate(this.date, 'utc');
                this.hV = stohex(this.s);
            };

            this.getFreshValueHex = function() {
                if (typeof this.date == "undefined" && typeof this.s == "undefined") {
                    this.date = new Date();
                    this.s = this.formatDate(this.date, 'utc');
                    this.hV = stohex(this.s);
                }
                return this.hV;
            };

            if (params !== undefined) {
                if (params.str !== undefined) {
                    this.setString(params.str);
                } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
                    this.setString(params);
                } else if (params.hex !== undefined) {
                    this.setStringHex(params.hex);
                } else if (params.date !== undefined) {
                    this.setByDate(params.date);
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);


        KJUR.asn1.DERGeneralizedTime = function(params) {
            KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
            this.hT = "18";
            this.withMillis = false;

            
            this.setByDate = function(dateObject) {
                this.hTLV = null;
                this.isModified = true;
                this.date = dateObject;
                this.s = this.formatDate(this.date, 'gen', this.withMillis);
                this.hV = stohex(this.s);
            };

            this.getFreshValueHex = function() {
                if (this.date === undefined && this.s === undefined) {
                    this.date = new Date();
                    this.s = this.formatDate(this.date, 'gen', this.withMillis);
                    this.hV = stohex(this.s);
                }
                return this.hV;
            };

            if (params !== undefined) {
                if (params.str !== undefined) {
                    this.setString(params.str);
                } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
                    this.setString(params);
                } else if (params.hex !== undefined) {
                    this.setStringHex(params.hex);
                } else if (params.date !== undefined) {
                    this.setByDate(params.date);
                }
                if (params.millis === true) {
                    this.withMillis = true;
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);


        KJUR.asn1.DERSequence = function(params) {
            KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
            this.hT = "30";
            this.getFreshValueHex = function() {
                var h = '';
                for (var i = 0; i < this.asn1Array.length; i++) {
                    var asn1Obj = this.asn1Array[i];
                    h += asn1Obj.getEncodedHex();
                }
                this.hV = h;
                return this.hV;
            };
        };
        YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);


        KJUR.asn1.DERSet = function(params) {
            KJUR.asn1.DERSet.superclass.constructor.call(this, params);
            this.hT = "31";
            this.sortFlag = true; // item shall be sorted only in ASN.1 DER
            this.getFreshValueHex = function() {
                var a = new Array();
                for (var i = 0; i < this.asn1Array.length; i++) {
                    var asn1Obj = this.asn1Array[i];
                    a.push(asn1Obj.getEncodedHex());
                }
                if (this.sortFlag == true) a.sort();
                this.hV = a.join('');
                return this.hV;
            };

            if (typeof params != "undefined") {
                if (typeof params.sortflag != "undefined" &&
                    params.sortflag == false)
                    this.sortFlag = false;
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);


        KJUR.asn1.DERTaggedObject = function(params) {
            KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
            this.hT = "a0";
            this.hV = '';
            this.isExplicit = true;
            this.asn1Object = null;

            
            this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
                this.hT = tagNoHex;
                this.isExplicit = isExplicitFlag;
                this.asn1Object = asn1Object;
                if (this.isExplicit) {
                    this.hV = this.asn1Object.getEncodedHex();
                    this.hTLV = null;
                    this.isModified = true;
                } else {
                    this.hV = null;
                    this.hTLV = asn1Object.getEncodedHex();
                    this.hTLV = this.hTLV.replace(/^../, tagNoHex);
                    this.isModified = false;
                }
            };

            this.getFreshValueHex = function() {
                return this.hV;
            };

            if (typeof params != "undefined") {
                if (typeof params['tag'] != "undefined") {
                    this.hT = params['tag'];
                }
                if (typeof params['explicit'] != "undefined") {
                    this.isExplicit = params['explicit'];
                }
                if (typeof params['obj'] != "undefined") {
                    this.asn1Object = params['obj'];
                    this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
                }
            }
        };
        YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);


        var dbits;

        // JavaScript engine analysis
        var canary = 0xdeadbeefcafe;
        var j_lm = ((canary&0xffffff)==0xefcafe);

        // (public) Constructor
        function BigInteger(a,b,c) {
          if(a != null)
            if("number" == typeof a) this.fromNumber(a,b,c);
            else if(b == null && "string" != typeof a) this.fromString(a,256);
            else this.fromString(a,b);
        }

        // return new, unset BigInteger
        function nbi() { return new BigInteger(null); }


        function am1(i,x,w,j,c,n) {
          while(--n >= 0) {
            var v = x*this[i++]+w[j]+c;
            c = Math.floor(v/0x4000000);
            w[j++] = v&0x3ffffff;
          }
          return c;
        }

        function am2(i,x,w,j,c,n) {
          var xl = x&0x7fff, xh = x>>15;
          while(--n >= 0) {
            var l = this[i]&0x7fff;
            var h = this[i++]>>15;
            var m = xh*l+h*xl;
            l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
            c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
            w[j++] = l&0x3fffffff;
          }
          return c;
        }
        // Alternately, set max digit bits to 28 since some
        // browsers slow down when dealing with 32-bit numbers.
        function am3(i,x,w,j,c,n) {
          var xl = x&0x3fff, xh = x>>14;
          while(--n >= 0) {
            var l = this[i]&0x3fff;
            var h = this[i++]>>14;
            var m = xh*l+h*xl;
            l = xl*l+((m&0x3fff)<<14)+w[j]+c;
            c = (l>>28)+(m>>14)+xh*h;
            w[j++] = l&0xfffffff;
          }
          return c;
        }
        if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
          BigInteger.prototype.am = am2;
          dbits = 30;
        }
        else if(j_lm && (navigator.appName != "Netscape")) {
          BigInteger.prototype.am = am1;
          dbits = 26;
        }
        else { // Mozilla/Netscape seems to prefer am3
          BigInteger.prototype.am = am3;
          dbits = 28;
        }

        BigInteger.prototype.DB = dbits;
        BigInteger.prototype.DM = ((1<<dbits)-1);
        BigInteger.prototype.DV = (1<<dbits);

        var BI_FP = 52;
        BigInteger.prototype.FV = Math.pow(2,BI_FP);
        BigInteger.prototype.F1 = BI_FP-dbits;
        BigInteger.prototype.F2 = 2*dbits-BI_FP;

        // Digit conversions
        var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
        var BI_RC = new Array();
        var rr,vv;
        rr = "0".charCodeAt(0);
        for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
        rr = "a".charCodeAt(0);
        for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
        rr = "A".charCodeAt(0);
        for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;

        function int2char(n) { return BI_RM.charAt(n); }
        function intAt(s,i) {
          var c = BI_RC[s.charCodeAt(i)];
          return (c==null)?-1:c;
        }

        // (protected) copy this to r
        function bnpCopyTo(r) {
          for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
          r.t = this.t;
          r.s = this.s;
        }

        // (protected) set from integer value x, -DV <= x < DV
        function bnpFromInt(x) {
          this.t = 1;
          this.s = (x<0)?-1:0;
          if(x > 0) this[0] = x;
          else if(x < -1) this[0] = x+this.DV;
          else this.t = 0;
        }

        // return bigint initialized to value
        function nbv(i) { var r = nbi(); r.fromInt(i); return r; }

        // (protected) set from string and radix
        function bnpFromString(s,b) {
          var k;
          if(b == 16) k = 4;
          else if(b == 8) k = 3;
          else if(b == 256) k = 8; // byte array
          else if(b == 2) k = 1;
          else if(b == 32) k = 5;
          else if(b == 4) k = 2;
          else { this.fromRadix(s,b); return; }
          this.t = 0;
          this.s = 0;
          var i = s.length, mi = false, sh = 0;
          while(--i >= 0) {
            var x = (k==8)?s[i]&0xff:intAt(s,i);
            if(x < 0) {
              if(s.charAt(i) == "-") mi = true;
              continue;
            }
            mi = false;
            if(sh == 0)
              this[this.t++] = x;
            else if(sh+k > this.DB) {
              this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
              this[this.t++] = (x>>(this.DB-sh));
            }
            else
              this[this.t-1] |= x<<sh;
            sh += k;
            if(sh >= this.DB) sh -= this.DB;
          }
          if(k == 8 && (s[0]&0x80) != 0) {
            this.s = -1;
            if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
          }
          this.clamp();
          if(mi) BigInteger.ZERO.subTo(this,this);
        }

        // (protected) clamp off excess high words
        function bnpClamp() {
          var c = this.s&this.DM;
          while(this.t > 0 && this[this.t-1] == c) --this.t;
        }

        // (public) return string representation in given radix
        function bnToString(b) {
          if(this.s < 0) return "-"+this.negate().toString(b);
          var k;
          if(b == 16) k = 4;
          else if(b == 8) k = 3;
          else if(b == 2) k = 1;
          else if(b == 32) k = 5;
          else if(b == 4) k = 2;
          else return this.toRadix(b);
          var km = (1<<k)-1, d, m = false, r = "", i = this.t;
          var p = this.DB-(i*this.DB)%k;
          if(i-- > 0) {
            if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
            while(i >= 0) {
              if(p < k) {
                d = (this[i]&((1<<p)-1))<<(k-p);
                d |= this[--i]>>(p+=this.DB-k);
              }
              else {
                d = (this[i]>>(p-=k))&km;
                if(p <= 0) { p += this.DB; --i; }
              }
              if(d > 0) m = true;
              if(m) r += int2char(d);
            }
          }
          return m?r:"0";
        }

        // (public) -this
        function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }

        // (public) |this|
        function bnAbs() { return (this.s<0)?this.negate():this; }

        // (public) return + if this > a, - if this < a, 0 if equal
        function bnCompareTo(a) {
          var r = this.s-a.s;
          if(r != 0) return r;
          var i = this.t;
          r = i-a.t;
          if(r != 0) return (this.s<0)?-r:r;
          while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
          return 0;
        }

        // returns bit length of the integer x
        function nbits(x) {
          var r = 1, t;
          if((t=x>>>16) != 0) { x = t; r += 16; }
          if((t=x>>8) != 0) { x = t; r += 8; }
          if((t=x>>4) != 0) { x = t; r += 4; }
          if((t=x>>2) != 0) { x = t; r += 2; }
          if((t=x>>1) != 0) { x = t; r += 1; }
          return r;
        }

        // (public) return the number of bits in "this"
        function bnBitLength() {
          if(this.t <= 0) return 0;
          return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
        }

        // (protected) r = this << n*DB
        function bnpDLShiftTo(n,r) {
          var i;
          for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
          for(i = n-1; i >= 0; --i) r[i] = 0;
          r.t = this.t+n;
          r.s = this.s;
        }

        // (protected) r = this >> n*DB
        function bnpDRShiftTo(n,r) {
          for(var i = n; i < this.t; ++i) r[i-n] = this[i];
          r.t = Math.max(this.t-n,0);
          r.s = this.s;
        }

        // (protected) r = this << n
        function bnpLShiftTo(n,r) {
          var bs = n%this.DB;
          var cbs = this.DB-bs;
          var bm = (1<<cbs)-1;
          var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
          for(i = this.t-1; i >= 0; --i) {
            r[i+ds+1] = (this[i]>>cbs)|c;
            c = (this[i]&bm)<<bs;
          }
          for(i = ds-1; i >= 0; --i) r[i] = 0;
          r[ds] = c;
          r.t = this.t+ds+1;
          r.s = this.s;
          r.clamp();
        }

        // (protected) r = this >> n
        function bnpRShiftTo(n,r) {
          r.s = this.s;
          var ds = Math.floor(n/this.DB);
          if(ds >= this.t) { r.t = 0; return; }
          var bs = n%this.DB;
          var cbs = this.DB-bs;
          var bm = (1<<bs)-1;
          r[0] = this[ds]>>bs;
          for(var i = ds+1; i < this.t; ++i) {
            r[i-ds-1] |= (this[i]&bm)<<cbs;
            r[i-ds] = this[i]>>bs;
          }
          if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
          r.t = this.t-ds;
          r.clamp();
        }

        // (protected) r = this - a
        function bnpSubTo(a,r) {
          var i = 0, c = 0, m = Math.min(a.t,this.t);
          while(i < m) {
            c += this[i]-a[i];
            r[i++] = c&this.DM;
            c >>= this.DB;
          }
          if(a.t < this.t) {
            c -= a.s;
            while(i < this.t) {
              c += this[i];
              r[i++] = c&this.DM;
              c >>= this.DB;
            }
            c += this.s;
          }
          else {
            c += this.s;
            while(i < a.t) {
              c -= a[i];
              r[i++] = c&this.DM;
              c >>= this.DB;
            }
            c -= a.s;
          }
          r.s = (c<0)?-1:0;
          if(c < -1) r[i++] = this.DV+c;
          else if(c > 0) r[i++] = c;
          r.t = i;
          r.clamp();
        }

        // (protected) r = this * a, r != this,a (HAC 14.12)
        // "this" should be the larger one if appropriate.
        function bnpMultiplyTo(a,r) {
          var x = this.abs(), y = a.abs();
          var i = x.t;
          r.t = i+y.t;
          while(--i >= 0) r[i] = 0;
          for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
          r.s = 0;
          r.clamp();
          if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
        }

        // (protected) r = this^2, r != this (HAC 14.16)
        function bnpSquareTo(r) {
          var x = this.abs();
          var i = r.t = 2*x.t;
          while(--i >= 0) r[i] = 0;
          for(i = 0; i < x.t-1; ++i) {
            var c = x.am(i,x[i],r,2*i,0,1);
            if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
              r[i+x.t] -= x.DV;
              r[i+x.t+1] = 1;
            }
          }
          if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
          r.s = 0;
          r.clamp();
        }

        // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
        // r != q, this != m.  q or r may be null.
        function bnpDivRemTo(m,q,r) {
          var pm = m.abs();
          if(pm.t <= 0) return;
          var pt = this.abs();
          if(pt.t < pm.t) {
            if(q != null) q.fromInt(0);
            if(r != null) this.copyTo(r);
            return;
          }
          if(r == null) r = nbi();
          var y = nbi(), ts = this.s, ms = m.s;
          var nsh = this.DB-nbits(pm[pm.t-1]);  // normalize modulus
          if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
          else { pm.copyTo(y); pt.copyTo(r); }
          var ys = y.t;
          var y0 = y[ys-1];
          if(y0 == 0) return;
          var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
          var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
          var i = r.t, j = i-ys, t = (q==null)?nbi():q;
          y.dlShiftTo(j,t);
          if(r.compareTo(t) >= 0) {
            r[r.t++] = 1;
            r.subTo(t,r);
          }
          BigInteger.ONE.dlShiftTo(ys,t);
          t.subTo(y,y); // "negative" y so we can replace sub with am later
          while(y.t < ys) y[y.t++] = 0;
          while(--j >= 0) {
            // Estimate quotient digit
            var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
            if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) {  // Try it out
              y.dlShiftTo(j,t);
              r.subTo(t,r);
              while(r[i] < --qd) r.subTo(t,r);
            }
          }
          if(q != null) {
            r.drShiftTo(ys,q);
            if(ts != ms) BigInteger.ZERO.subTo(q,q);
          }
          r.t = ys;
          r.clamp();
          if(nsh > 0) r.rShiftTo(nsh,r);  // Denormalize remainder
          if(ts < 0) BigInteger.ZERO.subTo(r,r);
        }

        // (public) this mod a
        function bnMod(a) {
          var r = nbi();
          this.abs().divRemTo(a,null,r);
          if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
          return r;
        }

        // Modular reduction using "classic" algorithm
        function Classic(m) { this.m = m; }
        function cConvert(x) {
          if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
          else return x;
        }
        function cRevert(x) { return x; }
        function cReduce(x) { x.divRemTo(this.m,null,x); }
        function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
        function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }

        Classic.prototype.convert = cConvert;
        Classic.prototype.revert = cRevert;
        Classic.prototype.reduce = cReduce;
        Classic.prototype.mulTo = cMulTo;
        Classic.prototype.sqrTo = cSqrTo;


        function bnpInvDigit() {
          if(this.t < 1) return 0;
          var x = this[0];
          if((x&1) == 0) return 0;
          var y = x&3;    // y == 1/x mod 2^2
          y = (y*(2-(x&0xf)*y))&0xf;  // y == 1/x mod 2^4
          y = (y*(2-(x&0xff)*y))&0xff;  // y == 1/x mod 2^8
          y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
          // last step - calculate inverse mod DV directly;
          // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
          y = (y*(2-x*y%this.DV))%this.DV;    // y == 1/x mod 2^dbits
          // we really want the negative inverse, and -DV < y < DV
          return (y>0)?this.DV-y:-y;
        }

        // Montgomery reduction
        function Montgomery(m) {
          this.m = m;
          this.mp = m.invDigit();
          this.mpl = this.mp&0x7fff;
          this.mph = this.mp>>15;
          this.um = (1<<(m.DB-15))-1;
          this.mt2 = 2*m.t;
        }

        // xR mod m
        function montConvert(x) {
          var r = nbi();
          x.abs().dlShiftTo(this.m.t,r);
          r.divRemTo(this.m,null,r);
          if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
          return r;
        }

        // x/R mod m
        function montRevert(x) {
          var r = nbi();
          x.copyTo(r);
          this.reduce(r);
          return r;
        }

        // x = x/R mod m (HAC 14.32)
        function montReduce(x) {
          while(x.t <= this.mt2)  // pad x so am has enough room later
            x[x.t++] = 0;
          for(var i = 0; i < this.m.t; ++i) {
            // faster way of calculating u0 = x[i]*mp mod DV
            var j = x[i]&0x7fff;
            var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
            // use am to combine the multiply-shift-add into one call
            j = i+this.m.t;
            x[j] += this.m.am(0,u0,x,i,0,this.m.t);
            // propagate carry
            while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
          }
          x.clamp();
          x.drShiftTo(this.m.t,x);
          if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
        }

        // r = "x^2/R mod m"; x != r
        function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }

        // r = "xy/R mod m"; x,y != r
        function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }

        Montgomery.prototype.convert = montConvert;
        Montgomery.prototype.revert = montRevert;
        Montgomery.prototype.reduce = montReduce;
        Montgomery.prototype.mulTo = montMulTo;
        Montgomery.prototype.sqrTo = montSqrTo;

        // (protected) true iff this is even
        function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }

        // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
        function bnpExp(e,z) {
          if(e > 0xffffffff || e < 1) return BigInteger.ONE;
          var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
          g.copyTo(r);
          while(--i >= 0) {
            z.sqrTo(r,r2);
            if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
            else { var t = r; r = r2; r2 = t; }
          }
          return z.revert(r);
        }

        // (public) this^e % m, 0 <= e < 2^32
        function bnModPowInt(e,m) {
          var z;
          if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
          return this.exp(e,z);
        }

        // protected
        BigInteger.prototype.copyTo = bnpCopyTo;
        BigInteger.prototype.fromInt = bnpFromInt;
        BigInteger.prototype.fromString = bnpFromString;
        BigInteger.prototype.clamp = bnpClamp;
        BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
        BigInteger.prototype.drShiftTo = bnpDRShiftTo;
        BigInteger.prototype.lShiftTo = bnpLShiftTo;
        BigInteger.prototype.rShiftTo = bnpRShiftTo;
        BigInteger.prototype.subTo = bnpSubTo;
        BigInteger.prototype.multiplyTo = bnpMultiplyTo;
        BigInteger.prototype.squareTo = bnpSquareTo;
        BigInteger.prototype.divRemTo = bnpDivRemTo;
        BigInteger.prototype.invDigit = bnpInvDigit;
        BigInteger.prototype.isEven = bnpIsEven;
        BigInteger.prototype.exp = bnpExp;

        // public
        BigInteger.prototype.toString = bnToString;
        BigInteger.prototype.negate = bnNegate;
        BigInteger.prototype.abs = bnAbs;
        BigInteger.prototype.compareTo = bnCompareTo;
        BigInteger.prototype.bitLength = bnBitLength;
        BigInteger.prototype.mod = bnMod;
        BigInteger.prototype.modPowInt = bnModPowInt;

        // "constants"
        BigInteger.ZERO = nbv(0);
        BigInteger.ONE = nbv(1);



        /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
         */
        var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var b64pad="=";

        function hex2b64(h) {
          var i;
          var c;
          var ret = "";
          for(i = 0; i+3 <= h.length; i+=3) {
            c = parseInt(h.substring(i,i+3),16);
            ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
          }
          if(i+1 == h.length) {
            c = parseInt(h.substring(i,i+1),16);
            ret += b64map.charAt(c << 2);
          }
          else if(i+2 == h.length) {
            c = parseInt(h.substring(i,i+2),16);
            ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
          }
          if (b64pad) while((ret.length & 3) > 0) ret += b64pad;
          return ret;
        }

        // convert a base64 string to hex
        function b64tohex(s) {
          var ret = "";
          var i;
          var k = 0; // b64 state, 0-3
          var slop;
          var v;
          for(i = 0; i < s.length; ++i) {
            if(s.charAt(i) == b64pad) break;
            v = b64map.indexOf(s.charAt(i));
            if(v < 0) continue;
            if(k == 0) {
              ret += int2char(v >> 2);
              slop = v & 3;
              k = 1;
            }
            else if(k == 1) {
              ret += int2char((slop << 2) | (v >> 4));
              slop = v & 0xf;
              k = 2;
            }
            else if(k == 2) {
              ret += int2char(slop);
              ret += int2char(v >> 2);
              slop = v & 3;
              k = 3;
            }
            else {
              ret += int2char((slop << 2) | (v >> 4));
              ret += int2char(v & 0xf);
              k = 0;
            }
          }
          if(k == 1)
            ret += int2char(slop << 2);
          return ret;
        }

        // convert a base64 string to a byte/number array
        function b64toBA(s) {
          //piggyback on b64tohex for now, optimize later
          var h = b64tohex(s);
          var i;
          var a = new Array();
          for(i = 0; 2*i < h.length; ++i) {
            a[i] = parseInt(h.substring(2*i,2*i+2),16);
          }
          return a;
        }


        /*
        -------------------------------------------------------------------------------------------------
         */
        function Arcfour() {
          this.i = 0;
          this.j = 0;
          this.S = new Array();
        }

        // Initialize arcfour context from key, an array of ints, each from [0..255]
        function ARC4init(key) {
          var i, j, t;
          for(i = 0; i < 256; ++i)
            this.S[i] = i;
          j = 0;
          for(i = 0; i < 256; ++i) {
            j = (j + this.S[i] + key[i % key.length]) & 255;
            t = this.S[i];
            this.S[i] = this.S[j];
            this.S[j] = t;
          }
          this.i = 0;
          this.j = 0;
        }

        function ARC4next() {
          var t;
          this.i = (this.i + 1) & 255;
          this.j = (this.j + this.S[this.i]) & 255;
          t = this.S[this.i];
          this.S[this.i] = this.S[this.j];
          this.S[this.j] = t;
          return this.S[(t + this.S[this.i]) & 255];
        }

        Arcfour.prototype.init = ARC4init;
        Arcfour.prototype.next = ARC4next;

        // Plug in your RNG constructor here
        function prng_newstate() {
          return new Arcfour();
        }

        // Pool size must be a multiple of 4 and greater than 32.
        // An array of bytes the size of the pool will be passed to init()
        var rng_psize = 256;

        /*
        ---------------------------------------SecureRandom----------------------------------------------------------
         */
        var rng_state;
        var rng_pool;
        var rng_pptr;

        // Mix in a 32-bit integer into the pool
        function rng_seed_int(x) {
          rng_pool[rng_pptr++] ^= x & 255;
          rng_pool[rng_pptr++] ^= (x >> 8) & 255;
          rng_pool[rng_pptr++] ^= (x >> 16) & 255;
          rng_pool[rng_pptr++] ^= (x >> 24) & 255;
          if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
        }

        // Mix in the current time (w/milliseconds) into the pool
        function rng_seed_time() {
          rng_seed_int(new Date().getTime());
        }

        // Initialize the pool with junk if needed.
        if (rng_pool == null) {
          rng_pool = new Array();
          rng_pptr = 0;
          var t;
          if (window !== undefined &&
              (window.crypto !== undefined ||
               window.msCrypto !== undefined)) {
            var crypto = window.crypto || window.msCrypto;
            if (crypto.getRandomValues) {
              // Use webcrypto if available
              var ua = new Uint8Array(32);
              crypto.getRandomValues(ua);
              for(t = 0; t < 32; ++t)
                rng_pool[rng_pptr++] = ua[t];
            } else if (navigator.appName == "Netscape" && navigator.appVersion < "5") {
              // Extract entropy (256 bits) from NS4 RNG if available
              var z = window.crypto.random(32);
              for(t = 0; t < z.length; ++t)
                rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
            }
          }  
          while (rng_pptr < rng_psize) {  // extract some randomness from Math.random()
            t = Math.floor(65536 * Math.random());
            rng_pool[rng_pptr++] = t >>> 8;
            rng_pool[rng_pptr++] = t & 255;
          }
          rng_pptr = 0;
          rng_seed_time();
          //rng_seed_int(window.screenX);
          //rng_seed_int(window.screenY);
        }

        function rng_get_byte() {
          if (rng_state == null) {
            rng_seed_time();
            rng_state = prng_newstate();
            rng_state.init(rng_pool);
            for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
              rng_pool[rng_pptr] = 0;
            rng_pptr = 0;
            //rng_pool = null;
          }
          // TODO: allow reseeding after first request
          return rng_state.next();
        }

        function rng_get_bytes(ba) {
          var i;
          for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
        }

        function SecureRandom() {}

        SecureRandom.prototype.nextBytes = rng_get_bytes;


        /*
        ---------------------------------------CryptoJS----------------------------------------------------------
         */

        var CryptoJS = CryptoJS || (function (Math, undefined$1) {
            /**
             * CryptoJS namespace.
             */
            var C = {};

            /**
             * Library namespace.
             */
            var C_lib = C.lib = {};

            /**
             * Base object for prototypal inheritance.
             */
            var Base = C_lib.Base = (function () {
                function F() {}

                return {
                    
                    extend: function (overrides) {
                        // Spawn
                        F.prototype = this;
                        var subtype = new F();

                        // Augment
                        if (overrides) {
                            subtype.mixIn(overrides);
                        }

                        // Create default initializer
                        if (!subtype.hasOwnProperty('init')) {
                            subtype.init = function () {
                                subtype.$super.init.apply(this, arguments);
                            };
                        }

                        // Initializer's prototype is the subtype object
                        subtype.init.prototype = subtype;

                        // Reference supertype
                        subtype.$super = this;

                        return subtype;
                    },

                    
                    create: function () {
                        var instance = this.extend();
                        instance.init.apply(instance, arguments);

                        return instance;
                    },

                   
                    init: function () {
                    },

                    
                    mixIn: function (properties) {
                        for (var propertyName in properties) {
                            if (properties.hasOwnProperty(propertyName)) {
                                this[propertyName] = properties[propertyName];
                            }
                        }

                        // IE won't copy toString using the loop above
                        if (properties.hasOwnProperty('toString')) {
                            this.toString = properties.toString;
                        }
                    },

                    
                    clone: function () {
                        return this.init.prototype.extend(this);
                    }
                };
            }());

            
            var WordArray = C_lib.WordArray = Base.extend({
                
                init: function (words, sigBytes) {
                    words = this.words = words || [];

                    if (sigBytes != undefined$1) {
                        this.sigBytes = sigBytes;
                    } else {
                        this.sigBytes = words.length * 4;
                    }
                },

               
                toString: function (encoder) {
                    return (encoder || Hex).stringify(this);
                },

                
                concat: function (wordArray) {
                    // Shortcuts
                    var thisWords = this.words;
                    var thatWords = wordArray.words;
                    var thisSigBytes = this.sigBytes;
                    var thatSigBytes = wordArray.sigBytes;

                    // Clamp excess bits
                    this.clamp();

                    // Concat
                    if (thisSigBytes % 4) {
                        // Copy one byte at a time
                        for (var i = 0; i < thatSigBytes; i++) {
                            var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
                            thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
                        }
                    } else {
                        // Copy one word at a time
                        for (var i = 0; i < thatSigBytes; i += 4) {
                            thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
                        }
                    }
                    this.sigBytes += thatSigBytes;

                    // Chainable
                    return this;
                },

                
                clamp: function () {
                    // Shortcuts
                    var words = this.words;
                    var sigBytes = this.sigBytes;

                    // Clamp
                    words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
                    words.length = Math.ceil(sigBytes / 4);
                },

               
                clone: function () {
                    var clone = Base.clone.call(this);
                    clone.words = this.words.slice(0);

                    return clone;
                },

                
                random: function (nBytes) {
                    var words = [];
                    for (var i = 0; i < nBytes; i += 4) {
                        words.push((Math.random() * 0x100000000) | 0);
                    }

                    return new WordArray.init(words, nBytes);
                }
            });


            var C_enc = C.enc = {};

            
            var Hex = C_enc.Hex = {
                
                stringify: function (wordArray) {
                    // Shortcuts
                    var words = wordArray.words;
                    var sigBytes = wordArray.sigBytes;

                    // Convert
                    var hexChars = [];
                    for (var i = 0; i < sigBytes; i++) {
                        var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
                        hexChars.push((bite >>> 4).toString(16));
                        hexChars.push((bite & 0x0f).toString(16));
                    }

                    return hexChars.join('');
                },

               
                parse: function (hexStr) {
                    // Shortcut
                    var hexStrLength = hexStr.length;

                    // Convert
                    var words = [];
                    for (var i = 0; i < hexStrLength; i += 2) {
                        words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
                    }

                    return new WordArray.init(words, hexStrLength / 2);
                }
            };

            /**
             * Latin1 encoding strategy.
             */
            var Latin1 = C_enc.Latin1 = {
               
                stringify: function (wordArray) {
                    // Shortcuts
                    var words = wordArray.words;
                    var sigBytes = wordArray.sigBytes;

                    // Convert
                    var latin1Chars = [];
                    for (var i = 0; i < sigBytes; i++) {
                        var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
                        latin1Chars.push(String.fromCharCode(bite));
                    }

                    return latin1Chars.join('');
                },

                
                parse: function (latin1Str) {
                    // Shortcut
                    var latin1StrLength = latin1Str.length;

                    // Convert
                    var words = [];
                    for (var i = 0; i < latin1StrLength; i++) {
                        words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
                    }

                    return new WordArray.init(words, latin1StrLength);
                }
            };

           
            var Utf8 = C_enc.Utf8 = {
                
                stringify: function (wordArray) {
                    try {
                        return decodeURIComponent(escape(Latin1.stringify(wordArray)));
                    } catch (e) {
                        throw new Error('Malformed UTF-8 data');
                    }
                },

                
                parse: function (utf8Str) {
                    return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
                }
            };

            
            var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
                
                reset: function () {
                    // Initial values
                    this._data = new WordArray.init();
                    this._nDataBytes = 0;
                },

                
                _append: function (data) {
                    // Convert string to WordArray, else assume WordArray already
                    if (typeof data == 'string') {
                        data = Utf8.parse(data);
                    }

                    // Append
                    this._data.concat(data);
                    this._nDataBytes += data.sigBytes;
                },

                _process: function (doFlush) {
                    // Shortcuts
                    var data = this._data;
                    var dataWords = data.words;
                    var dataSigBytes = data.sigBytes;
                    var blockSize = this.blockSize;
                    var blockSizeBytes = blockSize * 4;

                    // Count blocks ready
                    var nBlocksReady = dataSigBytes / blockSizeBytes;
                    if (doFlush) {
                        // Round up to include partial blocks
                        nBlocksReady = Math.ceil(nBlocksReady);
                    } else {
                        // Round down to include only full blocks,
                        // less the number of blocks that must remain in the buffer
                        nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
                    }

                    // Count words ready
                    var nWordsReady = nBlocksReady * blockSize;

                    // Count bytes ready
                    var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);

                    // Process blocks
                    if (nWordsReady) {
                        for (var offset = 0; offset < nWordsReady; offset += blockSize) {
                            // Perform concrete-algorithm logic
                            this._doProcessBlock(dataWords, offset);
                        }

                        // Remove processed words
                        var processedWords = dataWords.splice(0, nWordsReady);
                        data.sigBytes -= nBytesReady;
                    }

                    // Return processed words
                    return new WordArray.init(processedWords, nBytesReady);
                },

               
                clone: function () {
                    var clone = Base.clone.call(this);
                    clone._data = this._data.clone();

                    return clone;
                },

                _minBufferSize: 0
            });

           
            var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
                /**
                 * Configuration options.
                 */
                cfg: Base.extend(),

                
                init: function (cfg) {
                    // Apply config defaults
                    this.cfg = this.cfg.extend(cfg);

                    // Set initial values
                    this.reset();
                },

                
                reset: function () {
                    // Reset data buffer
                    BufferedBlockAlgorithm.reset.call(this);

                    // Perform concrete-hasher logic
                    this._doReset();
                },

                
                update: function (messageUpdate) {
                    // Append
                    this._append(messageUpdate);

                    // Update the hash
                    this._process();

                    // Chainable
                    return this;
                },

                
                finalize: function (messageUpdate) {
                    // Final message update
                    if (messageUpdate) {
                        this._append(messageUpdate);
                    }

                    // Perform concrete-hasher logic
                    var hash = this._doFinalize();

                    return hash;
                },

                blockSize: 512/32,

                
                _createHelper: function (hasher) {
                    return function (message, cfg) {
                        return new hasher.init(cfg).finalize(message);
                    };
                },

                
                _createHmacHelper: function (hasher) {
                    return function (message, key) {
                        return new C_algo.HMAC.init(hasher, key).finalize(message);
                    };
                }
            });

           
            var C_algo = C.algo = {};

            return C;
        }(Math));






        (function () {
            // Shortcuts
            var C = CryptoJS;
            var C_lib = C.lib;
            var WordArray = C_lib.WordArray;
            var Hasher = C_lib.Hasher;
            var C_algo = C.algo;

            // Reusable object
            var W = [];

            /**
             * SHA-1 hash algorithm.
             */
            var SHA1 = C_algo.SHA1 = Hasher.extend({
                _doReset: function () {
                    this._hash = new WordArray.init([
                        0x67452301, 0xefcdab89,
                        0x98badcfe, 0x10325476,
                        0xc3d2e1f0
                    ]);
                },

                _doProcessBlock: function (M, offset) {
                    // Shortcut
                    var H = this._hash.words;

                    // Working variables
                    var a = H[0];
                    var b = H[1];
                    var c = H[2];
                    var d = H[3];
                    var e = H[4];

                    // Computation
                    for (var i = 0; i < 80; i++) {
                        if (i < 16) {
                            W[i] = M[offset + i] | 0;
                        } else {
                            var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
                            W[i] = (n << 1) | (n >>> 31);
                        }

                        var t = ((a << 5) | (a >>> 27)) + e + W[i];
                        if (i < 20) {
                            t += ((b & c) | (~b & d)) + 0x5a827999;
                        } else if (i < 40) {
                            t += (b ^ c ^ d) + 0x6ed9eba1;
                        } else if (i < 60) {
                            t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
                        } else /* if (i < 80) */ {
                            t += (b ^ c ^ d) - 0x359d3e2a;
                        }

                        e = d;
                        d = c;
                        c = (b << 30) | (b >>> 2);
                        b = a;
                        a = t;
                    }

                    // Intermediate hash value
                    H[0] = (H[0] + a) | 0;
                    H[1] = (H[1] + b) | 0;
                    H[2] = (H[2] + c) | 0;
                    H[3] = (H[3] + d) | 0;
                    H[4] = (H[4] + e) | 0;
                },

                _doFinalize: function () {
                    // Shortcuts
                    var data = this._data;
                    var dataWords = data.words;

                    var nBitsTotal = this._nDataBytes * 8;
                    var nBitsLeft = data.sigBytes * 8;

                    // Add padding
                    dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
                    dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
                    dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
                    data.sigBytes = dataWords.length * 4;

                    // Hash final blocks
                    this._process();

                    // Return final computed hash
                    return this._hash;
                },

                clone: function () {
                    var clone = Hasher.clone.call(this);
                    clone._hash = this._hash.clone();

                    return clone;
                }
            });

            C.SHA1 = Hasher._createHelper(SHA1);
            C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
        }());




        (function (Math) {
            // Shortcuts
            var C = CryptoJS;
            var C_lib = C.lib;
            var WordArray = C_lib.WordArray;
            var Hasher = C_lib.Hasher;
            var C_algo = C.algo;

            // Initialization and round constants tables
            var H = [];
            var K = [];

            // Compute constants
            (function () {
                function isPrime(n) {
                    var sqrtN = Math.sqrt(n);
                    for (var factor = 2; factor <= sqrtN; factor++) {
                        if (!(n % factor)) {
                            return false;
                        }
                    }

                    return true;
                }

                function getFractionalBits(n) {
                    return ((n - (n | 0)) * 0x100000000) | 0;
                }

                var n = 2;
                var nPrime = 0;
                while (nPrime < 64) {
                    if (isPrime(n)) {
                        if (nPrime < 8) {
                            H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
                        }
                        K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));

                        nPrime++;
                    }

                    n++;
                }
            }());

            // Reusable object
            var W = [];

            /**
             * SHA-256 hash algorithm.
             */
            var SHA256 = C_algo.SHA256 = Hasher.extend({
                _doReset: function () {
                    this._hash = new WordArray.init(H.slice(0));
                },

                _doProcessBlock: function (M, offset) {
                    // Shortcut
                    var H = this._hash.words;

                    // Working variables
                    var a = H[0];
                    var b = H[1];
                    var c = H[2];
                    var d = H[3];
                    var e = H[4];
                    var f = H[5];
                    var g = H[6];
                    var h = H[7];

                    // Computation
                    for (var i = 0; i < 64; i++) {
                        if (i < 16) {
                            W[i] = M[offset + i] | 0;
                        } else {
                            var gamma0x = W[i - 15];
                            var gamma0  = ((gamma0x << 25) | (gamma0x >>> 7))  ^
                                          ((gamma0x << 14) | (gamma0x >>> 18)) ^
                                           (gamma0x >>> 3);

                            var gamma1x = W[i - 2];
                            var gamma1  = ((gamma1x << 15) | (gamma1x >>> 17)) ^
                                          ((gamma1x << 13) | (gamma1x >>> 19)) ^
                                           (gamma1x >>> 10);

                            W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
                        }

                        var ch  = (e & f) ^ (~e & g);
                        var maj = (a & b) ^ (a & c) ^ (b & c);

                        var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
                        var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7)  | (e >>> 25));

                        var t1 = h + sigma1 + ch + K[i] + W[i];
                        var t2 = sigma0 + maj;

                        h = g;
                        g = f;
                        f = e;
                        e = (d + t1) | 0;
                        d = c;
                        c = b;
                        b = a;
                        a = (t1 + t2) | 0;
                    }

                    // Intermediate hash value
                    H[0] = (H[0] + a) | 0;
                    H[1] = (H[1] + b) | 0;
                    H[2] = (H[2] + c) | 0;
                    H[3] = (H[3] + d) | 0;
                    H[4] = (H[4] + e) | 0;
                    H[5] = (H[5] + f) | 0;
                    H[6] = (H[6] + g) | 0;
                    H[7] = (H[7] + h) | 0;
                },

                _doFinalize: function () {
                    // Shortcuts
                    var data = this._data;
                    var dataWords = data.words;

                    var nBitsTotal = this._nDataBytes * 8;
                    var nBitsLeft = data.sigBytes * 8;

                    // Add padding
                    dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
                    dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
                    dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
                    data.sigBytes = dataWords.length * 4;

                    // Hash final blocks
                    this._process();

                    // Return final computed hash
                    return this._hash;
                },

                clone: function () {
                    var clone = Hasher.clone.call(this);
                    clone._hash = this._hash.clone();

                    return clone;
                }
            });

            C.SHA256 = Hasher._createHelper(SHA256);


            C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
        }(Math));


        /*

        --------------------------------------------------asn1hex-1.1-------------------------------------------------------
        */
        var ASN1HEX = new function() {
        };

        ASN1HEX.getLblen = function(s, idx) {
            if (s.substr(idx + 2, 1) != '8') return 1;
            var i = parseInt(s.substr(idx + 3, 1));
            if (i == 0) return -1;             // length octet '80' indefinite length
            if (0 < i && i < 10) return i + 1; // including '8?' octet;
            return -2;                         // malformed format
        };

        ASN1HEX.getL = function(s, idx) {
            var len = ASN1HEX.getLblen(s, idx);
            if (len < 1) return '';
            return s.substr(idx + 2, len * 2);
        };

        ASN1HEX.getVblen = function(s, idx) {
            var hLen, bi;
            hLen = ASN1HEX.getL(s, idx);
            if (hLen == '') return -1;
            if (hLen.substr(0, 1) === '8') {
                bi = new BigInteger(hLen.substr(2), 16);
            } else {
                bi = new BigInteger(hLen, 16);
            }
        //  console.log("bi---",bi, BigInteger)
            return bi.intValue();
        };


        ASN1HEX.getVidx = function(s, idx) {
            var l_len = ASN1HEX.getLblen(s, idx);
            if (l_len < 0) return l_len;
            return idx + (l_len + 1) * 2;
        };


        ASN1HEX.getV = function(s, idx) {
            var idx1 = ASN1HEX.getVidx(s, idx);
            var blen = ASN1HEX.getVblen(s, idx);
            return s.substr(idx1, blen * 2);
        };

        ASN1HEX.getTLV = function(s, idx) {
            return s.substr(idx, 2) + ASN1HEX.getL(s, idx) + ASN1HEX.getV(s, idx);
        };

        // ========== sibling methods ================================

        ASN1HEX.getNextSiblingIdx = function(s, idx) {
            var idx1 = ASN1HEX.getVidx(s, idx);
            var blen = ASN1HEX.getVblen(s, idx);
            return idx1 + blen * 2;
        };

        // ========== children methods ===============================

        ASN1HEX.getChildIdx = function(h, pos) {
            var _ASN1HEX = ASN1HEX;
            var a = new Array();
            var p0 = _ASN1HEX.getVidx(h, pos);
            if (h.substr(pos, 2) == "03") {
            a.push(p0 + 2); // BITSTRING value without unusedbits
            } else {
            a.push(p0);
            }

            var blen = _ASN1HEX.getVblen(h, pos);
            var p = p0;
            var k = 0;
            while (1) {
                var pNext = _ASN1HEX.getNextSiblingIdx(h, p);
                if (pNext == null || (pNext - p0  >= (blen * 2))) break;
                if (k >= 200) break;
                    
                a.push(pNext);
                p = pNext;
                    
                k++;
            }
            
            return a;
        };


        ASN1HEX.getNthChildIdx = function(h, idx, nth) {
            var a = ASN1HEX.getChildIdx(h, idx);
            return a[nth];
        };

        // ========== decendant methods ==============================

        ASN1HEX.getIdxbyList = function(h, currentIndex, nthList, checkingTag) {
            var _ASN1HEX = ASN1HEX;
            var firstNth, a;
            if (nthList.length == 0) {
            if (checkingTag !== undefined) {
                    if (h.substr(currentIndex, 2) !== checkingTag) {
                throw "checking tag doesn't match: " + 
                            h.substr(currentIndex, 2) + "!=" + checkingTag;
                    }
            }
                return currentIndex;
            }
            firstNth = nthList.shift();
            a = _ASN1HEX.getChildIdx(h, currentIndex);
            return _ASN1HEX.getIdxbyList(h, a[firstNth], nthList, checkingTag);
        };


        ASN1HEX.getTLVbyList = function(h, currentIndex, nthList, checkingTag) {
            var _ASN1HEX = ASN1HEX;
            var idx = _ASN1HEX.getIdxbyList(h, currentIndex, nthList);
            if (idx === undefined) {
                throw "can't find nthList object";
            }
            if (checkingTag !== undefined) {
                if (h.substr(idx, 2) != checkingTag) {
                    throw "checking tag doesn't match: " + 
                        h.substr(idx,2) + "!=" + checkingTag;
                }
            }
            return _ASN1HEX.getTLV(h, idx);
        };


        ASN1HEX.getVbyList = function(h, currentIndex, nthList, checkingTag, removeUnusedbits) {
            var _ASN1HEX = ASN1HEX;
            var idx, v;
            idx = _ASN1HEX.getIdxbyList(h, currentIndex, nthList, checkingTag);
            
            if (idx === undefined) {
                throw "can't find nthList object";
            }

            v = _ASN1HEX.getV(h, idx);
            if (removeUnusedbits === true) v = v.substr(2);
            return v;
        };


        ASN1HEX.hextooidstr = function(hex) {
            var zeroPadding = function(s, len) {
                if (s.length >= len) return s;
                return new Array(len - s.length + 1).join('0') + s;
            };

            var a = [];

            // a[0], a[1]
            var hex0 = hex.substr(0, 2);
            var i0 = parseInt(hex0, 16);
            a[0] = new String(Math.floor(i0 / 40));
            a[1] = new String(i0 % 40);

            // a[2]..a[n]
           var hex1 = hex.substr(2);
            var b = [];
            for (var i = 0; i < hex1.length / 2; i++) {
            b.push(parseInt(hex1.substr(i * 2, 2), 16));
            }
            var c = [];
            var cbin = "";
            for (var i = 0; i < b.length; i++) {
                if (b[i] & 0x80) {
                    cbin = cbin + zeroPadding((b[i] & 0x7f).toString(2), 7);
                } else {
                    cbin = cbin + zeroPadding((b[i] & 0x7f).toString(2), 7);
                    c.push(new String(parseInt(cbin, 2)));
                    cbin = "";
                }
            }

            var s = a.join(".");
            if (c.length > 0) s = s + "." + c.join(".");
            return s;
        };

        ASN1HEX.dump = function(hexOrObj, flags, idx, indent) {
            var _ASN1HEX = ASN1HEX;
            var _getV = _ASN1HEX.getV;
            var _dump = _ASN1HEX.dump;
            var _getChildIdx = _ASN1HEX.getChildIdx;

            var hex = hexOrObj;
            if (hexOrObj instanceof KJUR.asn1.ASN1Object)
            hex = hexOrObj.getEncodedHex();

            var _skipLongHex = function(hex, limitNumOctet) {
            if (hex.length <= limitNumOctet * 2) {
                return hex;
            } else {
                var s = hex.substr(0, limitNumOctet) + 
                    "..(total " + hex.length / 2 + "bytes).." +
                    hex.substr(hex.length - limitNumOctet, limitNumOctet);
                return s;
            };
            };

            if (flags === undefined) flags = { "ommit_long_octet": 32 };
            if (idx === undefined) idx = 0;
            if (indent === undefined) indent = "";
            var skipLongHex = flags.ommit_long_octet;

            if (hex.substr(idx, 2) == "01") {
            var v = _getV(hex, idx);
            if (v == "00") {
                return indent + "BOOLEAN FALSE\n";
            } else {
                return indent + "BOOLEAN TRUE\n";
            }
            }
            if (hex.substr(idx, 2) == "02") {
            var v = _getV(hex, idx);
            return indent + "INTEGER " + _skipLongHex(v, skipLongHex) + "\n";
            }
            if (hex.substr(idx, 2) == "03") {
            var v = _getV(hex, idx);
            return indent + "BITSTRING " + _skipLongHex(v, skipLongHex) + "\n";
            }
            if (hex.substr(idx, 2) == "04") {
            var v = _getV(hex, idx);
            if (_ASN1HEX.isASN1HEX(v)) {
                var s = indent + "OCTETSTRING, encapsulates\n";
                s = s + _dump(v, flags, 0, indent + "  ");
                return s;
            } else {
                return indent + "OCTETSTRING " + _skipLongHex(v, skipLongHex) + "\n";
            }
            }
            if (hex.substr(idx, 2) == "05") {
            return indent + "NULL\n";
            }
            if (hex.substr(idx, 2) == "06") {
            var hV = _getV(hex, idx);
                var oidDot = KJUR.asn1.ASN1Util.oidHexToInt(hV);
                var oidName = KJUR.asn1.x509.OID.oid2name(oidDot);
            var oidSpc = oidDot.replace(/\./g, ' ');
                if (oidName != '') {
                return indent + "ObjectIdentifier " + oidName + " (" + oidSpc + ")\n";
            } else {
                return indent + "ObjectIdentifier (" + oidSpc + ")\n";
            }
            }
            if (hex.substr(idx, 2) == "0c") {
            return indent + "UTF8String '" + hextoutf8(_getV(hex, idx)) + "'\n";
            }
            if (hex.substr(idx, 2) == "13") {
            return indent + "PrintableString '" + hextoutf8(_getV(hex, idx)) + "'\n";
            }
            if (hex.substr(idx, 2) == "14") {
            return indent + "TeletexString '" + hextoutf8(_getV(hex, idx)) + "'\n";
            }
            if (hex.substr(idx, 2) == "16") {
            return indent + "IA5String '" + hextoutf8(_getV(hex, idx)) + "'\n";
            }
            if (hex.substr(idx, 2) == "17") {
            return indent + "UTCTime " + hextoutf8(_getV(hex, idx)) + "\n";
            }
            if (hex.substr(idx, 2) == "18") {
            return indent + "GeneralizedTime " + hextoutf8(_getV(hex, idx)) + "\n";
            }
            if (hex.substr(idx, 2) == "30") {
            if (hex.substr(idx, 4) == "3000") {
                return indent + "SEQUENCE {}\n";
            }

            var s = indent + "SEQUENCE\n";
            var aIdx = _getChildIdx(hex, idx);

            var flagsTemp = flags;
            
            if ((aIdx.length == 2 || aIdx.length == 3) &&
                hex.substr(aIdx[0], 2) == "06" &&
                hex.substr(aIdx[aIdx.length - 1], 2) == "04") { // supposed X.509v3 extension
                var oidName = _ASN1HEX.oidname(_getV(hex, aIdx[0]));
                var flagsClone = JSON.parse(JSON.stringify(flags));
                flagsClone.x509ExtName = oidName;
                flagsTemp = flagsClone;
            }
            
            for (var i = 0; i < aIdx.length; i++) {
                s = s + _dump(hex, flagsTemp, aIdx[i], indent + "  ");
            }
            return s;
            }
            if (hex.substr(idx, 2) == "31") {
            var s = indent + "SET\n";
            var aIdx = _getChildIdx(hex, idx);
            for (var i = 0; i < aIdx.length; i++) {
                s = s + _dump(hex, flags, aIdx[i], indent + "  ");
            }
            return s;
            }
            var tag = parseInt(hex.substr(idx, 2), 16);
            if ((tag & 128) != 0) { // context specific 
            var tagNumber = tag & 31;
            if ((tag & 32) != 0) { // structured tag
                var s = indent + "[" + tagNumber + "]\n";
                var aIdx = _getChildIdx(hex, idx);
                for (var i = 0; i < aIdx.length; i++) {
                s = s + _dump(hex, flags, aIdx[i], indent + "  ");
                }
                return s;
            } else { // primitive tag
                var v = _getV(hex, idx);
                if (v.substr(0, 8) == "68747470") { // http
                v = hextoutf8(v);
                }
                if (flags.x509ExtName === "subjectAltName" &&
                tagNumber == 2) {
                v = hextoutf8(v);
                }
                
                var s = indent + "[" + tagNumber + "] " + v + "\n";
                return s;
            }
            }
            return indent + "UNKNOWN(" + hex.substr(idx, 2) + ") " + 
               _getV(hex, idx) + "\n";
        };


        ASN1HEX.isASN1HEX = function(hex) {
            var _ASN1HEX = ASN1HEX;
            if (hex.length % 2 == 1) return false;

            var intL = _ASN1HEX.getVblen(hex, 0);
            var tV = hex.substr(0, 2);
            var lV = _ASN1HEX.getL(hex, 0);
            var hVLength = hex.length - tV.length - lV.length;
            if (hVLength == intL * 2) return true;

            return false;
        };

        ASN1HEX.oidname = function(oidDotOrHex) {
            var _KJUR_asn1 = KJUR.asn1;
            if (KJUR.lang.String.isHex(oidDotOrHex))
            oidDotOrHex = _KJUR_asn1.ASN1Util.oidHexToInt(oidDotOrHex);
            var name = _KJUR_asn1.x509.OID.oid2name(oidDotOrHex);
            if (name === "") name = oidDotOrHex;
            return name;
        };


        /*

        --------------------------------------------------base64x-1.1-------------------------------------------------------
        */
        var KJUR;
        if (typeof KJUR == "undefined" || !KJUR) KJUR = {};
        if (typeof KJUR.lang == "undefined" || !KJUR.lang) KJUR.lang = {};


        KJUR.lang.String = function() {};


        function Base64x() {
        }


        function stoBA(s) {
            var a = new Array();
            for (var i = 0; i < s.length; i++) {
            a[i] = s.charCodeAt(i);
            }
            return a;
        }


        function BAtos(a) {
            var s = "";
            for (var i = 0; i < a.length; i++) {
            s = s + String.fromCharCode(a[i]);
            }
            return s;
        }


        function BAtohex(a) {
            var s = "";
            for (var i = 0; i < a.length; i++) {
            var hex1 = a[i].toString(16);
            if (hex1.length == 1) hex1 = "0" + hex1;
            s = s + hex1;
            }
            return s;
        }


        function stohex(s) {
            return BAtohex(stoBA(s));
        }

        function stob64(s) {
            return hex2b64(stohex(s));
        }

        function stob64u(s) {
            return b64tob64u(hex2b64(stohex(s)));
        }

        function b64utos(s) {
            return BAtos(b64toBA(b64utob64(s)));
        }

        function b64tob64u(s) {
            s = s.replace(/\=/g, "");
            s = s.replace(/\+/g, "-");
            s = s.replace(/\//g, "_");
            return s;
        }

        function b64utob64(s) {
            if (s.length % 4 == 2) s = s + "==";
            else if (s.length % 4 == 3) s = s + "=";
            s = s.replace(/-/g, "+");
            s = s.replace(/_/g, "/");
            return s;
        }

        function hextob64u(s) {
            if (s.length % 2 == 1) s = "0" + s;
            return b64tob64u(hex2b64(s));
        }

        function b64utohex(s) {
            return b64tohex(b64utob64(s));
        }

        var utf8tob64u, b64utoutf8;

        if (typeof Buffer === 'function') {
          utf8tob64u = function (s) {
            return b64tob64u(new Buffer(s, 'utf8').toString('base64'));
          };

          b64utoutf8 = function (s) {
            return new Buffer(b64utob64(s), 'base64').toString('utf8');
          };
        } else {
          utf8tob64u = function (s) {
            return hextob64u(uricmptohex(encodeURIComponentAll(s)));
          };

          b64utoutf8 = function (s) {
            return decodeURIComponent(hextouricmp(b64utohex(s)));
          };
        }

        function utf8tob64(s) {
          return hex2b64(uricmptohex(encodeURIComponentAll(s)));
        }

        function b64toutf8(s) {
          return decodeURIComponent(hextouricmp(b64tohex(s)));
        }

        function utf8tohex(s) {
          return uricmptohex(encodeURIComponentAll(s));
        }

        function hextoutf8(s) {
          return decodeURIComponent(hextouricmp(s));
        }

        function hextorstr(sHex) {
            var s = "";
            for (var i = 0; i < sHex.length - 1; i += 2) {
                s += String.fromCharCode(parseInt(sHex.substr(i, 2), 16));
            }
            return s;
        }

        function rstrtohex(s) {
            var result = "";
            for (var i = 0; i < s.length; i++) {
                result += ("0" + s.charCodeAt(i).toString(16)).slice(-2);
            }
            return result;
        }

        function hextob64(s) {
            return hex2b64(s);
        }

        function hextob64nl(s) {
            var b64 = hextob64(s);
            var b64nl = b64.replace(/(.{64})/g, "$1\r\n");
            b64nl = b64nl.replace(/\r\n$/, '');
            return b64nl;
        }


        function b64nltohex(s) {
            var b64 = s.replace(/[^0-9A-Za-z\/+=]*/g, '');
            var hex = b64tohex(b64);
            return hex;
        } 

        function hextopem(dataHex, pemHeader) {
            var pemBody = hextob64nl(dataHex);
            return "-----BEGIN " + pemHeader + "-----\r\n" + 
                pemBody + 
                "\r\n-----END " + pemHeader + "-----\r\n";
        }

        function pemtohex(s, sHead) {
            if (s.indexOf("-----BEGIN ") == -1)
                throw "can't find PEM header: " + sHead;

            if (sHead !== undefined) {
                s = s.replace("-----BEGIN " + sHead + "-----", "");
                s = s.replace("-----END " + sHead + "-----", "");
            } else {
                s = s.replace(/-----BEGIN [^-]+-----/, '');
                s = s.replace(/-----END [^-]+-----/, '');
            }
            return b64nltohex(s);
        }

        function hextoArrayBuffer(hex) {
            if (hex.length % 2 != 0) throw "input is not even length";
            if (hex.match(/^[0-9A-Fa-f]+$/) == null) throw "input is not hexadecimal";

            var buffer = new ArrayBuffer(hex.length / 2);
            var view = new DataView(buffer);

            for (var i = 0; i < hex.length / 2; i++) {
            view.setUint8(i, parseInt(hex.substr(i * 2, 2), 16));
            }

            return buffer;
        }

        function ArrayBuffertohex(buffer) {
            var hex = "";
            var view = new DataView(buffer);

            for (var i = 0; i < buffer.byteLength; i++) {
            hex += ("00" + view.getUint8(i).toString(16)).slice(-2);
            }

            return hex;
        }

        function zulutomsec(s) {
            var year, month, day, hour, min, sec, msec, d;
            var sYear, sFrac, sMsec, matchResult;

            matchResult = s.match(/^(\d{2}|\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/);

            if (matchResult) {
                sYear = matchResult[1];
            year = parseInt(sYear);
                if (sYear.length === 2) {
                if (50 <= year && year < 100) {
                year = 1900 + year;
                } else if (0 <= year && year < 50) {
                year = 2000 + year;
                }
            }
            month = parseInt(matchResult[2]) - 1;
            day = parseInt(matchResult[3]);
            hour = parseInt(matchResult[4]);
            min = parseInt(matchResult[5]);
            sec = parseInt(matchResult[6]);
            msec = 0;

            sFrac = matchResult[7];
            if (sFrac !== "") {
                sMsec = (sFrac.substr(1) + "00").substr(0, 3); // .12 -> 012
                msec = parseInt(sMsec);
            }
            return Date.UTC(year, month, day, hour, min, sec, msec);
            }
            throw "unsupported zulu format: " + s;
        }

        function zulutosec(s) {
            var msec = zulutomsec(s);
            return ~~(msec / 1000);
        }

        function zulutodate(s) {
            return new Date(zulutomsec(s));
        }

        function datetozulu(d, flagUTCTime, flagMilli) {
            var s;
            var year = d.getUTCFullYear();
            if (flagUTCTime) {
            if (year < 1950 || 2049 < year) 
                throw "not proper year for UTCTime: " + year;
            s = ("" + year).slice(-2);
            } else {
            s = ("000" + year).slice(-4);
            }
            s += ("0" + (d.getUTCMonth() + 1)).slice(-2);
            s += ("0" + d.getUTCDate()).slice(-2);
            s += ("0" + d.getUTCHours()).slice(-2);
            s += ("0" + d.getUTCMinutes()).slice(-2);
            s += ("0" + d.getUTCSeconds()).slice(-2);
            if (flagMilli) {
            var milli = d.getUTCMilliseconds();
            if (milli !== 0) {
                milli = ("00" + milli).slice(-3);
                milli = milli.replace(/0+$/g, "");
                s += "." + milli;
            }
            }
            s += "Z";
            return s;
        }

        function uricmptohex(s) {
          return s.replace(/%/g, "");
        }

        function hextouricmp(s) {
          return s.replace(/(..)/g, "%$1");
        }

        function ipv6tohex(s) {
          var msgMalformedAddress = "malformed IPv6 address";
          if (! s.match(/^[0-9A-Fa-f:]+$/))
            throw msgMalformedAddress;

          // 1. downcase
          s = s.toLowerCase();

          // 2. expand ::
          var num_colon = s.split(':').length - 1;
          if (num_colon < 2) throw msgMalformedAddress;
          var colon_replacer = ':'.repeat(7 - num_colon + 2);
          s = s.replace('::', colon_replacer);

          // 3. fill zero
          var a = s.split(':');
          if (a.length != 8) throw msgMalformedAddress;
          for (var i = 0; i < 8; i++) {
            a[i] = ("0000" + a[i]).slice(-4);
          }
          return a.join('');
        }

        function hextoipv6(s) {
          if (! s.match(/^[0-9A-Fa-f]{32}$/))
            throw "malformed IPv6 address octet";

          // 1. downcase
          s = s.toLowerCase();

          // 2. split 4
          var a = s.match(/.{1,4}/g);

          // 3. trim leading 0
          for (var i = 0; i < 8; i++) {
            a[i] = a[i].replace(/^0+/, "");
            if (a[i] == '') a[i] = '0';
          }
          s = ":" + a.join(":") + ":";

          // 4. find shrinkables :0:0:...
          var aZero = s.match(/:(0:){2,}/g);

          // 5. no shrinkable
          if (aZero === null) return s.slice(1, -1);

          // 6. find max length :0:0:...
          var item = '';
          for (var i = 0; i < aZero.length; i++) {
            if (aZero[i].length > item.length) item = aZero[i];
          }

          // 7. shrink
          s = s.replace(item, '::');
          return s.slice(1, -1);
        }

        function hextoip(s) {
          var malformedMsg = "malformed hex value";
          if (! s.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))
            throw malformedMsg;
          if (s.length == 8) { // ipv4
            var ip;
            try {
              ip = parseInt(s.substr(0, 2), 16) + "." +
                   parseInt(s.substr(2, 2), 16) + "." +
                   parseInt(s.substr(4, 2), 16) + "." +
                   parseInt(s.substr(6, 2), 16);
              return ip;
            } catch (ex) {
              throw malformedMsg;
            }
          } else if (s.length == 32) {
            return hextoipv6(s);
          } else {
            return s;
          }
        }

        function iptohex(s) {
          var malformedMsg = "malformed IP address";
          s = s.toLowerCase(s);

          if (s.match(/^[0-9.]+$/)) {
            var a = s.split(".");
            if (a.length !== 4) throw malformedMsg;
            var hex = "";
            try {
              for (var i = 0; i < 4; i++) {
                var d = parseInt(a[i]);
                hex += ("0" + d.toString(16)).slice(-2);
              }
              return hex;
            } catch(ex) {
              throw malformedMsg;
            }
          } else if (s.match(/^[0-9a-f:]+$/) && s.indexOf(":") !== -1) {
            return ipv6tohex(s);
          } else {
            throw malformedMsg;
          }
        }

        function encodeURIComponentAll(u8) {
          var s = encodeURIComponent(u8);
          var s2 = "";
          for (var i = 0; i < s.length; i++) {
            if (s[i] == "%") {
              s2 = s2 + s.substr(i, 3);
              i = i + 2;
            } else {
              s2 = s2 + "%" + stohex(s[i]);
            }
          }
          return s2;
        }

        // ==== new lines ================================
        function newline_toUnix(s) {
            s = s.replace(/\r\n/mg, "\n");
            return s;
        }

        function newline_toDos(s) {
            s = s.replace(/\r\n/mg, "\n");
            s = s.replace(/\n/mg, "\r\n");
            return s;
        }


        KJUR.lang.String.isInteger = function(s) {
            if (s.match(/^[0-9]+$/)) {
            return true;
            } else if (s.match(/^-[0-9]+$/)) {
            return true;
            } else {
            return false;
            }
        };

        KJUR.lang.String.isHex = function(s) {
            if (s.length % 2 == 0 &&
            (s.match(/^[0-9a-f]+$/) || s.match(/^[0-9A-F]+$/))) {
            return true;
            } else {
            return false;
            }
        };

        KJUR.lang.String.isBase64 = function(s) {
            s = s.replace(/\s+/g, "");
            if (s.match(/^[0-9A-Za-z+\/]+={0,3}$/) && s.length % 4 == 0) {
            return true;
            } else {
            return false;
            }
        };

        KJUR.lang.String.isBase64URL = function(s) {
            if (s.match(/[+/=]/)) return false;
            s = b64utob64(s);
            return KJUR.lang.String.isBase64(s);
        };

        KJUR.lang.String.isIntegerArray = function(s) {
            s = s.replace(/\s+/g, "");
            if (s.match(/^\[[0-9,]+\]$/)) {
            return true;
            } else {
            return false;
            }
        };


        function hextoposhex(s) {
            if (s.length % 2 == 1) return "0" + s;
            if (s.substr(0, 1) > "7") return "00" + s;
            return s;
        }

        function intarystrtohex(s) {
          s = s.replace(/^\s*\[\s*/, '');
          s = s.replace(/\s*\]\s*$/, '');
          s = s.replace(/\s*/g, '');
          try {
            var hex = s.split(/,/).map(function(element, index, array) {
              var i = parseInt(element);
              if (i < 0 || 255 < i) throw "integer not in range 0-255";
              var hI = ("00" + i.toString(16)).slice(-2);
              return hI;
            }).join('');
            return hex;
          } catch(ex) {
            throw "malformed integer array string: " + ex;
          }
        }

        var strdiffidx = function(s1, s2) {
            var n = s1.length;
            if (s1.length > s2.length) n = s2.length;
            for (var i = 0; i < n; i++) {
            if (s1.charCodeAt(i) != s2.charCodeAt(i)) return i;
            }
            if (s1.length != s2.length) return n;
            return -1; // same
        };




        /*

        --------------------------------------------------crypto-1.1-------------------------------------------------------
        */

        if (typeof KJUR == "undefined" || !KJUR) KJUR = {};

        if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) KJUR.crypto = {};


        KJUR.crypto.Util = new function() {
            this.DIGESTINFOHEAD = {
            'sha1':      "3021300906052b0e03021a05000414",
            'sha224':    "302d300d06096086480165030402040500041c",
            'sha256':    "3031300d060960864801650304020105000420",
            'sha384':    "3041300d060960864801650304020205000430",
            'sha512':    "3051300d060960864801650304020305000440",
            'md2':       "3020300c06082a864886f70d020205000410",
            'md5':       "3020300c06082a864886f70d020505000410",
            'ripemd160': "3021300906052b2403020105000414",
            };

            /*
             * @since crypto 1.1.1
             */
            this.DEFAULTPROVIDER = {
            'md5':          'cryptojs',
            'sha1':         'cryptojs',
            'sha224':       'cryptojs',
            'sha256':       'cryptojs',
            'sha384':       'cryptojs',
            'sha512':       'cryptojs',
            'ripemd160':        'cryptojs',
            'hmacmd5':      'cryptojs',
            'hmacsha1':     'cryptojs',
            'hmacsha224':       'cryptojs',
            'hmacsha256':       'cryptojs',
            'hmacsha384':       'cryptojs',
            'hmacsha512':       'cryptojs',
            'hmacripemd160':    'cryptojs',

            'MD5withRSA':       'cryptojs/jsrsa',
            'SHA1withRSA':      'cryptojs/jsrsa',
            'SHA224withRSA':    'cryptojs/jsrsa',
            'SHA256withRSA':    'cryptojs/jsrsa',
            'SHA384withRSA':    'cryptojs/jsrsa',
            'SHA512withRSA':    'cryptojs/jsrsa',
            'RIPEMD160withRSA': 'cryptojs/jsrsa',

            'MD5withECDSA':     'cryptojs/jsrsa',
            'SHA1withECDSA':    'cryptojs/jsrsa',
            'SHA224withECDSA':  'cryptojs/jsrsa',
            'SHA256withECDSA':  'cryptojs/jsrsa',
            'SHA384withECDSA':  'cryptojs/jsrsa',
            'SHA512withECDSA':  'cryptojs/jsrsa',
            'RIPEMD160withECDSA':   'cryptojs/jsrsa',

            'SHA1withDSA':      'cryptojs/jsrsa',
            'SHA224withDSA':    'cryptojs/jsrsa',
            'SHA256withDSA':    'cryptojs/jsrsa',

            'MD5withRSAandMGF1':        'cryptojs/jsrsa',
            'SHA1withRSAandMGF1':       'cryptojs/jsrsa',
            'SHA224withRSAandMGF1':     'cryptojs/jsrsa',
            'SHA256withRSAandMGF1':     'cryptojs/jsrsa',
            'SHA384withRSAandMGF1':     'cryptojs/jsrsa',
            'SHA512withRSAandMGF1':     'cryptojs/jsrsa',
            'RIPEMD160withRSAandMGF1':  'cryptojs/jsrsa',
            };

            this.CRYPTOJSMESSAGEDIGESTNAME = {
            'md5':      CryptoJS.algo.MD5,
            'sha1':     CryptoJS.algo.SHA1,
            'sha224':   CryptoJS.algo.SHA224,
            'sha256':   CryptoJS.algo.SHA256,
            'sha384':   CryptoJS.algo.SHA384,
            'sha512':   CryptoJS.algo.SHA512,
            'ripemd160':    CryptoJS.algo.RIPEMD160
            };

            this.getDigestInfoHex = function(hHash, alg) {
            if (typeof this.DIGESTINFOHEAD[alg] == "undefined")
                throw "alg not supported in Util.DIGESTINFOHEAD: " + alg;
            return this.DIGESTINFOHEAD[alg] + hHash;
            };

            this.getPaddedDigestInfoHex = function(hHash, alg, keySize) {
            var hDigestInfo = this.getDigestInfoHex(hHash, alg);
            var pmStrLen = keySize / 4; // minimum PM length

            if (hDigestInfo.length + 22 > pmStrLen) // len(0001+ff(*8)+00+hDigestInfo)=22
                throw "key is too short for SigAlg: keylen=" + keySize + "," + alg;

            var hHead = "0001";
            var hTail = "00" + hDigestInfo;
            var hMid = "";
            var fLen = pmStrLen - hHead.length - hTail.length;
            for (var i = 0; i < fLen; i += 2) {
                hMid += "ff";
            }
            var hPaddedMessage = hHead + hMid + hTail;
            return hPaddedMessage;
            };

            this.hashString = function(s, alg) {
                var md = new KJUR.crypto.MessageDigest({'alg': alg});
                return md.digestString(s);
            };

            this.hashHex = function(sHex, alg) {
                var md = new KJUR.crypto.MessageDigest({'alg': alg});
                return md.digestHex(sHex);
            };

            this.sha1 = function(s) {
                var md = new KJUR.crypto.MessageDigest({'alg':'sha1', 'prov':'cryptojs'});
                return md.digestString(s);
            };

            this.sha256 = function(s) {
                var md = new KJUR.crypto.MessageDigest({'alg':'sha256', 'prov':'cryptojs'});
                return md.digestString(s);
            };

            this.sha256Hex = function(s) {
                var md = new KJUR.crypto.MessageDigest({'alg':'sha256', 'prov':'cryptojs'});
                return md.digestHex(s);
            };

            this.sha512 = function(s) {
                var md = new KJUR.crypto.MessageDigest({'alg':'sha512', 'prov':'cryptojs'});
                return md.digestString(s);
            };

            this.sha512Hex = function(s) {
                var md = new KJUR.crypto.MessageDigest({'alg':'sha512', 'prov':'cryptojs'});
                return md.digestHex(s);
            };

        };

        KJUR.crypto.Util.md5 = function(s) {
            var md = new KJUR.crypto.MessageDigest({'alg':'md5', 'prov':'cryptojs'});
            return md.digestString(s);
        };

        KJUR.crypto.Util.ripemd160 = function(s) {
            var md = new KJUR.crypto.MessageDigest({'alg':'ripemd160', 'prov':'cryptojs'});
            return md.digestString(s);
        };

        KJUR.crypto.Util.SECURERANDOMGEN = new SecureRandom();

        KJUR.crypto.Util.getRandomHexOfNbytes = function(n) {
            var ba = new Array(n);
            KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(ba);
            return BAtohex(ba);
        };

        KJUR.crypto.Util.getRandomBigIntegerOfNbytes = function(n) {
            return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbytes(n), 16);
        };


        KJUR.crypto.Util.getRandomHexOfNbits = function(n) {
            var n_remainder = n % 8;
            var n_quotient = (n - n_remainder) / 8;
            var ba = new Array(n_quotient + 1);
            KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(ba);
            ba[0] = (((255 << n_remainder) & 255) ^ 255) & ba[0];
            return BAtohex(ba);
        };

        KJUR.crypto.Util.getRandomBigIntegerOfNbits = function(n) {
            return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbits(n), 16);
        };

        KJUR.crypto.Util.getRandomBigIntegerZeroToMax = function(biMax) {
            var bitLenMax = biMax.bitLength();
            while (1) {
            var biRand = KJUR.crypto.Util.getRandomBigIntegerOfNbits(bitLenMax);
            if (biMax.compareTo(biRand) != -1) return biRand;
            }
        };

        KJUR.crypto.Util.getRandomBigIntegerMinToMax = function(biMin, biMax) {
            var flagCompare = biMin.compareTo(biMax);
            if (flagCompare == 1) throw "biMin is greater than biMax";
            if (flagCompare == 0) return biMin;

            var biDiff = biMax.subtract(biMin);
            var biRand = KJUR.crypto.Util.getRandomBigIntegerZeroToMax(biDiff);
            return biRand.add(biMin);
        };

        KJUR.crypto.MessageDigest = function(params) {
            var md = null;
            var algName = null;
            var provName = null;

            this.setAlgAndProvider = function(alg, prov) {
            alg = KJUR.crypto.MessageDigest.getCanonicalAlgName(alg);

            if (alg !== null && prov === undefined) prov = KJUR.crypto.Util.DEFAULTPROVIDER[alg];

            // for cryptojs
            if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(alg) != -1 &&
                prov == 'cryptojs') {
                try {
                  console.log('KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[alg]--',KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME, alg, "-----:",CryptoJS);
                this.md = KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[alg].create();
                } catch (ex) {
                throw "setAlgAndProvider hash alg set fail alg=" + alg + "/" + ex;
                }
                this.updateString = function(str) {
                this.md.update(str);
                };
                this.updateHex = function(hex) {
                var wHex = CryptoJS.enc.Hex.parse(hex);
                this.md.update(wHex);
                };
                this.digest = function() {
                var hash = this.md.finalize();
                return hash.toString(CryptoJS.enc.Hex);
                };
                this.digestString = function(str) {
                this.updateString(str);
                return this.digest();
                };
                this.digestHex = function(hex) {
                this.updateHex(hex);
                return this.digest();
                };
            }
            if (':sha256:'.indexOf(alg) != -1 &&
                prov == 'sjcl') {
                try {
                this.md = new sjcl.hash.sha256();
                } catch (ex) {
                throw "setAlgAndProvider hash alg set fail alg=" + alg + "/" + ex;
                }
                this.updateString = function(str) {
                this.md.update(str);
                };
                this.updateHex = function(hex) {
                var baHex = sjcl.codec.hex.toBits(hex);
                this.md.update(baHex);
                };
                this.digest = function() {
                var hash = this.md.finalize();
                return sjcl.codec.hex.fromBits(hash);
                };
                this.digestString = function(str) {
                this.updateString(str);
                return this.digest();
                };
                this.digestHex = function(hex) {
                this.updateHex(hex);
                return this.digest();
                };
            }
            };

            this.updateString = function(str) {
            throw "updateString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName;
            };

            this.updateHex = function(hex) {
            throw "updateHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName;
            };

            this.digest = function() {
            throw "digest() not supported for this alg/prov: " + this.algName + "/" + this.provName;
            };

            this.digestString = function(str) {
            throw "digestString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName;
            };

            this.digestHex = function(hex) {
            throw "digestHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName;
            };

            if (params !== undefined) {
            if (params['alg'] !== undefined) {
                this.algName = params['alg'];
                if (params['prov'] === undefined)
                this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
                this.setAlgAndProvider(this.algName, this.provName);
            }
            }
        };

        KJUR.crypto.MessageDigest.getCanonicalAlgName = function(alg) {
            if (typeof alg === "string") {
            alg = alg.toLowerCase();
            alg = alg.replace(/-/, '');
            }
            return alg;
        };

        KJUR.crypto.MessageDigest.getHashLength = function(alg) {
            var MD = KJUR.crypto.MessageDigest;
            var alg2 = MD.getCanonicalAlgName(alg);
            if (MD.HASHLENGTH[alg2] === undefined)
            throw "not supported algorithm: " + alg;
            return MD.HASHLENGTH[alg2];
        };

        // described in KJUR.crypto.MessageDigest class (since jsrsasign 6.2.0 crypto 1.1.10)
        KJUR.crypto.MessageDigest.HASHLENGTH = {
            'md5':      16,
            'sha1':     20,
            'sha224':       28,
            'sha256':       32,
            'sha384':       48,
            'sha512':       64,
            'ripemd160':    20
        };

        KJUR.crypto.Mac = function(params) {
            var mac = null;
            var pass = null;
            var algName = null;
            var provName = null;
            var algProv = null;

            this.setAlgAndProvider = function(alg, prov) {
            alg = alg.toLowerCase();

            if (alg == null) alg = "hmacsha1";

            alg = alg.toLowerCase();
                if (alg.substr(0, 4) != "hmac") {
                throw "setAlgAndProvider unsupported HMAC alg: " + alg;
            }

            if (prov === undefined) prov = KJUR.crypto.Util.DEFAULTPROVIDER[alg];
            this.algProv = alg + "/" + prov;

            var hashAlg = alg.substr(4);

            // for cryptojs
            if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(hashAlg) != -1 &&
                prov == 'cryptojs') {
                try {
                var mdObj = KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[hashAlg];
                this.mac = CryptoJS.algo.HMAC.create(mdObj, this.pass);
                } catch (ex) {
                throw "setAlgAndProvider hash alg set fail hashAlg=" + hashAlg + "/" + ex;
                }
                this.updateString = function(str) {
                this.mac.update(str);
                };
                this.updateHex = function(hex) {
                var wHex = CryptoJS.enc.Hex.parse(hex);
                this.mac.update(wHex);
                };
                this.doFinal = function() {
                var hash = this.mac.finalize();
                return hash.toString(CryptoJS.enc.Hex);
                };
                this.doFinalString = function(str) {
                this.updateString(str);
                return this.doFinal();
                };
                this.doFinalHex = function(hex) {
                this.updateHex(hex);
                return this.doFinal();
                };
            }
            };

            this.updateString = function(str) {
            throw "updateString(str) not supported for this alg/prov: " + this.algProv;
            };

            this.updateHex = function(hex) {
            throw "updateHex(hex) not supported for this alg/prov: " + this.algProv;
            };

            this.doFinal = function() {
            throw "digest() not supported for this alg/prov: " + this.algProv;
            };

            this.doFinalString = function(str) {
            throw "digestString(str) not supported for this alg/prov: " + this.algProv;
            };

            this.doFinalHex = function(hex) {
            throw "digestHex(hex) not supported for this alg/prov: " + this.algProv;
            };

            this.setPassword = function(pass) {

            if (typeof pass == 'string') {
                var hPass = pass;
                if (pass.length % 2 == 1 || ! pass.match(/^[0-9A-Fa-f]+$/)) { // raw str
                hPass = rstrtohex(pass);
                }
                this.pass = CryptoJS.enc.Hex.parse(hPass);
                return;
            }

            if (typeof pass != 'object')
                throw "KJUR.crypto.Mac unsupported password type: " + pass;
            
            var hPass = null;
            if (pass.hex  !== undefined) {
                if (pass.hex.length % 2 != 0 || ! pass.hex.match(/^[0-9A-Fa-f]+$/))
                throw "Mac: wrong hex password: " + pass.hex;
                hPass = pass.hex;
            }
            if (pass.utf8 !== undefined) hPass = utf8tohex(pass.utf8);
            if (pass.rstr !== undefined) hPass = rstrtohex(pass.rstr);
            if (pass.b64  !== undefined) hPass = b64tohex(pass.b64);
            if (pass.b64u !== undefined) hPass = b64utohex(pass.b64u);

            if (hPass == null)
                throw "KJUR.crypto.Mac unsupported password type: " + pass;

            this.pass = CryptoJS.enc.Hex.parse(hPass);
            };

            if (params !== undefined) {
            if (params.pass !== undefined) {
                this.setPassword(params.pass);
            }
            if (params.alg !== undefined) {
                this.algName = params.alg;
                if (params['prov'] === undefined)
                this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
                this.setAlgAndProvider(this.algName, this.provName);
            }
            }
        };

        KJUR.crypto.Signature = function(params) {
            var prvKey = null; // RSAKey/KJUR.crypto.{ECDSA,DSA} object for signing
            var pubKey = null; // RSAKey/KJUR.crypto.{ECDSA,DSA} object for verifying

            var md = null; // KJUR.crypto.MessageDigest object
            var sig = null;
            var algName = null;
            var provName = null;
            var algProvName = null;
            var mdAlgName = null;
            var pubkeyAlgName = null;   // rsa,ecdsa,rsaandmgf1(=rsapss)
            var state = null;
            var pssSaltLen = -1;
            var initParams = null;

            var sHashHex = null; // hex hash value for hex
            var hDigestInfo = null;
            var hPaddedDigestInfo = null;
            var hSign = null;

            this._setAlgNames = function() {
            var matchResult = this.algName.match(/^(.+)with(.+)$/);
            if (matchResult) {
                this.mdAlgName = matchResult[1].toLowerCase();
                this.pubkeyAlgName = matchResult[2].toLowerCase();
            }
            };

            this._zeroPaddingOfSignature = function(hex, bitLength) {
            var s = "";
            var nZero = bitLength / 4 - hex.length;
            for (var i = 0; i < nZero; i++) {
                s = s + "0";
            }
            return s + hex;
            };

            this.setAlgAndProvider = function(alg, prov) {
            this._setAlgNames();
            if (prov != 'cryptojs/jsrsa')
                throw "provider not supported: " + prov;

            if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(this.mdAlgName) != -1) {
                try {
                this.md = new KJUR.crypto.MessageDigest({'alg':this.mdAlgName});
                } catch (ex) {
                throw "setAlgAndProvider hash alg set fail alg=" +
                            this.mdAlgName + "/" + ex;
                }
                
                this.init = function(keyparam, pass) {
                var keyObj = null;
                try {
                    if (pass === undefined) {
                    keyObj = KEYUTIL.getKey(keyparam);
                    } else {
                    keyObj = KEYUTIL.getKey(keyparam, pass);
                    }
                } catch (ex) {
                    throw "init failed:" + ex;
                }

                if (keyObj.isPrivate === true) {
                    this.prvKey = keyObj;
                    this.state = "SIGN";
                } else if (keyObj.isPublic === true) {
                    this.pubKey = keyObj;
                    this.state = "VERIFY";
                } else {
                    throw "init failed.:" + keyObj;
                }
                };

                this.updateString = function(str) {
                this.md.updateString(str);
                };

                this.updateHex = function(hex) {
                this.md.updateHex(hex);
                };

                this.sign = function() {
                this.sHashHex = this.md.digest();
                if (typeof this.ecprvhex != "undefined" &&
                    typeof this.eccurvename != "undefined") {
                    var ec = new KJUR.crypto.ECDSA({'curve': this.eccurvename});
                    this.hSign = ec.signHex(this.sHashHex, this.ecprvhex);
                } else if (this.prvKey instanceof RSAKey &&
                           this.pubkeyAlgName === "rsaandmgf1") {
                    this.hSign = this.prvKey.signWithMessageHashPSS(this.sHashHex,
                                            this.mdAlgName,
                                            this.pssSaltLen);
                } else if (this.prvKey instanceof RSAKey &&
                       this.pubkeyAlgName === "rsa") {
                    this.hSign = this.prvKey.signWithMessageHash(this.sHashHex,
                                         this.mdAlgName);
                } else if (this.prvKey instanceof KJUR.crypto.ECDSA) {
                    this.hSign = this.prvKey.signWithMessageHash(this.sHashHex);
                } else if (this.prvKey instanceof KJUR.crypto.DSA) {
                    this.hSign = this.prvKey.signWithMessageHash(this.sHashHex);
                } else {
                    throw "Signature: unsupported private key alg: " + this.pubkeyAlgName;
                }
                return this.hSign;
                };
                this.signString = function(str) {
                this.updateString(str);
                return this.sign();
                };
                this.signHex = function(hex) {
                this.updateHex(hex);
                return this.sign();
                };
                this.verify = function(hSigVal) {
                    this.sHashHex = this.md.digest();
                if (typeof this.ecpubhex != "undefined" &&
                    typeof this.eccurvename != "undefined") {
                    var ec = new KJUR.crypto.ECDSA({curve: this.eccurvename});
                    return ec.verifyHex(this.sHashHex, hSigVal, this.ecpubhex);
                } else if (this.pubKey instanceof RSAKey &&
                       this.pubkeyAlgName === "rsaandmgf1") {
                    return this.pubKey.verifyWithMessageHashPSS(this.sHashHex, hSigVal, 
                                        this.mdAlgName,
                                        this.pssSaltLen);
                } else if (this.pubKey instanceof RSAKey &&
                       this.pubkeyAlgName === "rsa") {
                    return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal);
                } else if (KJUR.crypto.ECDSA !== undefined &&
                       this.pubKey instanceof KJUR.crypto.ECDSA) {
                    return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal);
                } else if (KJUR.crypto.DSA !== undefined &&
                       this.pubKey instanceof KJUR.crypto.DSA) {
                    return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal);
                } else {
                    throw "Signature: unsupported public key alg: " + this.pubkeyAlgName;
                }
                };
            }
            };

            this.init = function(key, pass) {
            throw "init(key, pass) not supported for this alg:prov=" +
                  this.algProvName;
            };

            this.updateString = function(str) {
            throw "updateString(str) not supported for this alg:prov=" + this.algProvName;
            };

            this.updateHex = function(hex) {
            throw "updateHex(hex) not supported for this alg:prov=" + this.algProvName;
            };

            this.sign = function() {
            throw "sign() not supported for this alg:prov=" + this.algProvName;
            };

            this.signString = function(str) {
            throw "digestString(str) not supported for this alg:prov=" + this.algProvName;
            };

            this.signHex = function(hex) {
            throw "digestHex(hex) not supported for this alg:prov=" + this.algProvName;
            };

            this.verify = function(hSigVal) {
            throw "verify(hSigVal) not supported for this alg:prov=" + this.algProvName;
            };

            this.initParams = params;

            if (params !== undefined) {
            if (params.alg !== undefined) {
                this.algName = params.alg;
                if (params.prov === undefined) {
                this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
                } else {
                this.provName = params.prov;
                }
                this.algProvName = this.algName + ":" + this.provName;
                this.setAlgAndProvider(this.algName, this.provName);
                this._setAlgNames();
            }

            if (params['psssaltlen'] !== undefined) this.pssSaltLen = params['psssaltlen'];

            if (params.prvkeypem !== undefined) {
                if (params.prvkeypas !== undefined) {
                throw "both prvkeypem and prvkeypas parameters not supported";
                } else {
                try {
                    var prvKey = KEYUTIL.getKey(params.prvkeypem);
                    this.init(prvKey);
                } catch (ex) {
                    throw "fatal error to load pem private key: " + ex;
                }
                }
            }
            }
        };

        KJUR.crypto.Cipher = function(params) {
        };

        KJUR.crypto.Cipher.encrypt = function(s, keyObj, algName) {
            if (keyObj instanceof RSAKey && keyObj.isPublic) {
            var algName2 = KJUR.crypto.Cipher.getAlgByKeyAndName(keyObj, algName);
            if (algName2 === "RSA") return keyObj.encrypt(s);
            if (algName2 === "RSAOAEP") return keyObj.encryptOAEP(s, "sha1");

            var a = algName2.match(/^RSAOAEP(\d+)$/);
            if (a !== null) return keyObj.encryptOAEP(s, "sha" + a[1]);

            throw "Cipher.encrypt: unsupported algorithm for RSAKey: " + algName;
            } else {
            throw "Cipher.encrypt: unsupported key or algorithm";
            }
        };

        KJUR.crypto.Cipher.decrypt = function(hex, keyObj, algName) {
            if (keyObj instanceof RSAKey && keyObj.isPrivate) {
            var algName2 = KJUR.crypto.Cipher.getAlgByKeyAndName(keyObj, algName);
            if (algName2 === "RSA") return keyObj.decrypt(hex);
            if (algName2 === "RSAOAEP") return keyObj.decryptOAEP(hex, "sha1");

            var a = algName2.match(/^RSAOAEP(\d+)$/);
            if (a !== null) return keyObj.decryptOAEP(hex, "sha" + a[1]);

            throw "Cipher.decrypt: unsupported algorithm for RSAKey: " + algName;
            } else {
            throw "Cipher.decrypt: unsupported key or algorithm";
            }
        };

        KJUR.crypto.Cipher.getAlgByKeyAndName = function(keyObj, algName) {
            if (keyObj instanceof RSAKey) {
            if (":RSA:RSAOAEP:RSAOAEP224:RSAOAEP256:RSAOAEP384:RSAOAEP512:".indexOf(algName) != -1)
                return algName;
            if (algName === null || algName === undefined) return "RSA";
            throw "getAlgByKeyAndName: not supported algorithm name for RSAKey: " + algName;
            }
            throw "getAlgByKeyAndName: not supported algorithm name: " + algName;
        };

        KJUR.crypto.OID = new function() {
            this.oidhex2name = {
            '2a864886f70d010101': 'rsaEncryption',
            '2a8648ce3d0201': 'ecPublicKey',
            '2a8648ce380401': 'dsa',
            '2a8648ce3d030107': 'secp256r1',
            '2b8104001f': 'secp192k1',
            '2b81040021': 'secp224r1',
            '2b8104000a': 'secp256k1',
            '2b81040023': 'secp521r1',
            '2b81040022': 'secp384r1',
            '2a8648ce380403': 'SHA1withDSA', // 1.2.840.10040.4.3
            '608648016503040301': 'SHA224withDSA', // 2.16.840.1.101.3.4.3.1
            '608648016503040302': 'SHA256withDSA', // 2.16.840.1.101.3.4.3.2
            };
        };


        /*

        --------------------------------------------------rsa-------------------------------------------------------
        */

        function parseBigInt(str,r) {
          return new BigInteger(str,r);
        }

        function linebrk(s,n) {
          var ret = "";
          var i = 0;
          while(i + n < s.length) {
            ret += s.substring(i,i+n) + "\n";
            i += n;
          }
          return ret + s.substring(i,s.length);
        }

        function byte2Hex(b) {
          if(b < 0x10)
            return "0" + b.toString(16);
          else
            return b.toString(16);
        }

        // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
        function pkcs1pad2(s,n) {
          if(n < s.length + 11) { // TODO: fix for utf-8
            throw "Message too long for RSA";
            return null;
          }
          var ba = new Array();
          var i = s.length - 1;
          while(i >= 0 && n > 0) {
            var c = s.charCodeAt(i--);
            if(c < 128) { // encode using utf-8
              ba[--n] = c;
            }
            else if((c > 127) && (c < 2048)) {
              ba[--n] = (c & 63) | 128;
              ba[--n] = (c >> 6) | 192;
            }
            else {
              ba[--n] = (c & 63) | 128;
              ba[--n] = ((c >> 6) & 63) | 128;
              ba[--n] = (c >> 12) | 224;
            }
          }
          ba[--n] = 0;
          var rng = new SecureRandom();
          var x = new Array();
          while(n > 2) { // random non-zero pad
            x[0] = 0;
            while(x[0] == 0) rng.nextBytes(x);
            ba[--n] = x[0];
          }
          ba[--n] = 2;
          ba[--n] = 0;
          return new BigInteger(ba);
        }

        // PKCS#1 (OAEP) mask generation function
        function oaep_mgf1_arr(seed, len, hash)
        {
            var mask = '', i = 0;

            while (mask.length < len)
            {
                mask += hash(String.fromCharCode.apply(String, seed.concat([
                        (i & 0xff000000) >> 24,
                        (i & 0x00ff0000) >> 16,
                        (i & 0x0000ff00) >> 8,
                        i & 0x000000ff])));
                i += 1;
            }

            return mask;
        }

        function oaep_pad(s, n, hash, hashLen) {
            var MD = KJUR.crypto.MessageDigest;
            var Util = KJUR.crypto.Util;
            var algName = null;

            if (!hash) hash = "sha1";

            if (typeof hash === "string") {
                algName = MD.getCanonicalAlgName(hash);
                hashLen = MD.getHashLength(algName);
                hash = function(s) {
                    return hextorstr(Util.hashHex(rstrtohex(s), algName));
                };
            }

            if (s.length + 2 * hashLen + 2 > n) {
                throw "Message too long for RSA";
            }

            var PS = '', i;

            for (i = 0; i < n - s.length - 2 * hashLen - 2; i += 1) {
                PS += '\x00';
            }

            var DB = hash('') + PS + '\x01' + s;
            var seed = new Array(hashLen);
            new SecureRandom().nextBytes(seed);
            
            var dbMask = oaep_mgf1_arr(seed, DB.length, hash);
            var maskedDB = [];

            for (i = 0; i < DB.length; i += 1) {
                maskedDB[i] = DB.charCodeAt(i) ^ dbMask.charCodeAt(i);
            }

            var seedMask = oaep_mgf1_arr(maskedDB, seed.length, hash);
            var maskedSeed = [0];

            for (i = 0; i < seed.length; i += 1) {
                maskedSeed[i + 1] = seed[i] ^ seedMask.charCodeAt(i);
            }

            return new BigInteger(maskedSeed.concat(maskedDB));
        }

        // "empty" RSA key constructor
        function RSAKey() {
          this.n = null;
          this.e = 0;
          this.d = null;
          this.p = null;
          this.q = null;
          this.dmp1 = null;
          this.dmq1 = null;
          this.coeff = null;
        }

        // Set the public key fields N and e from hex strings
        function RSASetPublic(N, E) {
            this.isPublic = true;
            this.isPrivate = false;
            if (typeof N !== "string") {
            this.n = N;
            this.e = E;
            } else if(N != null && E != null && N.length > 0 && E.length > 0) {
            this.n = parseBigInt(N,16);
            this.e = parseInt(E,16);
            } else {
            throw "Invalid RSA public key";
            }
        }

        // Perform raw public operation on "x": return x^e (mod n)
        function RSADoPublic(x) {
          return x.modPowInt(this.e, this.n);
        }

        // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
        function RSAEncrypt(text) {
          var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
          if(m == null) return null;
          var c = this.doPublic(m);
          if(c == null) return null;
          var h = c.toString(16);
          if((h.length & 1) == 0) return h; else return "0" + h;
        }

        // Return the PKCS#1 OAEP RSA encryption of "text" as an even-length hex string
        function RSAEncryptOAEP(text, hash, hashLen) {
          var m = oaep_pad(text, (this.n.bitLength() + 7) >> 3, hash, hashLen);
          if(m == null) return null;
          var c = this.doPublic(m);
          if(c == null) return null;
          var h = c.toString(16);
          if((h.length & 1) == 0) return h; else return "0" + h;
        }

        // protected
        RSAKey.prototype.doPublic = RSADoPublic;

        // public
        RSAKey.prototype.setPublic = RSASetPublic;
        RSAKey.prototype.encrypt = RSAEncrypt;
        RSAKey.prototype.encryptOAEP = RSAEncryptOAEP;
        //RSAKey.prototype.encrypt_b64 = RSAEncryptB64;

        RSAKey.prototype.type = "RSA";




        /*

        --------------------------------------------------rsapem-1.1-------------------------------------------------------
        */

        RSAKey.getPosArrayOfChildrenFromHex = function(hPrivateKey) {
            return ASN1HEX.getChildIdx(hPrivateKey, 0);
        };

        RSAKey.getHexValueArrayOfChildrenFromHex = function(hPrivateKey) {
            var _ASN1HEX = ASN1HEX;
            var _getV = _ASN1HEX.getV;
            var a = RSAKey.getPosArrayOfChildrenFromHex(hPrivateKey);
            var h_v =  _getV(hPrivateKey, a[0]);
            var h_n =  _getV(hPrivateKey, a[1]);
            var h_e =  _getV(hPrivateKey, a[2]);
            var h_d =  _getV(hPrivateKey, a[3]);
            var h_p =  _getV(hPrivateKey, a[4]);
            var h_q =  _getV(hPrivateKey, a[5]);
            var h_dp = _getV(hPrivateKey, a[6]);
            var h_dq = _getV(hPrivateKey, a[7]);
            var h_co = _getV(hPrivateKey, a[8]);
            var a = new Array();
            a.push(h_v, h_n, h_e, h_d, h_p, h_q, h_dp, h_dq, h_co);
            return a;
        };

        RSAKey.prototype.readPrivateKeyFromPEMString = function(keyPEM) {
            var keyHex = pemtohex(keyPEM);
            var a = RSAKey.getHexValueArrayOfChildrenFromHex(keyHex);
            this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);
        };

        RSAKey.prototype.readPKCS5PrvKeyHex = function(h) {
            var a = RSAKey.getHexValueArrayOfChildrenFromHex(h);
            this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);
        };

        RSAKey.prototype.readPKCS8PrvKeyHex = function(h) {
            var hN, hE, hD, hP, hQ, hDP, hDQ, hCO;
            var _ASN1HEX = ASN1HEX;
            var _getVbyList = _ASN1HEX.getVbyList;

            if (_ASN1HEX.isASN1HEX(h) === false)
            throw "not ASN.1 hex string";

            try {
            hN  = _getVbyList(h, 0, [2, 0, 1], "02");
            hE  = _getVbyList(h, 0, [2, 0, 2], "02");
            hD  = _getVbyList(h, 0, [2, 0, 3], "02");
            hP  = _getVbyList(h, 0, [2, 0, 4], "02");
            hQ  = _getVbyList(h, 0, [2, 0, 5], "02");
            hDP = _getVbyList(h, 0, [2, 0, 6], "02");
            hDQ = _getVbyList(h, 0, [2, 0, 7], "02");
            hCO = _getVbyList(h, 0, [2, 0, 8], "02");
            } catch(ex) {
            throw "malformed PKCS#8 plain RSA private key";
            }

            this.setPrivateEx(hN, hE, hD, hP, hQ, hDP, hDQ, hCO);
        };

        RSAKey.prototype.readPKCS5PubKeyHex = function(h) {
            var _ASN1HEX = ASN1HEX;
            var _getV = _ASN1HEX.getV;

            if (_ASN1HEX.isASN1HEX(h) === false)
            throw "keyHex is not ASN.1 hex string";
            var aIdx = _ASN1HEX.getChildIdx(h, 0);
            if (aIdx.length !== 2 ||
            h.substr(aIdx[0], 2) !== "02" ||
            h.substr(aIdx[1], 2) !== "02")
            throw "wrong hex for PKCS#5 public key";
            var hN = _getV(h, aIdx[0]);
            var hE = _getV(h, aIdx[1]);
            this.setPublic(hN, hE);
        };

        RSAKey.prototype.readPKCS8PubKeyHex = function(h) {
            var _ASN1HEX = ASN1HEX;
            if (_ASN1HEX.isASN1HEX(h) === false)
            throw "not ASN.1 hex string";

            // 06092a864886f70d010101: OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
            if (_ASN1HEX.getTLVbyList(h, 0, [0, 0]) !== "06092a864886f70d010101")
            throw "not PKCS8 RSA public key";

            var p5hex = _ASN1HEX.getTLVbyList(h, 0, [1, 0]);
            this.readPKCS5PubKeyHex(p5hex);
        };

        RSAKey.prototype.readCertPubKeyHex = function(h, nthPKI) {
            var x, hPub;
            x = new X509();
            x.readCertHex(h);
            hPub = x.getPublicKeyHex();
            this.readPKCS8PubKeyHex(hPub);
        };




        /*

        ---------------------------------------------rsasign-1.2------------------------------------------------------------
        */

        var _RE_HEXDECONLY = new RegExp("");
        _RE_HEXDECONLY.compile("[^0-9a-f]", "gi");

        function _rsasign_getHexPaddedDigestInfoForString(s, keySize, hashAlg) {
            var hashFunc = function(s) { return KJUR.crypto.Util.hashString(s, hashAlg); };
            var sHashHex = hashFunc(s);

            return KJUR.crypto.Util.getPaddedDigestInfoHex(sHashHex, hashAlg, keySize);
        }

        function _zeroPaddingOfSignature(hex, bitLength) {
            var s = "";
            var nZero = bitLength / 4 - hex.length;
            for (var i = 0; i < nZero; i++) {
          s = s + "0";
            }
            return s + hex;
        }

        RSAKey.prototype.sign = function(s, hashAlg) {
            var hashFunc = function(s) { return KJUR.crypto.Util.hashString(s, hashAlg); };
            var sHashHex = hashFunc(s);

            return this.signWithMessageHash(sHashHex, hashAlg);
        };

        RSAKey.prototype.signWithMessageHash = function(sHashHex, hashAlg) {
            var hPM = KJUR.crypto.Util.getPaddedDigestInfoHex(sHashHex, hashAlg, this.n.bitLength());
            var biPaddedMessage = parseBigInt(hPM, 16);
            var biSign = this.doPrivate(biPaddedMessage);
            var hexSign = biSign.toString(16);
            return _zeroPaddingOfSignature(hexSign, this.n.bitLength());
        };

        // PKCS#1 (PSS) mask generation function
        function pss_mgf1_str(seed, len, hash) {
            var mask = '', i = 0;

            while (mask.length < len) {
                mask += hextorstr(hash(rstrtohex(seed + String.fromCharCode.apply(String, [
                        (i & 0xff000000) >> 24,
                        (i & 0x00ff0000) >> 16,
                        (i & 0x0000ff00) >> 8,
                        i & 0x000000ff]))));
                i += 1;
            }

            return mask;
        }

        RSAKey.prototype.signPSS = function(s, hashAlg, sLen) {
            var hashFunc = function(sHex) { return KJUR.crypto.Util.hashHex(sHex, hashAlg); }; 
            var hHash = hashFunc(rstrtohex(s));

            if (sLen === undefined) sLen = -1;
            return this.signWithMessageHashPSS(hHash, hashAlg, sLen);
        };

        RSAKey.prototype.signWithMessageHashPSS = function(hHash, hashAlg, sLen) {
            var mHash = hextorstr(hHash);
            var hLen = mHash.length;
            var emBits = this.n.bitLength() - 1;
            var emLen = Math.ceil(emBits / 8);
            var i;
            var hashFunc = function(sHex) { return KJUR.crypto.Util.hashHex(sHex, hashAlg); }; 

            if (sLen === -1 || sLen === undefined) {
                sLen = hLen; // same as hash length
            } else if (sLen === -2) {
                sLen = emLen - hLen - 2; // maximum
            } else if (sLen < -2) {
                throw "invalid salt length";
            }

            if (emLen < (hLen + sLen + 2)) {
                throw "data too long";
            }

            var salt = '';

            if (sLen > 0) {
                salt = new Array(sLen);
                new SecureRandom().nextBytes(salt);
                salt = String.fromCharCode.apply(String, salt);
            }

            var H = hextorstr(hashFunc(rstrtohex('\x00\x00\x00\x00\x00\x00\x00\x00' + mHash + salt)));
            var PS = [];

            for (i = 0; i < emLen - sLen - hLen - 2; i += 1) {
                PS[i] = 0x00;
            }

            var DB = String.fromCharCode.apply(String, PS) + '\x01' + salt;
            var dbMask = pss_mgf1_str(H, DB.length, hashFunc);
            var maskedDB = [];

            for (i = 0; i < DB.length; i += 1) {
                maskedDB[i] = DB.charCodeAt(i) ^ dbMask.charCodeAt(i);
            }

            var mask = (0xff00 >> (8 * emLen - emBits)) & 0xff;
            maskedDB[0] &= ~mask;

            for (i = 0; i < hLen; i++) {
                maskedDB.push(H.charCodeAt(i));
            }

            maskedDB.push(0xbc);

            return _zeroPaddingOfSignature(this.doPrivate(new BigInteger(maskedDB)).toString(16),
                   this.n.bitLength());
        };

        function _rsasign_getDecryptSignatureBI(biSig, hN, hE) {
            var rsa = new RSAKey();
            rsa.setPublic(hN, hE);
            var biDecryptedSig = rsa.doPublic(biSig);
            return biDecryptedSig;
        }

        function _rsasign_getHexDigestInfoFromSig(biSig, hN, hE) {
            var biDecryptedSig = _rsasign_getDecryptSignatureBI(biSig, hN, hE);
            var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, '');
            return hDigestInfo;
        }

        function _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo) {
            for (var algName in KJUR.crypto.Util.DIGESTINFOHEAD) {
          var head = KJUR.crypto.Util.DIGESTINFOHEAD[algName];
          var len = head.length;
          if (hDigestInfo.substring(0, len) == head) {
              var a = [algName, hDigestInfo.substring(len)];
              return a;
          }
            }
            return [];
        }

        RSAKey.prototype.verify = function(sMsg, hSig) {
            hSig = hSig.replace(_RE_HEXDECONLY, '');
            hSig = hSig.replace(/[ \n]+/g, "");
            var biSig = parseBigInt(hSig, 16);
            if (biSig.bitLength() > this.n.bitLength()) return 0;
            var biDecryptedSig = this.doPublic(biSig);
            var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, '');
            var digestInfoAry = _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo);
          
            if (digestInfoAry.length == 0) return false;
            var algName = digestInfoAry[0];
            var diHashValue = digestInfoAry[1];
            var ff = function(s) { return KJUR.crypto.Util.hashString(s, algName); };
            var msgHashValue = ff(sMsg);
            return (diHashValue == msgHashValue);
        };

        RSAKey.prototype.verifyWithMessageHash = function(sHashHex, hSig) {
            hSig = hSig.replace(_RE_HEXDECONLY, '');
            hSig = hSig.replace(/[ \n]+/g, "");
            var biSig = parseBigInt(hSig, 16);
            if (biSig.bitLength() > this.n.bitLength()) return 0;
            var biDecryptedSig = this.doPublic(biSig);
            var hDigestInfo = biDecryptedSig.toString(16).replace(/^1f+00/, '');
            var digestInfoAry = _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo);
          
            if (digestInfoAry.length == 0) return false;
            var algName = digestInfoAry[0];
            var diHashValue = digestInfoAry[1];
            return (diHashValue == sHashHex);
        };

        RSAKey.prototype.verifyPSS = function(sMsg, hSig, hashAlg, sLen) {
            var hashFunc = function(sHex) { return KJUR.crypto.Util.hashHex(sHex, hashAlg); };
            var hHash = hashFunc(rstrtohex(sMsg));

            if (sLen === undefined) sLen = -1;
            return this.verifyWithMessageHashPSS(hHash, hSig, hashAlg, sLen);
        };

        RSAKey.prototype.verifyWithMessageHashPSS = function(hHash, hSig, hashAlg, sLen) {
            var biSig = new BigInteger(hSig, 16);

            if (biSig.bitLength() > this.n.bitLength()) {
                return false;
            }

            var hashFunc = function(sHex) { return KJUR.crypto.Util.hashHex(sHex, hashAlg); };
            var mHash = hextorstr(hHash);
            var hLen = mHash.length;
            var emBits = this.n.bitLength() - 1;
            var emLen = Math.ceil(emBits / 8);
            var i;

            if (sLen === -1 || sLen === undefined) {
                sLen = hLen; // same as hash length
            } else if (sLen === -2) {
                sLen = emLen - hLen - 2; // recover
            } else if (sLen < -2) {
                throw "invalid salt length";
            }

            if (emLen < (hLen + sLen + 2)) {
                throw "data too long";
            }

            var em = this.doPublic(biSig).toByteArray();

            for (i = 0; i < em.length; i += 1) {
                em[i] &= 0xff;
            }

            while (em.length < emLen) {
                em.unshift(0);
            }

            if (em[emLen -1] !== 0xbc) {
                throw "encoded message does not end in 0xbc";
            }

            em = String.fromCharCode.apply(String, em);

            var maskedDB = em.substr(0, emLen - hLen - 1);
            var H = em.substr(maskedDB.length, hLen);

            var mask = (0xff00 >> (8 * emLen - emBits)) & 0xff;

            if ((maskedDB.charCodeAt(0) & mask) !== 0) {
                throw "bits beyond keysize not zero";
            }

            var dbMask = pss_mgf1_str(H, maskedDB.length, hashFunc);
            var DB = [];

            for (i = 0; i < maskedDB.length; i += 1) {
                DB[i] = maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i);
            }

            DB[0] &= ~mask;

            var checkLen = emLen - hLen - sLen - 2;

            for (i = 0; i < checkLen; i += 1) {
                if (DB[i] !== 0x00) {
                    throw "leftmost octets not zero";
                }
            }

            if (DB[checkLen] !== 0x01) {
                throw "0x01 marker not found";
            }

            return H === hextorstr(hashFunc(rstrtohex('\x00\x00\x00\x00\x00\x00\x00\x00' + mHash +
                     String.fromCharCode.apply(String, DB.slice(-sLen)))));
        };

        RSAKey.SALT_LEN_HLEN = -1;
        RSAKey.SALT_LEN_MAX = -2;
        RSAKey.SALT_LEN_RECOVER = -2;

        class ULAdvBase extends ULModuleBase {
            constructor() {
                super();
                this._initState = false;
                this.onInitModule();
            }
            get initState() {
                return this._initState;
            }
            set initState(v) {
                this._initState = v;
            }
        }

        let qg$1$1 = window["qg"];
        class ULAdvOppoQg extends ULAdvBase {
            constructor() {
                super();
                this.className = "ULAdvOppoQg";
            }
            onInitModule() {
                qg$1$1.getSystemInfoSync().platformVersion;
                let platformVersionCode = qg$1$1.getSystemInfoSync().platformVersionCode;
                if (platformVersionCode >= 1051) {
                    this.initState = true;
                    this.notifyInitState(this.initState);
                }
                else {
                    this.initAdv();
                }
            }
            notifyInitState(initState) {
                let templateItemObjectArray = ULSdkManager.getInstance().advManager.getAdvObjectsByName("ULAdvOppoQg");
                if (!templateItemObjectArray) {
                    return;
                }
                for (const baseObj of templateItemObjectArray) {
                    baseObj.receiveMainClassInitState(initState);
                }
            }
            initAdv() {
                let config = ULConfig.getConfig();
                let appId = config.s_sdk_oppoqg_appid;
                qg$1$1.initAdService({
                    appId: appId,
                    isDebug: false,
                    success: (res) => {
                        ULLog.console.log("ULAdvOppoQg.init success");
                        this.initState = true;
                        this.notifyInitState(this.initState);
                    },
                    fail: (res) => {
                        console.warn("ULAdvOppoQg.init fail", res.code, res.msg);
                        this.initState = false;
                        this.notifyInitState(this.initState);
                    },
                    complete: (res) => {
                        ULLog.console.log("ULAdvOppoQg.init complete");
                    }
                });
            }
        }
        ULAdvOppoQg.NORMAL_ADVERTISER = "ULAdvOppoQg";
        ULAdvOppoQg.NATIVE_ADVERTISER = "ULAdvOppoQgNative";

        class ULChannelModuleBase extends ULModuleBase {
            constructor() {
                super();
                ULLog.console.log("ULChannelModuleBase-constructor");
            }
            init() {
                super.init();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_GET_STORAGE, ULConst.PRIORITY_NONE, this.onCmdSdkGetStorage.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_SET_STORAGE, ULConst.PRIORITY_NONE, this.onCmdSdkSetStorage.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_GET_CLIPBOARD_DATA, ULConst.PRIORITY_NONE, this.onCmdSdkGetClipboardData.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_SET_CLIPBOARD_DATA, ULConst.PRIORITY_NONE, this.onCmdSdkSetClipboardData.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_IS_SUPPORT_CLIPBOARD, ULConst.PRIORITY_NONE, this.onCmdSdkIsSupportClipboard.bind(this));
                this.genSdkUserId();
                ULSdkManager.getInstance().channelInfo._sdkUserId = this.sdkUserId;
                ULSdkManager.getInstance().channelInfo.isNewUser = this.isNewUser;
                ULLog.console.log("ULChannelModuleBase.init isNewUser:", this.isNewUser);
            }
            genSdkUserId() {
                let config = ULConfig.getConfig();
                let key = ULTools.format("mUserId_%s", config.s_sdk_megadata_game_id);
                this.isNewUser = false;
                this.sdkUserId = ULStorageManager.getInstance().getStorage(key);
                if (!this.sdkUserId) {
                    this.sdkUserId = ULTools.format("%s_%s_%s", config.s_sdk_cop_game_id, ULTools.createRandomUserId(), config.s_sdk_cop_channel_id);
                    ULStorageManager.getInstance().setStorage(key, this.sdkUserId);
                    this.isNewUser = true;
                }
            }
            onCmdSdkGetStorage(e) {
                let data = e.data;
                let key = data.key;
                e.setReturnValue(this._hook_getStorage(key));
            }
            onCmdSdkSetStorage(e) {
                let key = e.data.key;
                let data = e.data.data;
                this._hook_setStorage(key, data);
                e.stopImmediatePropagation();
            }
            onCmdSdkGetClipboardData(e) {
                let data = e.data;
                let finishCallback = data.finishCallback;
                this._hook_getClipboardData(finishCallback);
                e.stopImmediatePropagation();
            }
            onCmdSdkSetClipboardData(e) {
                let clipboardData = e.data.data;
                let finishCallback = e.data.finishCallback;
                this._hook_setClipboardData(clipboardData, finishCallback);
                e.stopImmediatePropagation();
            }
            onCmdSdkIsSupportClipboard(e) {
                let data = e.data;
                e.setReturnValue(this._hook_isSupportClipboard());
                e.stopImmediatePropagation();
            }
        }

        class ULAdvObjectBase extends ULModuleBase {
            constructor(arg, advType, advKey) {
                super();
                this._preLoadState = ULConst.ADV_PRELOAD_STATE_NOAD;
                this.onLoadFailErr = { code: "", msg: "" };
                this._statisticsAdvertiser = "";
                this._statisticsType = "";
                this.advKey_2_lastRequestTime = {};
                this._supportLoadType = [];
                this._loadType = undefined;
                this.isReportLoading = false;
                this.isDispose = false;
                this._arg = arg;
                this._advType = advType;
                this._advKey = advKey;
            }
            onDisposeModule() {
                super.onDisposeModule();
                this.isDispose = true;
                ULLog.console.log("ULAdvObjectBase-onDisposeModule arg:", this.arg);
            }
            get arg() {
                return this._arg;
            }
            get advKey() {
                return this._advKey;
            }
            get preLoadState() {
                return this._preLoadState;
            }
            set preLoadState(preLoadState) {
                if (this._preLoadState == preLoadState)
                    return;
                this._preLoadState = preLoadState;
                ULSdkManager.getInstance().advManager.onAdvObjectPreloadStateChanged(this.advKey);
            }
            get advType() {
                return this._advType;
            }
            get isOpened() {
                return this._isOpened;
            }
            set isOpened(opened) {
                this._isOpened = opened;
            }
            get showData() {
                return this._mShowData;
            }
            set showData(mShowData) {
                this._mShowData = mShowData;
            }
            getMainClassNameString() {
                return this.getMainClassName();
            }
            receiveMainClassInitState(initState) {
                this.receiveInitState(initState);
            }
            preLoadAdv() {
                this.onLoadFailErr.code = "";
                this.onLoadFailErr.msg = "";
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_LOADING;
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                let rcd = ULSdkManager.getInstance().advManager.getRcdByAdvKey(this.advKey);
                if (rcd) {
                    let lastRequestTime = this.advKey_2_lastRequestTime[this.advKey];
                    let now = (new Date()).valueOf();
                    if (lastRequestTime) {
                        if ((now - lastRequestTime) < rcd) {
                            console.warn(`${this.className}-preLoadAdv:模块[ + ${this.advKey} + ]in cd`);
                            this.preLoadState = ULConst.ADV_PRELOAD_STATE_NOAD;
                            this.reLoadAdv();
                            return;
                        }
                        else {
                            this.advKey_2_lastRequestTime[this.advKey] = now;
                        }
                    }
                    else {
                        this.advKey_2_lastRequestTime[this.advKey] = now;
                    }
                }
                this.loadAdv();
            }
            reLoadAdv() {
                ULTimer.callLater(ULSdkManager.getInstance().advManager.getAdvReloadTime() / 1000, () => {
                    if (!this.isDispose) {
                        this.preLoadAdv();
                    }
                });
            }
            advSkip(data, info) {
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleSkip(this.advKey, info, data);
            }
            get statisticsAdvertiser() {
                return this._statisticsAdvertiser;
            }
            set statisticsAdvertiser(statisticsAdvertiser) {
                this._statisticsAdvertiser = statisticsAdvertiser;
            }
            get statisticsType() {
                return this._statisticsType;
            }
            set statisticsType(statisticsType) {
                this._statisticsType = statisticsType;
            }
            set setSupportLoadType(types) {
                this._supportLoadType = types;
            }
            get getSupportLoadType() {
                return this._supportLoadType;
            }
            set setLoadType(type) {
                if (type == undefined) {
                    return;
                }
                this._loadType = type;
            }
            get getLoadType() {
                return this._loadType;
            }
        }

        class ULAdvNativeObjectBase extends ULAdvObjectBase {
            constructor(arg, advType, templateItemName) {
                super(arg, advType, templateItemName);
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_CLICK_NATIVE_ADV, ULConst.PRIORITY_NONE, this.clickNativeAdv.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_CLOSE_NATIVE_ADV, ULConst.PRIORITY_NONE, this.closeNativeAdv.bind(this));
            }
            get nativeShowState() {
                return this._nativeShowState;
            }
            set nativeShowState(nativeShowState) {
                this._nativeShowState = nativeShowState;
            }
            get nativeData() {
                return this._nativeData;
            }
            set nativeData(nativeData) {
                this._nativeData = nativeData;
            }
        }

        const EvalSYMBOL = {
            ",": { order: -2, argCount: 1, handler: (args) => { return args[0]; } },
            "*": { order: 3, argCount: 2, handler: (args) => { return args[0] * args[1]; } },
            "/": { order: 3, argCount: 2, handler: (args) => { return args[0] / args[1]; } },
            "%": { order: 3, argCount: 2, handler: (args) => { return args[0] % args[1]; } },
            "+": { order: 2, argCount: 2, handler: (args) => { return args[0] + args[1]; } },
            "-": {
                order: 2, argCount: 2, handler: (args) => {
                    if (args.length == 1)
                        return 0 - args[0];
                    return args[0] - args[1];
                }
            },
            ">=": { order: 1, argCount: 2, handler: (args) => { return args[0] >= args[1]; } },
            ">": { order: 1, argCount: 2, handler: (args) => { return args[0] > args[1]; } },
            "<=": { order: 1, argCount: 2, handler: (args) => { return args[0] <= args[1]; } },
            "<": { order: 1, argCount: 2, handler: (args) => { return args[0] < args[1]; } },
            "==": { order: 0, argCount: 2, handler: (args) => { return args[0] == args[1]; } },
            "!=": { order: 0, argCount: 2, handler: (args) => { return args[0] != args[1]; } },
            "&&": { order: -1, argCount: 2, handler: (args) => { return args[0] && args[1]; } },
            "||": { order: -1, argCount: 2, handler: (args) => { return args[0] || args[1]; } },
            "[": { order: 4, argChar: "]", handler: (args) => { let a = args[0]; let b = args[1]; return a[b]; } },
            "(": {
                order: 4, argChar: ')', handler: (args) => {
                    let a = args[0];
                    if (Object.prototype.toString.call(a) === "[object Function]") {
                        args.shift();
                        return a(...args);
                    }
                    else {
                        return a;
                    }
                }
            },
            ".": {
                order: 5, argCount: 2, handler: (args) => {
                    if (typeof (args[1]) == "number") {
                        return Number(`${args[0]}.${args[1]}`);
                    }
                    else {
                        let item = args[0][args[1]];
                        if (Object.prototype.toString.call(item) === "[object Function]") {
                            return item.bind(args[0]);
                        }
                        else {
                            return item;
                        }
                    }
                }
            },
            "\"\"": { order: 6, argCount: 1, handler: (args) => { return args[0].toString(); } },
            "\'\'": { order: 6, argCount: 1, handler: (args) => { return args[0].toString(); } },
            "undefined": { order: 5, argCount: 0, handler: (args) => { return undefined; } },
            "window": { order: 5, argCount: 0, handler: (args) => { return window; } },
            "ULConfig": { order: 5, argCount: 0, handler: (args) => { return ULConfig; } },
            "ULTools": { order: 5, argCount: 0, handler: (args) => { return ULTools; } },
            "true": { order: 5, argCount: 0, handler: (args) => { return true; } },
            "false": { order: 5, argCount: 0, handler: (args) => { return false; } },
        };
        let EvalSYMBOL_keys = Object.keys(EvalSYMBOL);
        let EvalSYMBOLKeysDic = {};
        EvalSYMBOL_keys.forEach((value) => {
            EvalSYMBOLKeysDic[value.length] = true;
        });
        let EvalSYMBOLKeys = Object.keys(EvalSYMBOLKeysDic).map(a => {
            return Number(a);
        }).sort((a, b) => {
            return b - a;
        });
        class ULEvalExp {
            static trimCalcExp(exp) {
                exp = exp.replace(/\s/g, "");
                let expArray = exp.split("");
                var expSignCache = [];
                var expSignSetting = {
                    ")": {
                        cut: [")", "\'", "\""],
                        end: "(",
                        symbol: "(",
                        handle: (str) => {
                            let expCache = this.trimCalcExp(str);
                            expCache.push("\")\"");
                            return expCache;
                        }
                    },
                    "]": {
                        cut: [")", "\'", "\""],
                        end: "[",
                        symbol: "[",
                        handle: (str) => {
                            let expCache = this.trimCalcExp(str);
                            expCache.push("\"]\"");
                            return expCache;
                        }
                    },
                    "\"": {
                        cut: [],
                        end: "\"",
                        handle: (str) => {
                            return [`"${str}"`];
                        }
                    },
                    "\'": {
                        cut: [],
                        end: "\'",
                        handle: (str) => {
                            return [`'${str}'`];
                        }
                    }
                };
                let value = "";
                let expCache = [];
                let symbolCache = [];
                let expCacheString = "";
                while (expArray.length) {
                    let char = expArray.pop();
                    let lastExpChar = expSignCache.length ? expSignCache[expSignCache.length - 1] : null;
                    if (lastExpChar) {
                        let cut = expSignSetting[lastExpChar].cut;
                        let end = expSignSetting[lastExpChar].end;
                        let symbol = expSignSetting[lastExpChar].symbol;
                        let handle = expSignSetting[lastExpChar].handle;
                        if (char == end) {
                            expSignCache.pop();
                            if (expSignCache.length == 0) {
                                expCache = expCache.concat(handle(expCacheString).reverse());
                                symbol && symbolCache.push(symbol);
                                expCacheString = "";
                                continue;
                            }
                        }
                        else if (cut.indexOf(char) >= 0) {
                            expSignCache.push(char);
                        }
                        expCacheString = char + expCacheString;
                    }
                    else {
                        if (expSignSetting[char]) {
                            if (value.length) {
                                expCache.push(value);
                                value = "";
                            }
                            expSignCache.push(char);
                            continue;
                        }
                        let symbol = null;
                        for (let i = 0; i < EvalSYMBOLKeys.length; i++) {
                            let length = EvalSYMBOLKeys[i] - 1;
                            if (expArray.length > length) {
                                let key = expArray.slice(expArray.length - length, expArray.length) + char;
                                if (EvalSYMBOL[key]) {
                                    char = key;
                                    symbol = EvalSYMBOL[key];
                                    expArray = expArray.slice(0, expArray.length - length);
                                    break;
                                }
                            }
                        }
                        if (symbol) {
                            if (value.length) {
                                expCache.push(value);
                                value = "";
                            }
                            if (symbolCache.length) {
                                for (let i = symbolCache.length - 1; i >= 0; i--) {
                                    let lastKey = symbolCache.pop();
                                    let lastSymbol = EvalSYMBOL[lastKey];
                                    if (lastSymbol && lastSymbol.order > symbol.order) {
                                        expCache.push(lastKey);
                                    }
                                    else {
                                        symbolCache.push(lastKey);
                                        break;
                                    }
                                }
                            }
                            symbolCache.push(char);
                            continue;
                        }
                        value = char + value;
                    }
                }
                if (value.length) {
                    expCache.push(value);
                    value = "";
                }
                expCache = expCache.filter((element, index, array) => {
                    return (element != "");
                });
                expCache = expCache.concat(symbolCache.reverse()).reverse();
                return expCache;
            }
            static getCalcExpArray(exp, getObjCallback = null) {
                exp = exp.split(".").join(".^");
                let expCache = this.trimCalcExp(exp);
                let trimExpCache = expCache.map((item, index, arr) => {
                    if (EvalSYMBOL[item])
                        return item;
                    let char = item.charAt(0);
                    if (char == '"' || char == "'") {
                        let trimItem = item.substring(1, item.length - 1);
                        return trimItem.split(".^").join(".");
                    }
                    else if (char == '^') {
                        let trimItem = item.substring(1, item.length);
                        char = trimItem.charAt(0);
                        if (char <= '9' && char >= '0') {
                            return Number(trimItem);
                        }
                        return trimItem;
                    }
                    else if (!isNaN(Number(item))) {
                        return Number(item);
                    }
                    else {
                        let value = getObjCallback ? getObjCallback(item) : undefined;
                        if (!value)
                            ULLog.console.warn(`ULEvalExp item:${item} value:${value}`);
                        return value;
                    }
                });
                return trimExpCache;
            }
            static evalExpResults(exp, getObjCallback = null) {
                var result = true;
                try {
                    let expArray = this.getCalcExpArray(exp, getObjCallback);
                    ULLog.console.log(expArray);
                    result = this.evalExpArrayResults(expArray);
                    ULLog.console.log("ULEvalExp result:", result);
                }
                catch (error) {
                    ULLog.console.log("ULEvalExp exp规则错误:", error.stack);
                    result = false;
                }
                return result;
            }
            static evalExpArrayResults(expArray) {
                if (expArray.length == 0)
                    return true;
                let argCountDefalutHandler = (resultArray, argChar, argCount) => {
                    let args = [];
                    while (resultArray.length > 0) {
                        if (argChar) {
                            let arg = resultArray.pop();
                            if (arg == argChar)
                                break;
                            args.push(arg);
                        }
                        else {
                            if (argCount-- <= 0)
                                break;
                            args.push(resultArray.pop());
                        }
                    }
                    return args;
                };
                let resultArray = [];
                while (expArray.length) {
                    let key = expArray.pop();
                    if (EvalSYMBOL_keys.indexOf(key) > -1) {
                        let value = EvalSYMBOL[key];
                        let argChar = value.argChar;
                        let argCount = value.argCount;
                        let args = argCountDefalutHandler(resultArray, argChar, argCount);
                        let result = value.handler(args);
                        resultArray.push(result);
                    }
                    else {
                        resultArray.push(key);
                    }
                }
                return resultArray[0];
            }
        }

        class ULAdvExpManager {
            constructor() {
                this._timeString = "";
                this.availableExpKeyArray = [];
                this.updateValue = 10;
                this._timeString = ULTools.formatDate(new Date(), "yyyyMMddss");
            }
            static getInstance() {
                if (this.instance == null) {
                    this.instance = new ULAdvExpManager();
                    this.instance.addListern();
                }
                return this.instance;
            }
            get expValueCache() {
                if (!this._expValueCache) {
                    let recordExpKey = this._getRecordKey();
                    let recordStr = ULStorageManager.getInstance().getStorage(recordExpKey) || "{}";
                    let record;
                    try {
                        record = JSON.parse(recordStr);
                    }
                    catch (error) {
                        record = {};
                    }
                    for (const key in record) {
                        let timeString = this.getKeyTimeString(key);
                        let expValueItem = record[key];
                        if (timeString != expValueItem.exp_time) {
                            delete record[key];
                        }
                    }
                    this._expValueCache = record;
                }
                return this._expValueCache;
            }
            addListern() {
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_PAUSE, ULConst.PRIORITY_NONE, this.onCmdSdkOnGamePause.bind(this));
            }
            onCmdSdkOnGamePause(e) {
                this.saveStoreValue();
            }
            static updateExpKeys(expKeyArray) {
                ULAdvExpManager.getInstance().availableExpKeyArray = expKeyArray.slice(0);
            }
            static calcExp(exp) {
                return ULAdvExpManager.getInstance().calcExpResults(exp);
            }
            static updateExpValue(expKey) {
                ULAdvExpManager.getInstance().setStoreValue(expKey);
            }
            calcExpResults(exp) {
                if (!exp)
                    return true;
                ULLog.console.log("ULAdvExpManager calcExp:", exp);
                let trimExp = exp.replace(/\s/g, "");
                trimExp = trimExp.split(".").join("^");
                return ULEvalExp.evalExpResults(trimExp, (key) => {
                    let trimKey = key.split("^").join(".");
                    return this.getCalcExpValue(trimKey);
                });
            }
            _getRecordKey() {
                let config = ULConfig.getConfig();
                return ULTools.format("ULAdvExpManager_record_%d", config.s_sdk_megadata_game_id);
            }
            getCalcExpValue(anyObject) {
                if (typeof (anyObject) == "string" && this.availableExpKeyArray.indexOf(anyObject) != -1) {
                    return this.getStoreValue(anyObject);
                }
                return anyObject;
            }
            getStoreValue(key) {
                let expValueItem = this.expValueCache[key];
                if (!expValueItem) {
                    return 0;
                }
                let timeString = this.getKeyTimeString(key);
                if (timeString != expValueItem.exp_time) {
                    expValueItem.exp_time = timeString;
                    expValueItem.exp_value = 0;
                }
                return expValueItem.exp_value;
            }
            setStoreValue(key) {
                if (typeof (key) != "string" || this.availableExpKeyArray.indexOf(key) == -1) {
                    return;
                }
                let timeString = this.getKeyTimeString(key);
                let expValueItem = this.expValueCache[key];
                if (!expValueItem) {
                    expValueItem = {
                        exp_name: key,
                        exp_time: timeString,
                        exp_value: 1
                    };
                    this.expValueCache[key] = expValueItem;
                }
                else {
                    if (timeString != expValueItem.exp_time) {
                        expValueItem.exp_time = timeString;
                        expValueItem.exp_value = 1;
                    }
                    else {
                        expValueItem.exp_value += 1;
                    }
                }
                this.updateValue--;
                if (this.updateValue <= 0) {
                    this.updateValue = 10;
                    this.saveStoreValue();
                }
            }
            saveStoreValue() {
                let recordExpKey = this._getRecordKey();
                ULStorageManager.getInstance().setStorage(recordExpKey, JSON.stringify(this.expValueCache));
            }
            getKeyTimeString(key) {
                let timeString = this._timeString;
                let keyFirstChar = key.substr(0, 1);
                switch (keyFirstChar) {
                    case "d":
                        timeString = ULTools.formatDate(new Date(), "yyyyMMdd");
                        break;
                    case "w":
                        let today = new Date();
                        let day = today.getDay() || 7;
                        let date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1 - day);
                        timeString = ULTools.formatDate(date, "yyyyMMdd");
                        break;
                    case "m":
                        timeString = ULTools.formatDate(new Date(), "yyyyMM");
                        break;
                    case "y":
                        timeString = ULTools.formatDate(new Date(), "yyyy");
                        break;
                }
                return timeString;
            }
        }
        ULAdvExpManager.instance = null;

        class ULAdvSlot {
            constructor(advId, schemes, subAids, rcd) {
                this.advId = advId;
                this.schemes = schemes;
                this._subAids = subAids;
                this._rcd = rcd;
            }
            refreshValidAdvKeys() {
                let validSchemes = this.getValidSchemes();
                if (!validSchemes || validSchemes.length == 0) {
                    return;
                }
                this.validAdvKeys = [];
                for (let i = 0, len = validSchemes.length; i < len; i++) {
                    let scheme = validSchemes[i];
                    let validTemplates = this.getValidTemplates(scheme);
                    if (!validTemplates || validTemplates.length == 0) {
                        continue;
                    }
                    for (const template of validTemplates) {
                        let tid = template.templateId;
                        let keys = ULSdkManager.getInstance().advManager.getAdvKeysByTemplateId(tid);
                        if (!keys || keys.length == 0) {
                            continue;
                        }
                        for (const key of keys) {
                            if (this.validAdvKeys.indexOf(key) == -1) {
                                this.validAdvKeys.push(key);
                            }
                        }
                    }
                }
            }
            set openingInfo(v) {
                this._openingInfo = v;
            }
            get openingInfo() {
                return this._openingInfo;
            }
            get preLoadState() {
                return this._preLoadState;
            }
            set preLoadState(v) {
                this._preLoadState = v;
                ULSdkManager.getInstance().advManager.onAdvSlotPreloadStateChanged(this.advId);
            }
            get rcd() {
                return this._rcd;
            }
            get subAids() {
                return this._subAids;
            }
            set showTid(t) {
                this._showTid = t;
            }
            get showTid() {
                return this._showTid;
            }
            openAdv(advRequestSerialNum, data) {
                let ulAdvInfo = {
                    data: data,
                    requestSerialNum: advRequestSerialNum
                };
                this.openingInfo = ulAdvInfo;
                let scheme = this.getShowScheme();
                if (!scheme) {
                    console.warn("ULAdvSlot-openAdv:广告位[" + this.advId + "]未获取到有效策略");
                    this.openingInfo = null;
                    ULSdkManager.getInstance().advManager.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, { code: "", msg: `广告位[${this.advId}]未获取到有效策略` });
                    return;
                }
                let validTemplates = this.getValidTemplates(scheme);
                if (!validTemplates || validTemplates.length == 0) {
                    console.warn("ULAdvSlot-openAdv:广告位[" + this.advId + "]未获取到可用模板");
                    this.openingInfo = null;
                    ULSdkManager.getInstance().advManager.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, { code: "", msg: `广告位[${this.advId}]未获取到可用模板` });
                    return;
                }
                ULLog.console.log("ULAdvSlot-openAdv:广告位[" + this.advId + "]当前展示策略：" + JSON.stringify(scheme));
                this.openingInfo.scheme = scheme;
                let validTemplateIdArray = [];
                let validTemplateWeightArray = [];
                for (let i = 0; i < validTemplates.length; i++) {
                    let tid = validTemplates[i].templateId;
                    let tidWeight = 0;
                    let tidsArray = scheme.tids;
                    let tidsWeightsArray = scheme.tidWeights;
                    for (let j = 0; j < tidsArray.length; j++) {
                        if (tid == tidsArray[j].toString()) {
                            tidWeight = Number(tidsWeightsArray[j] || 0);
                            validTemplateIdArray.push(tid);
                            validTemplateWeightArray.push(tidWeight);
                            break;
                        }
                    }
                }
                this.openingInfo.validTemplateIdArray = validTemplateIdArray;
                this.openingInfo.validTemplateWeightArray = validTemplateWeightArray;
                this.showNextAdv(data);
            }
            showNextAdv(data, info) {
                let validTemplateIdArray = this.openingInfo.validTemplateIdArray;
                let validTemplateWeightArray = this.openingInfo.validTemplateWeightArray;
                let index = ULTools.calcWheelTargetByArray(validTemplateWeightArray, ULConst.ADV_MUST_DEFAULT_WEIGHT);
                if (index == null) {
                    console.warn("ULAdvSlot-showNextAdv:广告位[" + this.advId + "]无有效模板展示");
                    this.openingInfo = null;
                    let mInfo = {
                        code: "",
                        msg: `广告位[${this.advId}]无有效模板展示`
                    };
                    ULSdkManager.getInstance().advManager.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, info ? info : mInfo);
                    return;
                }
                let templateId = validTemplateIdArray[index];
                this.openingInfo.tid = templateId;
                this.showTid = templateId;
                validTemplateIdArray.splice(index, 1);
                this.openingInfo.validTemplateIdArray = validTemplateIdArray;
                validTemplateWeightArray.splice(index, 1);
                this.openingInfo.validTemplateWeightArray = validTemplateWeightArray;
                let advType = ULSdkManager.getInstance().advManager.getAdvTypeByTemplateId(templateId);
                let type_ad_ecd = ULSdkManager.getInstance().advManager.getLaunchCdByType(advType);
                if (ULTools.time() - ULSdkManager.getInstance().advManager.sdkInitTime < type_ad_ecd / 1000) {
                    ULLog.console.log(`ULAdvSlot-showNextAdv:广告${advType}处于启动请求cd中`);
                    this.showNextAdv(data);
                    return;
                }
                let advTypeCd = ULSdkManager.getInstance().advManager.getAdvTypeCd(advType);
                if (advTypeCd > 0) {
                    let lastTriggerTime = (ULSdkManager.getInstance().advManager.getAdvTypeLastTriggerTimeLog())[advType] || 0;
                    let triggerGap = ULTools.time() - lastTriggerTime;
                    ULLog.console.log(ULTools.format("ULAdvSlot-showNextAdv:检查广告类型cd。上次播放间隔%d秒，cd%d秒", triggerGap, advTypeCd / 1000));
                    if (triggerGap <= advTypeCd / 1000) {
                        ULLog.console.log(ULTools.format("ULAdvSlot-showNextAdv:广告类型[%s]cd中，请%d后再试", advType, (advTypeCd / 1000) - triggerGap));
                        this.showNextAdv(data);
                        return;
                    }
                }
                let advTypeDailyLimit = ULSdkManager.getInstance().advManager.getAdvTypeDailyLimit(advType);
                if (advTypeDailyLimit > 0) {
                    let dailyCount = (ULSdkManager.getInstance().advManager.getAdvTypeDailyCountLog())[advType] || 0;
                    ULLog.console.log(ULTools.format("检查广告日限。今日已播放%d次，日限制%d次", dailyCount, advTypeDailyLimit));
                    if (dailyCount >= advTypeDailyLimit) {
                        ULLog.console.log(ULTools.format("广告类型[%s]今日已播放%d次，限制%d次。无法播放。", advType, dailyCount, advTypeDailyLimit));
                        this.showNextAdv(data);
                        return;
                    }
                }
                if (ULSdkManager.getInstance().advManager.isAdvTypeOpened(advType)) {
                    console.warn("ULAdvSlot-showNextAdv:一个广告类型，同一时间只允许启动一个广告");
                    this.showNextAdv(data);
                    return;
                }
                let ulAdvTemplate = ULSdkManager.getInstance().advManager.getTemplateObjByTid(templateId);
                let rcd = ulAdvTemplate.rcd || 0;
                let lastRequestTime = ULAdvSlot.tid_lastRequestTime[templateId] || 0;
                let nowTime = (new Date()).valueOf();
                if ((nowTime - lastRequestTime) < rcd) {
                    console.warn("ULAdvSlot-showNextAdv:广告位[" + this.advId + "]当前展示模板【" + templateId + "】in rcd");
                    this.showNextAdv(data);
                    return;
                }
                else {
                    ULAdvSlot.tid_lastRequestTime[templateId] = nowTime;
                }
                let advObject = this.calcValidObjectByTemplateId(templateId);
                if (advObject == null) {
                    console.warn("ULAdvSlot-showNextAdv:广告位[" + this.advId + "]当前展示模板【" + templateId + "】未获取到可用广告对象");
                    this.showNextAdv(data);
                    return;
                }
                if (advType == typeExp.video) {
                    let tag = data.tag || "";
                    if (ULSdkManager.getInstance().advManager.isFirstPlayVideo) {
                        ULSdkManager.getInstance().advManager.isFirstPlayVideo = false;
                        let firstOpenVideoTimeSec = ULTools.time() - ULSdkManager.getInstance().advManager.sdkInitTime;
                        firstOpenVideoTimeSec = Math.floor(firstOpenVideoTimeSec);
                        if (isNaN(firstOpenVideoTimeSec))
                            firstOpenVideoTimeSec = 0;
                        if (firstOpenVideoTimeSec < ULConfig.getConfig().t_sdk_miniplay_game_adv_point_first_click_event_report_time_limit) {
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_game_adv_point_first_click_event_id, tag, firstOpenVideoTimeSec.toString()]);
                        }
                    }
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_game_click_video_event_id, tag]);
                }
                ULSdkManager.getInstance().advManager.updateAdvIds(advType, this.advId);
                let advKey = advObject.advKey;
                this.openingInfo.advTemplateItemName = advKey;
                ULLog.console.log("ULAdvSlot-showNextAdv:广告位[" + this.advId + "]当前展示模板：" + JSON.stringify(this.openingInfo));
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShowRequest(advKey, data);
                data["type"] = advType;
                let rType = ULSdkManager.getInstance().advManager.getRewardTypeByTemplateId(templateId);
                data["rewardType"] = rType;
                advObject.showAdv(data);
            }
            closeAdv(data) {
                let advKey = this.openingInfo.advTemplateItemName;
                let objectBase = ULSdkManager.getInstance().advManager.getAdvObjectByAdvKey(advKey);
                if (!objectBase) {
                    ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "advobject未找到");
                    return;
                }
                if (objectBase.isOpened) {
                    objectBase.closeAdv(data);
                }
                else {
                    ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "广告未展示");
                }
            }
            getShowScheme() {
                let schemeList = this.getValidSchemes();
                if (!schemeList || schemeList.length == 0) {
                    return null;
                }
                let validSchemes = [];
                for (const scheme of schemeList) {
                    let validTemplates = this.getValidTemplates(scheme);
                    if (validTemplates && validTemplates.length > 0) {
                        validSchemes.push(scheme);
                    }
                }
                if (validSchemes.length == 0) {
                    return null;
                }
                let weightArray = new Array(validSchemes.length);
                for (let i = 0; i < validSchemes.length; i++) {
                    weightArray[i] = validSchemes[i].weight;
                }
                let index = ULTools.calcWheelTargetByArray(weightArray, ULConst.ADV_MUST_DEFAULT_WEIGHT);
                if (index != null) {
                    return validSchemes[index];
                }
                return null;
            }
            getValidSchemes() {
                let validSchemes = [];
                for (let scheme of this.schemes) {
                    if (!ULAdvExpManager.calcExp(scheme.exp)) {
                        continue;
                    }
                    let weight = scheme.weight;
                    if (weight <= 0) {
                        continue;
                    }
                    if (weight == 100) {
                        validSchemes.unshift(scheme);
                    }
                    else {
                        validSchemes.push(scheme);
                    }
                }
                if (validSchemes.length == 0) {
                    return null;
                }
                return validSchemes;
            }
            getValidTemplates(scheme) {
                let validTemplates = [];
                let tids = scheme.tids;
                if (!tids || tids.length == 0) {
                    return null;
                }
                for (let i = 0; i < tids.length; i++) {
                    let tidS = tids[i];
                    let ulAdvTemplate = ULSdkManager.getInstance().advManager.getTemplateObjByTid(tidS);
                    if (!ulAdvTemplate) {
                        console.warn("ULAdvSlot-getValidTemplates:广告位【" + this.advId + "】对应的模板【" + tidS + "】不存在模板对象，需检查模板列表中是否配置该模板id");
                        continue;
                    }
                    if (!ULAdvExpManager.calcExp(ulAdvTemplate.exp)) {
                        continue;
                    }
                    let tidWeight = scheme.tidWeights[i];
                    if (tidWeight <= 0) {
                        continue;
                    }
                    validTemplates.push(ulAdvTemplate);
                }
                return validTemplates;
            }
            calcValidObjectByTemplateId(tid) {
                let objectBases = ULSdkManager.getInstance().advManager.getAdvObjsByTid(tid);
                if (!objectBases || objectBases.length == 0)
                    return null;
                let readyObjects = [];
                for (const base of objectBases) {
                    if (base.preLoadState == ULConst.ADV_PRELOAD_STATE_READY) {
                        readyObjects.push(base);
                    }
                }
                let targetObjects;
                if (readyObjects.length == 0) {
                    targetObjects = objectBases;
                }
                else {
                    targetObjects = readyObjects;
                }
                let argWeights = new Array(targetObjects.length);
                let ulAdvTemplate = ULSdkManager.getInstance().advManager.getTemplateObjByTid(tid);
                if (!ulAdvTemplate) {
                    return null;
                }
                for (let j = 0, len = targetObjects.length; j < len; j++) {
                    let objectBase = targetObjects[j];
                    for (let i = 0, len = ulAdvTemplate.args.length; i < len; i++) {
                        let arg = ulAdvTemplate.args[i];
                        let key = ulAdvTemplate.moduleName + "_" + arg;
                        let argWeight = ulAdvTemplate.argWeights[i];
                        if (key == objectBase.advKey) {
                            argWeights[j] = argWeight;
                        }
                    }
                }
                let index = ULTools.calcWheelTargetByArray(argWeights, ULConst.ADV_MUST_DEFAULT_WEIGHT);
                if (index != null) {
                    return targetObjects[index];
                }
                return null;
            }
            onAdvObjectPreloadStateChanged(advKey) {
                if (!this.validAdvKeys || this.validAdvKeys.indexOf(advKey) == -1)
                    return;
                this.refreshPreloadState();
            }
            refreshPreloadState() {
                let bHasLoading = false;
                let bHasReady = false;
                for (const advKey of this.validAdvKeys) {
                    let state = ULSdkManager.getInstance().advManager.getAdvObjPreloadStateByAdvKey(advKey);
                    if (state == ULConst.ADV_PRELOAD_STATE_LOADING) {
                        bHasLoading = true;
                    }
                    else if (state == ULConst.ADV_PRELOAD_STATE_READY) {
                        bHasReady = true;
                    }
                }
                if (bHasReady) {
                    this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                }
                else if (bHasLoading) {
                    this.preLoadState = ULConst.ADV_PRELOAD_STATE_LOADING;
                }
                else {
                    this.preLoadState = ULConst.ADV_PRELOAD_STATE_NOAD;
                }
            }
            onAdvObjectLifeCycleSkip(data, info) {
                if (this.openingInfo == null) {
                    return;
                }
                if (this.openingInfo != null) {
                    this.openingInfo.advTemplateItemName = null;
                }
                this.showNextAdv(data, info);
            }
            onAdvObjectLifeCycleShow(msg, data) {
                let rType = ULSdkManager.getInstance().advManager.getRewardTypeByTemplateId(this.showTid);
                let advType = ULSdkManager.getInstance().advManager.getAdvTypeByTemplateId(this.showTid);
                ULSdkManager.getInstance().advManager.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, { code: "", msg: msg });
                if (rewardType.show == rType) {
                    ULSdkManager.getInstance().advManager.responseRewardAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, msg);
                }
            }
            onAdvObjectLifeCycleClick(msg, data) {
                ULSdkManager.getInstance().advManager.responseClickAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, msg);
                let rType = ULSdkManager.getInstance().advManager.getRewardTypeByTemplateId(this.showTid);
                if (rewardType.click == rType) {
                    ULSdkManager.getInstance().advManager.responseRewardAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, msg);
                }
            }
            onAdvObjectLifeCycleClose() {
                let advType = ULSdkManager.getInstance().advManager.getAdvTypeByTemplateId(this.showTid);
                ULSdkManager.getInstance().advManager.deleteAdvIdOpening(advType, this.advId);
                this.openingInfo = null;
            }
            onAdvObjectLifeCycleFail(info, data) {
                ULSdkManager.getInstance().advManager.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, info);
                this.openingInfo = null;
            }
        }
        ULAdvSlot.tid_lastRequestTime = {};

        class ULAdvItem {
            constructor(advId, userData, tag) {
                this.advId = advId;
                this.advType = ULSdkManager.getInstance().advManager.searchAdvTypeByAdvId(advId);
                this.advGroupId = ULSdkManager.getInstance().advManager.searchAdvGroupIdByAdvId(advId);
                this.userData = userData;
                this.tag = tag;
                this.serialId = ULAdvItem.SERIAL_ID++;
                this.bOpenAdvResultResponsed = false;
                this.bClickAdvResultResponsed = false;
                this.lifeCycleLog = {};
                this.bRequesting = true;
                this.statisChannelName = "";
                this.statisSdkAdvId = "";
                this.statisNativeAdTitle = "";
            }
            startimeoutTimer(timeoutSec) {
                if (this.timeoutTimer)
                    return;
                this.timeoutTimer = new ULTimer(timeoutSec, 1, () => {
                    ULSdkManager.getInstance().advManager.onAdvTimeout(this);
                });
                this.timeoutTimer.start();
            }
            stopTimeoutTimer() {
                if (this.timeoutTimer) {
                    this.timeoutTimer.stop();
                    this.timeoutTimer = null;
                }
            }
            setLifeCycleLogAllCycle() {
                this.lifeCycleLog = {
                    0: true, 1: true, 2: true, 3: true, 4: true, 5: true
                };
            }
            set advData(data) {
                this._advData = data;
            }
            get advData() {
                return this._advData;
            }
        }
        ULAdvItem.SERIAL_ID = 0;

        var ULErrorRuleLogic;
        (function (ULErrorRuleLogic) {
            ULErrorRuleLogic[ULErrorRuleLogic["ordinary"] = 0] = "ordinary";
            ULErrorRuleLogic[ULErrorRuleLogic["or"] = 1] = "or";
            ULErrorRuleLogic[ULErrorRuleLogic["with"] = 2] = "with";
            ULErrorRuleLogic[ULErrorRuleLogic["error"] = 3] = "error";
        })(ULErrorRuleLogic || (ULErrorRuleLogic = {}));
        class ULErrorRuleItem {
            constructor(ruleString = null) {
                this.ruleString = null;
                this.logic = ULErrorRuleLogic.ordinary;
                this.rule = null;
                this.rules = [];
                this.ruleString = ruleString;
                if (!ruleString || ruleString.length == 0) {
                    this.logic = ULErrorRuleLogic.error;
                    return;
                }
                this.initWithRule(this.ruleString);
            }
            get isWildcard() {
                return this.rule == "*";
            }
            initWithErrRule() {
                this.logic = ULErrorRuleLogic.error;
                this.rule = null;
                this.rules = [];
            }
            initWithRule(rule) {
                rule = rule.replace(/\s/g, "");
                let leftBracketNum = 0;
                let startLeftBracketNum = 0;
                let trimString = "";
                while (rule.length) {
                    let char = rule.charAt(0);
                    let nextChar = rule.length > 0 ? rule.charAt(1) : "";
                    rule = rule.slice(1);
                    switch (char) {
                        case "(":
                            {
                                leftBracketNum++;
                                let string = trimString;
                                if (string.replace(/\(/g, '') == "") {
                                    startLeftBracketNum++;
                                }
                            }
                            break;
                        case ")":
                            {
                                let string = rule;
                                if (string.replace(/\)/g, '') == "" && startLeftBracketNum != 0) {
                                    trimString = trimString.substring(startLeftBracketNum);
                                    return this.initWithRule(trimString);
                                }
                                leftBracketNum--;
                                startLeftBracketNum = leftBracketNum > startLeftBracketNum ? startLeftBracketNum : leftBracketNum;
                            }
                            break;
                        case "|":
                            {
                                if (leftBracketNum == 0) {
                                    if (char + nextChar == "||") {
                                        if (this.logic != ULErrorRuleLogic.or && this.logic != ULErrorRuleLogic.ordinary) {
                                            return this.initWithErrRule();
                                        }
                                        this.logic = ULErrorRuleLogic.or;
                                        this.rules.push(new ULErrorRuleItem(trimString));
                                        trimString = "";
                                    }
                                    continue;
                                }
                            }
                            break;
                        case "&":
                            {
                                if (leftBracketNum == 0) {
                                    if (char + nextChar == "&&") {
                                        if (this.logic != ULErrorRuleLogic.with && this.logic != ULErrorRuleLogic.ordinary) {
                                            return this.initWithErrRule();
                                        }
                                        this.logic = ULErrorRuleLogic.with;
                                        this.rules.push(new ULErrorRuleItem(trimString));
                                        trimString = "";
                                    }
                                    continue;
                                }
                            }
                            break;
                    }
                    trimString += char;
                }
                if (trimString.length > 0) {
                    if (this.logic == ULErrorRuleLogic.ordinary) {
                        this.rule = trimString;
                    }
                    else {
                        this.rules.push(new ULErrorRuleItem(trimString));
                    }
                }
            }
            complianceTheRules(key, customData = null) {
                switch (this.logic) {
                    case ULErrorRuleLogic.ordinary:
                        {
                            return this.judgmentStandard(key, customData);
                        }
                        break;
                    case ULErrorRuleLogic.or:
                        {
                            for (let subRuleItem of this.rules) {
                                if (subRuleItem.complianceTheRules(key, customData)) {
                                    return true;
                                }
                            }
                            return false;
                        }
                        break;
                    case ULErrorRuleLogic.with:
                        {
                            for (let subRuleItem of this.rules) {
                                if (!subRuleItem.complianceTheRules(key, customData)) {
                                    return false;
                                }
                            }
                            return true;
                        }
                        break;
                }
                return false;
            }
            judgmentStandard(key, customData = null) {
                if (this.rule == null) {
                    return false;
                }
                if (this.rule == "*") {
                    return true;
                }
                if (this.rule == key) {
                    return true;
                }
                if (this.rule.length > 2) {
                    let rule = this.rule;
                    let firstChar = rule.charAt(0);
                    let lastChar = rule.charAt(this.rule.length - 1);
                    if (firstChar + lastChar == '//') {
                        rule = rule.substring(1, rule.length - 1);
                        var reg = RegExp(rule);
                        if (reg.exec(key)) {
                            return true;
                        }
                    }
                }
                var patrn = /(?==|!=|>=|>|<|<=)/;
                if (customData && patrn.exec(this.rule)) {
                    let trimRule = this.rule.replace("this.", "customData.");
                    return ULEvalExp.evalExpResults(trimRule, (key) => {
                        if (key == "customData") {
                            return customData;
                        }
                        return null;
                    });
                }
                return false;
            }
        }
        class ULAdvTrimErrorManager {
            static trimErrMessage(msg, error) {
                let config = ULConfig.getConfig();
                if (!config.i_sdk_trim_adv_err_switch) {
                    return (error && ULTools.format("%s %d", ULConst.ADV_FAIL_TIP_NOAD, error.code || error.errCode)) || msg || ULTools.format(ULConst.ADV_FAIL_TIP_NOAD, ULConst.ADV_ERR_CODE_UNKNOWN);
                }
                let errJson = config.t_sdk_trim_adv_err_object || {};
                if (!error) {
                    return msg || ULTools.format(ULConst.ADV_FAIL_TIP_NOAD, ULConst.ADV_ERR_CODE_UNKNOWN);
                }
                let channelName = ULSdkManager.getInstance().channelInfo.channelName || "";
                let channelNameErrJson = {};
                channelNameErrJson[channelName] = error;
                let customMsg = null;
                try {
                    customMsg = this.getCustomMsgFromRules(errJson, channelNameErrJson);
                }
                catch (error) {
                    ULLog.console.error("ULAdvTrimErrorManager:错误整理报错-------------请检查配置");
                    ULLog.console.error("ULAdvTrimErrorManager:errJson：", errJson);
                    ULLog.console.error("ULAdvTrimErrorManager:channelNameErrJson：", channelNameErrJson);
                }
                if (customMsg) {
                    customMsg = ULTools.format("%s %d", customMsg, error.code || error.errCode);
                }
                let trimMsg = customMsg || msg || ULTools.format(ULConst.ADV_FAIL_TIP_NOAD, ULConst.ADV_ERR_CODE_UNKNOWN);
                return trimMsg;
            }
            static getCustomMsgFromRules(type, errorData) {
                let typeKeys = [];
                let errorDataKeys = [];
                if (typeof type === 'object') {
                    typeKeys = Object.keys(type);
                }
                else if (typeof type === 'string') {
                    return type;
                }
                else {
                    return "";
                }
                if (!errorData) {
                    return "";
                }
                else if (typeof errorData === 'object') {
                    errorDataKeys = Object.keys(errorData);
                }
                else {
                    errorDataKeys.push(errorData);
                }
                let count = typeKeys.length;
                while (typeKeys.length) {
                    let typeKey = typeKeys.shift();
                    count--;
                    let ruleItem = this.trimRules[typeKey];
                    if (!ruleItem) {
                        ruleItem = new ULErrorRuleItem(typeKey);
                        this.trimRules[typeKey] = ruleItem;
                    }
                    if (ruleItem.isWildcard && count > 0) {
                        typeKeys.join(typeKey);
                        continue;
                    }
                    let typeValue = type[typeKey];
                    for (let errorDataKey of errorDataKeys) {
                        if (ruleItem.complianceTheRules(errorDataKey, errorData)) {
                            let errorDataValue = errorData[errorDataKey] || null;
                            let returnString = this.getCustomMsgFromRules(typeValue, errorDataValue);
                            if (returnString) {
                                return returnString;
                            }
                        }
                    }
                }
                return "";
            }
        }
        ULAdvTrimErrorManager.trimRules = {};

        var typeExp;
        (function (typeExp) {
            typeExp["all"] = "all";
            typeExp["splash"] = "splash";
            typeExp["inter"] = "inter";
            typeExp["video"] = "video";
            typeExp["custom"] = "custom";
            typeExp["interVideo"] = "interVideo";
            typeExp["banner"] = "banner";
            typeExp["embed"] = "embed";
            typeExp["url"] = "url";
            typeExp["paster"] = "paster";
            typeExp["share"] = "share";
        })(typeExp || (typeExp = {}));
        var rewardType;
        (function (rewardType) {
            rewardType["show"] = "show";
            rewardType["click"] = "click";
        })(rewardType || (rewardType = {}));
        var countExp;
        (function (countExp) {
            countExp["rc"] = "rc";
            countExp["sc"] = "sc";
            countExp["cc"] = "cc";
            countExp["fc"] = "fc";
            countExp["mcc"] = "mcc";
        })(countExp || (countExp = {}));
        var cdExp;
        (function (cdExp) {
            cdExp["rcd"] = "rcd";
            cdExp["scd"] = "scd";
            cdExp["ecd"] = "ecd";
        })(cdExp || (cdExp = {}));
        var dataExp;
        (function (dataExp) {
            dataExp["t"] = "t";
            dataExp["d"] = "d";
            dataExp["w"] = "w";
            dataExp["m"] = "m";
            dataExp["y"] = "y";
        })(dataExp || (dataExp = {}));
        var openResult;
        (function (openResult) {
            openResult["totalAdvRequest"] = "totalAdvRequest";
            openResult["branchAdvRequest"] = "branchAdvRequest";
            openResult["success"] = "success";
            openResult["failed"] = "failed";
            openResult["clicked"] = "clicked";
            openResult["playStart"] = "playStart";
            openResult["playCompletion"] = "playCompletion";
            openResult["loadAdvRequest"] = "loadAdvRequest";
            openResult["close"] = "close";
            openResult["hide"] = "hide";
        })(openResult || (openResult = {}));
        var oldTypeExp;
        (function (oldTypeExp) {
            oldTypeExp["interstitial"] = "interstitial";
            oldTypeExp["embedded"] = "embedded";
            oldTypeExp["fullscreen"] = "fullscreen";
        })(oldTypeExp || (oldTypeExp = {}));
        class ULAdvManager {
            constructor() {
                this.systemAdvExpKeyArray = [];
                this.advExpKeyArray = [];
                this.advRequestSerialNum = 0;
                this.advId_2_advSlot = {};
                this.templateId_2_advTemplate = {};
                this.templateId_2_advTemplateItemArray = {};
                this.advKey_2_templateIdArray = {};
                this.moduleName_2_argsArray = {};
                this.moduleName_2_advIdsArray = {};
                this.templateId_2_moduleName = {};
                this.moduleName_2_advTemplate = {};
                this.mainName_2_advObjectArray = {};
                this.templateId_2_advObjectArray = {};
                this.advType_2_advObjectArray = {};
                this.moduleName_2_templateIdsArray = {};
                this.logKey_2_countNum = {};
                this.advKey_2_advIdArray = {};
                this.tid_2_advKeyArray = {};
                this.advId_2_tidArray = {};
                this.nativeType_2_advObjectArray = {};
                this.advKey_2_advObject = {};
                this.ADV_RELOAD_DEFAULT_TIME = 15000;
                this.ADV_RELOAD_TIME = 15000;
                this.bannerStartShowTime = 0;
                this.advKey_2_rcd = {};
                this.advId_2_lastRequestTime = {};
                this.adMainName_2_obj = {};
                this.type_2_advIds = {};
                this.exp_2_result = {};
                this.advTypeLastTriggerTimeLog = {};
            }
            static getInstance() {
                if (this.instance == null) {
                    this.instance = new ULAdvManager();
                }
                return this.instance;
            }
            get isFirstPlayVideo() {
                return this._isFirstPlayVideo;
            }
            set isFirstPlayVideo(v) {
                this._isFirstPlayVideo = v;
            }
            init() {
                this.loadRecord();
                this.initAdvExpKey();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_CONFIG, ULConst.PRIORITY_NONE, this.onCmdSdkCollectionModuleCheckerConfig.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_OPEN_ADV, ULConst.PRIORITY_NONE, this.onCmdOpenAdv.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_CLOSE_ADV, ULConst.PRIORITY_NONE, this.onCmdCloseAdv.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_CLOSE_NATIVE_ADV, ULConst.PRIORITY_NONE, this.onCmdCloseNativeAdv.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_CLICK_NATIVE_ADV, ULConst.PRIORITY_NONE, this.onCmdClickNativeAdv.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_RESUME, ULConst.PRIORITY_NONE, this.onCmdSdkOnGameResume.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_PAUSE, ULConst.PRIORITY_NONE, this.onCmdSdkOnGamePause.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_GET_ADV_STATE, ULConst.PRIORITY_NONE, this.onCmdGetAdvState.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_COP_CHANGED, 1, this.onCopChanged.bind(this));
                this._sdkInitTime = ULTools.time();
                this.isFirstPlayVideo = true;
            }
            loadRecord() {
                let recordStr = ULStorageManager.getInstance().getStorage(this._getRecordKey()) || "{}";
                let record;
                try {
                    record = JSON.parse(recordStr);
                }
                catch (error) {
                    record = {};
                }
                this.advTypeDailyCountLog = record.advTypeDailyCountLog || {};
                this.advTypeDailyRefreshTime = record.advTypeDailyRefreshTime || 0;
                this.tryDailyRefresh();
            }
            saveRecord() {
                let recordStr = ULStorageManager.getInstance().getStorage(this._getRecordKey()) || "{}";
                let record;
                try {
                    record = JSON.parse(recordStr);
                }
                catch (error) {
                    record = {};
                }
                record.advTypeDailyCountLog = this.advTypeDailyCountLog || {};
                record.advTypeDailyRefreshTime = this.advTypeDailyRefreshTime || 0,
                    ULStorageManager.getInstance().setStorage(this._getRecordKey(), JSON.stringify(record));
            }
            _getRecordKey() {
                let config = ULConfig.getConfig();
                return ULTools.format("ULAdvManager_record_%d", config.s_sdk_megadata_game_id);
            }
            tryDailyRefresh() {
                if (!ULTools.isOneDay(this.advTypeDailyRefreshTime, ULTools.time())) {
                    ULLog.console.log("ULAdvManager-tryDailyRefresh 进行日常刷新");
                    this.advTypeDailyCountLog = {};
                    this.advTypeDailyRefreshTime = ULTools.time();
                    this.saveRecord();
                }
            }
            searchAdvGroupIdByAdvId(advId) {
                let config = ULConfig.getConfig();
                let advInfo = config.s_sdk_adv_info;
                let advGroupId = "";
                ULTools.forEachMap(advInfo, (k, v) => {
                    if (v.group.indexOf(advId) >= 0) {
                        advGroupId = k;
                        return true;
                    }
                });
                return advGroupId;
            }
            searchAdvTypeByAdvId(advId) {
                let config = ULConfig.getConfig();
                let advInfo = config.s_sdk_adv_info;
                let advType = "";
                ULTools.forEachMap(advInfo, (k, v) => {
                    if (v.group.indexOf(advId) >= 0) {
                        advType = v.type;
                        return true;
                    }
                });
                return advType;
            }
            onCopChanged(e) {
                try {
                    this.initAdv();
                }
                catch (error) {
                    ULLog.console.error("ULAdvManager.onCopChanged err:", error.stack);
                }
            }
            onCmdSdkOnGameResume(e) {
                ULLog.console.log("ULAdvManager-onCmdSdkOnGameResume");
                let objectBase = this.getAdvObjectOpeningByAdvType(typeExp.banner);
                if (!objectBase)
                    return;
                this.bannerStartShowTime = ULTools.time();
            }
            onCmdSdkOnGamePause(e) {
                let objectBase = this.getAdvObjectOpeningByAdvType(typeExp.banner);
                if (!objectBase)
                    return;
                let nativeData;
                if (objectBase instanceof ULAdvNativeObjectBase) {
                    nativeData = objectBase.nativeData;
                }
                this.reportBannerShowTime(objectBase.advKey, objectBase.showData, nativeData);
            }
            onCmdSdkCollectionModuleCheckerConfig(e) {
                let config = e.getReturnValue() || [];
                let advTypes = ["interstitial", "banner", "embedded", "video", "url", "paster"];
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "广告cd限制:" });
                config.push({ type: "newLine" });
                for (let i = 0; i < advTypes.length; i++) {
                    const advType = advTypes[i];
                    let cdTag = "未配置CD";
                    let lastTriggerTag = "未触发";
                    let cd = this.getAdvTypeCd(advType);
                    if (cd > 0) {
                        cdTag = ULTools.format("CD%d秒", cd / 1000);
                    }
                    let lastTriggerTime = this.advTypeLastTriggerTimeLog[advType] || 0;
                    if (lastTriggerTime > 0) {
                        lastTriggerTag = ULTools.formatDate(new Date(lastTriggerTime * 1000), "触发时间：HH:mm:ss");
                    }
                    config.push({ type: "label", text: ULTools.format("%s: %s %s", advType, cdTag, lastTriggerTag) });
                    config.push({ type: "newLine" });
                }
                config.push({ type: "label", text: "广告次数限制:" });
                config.push({ type: "newLine" });
                for (let i = 0; i < advTypes.length; i++) {
                    const advType = advTypes[i];
                    let limitTag = "未配置次数限制";
                    let countTag = "未触发";
                    let dailyLimit = this.getAdvTypeDailyLimit(advType);
                    if (dailyLimit > 0) {
                        limitTag = ULTools.format("日限制%d次", dailyLimit);
                    }
                    let dailyCount = this.advTypeDailyCountLog[advType] || 0;
                    if (dailyCount > 0) {
                        countTag = ULTools.format("今日已触发%d次", dailyCount);
                    }
                    config.push({ type: "label", text: ULTools.format("%s: %s %s", advType, limitTag, countTag) });
                    config.push({ type: "newLine" });
                }
                e.setReturnValue(config, true);
            }
            initAdv() {
                let config = ULConfig.getConfig();
                this.ADV_RELOAD_TIME = config["i_sdk_adv_reload_time"] || this.ADV_RELOAD_DEFAULT_TIME;
                let showListS = config["o_sdk_adv_show_list"];
                if (!showListS || typeof (showListS) !== "string") {
                    console.warn("ULAdvManager-initAdv:adv show list error");
                    return;
                }
                let showListObject = JSON.parse(showListS);
                let templatesObj = showListObject["templates"];
                if (!templatesObj || typeof (templatesObj) !== "object") {
                    console.warn("ULAdvManager-initAdv:templates error");
                    return;
                }
                let advSlotsObj = showListObject["advSlots"];
                if (!advSlotsObj || typeof (advSlotsObj) !== "object") {
                    console.warn("ULAdvManager-initAdv:advSlots error");
                    return;
                }
                let old_advKey_2_advObject = this.advKey_2_advObject;
                this.advKey_2_advObject = {};
                this.advId_2_advSlot = {};
                this.templateId_2_advTemplate = {};
                this.templateId_2_advTemplateItemArray = {};
                this.advKey_2_templateIdArray = {};
                this.templateId_2_moduleName = {};
                this.mainName_2_advObjectArray = {};
                this.templateId_2_advObjectArray = {};
                this.advType_2_advObjectArray = {};
                this.moduleName_2_templateIdsArray = {};
                this.logKey_2_countNum = {};
                this.advKey_2_advIdArray = {};
                this.tid_2_advKeyArray = {};
                this.advId_2_tidArray = {};
                this.nativeType_2_advObjectArray = {};
                this.advKey_2_rcd = {};
                this.updateAdvExpKey(templatesObj);
                let templateArray = new Array();
                for (const key in templatesObj) {
                    let templateId = key;
                    let templateItem = templatesObj[templateId];
                    if (typeof (templateItem) !== "object") {
                        console.warn(`ULAdvManager-initAdv:模板【 ${templateId} 】格式配置非法`);
                        continue;
                    }
                    let moduleName = templateItem['moduleName'];
                    if (!moduleName || (typeof moduleName) !== "string") {
                        console.warn(`ULAdvManager-initAdv:模板【 ${templateId} 】缺少必配字段moduleName`);
                        continue;
                    }
                    let rewardType = templateItem['rewardType'];
                    if (!rewardType || (typeof moduleName) !== "string") {
                        console.warn(`ULAdvManager-initAdv:模板【 ${templateId} 】缺少必配字段rewardType`);
                        continue;
                    }
                    let args = templateItem['args'];
                    if (!args || !(args instanceof Array)) {
                        console.warn(`ULAdvManager-initAdv:模板【 ${templateId} 】缺少必配字段args，或格式非法`);
                        continue;
                    }
                    if (args.length == 0) {
                        console.warn(`ULAdvManager-initAdv:模板【 ${templateId} 】必配字段args长度不能为0`);
                        continue;
                    }
                    let exp = templateItem['exp'] || "";
                    let argWeights = templateItem["argWeights"] || [];
                    let loadTypes = templateItem["loadTypes"] || [];
                    let rcd = templateItem["rcd"];
                    if ((typeof rcd) !== "number") {
                        rcd = 0;
                        console.warn(`ULAdvManager-initAdv:模板【 ${templateId} 】字段rcd未配置或格式错误，写入默认值0`);
                    }
                    let templateIdsArray = this.moduleName_2_templateIdsArray[moduleName];
                    if (!templateIdsArray) {
                        templateIdsArray = [];
                        templateIdsArray.push(templateId);
                        this.moduleName_2_templateIdsArray[moduleName] = templateIdsArray;
                    }
                    else {
                        if (templateIdsArray.indexOf(templateId) == -1) {
                            templateIdsArray.push(templateId);
                        }
                    }
                    if (!this.templateId_2_moduleName[templateId]) {
                        this.templateId_2_moduleName[templateId] = moduleName;
                    }
                    if (templateArray.indexOf(templateId) == -1) {
                        templateArray.push(templateId);
                    }
                    let newArgWeights = [];
                    let newLoadTypes = [];
                    for (let i = 0, len = args.length; i < len; i++) {
                        let arg = args[i];
                        if (typeof (arg) !== "string") {
                            console.warn(`ULAdvManager-initAdv:模板【 ${templateId} 】字段args中的参数${arg}，为非字符串类型`);
                            arg = arg.toString();
                        }
                        let argWeight = 0;
                        if (argWeights.length == 0) {
                            argWeight = ULConst.ADV_RANDOM_DEFAULT_WEIGHT;
                        }
                        else {
                            argWeight = argWeights[i];
                        }
                        newArgWeights.push(argWeight);
                        let loadType = undefined;
                        try {
                            loadType = loadTypes[i];
                            if (loadType && typeof (loadType) !== "number") {
                                loadType = Number(loadType);
                            }
                        }
                        catch (error) {
                        }
                        newLoadTypes.push(loadType);
                        let ulAdvTemplateItem = {
                            templateId: templateId,
                            moduleName: moduleName,
                            rewardType: rewardType,
                            arg: arg,
                            argWeight: argWeight,
                            exp: exp,
                            loadType: loadType
                        };
                        let templateItemArray = this.templateId_2_advTemplateItemArray[templateId];
                        if (!templateItemArray) {
                            templateItemArray = [];
                            templateItemArray.push(ulAdvTemplateItem);
                            this.templateId_2_advTemplateItemArray[templateId] = templateItemArray;
                        }
                        else {
                            let bContains = false;
                            for (const item of templateItemArray) {
                                let key = item.templateId + "_" + item.arg;
                                let targetKey = templateId + "_" + arg;
                                if (key == targetKey) {
                                    bContains = true;
                                }
                            }
                            if (!bContains) {
                                templateItemArray.push(ulAdvTemplateItem);
                            }
                        }
                        let advKey = ULTools.format("%s%s%s", moduleName, "_", arg);
                        let tidArray = this.advKey_2_templateIdArray[advKey];
                        if (!tidArray) {
                            tidArray = [];
                            tidArray.push(templateId);
                            this.advKey_2_templateIdArray[advKey] = tidArray;
                        }
                        else {
                            if (tidArray.indexOf(templateId) == -1) {
                                tidArray.push(templateId);
                            }
                        }
                        let advkeyArray = this.tid_2_advKeyArray[templateId];
                        if (!advkeyArray) {
                            advkeyArray = [];
                            advkeyArray.push(advKey);
                            this.tid_2_advKeyArray[templateId] = advkeyArray;
                        }
                        else {
                            if (advkeyArray.indexOf(advKey) == -1) {
                                advkeyArray.push(advKey);
                            }
                        }
                        let num = this.advKey_2_rcd[advKey];
                        let cd;
                        if (num != undefined) {
                            cd = Math.min(rcd, num);
                        }
                        else {
                            cd = rcd;
                        }
                        this.advKey_2_rcd[advKey] = cd;
                    }
                    let advTemplate = {
                        templateId: templateId,
                        moduleName: moduleName,
                        rewardType: rewardType,
                        exp: exp,
                        args: args,
                        argWeights: newArgWeights,
                        rcd: rcd,
                        loadTypes: newLoadTypes
                    };
                    if (!this.templateId_2_advTemplate[templateId]) {
                        this.templateId_2_advTemplate[templateId] = advTemplate;
                    }
                }
                let tidsInAdvSlotsArray = [];
                for (const key in advSlotsObj) {
                    let advId = key;
                    let advSlotItem = advSlotsObj[advId];
                    if (typeof (advSlotItem) !== "object") {
                        console.warn(`ULAdvManager-initAdv:广告位【 ${advId} 】格式配置非法`);
                        continue;
                    }
                    let schemesArray = advSlotItem["schemes"];
                    if (!schemesArray) {
                        console.warn(`ULAdvManager-initAdv:广告位【 ${advId} 】缺少必配字段schemes,或该字段格式非法`);
                        continue;
                    }
                    let subAidsArray = advSlotItem["subAids"] || [];
                    let rcd = advSlotItem["rcd"];
                    if ((typeof rcd) !== "number") {
                        rcd = 0;
                        console.warn(`ULAdvManager-initAdv:广告位【 ${advId} 】字段rcd未配置或格式错误，写入默认值0`);
                    }
                    let schemeArray = [];
                    for (let i = 0, len = schemesArray.length; i < len; i++) {
                        const schemeItemObj = schemesArray[i];
                        let tids = schemeItemObj["tids"];
                        if (!tids) {
                            console.warn(`ULAdvManager-initAdv:广告位【 ${advId} 】第【 ${i + 1} 】条策略缺少必配字段tids,或该字段格式非法`);
                            continue;
                        }
                        if (tids.length == 0) {
                            console.warn(`ULAdvManager-initAdv:广告位【 ${advId} 】第【 ${i + 1} 】条策略必配字段tids长度不能为0`);
                            continue;
                        }
                        let tidWeights = schemeItemObj["tidWeights"] || [];
                        let newTidWeights = [];
                        for (let j = 0, len = tids.length; j < len; j++) {
                            let tid = tids[j];
                            let tidWeight = 0;
                            if (tidWeights.length == 0) {
                                console.warn(`ULAdvManager-initAdv:广告位【 ${advId} 】第【 ${i + 1} 】条策略第【 ${j + 1} 】个模板权重未配置，写入默认值${ULConst.ADV_MUST_DEFAULT_WEIGHT}`);
                                tidWeight = ULConst.ADV_MUST_DEFAULT_WEIGHT;
                            }
                            else {
                                let tidW = tidWeights[j];
                                if ((typeof tidW) !== "number") {
                                    console.warn(`ULAdvManager-initAdv:广告位【 ${advId} 】第【 ${i + 1} 】条策略第【 ${j + 1} 】个模板权重格式异常，写入默认值${ULConst.ADV_MUST_DEFAULT_WEIGHT}`);
                                    tidWeight = ULConst.ADV_MUST_DEFAULT_WEIGHT;
                                }
                                else {
                                    tidWeight = tidW;
                                }
                            }
                            newTidWeights.push(tidWeight);
                            if (tidsInAdvSlotsArray.indexOf(tid) == -1) {
                                tidsInAdvSlotsArray.push(tid);
                            }
                            let tidArray = this.advId_2_tidArray[advId];
                            if (!tidArray) {
                                tidArray = [];
                                tidArray.push(tid);
                                this.advId_2_tidArray[advId] = tidArray;
                            }
                            else {
                                if (tidArray.indexOf(tid) == -1) {
                                    tidArray.push(tid);
                                }
                            }
                            if (subAidsArray.length > 0) {
                                for (const advId of subAidsArray) {
                                    let tidArray = this.advId_2_tidArray[advId];
                                    if (!tidArray) {
                                        tidArray = [];
                                        tidArray.push(tid);
                                        this.advId_2_tidArray[advId] = tidArray;
                                    }
                                    else {
                                        if (tidArray.indexOf(tid) == -1) {
                                            tidArray.push(tid);
                                        }
                                    }
                                }
                            }
                        }
                        let exp = schemeItemObj["exp"] || "";
                        let weight = schemeItemObj["weight"];
                        if ((typeof weight) !== "number") {
                            weight = ULConst.ADV_RANDOM_DEFAULT_WEIGHT;
                            console.warn(`ULAdvManager-initAdv:广告位【 ${advId} 】第【 ${i + 1} 】条策略字段weight格式异常，写入默认值${ULConst.ADV_RANDOM_DEFAULT_WEIGHT}`);
                        }
                        let ulAdvScheme = {
                            tids: tids,
                            tidWeights: newTidWeights,
                            exp: exp,
                            weight: weight
                        };
                        schemeArray.push(ulAdvScheme);
                    }
                    let advSlot = new ULAdvSlot(advId, schemeArray, subAidsArray, rcd);
                    if (!this.advId_2_advSlot[advId]) {
                        this.advId_2_advSlot[advId] = advSlot;
                    }
                    if (subAidsArray.length > 0) {
                        for (const mAdvId of subAidsArray) {
                            let newSubAidsArray = ULTools.clone(subAidsArray);
                            let index = newSubAidsArray.indexOf(mAdvId);
                            if (index > -1) {
                                newSubAidsArray.splice(index, 1);
                            }
                            newSubAidsArray.push(advId);
                            let subIdAdvSlot = new ULAdvSlot(mAdvId, schemeArray, newSubAidsArray, rcd);
                            if (!this.advId_2_advSlot[mAdvId]) {
                                this.advId_2_advSlot[mAdvId] = subIdAdvSlot;
                            }
                        }
                    }
                }
                ULTools.forEachMap(this.advId_2_tidArray, (advId, tidArray) => {
                    for (const tid of tidArray) {
                        let advKeyArray = this.tid_2_advKeyArray[tid];
                        if (!advKeyArray)
                            continue;
                        for (const key of advKeyArray) {
                            let advIdArray = this.advKey_2_advIdArray[key];
                            if (!advIdArray) {
                                advIdArray = [];
                                advIdArray.push(advId);
                                this.advKey_2_advIdArray[key] = advIdArray;
                            }
                            else {
                                if (advIdArray.indexOf(advId) == -1) {
                                    advIdArray.push(advId);
                                }
                            }
                        }
                    }
                });
                let newAdvBaseObjectArray = [];
                for (const tid in this.templateId_2_advTemplateItemArray) {
                    let tidItemArray = this.templateId_2_advTemplateItemArray[tid];
                    if (tidsInAdvSlotsArray.indexOf(tid) == -1) {
                        console.warn("ULAdvManager-initAdv:tid [" + tid + "] no advId use");
                        continue;
                    }
                    let moduleName = this.templateId_2_moduleName[tid];
                    let moduleMainClass;
                    ULTools.forEachMap(ULSdkModuleLoader.getSubAdModuleClassName(), (k, v) => {
                        let moduleNameArray = v;
                        if (moduleNameArray.indexOf(moduleName) >= 0) {
                            moduleMainClass = k;
                            return true;
                        }
                    });
                    if (!moduleMainClass) {
                        console.warn("ULAdvManager-initAdv: class " + moduleName + " not found ,continue");
                        continue;
                    }
                    for (let i = 0, len = tidItemArray.length; i < len; i++) {
                        let templateItem = tidItemArray[i];
                        let advKey = templateItem.moduleName + "_" + templateItem.arg;
                        if (old_advKey_2_advObject[advKey]) {
                            let obj = old_advKey_2_advObject[advKey];
                            this.advKey_2_advObject[advKey] = obj;
                            delete old_advKey_2_advObject[advKey];
                        }
                        if (this.advKey_2_advObject[advKey]) {
                            console.warn("ULAdvManger-initAdv: class " + moduleName + " already init,continue");
                            let obj = this.advKey_2_advObject[advKey];
                            let templateItemObjectsArray = this.templateId_2_advObjectArray[tid];
                            if (!templateItemObjectsArray) {
                                templateItemObjectsArray = [];
                                templateItemObjectsArray.push(obj);
                                this.templateId_2_advObjectArray[tid] = templateItemObjectsArray;
                            }
                            else {
                                if (templateItemObjectsArray.indexOf(obj) == -1) {
                                    templateItemObjectsArray.push(obj);
                                }
                            }
                            continue;
                        }
                        let mainObj = ULSdkModuleLoader.getObjectByModuleName(moduleMainClass);
                        let targetObj = mainObj.createSubAdObj(moduleName, templateItem.arg);
                        targetObj.setLoadType = templateItem.loadType;
                        let advMainClassNameString = targetObj.getMainClassNameString();
                        if (newAdvBaseObjectArray.indexOf(targetObj) == -1) {
                            newAdvBaseObjectArray.push(targetObj);
                        }
                        let templateItemObjectArray = this.mainName_2_advObjectArray[advMainClassNameString];
                        if (!templateItemObjectArray) {
                            templateItemObjectArray = [];
                            templateItemObjectArray.push(targetObj);
                            this.mainName_2_advObjectArray[advMainClassNameString] = templateItemObjectArray;
                        }
                        else {
                            if (templateItemObjectArray.indexOf(targetObj) == -1) {
                                templateItemObjectArray.push(targetObj);
                            }
                        }
                        let templateItemObjectsArray = this.templateId_2_advObjectArray[tid];
                        if (!templateItemObjectsArray) {
                            templateItemObjectsArray = [];
                            templateItemObjectsArray.push(targetObj);
                            this.templateId_2_advObjectArray[tid] = templateItemObjectsArray;
                        }
                        else {
                            if (templateItemObjectsArray.indexOf(targetObj) == -1) {
                                templateItemObjectsArray.push(targetObj);
                            }
                        }
                        if (targetObj instanceof ULAdvNativeObjectBase) {
                            let type = targetObj.advType;
                            let ulAdvNativeObjectBases = this.nativeType_2_advObjectArray[type];
                            if (ulAdvNativeObjectBases == null) {
                                ulAdvNativeObjectBases = [];
                                ulAdvNativeObjectBases.push(targetObj);
                                this.nativeType_2_advObjectArray[type] = ulAdvNativeObjectBases;
                            }
                            else {
                                if (ulAdvNativeObjectBases.indexOf(targetObj) == -1) {
                                    ulAdvNativeObjectBases.push(targetObj);
                                }
                            }
                        }
                    }
                }
                ;
                ULTools.forEachMap(this.advKey_2_advObject, (k, v) => {
                    let objectBase = v;
                    let bases = this.advType_2_advObjectArray[objectBase.advType];
                    if (!bases) {
                        bases = [];
                        bases.push(objectBase);
                        this.advType_2_advObjectArray[objectBase.advType] = bases;
                    }
                    else {
                        if (bases.indexOf(objectBase) == -1) {
                            bases.push(objectBase);
                        }
                    }
                });
                for (const key in old_advKey_2_advObject) {
                    let object = old_advKey_2_advObject[key];
                    object.onDisposeModule();
                }
                ULTools.forEachMap(this.advId_2_advSlot, (advId, advSlot) => {
                    let slot = advSlot;
                    slot.refreshValidAdvKeys();
                });
                let newAdvBaseCache = {};
                for (let i = 0, len = newAdvBaseObjectArray.length; i < len; i++) {
                    let advObjectBaseCacheItem = newAdvBaseObjectArray[i];
                    let advMainClassNameString = advObjectBaseCacheItem.getMainClassNameString();
                    ULTools.forEachMap(ULSdkModuleLoader.getSubAdMainClassName(), (k, v) => {
                        let adMainClassName = v;
                        if (advMainClassNameString == adMainClassName) {
                            if (this.adMainName_2_obj[adMainClassName]) {
                                let targetObj = this.adMainName_2_obj[adMainClassName];
                                advObjectBaseCacheItem.receiveMainClassInitState(targetObj.initState);
                            }
                            else if (!newAdvBaseCache[adMainClassName]) {
                                let obj = ULSdkModuleLoader.getObjectByModuleName(k);
                                let targetObj = obj.createMainAdObj();
                                newAdvBaseCache[adMainClassName] = targetObj;
                            }
                        }
                    });
                }
                for (const key in newAdvBaseCache) {
                    this.adMainName_2_obj[key] = newAdvBaseCache[key];
                }
                ULLog.console.log("ULAdvManager-initAdv-advExpKeyArray:", this.advExpKeyArray);
                ULLog.console.log("ULAdvManager-initAdv-templateArray:", templateArray);
                ULLog.console.log("ULAdvManager-initAdv-advId_2_advSlot:", this.advId_2_advSlot);
                ULLog.console.log("ULAdvManager-initAdv-templateId_2_advTemplate:", this.templateId_2_advTemplate);
                ULLog.console.log("ULAdvManager-initAdv-templateId_2_advTemplateItemArray:", this.templateId_2_advTemplateItemArray);
                ULLog.console.log("ULAdvManager-initAdv-advKey_2_templateIdArray:", this.advKey_2_templateIdArray);
                ULLog.console.log("ULAdvManager-initAdv-templateId_2_moduleName:", this.templateId_2_moduleName);
                ULLog.console.log("ULAdvManager-initAdv-mainName_2_advObjectArray:", this.mainName_2_advObjectArray);
                ULLog.console.log("ULAdvManager-initAdv-templateId_2_advObjectArray:", this.templateId_2_advObjectArray);
                ULLog.console.log("ULAdvManager-initAdv-advType_2_advObjectArray:", this.advType_2_advObjectArray);
                ULLog.console.log("ULAdvManager-initAdv-moduleName_2_templateIdsArray:", this.moduleName_2_templateIdsArray);
                ULLog.console.log("ULAdvManager-initAdv-logKey_2_countNum:", this.logKey_2_countNum);
                ULLog.console.log("ULAdvManager-initAdv-advKey_2_advIdArray:", this.advKey_2_advIdArray);
                ULLog.console.log("ULAdvManager-initAdv-tid_2_advKeyArray:", this.tid_2_advKeyArray);
                ULLog.console.log("ULAdvManager-initAdv-advId_2_tidArray:", this.advId_2_tidArray);
                ULLog.console.log("ULAdvManager-initAdv-nativeType_2_advObjectArray:", this.nativeType_2_advObjectArray);
                ULLog.console.log("ULAdvManager-initAdv-advKey_2_advObject:", this.advKey_2_advObject);
                ULLog.console.log("ULAdvManager-initAdv-advKey_2_rcd:", this.advKey_2_rcd);
            }
            getAdvReloadTime() {
                return this.ADV_RELOAD_TIME;
            }
            getAdvExpKeyArray() {
                return this.advExpKeyArray;
            }
            getLogKeyCountNum() {
                return this.logKey_2_countNum;
            }
            initAdvExpKey() {
                let keyArray = new Array();
                for (const type in typeExp) {
                    for (const count in countExp) {
                        let key = ULTools.format("%s%s%s%s", ULConst.EXP_ADV_TYPE_CONST, type, ULConst.EXP_ADV_POINT_CONST, count);
                        if (keyArray.indexOf(key) == -1) {
                            keyArray.push(key);
                        }
                    }
                    for (const cd in cdExp) {
                        let key = ULTools.format("%s%s%s%s", ULConst.EXP_ADV_TYPE_CONST, type, ULConst.EXP_ADV_POINT_CONST, cd);
                        if (keyArray.indexOf(key) == -1) {
                            keyArray.push(key);
                        }
                    }
                }
                for (let i = 0; i < keyArray.length; i++) {
                    let key = keyArray[i];
                    for (const data in dataExp) {
                        let newKey;
                        if (data == dataExp.t) {
                            newKey = key;
                        }
                        else {
                            newKey = data + key;
                        }
                        if (this.systemAdvExpKeyArray.indexOf(newKey) == -1) {
                            this.systemAdvExpKeyArray.push(newKey);
                        }
                    }
                }
            }
            updateAdvExpKey(templatesObj) {
                this.advExpKeyArray = this.systemAdvExpKeyArray.slice(0);
                let keyArray = new Array();
                for (const template in templatesObj) {
                    for (const count in countExp) {
                        let key = ULTools.format("%s%s%s%s", ULConst.EXP_ADV_TEMPLATE_CONST, template, ULConst.EXP_ADV_POINT_CONST, count);
                        if (keyArray.indexOf(key) == -1) {
                            keyArray.push(key);
                        }
                    }
                    for (const cd in cdExp) {
                        let key = ULTools.format("%s%s%s%s", ULConst.EXP_ADV_TEMPLATE_CONST, template, ULConst.EXP_ADV_POINT_CONST, cd);
                        if (keyArray.indexOf(key) == -1) {
                            keyArray.push(key);
                        }
                    }
                }
                for (let i = 0; i < keyArray.length; i++) {
                    let key = keyArray[i];
                    for (const data in dataExp) {
                        let newKey;
                        if (data == dataExp.t) {
                            newKey = key;
                        }
                        else {
                            newKey = data + key;
                        }
                        if (this.advExpKeyArray.indexOf(newKey) == -1) {
                            this.advExpKeyArray.push(newKey);
                        }
                    }
                }
                ULAdvExpManager.updateExpKeys(this.advExpKeyArray);
            }
            updateAdvKeyObjMap(advKey, advObject) {
                this.advKey_2_advObject[advKey] = advObject;
            }
            updateAdvIds(type, advId) {
                let advIds = this.type_2_advIds[type];
                if (!advIds) {
                    advIds = [];
                    advIds.push(advId);
                    this.type_2_advIds[type] = advIds;
                }
                else {
                    if (advIds.indexOf(advId) == -1) {
                        advIds.push(advId);
                    }
                }
            }
            deleteAdvIdOpening(type, advId) {
                let advIds = this.type_2_advIds[type];
                if (advIds) {
                    advIds = advIds.filter(item => item !== advId);
                    this.type_2_advIds[type] = advIds;
                }
            }
            getAdvObjectsByName(mainName) {
                return this.mainName_2_advObjectArray[mainName];
            }
            onAdvObjectPreloadStateChanged(advKey) {
                ULTools.forEachMap(this.advId_2_advSlot, (k, v) => {
                    let advSlot = v;
                    advSlot.onAdvObjectPreloadStateChanged(advKey);
                });
            }
            onAdvSlotPreloadStateChanged(advId) {
                let ulAdvSlot = this.advId_2_advSlot[advId];
                if (!ulAdvSlot) {
                    return;
                }
                let states = {};
                states[advId] = ulAdvSlot.preLoadState;
            }
            getTemplateObjByTid(tid) {
                return this.templateId_2_advTemplate[tid];
            }
            getAdvObjsByTid(tid) {
                return this.templateId_2_advObjectArray[tid];
            }
            getAdvTypeByTemplateId(tid) {
                let advType = null;
                let advObjects = this.templateId_2_advObjectArray[tid];
                if (advObjects && advObjects.length > 0) {
                    advType = advObjects[0].advType;
                }
                return advType;
            }
            isAdvTypeOpened(advType) {
                let config = ULConfig.getConfig();
                let exemptArray = config.t_sdk_exempt_advType_limit_arrays;
                if (exemptArray.indexOf(advType) != -1) {
                    return false;
                }
                let mutuallyExclusive = config.t_sdk_mutuallyExclusive_advType_setting || {};
                let trimMutuallyExclusiv = {};
                for (let advType of Object.keys(mutuallyExclusive)) {
                    let itemList = mutuallyExclusive[advType];
                    for (let subAdvType of itemList) {
                        let list = trimMutuallyExclusiv[advType] || [advType];
                        let otherList = trimMutuallyExclusiv[subAdvType] || [subAdvType];
                        list.push(subAdvType);
                        otherList.push(advType);
                        trimMutuallyExclusiv[advType] = list;
                        trimMutuallyExclusiv[subAdvType] = otherList;
                    }
                }
                let itemList = trimMutuallyExclusiv[advType] || [advType];
                for (let subAdvType of itemList) {
                    let objectBases = this.advType_2_advObjectArray[subAdvType];
                    if (objectBases && objectBases.length > 0) {
                        for (let i = 0; i < objectBases.length; i++) {
                            let objectBase = objectBases[i];
                            if (objectBase.isOpened)
                                return true;
                        }
                    }
                }
                return false;
            }
            getAdvObjectByAdvKey(advKey) {
                return this.advKey_2_advObject[advKey];
            }
            getRcdByAdvKey(advkey) {
                return this.advKey_2_rcd[advkey];
            }
            getAdvKeysByTemplateId(tid) {
                return this.tid_2_advKeyArray[tid];
            }
            getAdvSlotByAdvId(advId) {
                return this.advId_2_advSlot[advId];
            }
            getAdvObjPreloadStateByAdvKey(advKey) {
                let objectBase = this.advKey_2_advObject[advKey];
                if (objectBase) {
                    return objectBase.preLoadState;
                }
                return ULConst.ADV_PRELOAD_STATE_NOAD;
            }
            getRewardTypeByTemplateId(tid) {
                let ulAdvTemplate = this.templateId_2_advTemplate[tid];
                if (!ulAdvTemplate) {
                    return rewardType.show;
                }
                return ulAdvTemplate.rewardType;
            }
            getAdvTypeDailyLimit(advType) {
                let config = ULConfig.getConfig();
                let dailyLimit = 0;
                switch (advType) {
                    case "interstitial":
                        dailyLimit = config.i_sdk_adv_type_interstitial_daily_limit;
                        break;
                    case "banner":
                        dailyLimit = config.i_sdk_adv_type_banner_daily_limit;
                        break;
                    case "embedded":
                        dailyLimit = config.i_sdk_adv_type_embedded_daily_limit;
                        break;
                    case "video":
                        dailyLimit = config.i_sdk_adv_type_video_daily_limit;
                        break;
                    case "url":
                        dailyLimit = config.i_sdk_adv_type_url_daily_limit;
                        break;
                    case "paster":
                        dailyLimit = config.i_sdk_adv_type_paster_daily_limit;
                        break;
                }
                if (dailyLimit == null)
                    return 0;
                if (isNaN(dailyLimit))
                    return 0;
                return dailyLimit;
            }
            getAdvTypeCd(advType) {
                let config = ULConfig.getConfig();
                let cd = 0;
                switch (advType) {
                    case typeExp.inter:
                        cd = config.i_sdk_adv_type_interstitial_cd;
                        break;
                    case typeExp.banner:
                        cd = config.i_sdk_adv_type_banner_cd;
                        break;
                    case typeExp.embed:
                        cd = config.i_sdk_adv_type_embedded_cd;
                        break;
                    case typeExp.video:
                        cd = config.i_sdk_adv_type_video_cd;
                        break;
                    case typeExp.url:
                        cd = config.i_sdk_adv_type_url_cd;
                        break;
                    case typeExp.paster:
                        cd = config.i_sdk_adv_type_paster_cd;
                        break;
                }
                if (cd == null)
                    return 0;
                if (isNaN(cd))
                    return 0;
                return cd;
            }
            getLaunchCdByType(advType) {
                let config = ULConfig.getConfig();
                let cd = 0;
                switch (advType) {
                    case typeExp.inter:
                        cd = config.i_sdk_adv_inter_launch_cd;
                        break;
                    case typeExp.banner:
                        cd = config.i_sdk_adv_banner_launch_cd;
                        break;
                    case typeExp.embed:
                        cd = config.i_sdk_adv_embed_launch_cd;
                        break;
                    case typeExp.video:
                        cd = config.i_sdk_adv_video_launch_cd;
                        break;
                    case typeExp.url:
                        cd = config.i_sdk_adv_url_launch_cd;
                        break;
                    case typeExp.paster:
                        cd = config.i_sdk_adv_paster_launch_cd;
                        break;
                    case typeExp.custom:
                        cd = config.i_sdk_adv_custom_launch_cd;
                        break;
                }
                if (cd == null)
                    return 0;
                if (isNaN(cd))
                    return 0;
                return cd;
            }
            get sdkInitTime() {
                return this._sdkInitTime;
            }
            getAdvTypeLastTriggerTimeLog() {
                return this.advTypeLastTriggerTimeLog;
            }
            getAdvTypeDailyCountLog() {
                return this.advTypeDailyCountLog;
            }
            getAdvObjectOpeningByAdvType(type) {
                for (let key in this.advType_2_advObjectArray) {
                    if (type !== key) {
                        continue;
                    }
                    let objectBases = this.advType_2_advObjectArray[key];
                    for (let objectBase of objectBases) {
                        if (objectBase.isOpened) {
                            return objectBase;
                        }
                    }
                }
                return null;
            }
            getNewAdvTypeByOld(oldType) {
                let type = "";
                if (!oldType) {
                    return type;
                }
                type = oldType;
                if (oldTypeExp.embedded == oldType) {
                    type = typeExp.embed;
                }
                else if (oldTypeExp.interstitial == oldType) {
                    type = typeExp.inter;
                }
                else if (oldTypeExp.fullscreen == oldType) {
                    type = typeExp.interVideo;
                }
                return type;
            }
            geOldAdvTypeByNew(newType) {
                let type = "";
                if (!newType) {
                    return type;
                }
                type = newType;
                if (typeExp.embed == newType) {
                    type = oldTypeExp.embedded;
                }
                else if (typeExp.inter == newType) {
                    type = oldTypeExp.interstitial;
                }
                else if (typeExp.interVideo == newType) {
                    type = oldTypeExp.fullscreen;
                }
                return type;
            }
            onCmdGetAdvState(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                let userData = data['userData'] || "";
                let advIds = data['advIds'] || [];
                let advIdPreLoadState = {};
                for (const advId of advIds) {
                    let ulAdvSlot = this.advId_2_advSlot[advId];
                    if (!ulAdvSlot) {
                        advIdPreLoadState[advId] = ULConst.ADV_PRELOAD_STATE_NOAD;
                        continue;
                    }
                    advIdPreLoadState[advId] = ulAdvSlot.preLoadState;
                }
                this.getAdvStateResult(advIdPreLoadState, userData);
            }
            onCmdOpenAdv(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                let config = ULConfig.getConfig();
                this.advRequestSerialNum++;
                let advId = data["advId"] || "";
                let userData = data.userData || "";
                let tag = data.tag || "";
                let advType = this.searchAdvTypeByAdvId(advId);
                let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                let advItem = new ULAdvItem(advId, userData, tag);
                advItem.advType = advType;
                advItem.advGroupId = advGroupId;
                ULSdkManager.getInstance().statisManager.reportAdvTotalRequest(advItem);
                let all_ad_ecd = config.i_sdk_adv_all_launch_cd;
                if (ULTools.time() - this.sdkInitTime < all_ad_ecd / 1000) {
                    ULLog.console.log("ULAdvManager-onCmdOpenAdv:广告处于启动请求cd中");
                    this.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, { code: "", msg: "in all adv launch cd" });
                    return;
                }
                let advSolt = this.advId_2_advSlot[advId];
                if (!advSolt) {
                    console.warn("ULAdvManager-onCmdOpenAdv:广告位[" + advId + "]对应的advSlot不存在");
                    this.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, { code: "", msg: `广告位${advId}对应的advSlot不存在` });
                    return;
                }
                let openingInfo = advSolt.openingInfo;
                if (openingInfo) {
                    console.warn("ULAdvManager-onCmdOpenAdv:广告位[" + advId + "]已有广告请求中或正在展示");
                    this.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, { code: "", msg: `广告位${advId}已有广告请求中或正在展示` });
                    return;
                }
                let rcd = advSolt.rcd;
                ULLog.console.log("ULAdvManager-onCmdOpenAdv-rcd:", rcd);
                let lastRequestTime = this.advId_2_lastRequestTime[advId];
                let nowTime = (new Date()).valueOf();
                if (lastRequestTime) {
                    if ((nowTime - lastRequestTime) < rcd) {
                        console.warn("ULAdvManager-onCmdOpenAdv:广告位[" + advId + "]in cd");
                        this.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, { code: "", msg: `广告位[${advId}]in cd` });
                        return;
                    }
                    else {
                        this.advId_2_lastRequestTime[advId] = nowTime;
                    }
                }
                else {
                    this.advId_2_lastRequestTime[advId] = nowTime;
                }
                advSolt.openAdv(this.advRequestSerialNum, data);
            }
            onCmdCloseAdv(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                let advId = data.advId;
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot) {
                    this.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "advSlot未找到!");
                    return;
                }
                if (!advSlot.openingInfo) {
                    this.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "advSlot没有广告执行!");
                    return;
                }
                let objectBase = this.getAdvObjectByAdvKey(advSlot.openingInfo.advTemplateItemName);
                if (objectBase) {
                    if (objectBase instanceof ULAdvNativeObjectBase) {
                        advSlot.closeAdv(data);
                        this.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, "close adv success");
                    }
                    else {
                        advSlot.closeAdv(data);
                    }
                }
                else {
                    this.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "no ad open!");
                }
            }
            onCmdCloseAllAdvByType(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                let type = data.type || "";
                let advIds = this.type_2_advIds[type];
                if (advIds == null || advIds.length == 0) {
                    this.responseCloseAllAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "no ad show");
                    return;
                }
                for (let advId of advIds) {
                    let advSlot = this.advId_2_advSlot[advId];
                    if (advSlot == null || advSlot.openingInfo == null) {
                        continue;
                    }
                    let objectBase = this.getAdvObjectByAdvKey(advSlot.openingInfo.advTemplateItemName);
                    if (objectBase != null) {
                        data["advId"] = advId;
                        if (objectBase instanceof ULAdvNativeObjectBase) {
                            objectBase.closeNativeAdv(data);
                        }
                        else {
                            advSlot.closeAdv(data);
                        }
                    }
                }
                this.responseCloseAllAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, "关闭成功");
            }
            onCmdCloseNativeAdv(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                let advId = data.advId;
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot) {
                    this.responseCloseNativeAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "no advSlot");
                    return;
                }
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CLOSE_NATIVE_ADV, data);
                this.responseCloseNativeAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, "关闭成功");
            }
            onCmdClickNativeAdv(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                let advId = data.advId;
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", "109", advId || '', ""]);
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot) {
                    this.responseClickNativeAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "no advSlot");
                    return;
                }
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CLICK_NATIVE_ADV, data);
                ULSdkManager.getInstance().advManager.responseClickNativeAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, "点击成功");
            }
            responseOpenAdvResult(data, code, info) {
                let returnData = {};
                returnData["code"] = code;
                returnData["msg"] = ULAdvTrimErrorManager.trimErrMessage(info.msg, info.code ? info : null);
                returnData["advId"] = data.advId || "";
                returnData["userData"] = data.userData || "";
                returnData["tag"] = data.tag || "";
                if (code == 1) {
                    returnData["type"] = data.type || "";
                    returnData["rewardType"] = data.rewardType || "";
                    this.advTypeLastTriggerTimeLog[data.type] = ULTools.time();
                    this.advTypeDailyCountLog[data.type] = (this.advTypeDailyCountLog[data.type] || 0) + 1;
                    this.saveRecord();
                    let actualShowCount = data["actualShowCount"];
                    returnData["actualShowCount"] = isNaN(actualShowCount) ? 1 : actualShowCount;
                }
                ULSdkManager.getInstance().response(ULConst.CMD_OPEN_ADV_RESULT, returnData);
            }
            responseRewardAdvResult(data, code, msg) {
                let returnData = {
                    code: code,
                    msg: msg,
                    advId: data.advId || "",
                    userData: data.userData || "",
                    tag: data.tag || ""
                };
                if (code == 1) {
                    let actualShowCount = data["actualShowCount"];
                    returnData["actualShowCount"] = isNaN(actualShowCount) ? 1 : actualShowCount;
                }
                ULSdkManager.getInstance().response(ULConst.CMD_REWARD_ADV_RESULT, returnData);
            }
            responseClickAdvResult(data, code, msg) {
                ULSdkManager.getInstance().response(ULConst.CMD_CLICK_ADV_RESULT, {
                    code: code,
                    msg: msg,
                    advId: data.advId || "",
                    userData: data.userData || "",
                    tag: data.tag || ""
                });
            }
            responseOpenNativeAdvResult(showData, nativeType, code, msg, nativeData) {
                let returnData = {};
                returnData["code"] = code;
                returnData["msg"] = msg;
                returnData["advId"] = showData.advId || "";
                returnData["userData"] = showData.userData || "";
                returnData["tag"] = showData.tag || "";
                returnData["nativeType"] = nativeType || "";
                returnData["nativeData"] = nativeData || {};
                if (code == 1) {
                    returnData["type"] = showData.type || "";
                    returnData["rewardType"] = showData.rewardType || "";
                }
                ULSdkManager.getInstance().response(ULConst.CMD_OPEN_NATIVE_ADV_RESULT, returnData);
            }
            responseClickNativeAdvResult(data, code, msg) {
                ULSdkManager.getInstance().response(ULConst.CMD_CLICK_NATIVE_ADV_RESULT, {
                    code: code,
                    msg: msg,
                    nativeType: data.nativeType || "",
                    advId: data.advId || "",
                    userData: data.userData || "",
                    tag: data.tag || ""
                });
            }
            responseCloseNativeAdvResult(data, code, msg) {
                ULSdkManager.getInstance().response(ULConst.CMD_CLOSE_NATIVE_ADV_RESULT, {
                    code: code,
                    msg: msg,
                    nativeType: data.nativeType || "",
                    advId: data.advId || "",
                    userData: data.userData || "",
                    tag: data.tag || ""
                });
            }
            responseCloseAdvResult(data, code, msg) {
                ULSdkManager.getInstance().response(ULConst.CMD_CLOSE_ADV_RESULT, {
                    code: code,
                    msg: msg,
                    advId: data.advId || "",
                    userData: data.userData || "",
                    tag: data.tag || ""
                });
            }
            responseCloseAllAdvResult(data, code, msg) {
                ULSdkManager.getInstance().response(ULConst.CMD_CLOSE_ALL_ADV_BY_TYPE_RESULT, {
                    code: code,
                    msg: msg,
                    type: data.type || "",
                    userData: data.userData || ""
                });
            }
            pauseSound() {
                ULSdkManager.getInstance().response(ULConst.CMD_PAUSE_SOUND_RESULT, {});
            }
            resumeSound() {
                ULSdkManager.getInstance().response(ULConst.CMD_RESUME_SOUND_RESULT, {});
            }
            getAdvStateResult(data, userData) {
                ULSdkManager.getInstance().response(ULConst.CMD_GET_ADV_STATE_RESULT, {
                    states: data,
                    userData: userData,
                });
            }
            onAdvObjectLifeCycleShowRequest(advKey, data) {
                this.addAdvCountLog(advKey, countExp.rc);
                let advId = data.advId || "";
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType && statisticsType != "") {
                        advType = statisticsType;
                    }
                    let userData = data.userData || "";
                    let tag = data.tag || "";
                    let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = advGroupId;
                    ULSdkManager.getInstance().statisManager.reportAdvBranchRequest(advItem, advertiser, arg);
                }
            }
            onAdvObjectLifeCycleSkip(advKey, info, data) {
                let advId = data["advId"] || "";
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot)
                    return;
                advSlot.onAdvObjectLifeCycleSkip(data, info);
                this.addAdvCountLog(advKey, countExp.fc);
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType && statisticsType != "") {
                        advType = statisticsType;
                    }
                    let userData = data.userData || "";
                    let tag = data.tag || "";
                    let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = advGroupId;
                    advItem.statisChannelName = advertiser;
                    advItem.statisSdkAdvId = arg;
                    ULSdkManager.getInstance().statisManager.reportAdvFail(advItem, "errCode=" + info.code + ";errMsg=" + info.msg);
                }
            }
            onAdvObjectLifeCycleShow(advKey, msg, data, nativeData) {
                let advId = data.advId || "";
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot)
                    return;
                advSlot.onAdvObjectLifeCycleShow(msg, data);
                this.addAdvCountLog(advKey, countExp.sc);
                this.reportVideoPlayCompletion(advKey, data, nativeData);
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType && statisticsType != "") {
                        advType = statisticsType;
                    }
                    if (typeExp.banner == advType) {
                        this.bannerStartShowTime = ULTools.time();
                    }
                    let title = nativeData ? nativeData.title : "";
                    let userData = data.userData || "";
                    let tag = data.tag || "";
                    let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = advGroupId;
                    advItem.statisChannelName = advertiser;
                    advItem.statisNativeAdTitle = title;
                    advItem.statisSdkAdvId = arg;
                    let actualShowCount = data["actualShowCount"];
                    ULSdkManager.getInstance().statisManager.reportAdvSuccess(advItem, title, isNaN(actualShowCount) ? 1 : actualShowCount);
                }
            }
            onAdvObjectLifeCycleClick(advKey, msg, data, nativeData) {
                let advId = data.advId || "";
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot)
                    return;
                advSlot.onAdvObjectLifeCycleClick(msg, data);
                this.addAdvCountLog(advKey, countExp.cc);
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType && statisticsType != "") {
                        advType = statisticsType;
                    }
                    let title = nativeData ? nativeData.title : "";
                    let userData = data.userData || "";
                    let tag = data.tag || "";
                    let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = advGroupId;
                    advItem.statisChannelName = advertiser;
                    advItem.statisNativeAdTitle = title;
                    advItem.statisSdkAdvId = arg;
                    ULSdkManager.getInstance().statisManager.reportAdvClicked(advItem);
                }
            }
            onAdvObjectLifeCycleClose(advKey, data, nativeData) {
                let advId = data.advId || "";
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot)
                    return;
                this.reportBannerShowTime(advKey, data, nativeData);
                this.reportVideoPlayStart(advKey, data, nativeData);
                advSlot.onAdvObjectLifeCycleClose();
                this.responseCloseAdvResult(data, 1, "success");
            }
            onAdvTimeout(advItem, msg) {
            }
            reportBannerShowTime(advKey, data, nativeData) {
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase != null) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType != null && statisticsType != "") {
                        advType = statisticsType;
                    }
                    if (typeExp.banner == advType) {
                        let bannerShowDuration = Math.floor(ULTools.time() - this.bannerStartShowTime);
                        if (bannerShowDuration <= 0) {
                            return;
                        }
                        let bannerShowTime = String(bannerShowDuration);
                        let advId = data.advId || "";
                        let userData = data.userData || "";
                        let tag = data.tag || "";
                        let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                        let advItem = new ULAdvItem(advId, userData, tag);
                        advItem.showAdvType = advType;
                        advItem.advGroupId = advGroupId;
                        advItem.statisChannelName = advertiser;
                        advItem.statisNativeAdTitle = nativeData ? nativeData.title : "";
                        advItem.statisSdkAdvId = arg;
                        ULSdkManager.getInstance().statisManager.reportAdvClose(advItem, bannerShowTime);
                    }
                }
            }
            reportVideoPlayStart(advKey, data, nativeData) {
                let advId = data.advId || "";
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot)
                    return;
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase != null) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType != null && statisticsType != "") {
                        advType = statisticsType;
                    }
                    if (typeExp.video == advType) {
                        let title = nativeData ? nativeData.title : "";
                        let userData = data.userData || "";
                        let tag = data.tag || "";
                        let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                        let advItem = new ULAdvItem(advId, userData, tag);
                        advItem.showAdvType = advType;
                        advItem.advGroupId = advGroupId;
                        advItem.statisChannelName = advertiser;
                        advItem.statisNativeAdTitle = title;
                        advItem.statisSdkAdvId = arg;
                        ULSdkManager.getInstance().statisManager.reportAdvPlayStart(advItem);
                    }
                }
            }
            reportVideoPlayCompletion(advKey, data, nativeData) {
                let advId = data.advId || "";
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot)
                    return;
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase != null) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType != null && statisticsType != "") {
                        advType = statisticsType;
                    }
                    if (typeExp.video == advType) {
                        let title = nativeData ? nativeData.title : "";
                        let userData = data.userData || "";
                        let tag = data.tag || "";
                        let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                        let advItem = new ULAdvItem(advId, userData, tag);
                        advItem.showAdvType = advType;
                        advItem.advGroupId = advGroupId;
                        advItem.statisChannelName = advertiser;
                        advItem.statisNativeAdTitle = title;
                        advItem.statisSdkAdvId = arg;
                        ULSdkManager.getInstance().statisManager.reportAdvPlayCompletion(advItem);
                    }
                }
            }
            onAdvObjectLifeCycleRequest(advKey) {
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase != null && !objectBase.isReportLoading) {
                    objectBase.isReportLoading = true;
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType != null && statisticsType != "") {
                        advType = statisticsType;
                    }
                    let advId = "";
                    let userData = "";
                    let tag = "";
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = "";
                    advItem.statisChannelName = advertiser;
                    advItem.statisNativeAdTitle = "";
                    advItem.statisSdkAdvId = arg;
                    ULSdkManager.getInstance().statisManager.reportAdvLoadAdvRequest(advItem);
                }
            }
            onAdvObjectLifeCycleRequestSuccess(advKey) {
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase != null && objectBase.isReportLoading) {
                    objectBase.isReportLoading = false;
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType != null && statisticsType != "") {
                        advType = statisticsType;
                    }
                    let advId = "";
                    let userData = "";
                    let tag = "";
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = "";
                    advItem.statisChannelName = advertiser;
                    advItem.statisNativeAdTitle = "";
                    advItem.statisSdkAdvId = arg;
                    ULSdkManager.getInstance().statisManager.reportAdvLoadAdvSuccess(advItem);
                }
            }
            onAdvObjectLifeCycleRequestFailed(advKey, info) {
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase != null && objectBase.isReportLoading) {
                    objectBase.isReportLoading = false;
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType != null && statisticsType != "") {
                        advType = statisticsType;
                    }
                    let advId = "";
                    let userData = "";
                    let tag = "";
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = "";
                    advItem.statisChannelName = advertiser;
                    advItem.statisSdkAdvId = arg;
                    ULSdkManager.getInstance().statisManager.reportAdvLoadAdvFailed(advItem, "errCode=" + info.code + ";errMsg=" + info.msg);
                }
            }
            onAdvObjectLifeCycleFail(advKey, info, data) {
                let advId = data.advId || "";
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot)
                    return;
                advSlot.onAdvObjectLifeCycleFail(info, data);
                this.addAdvCountLog(advKey, countExp.fc);
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType && statisticsType != "") {
                        advType = statisticsType;
                    }
                    let userData = data.userData || "";
                    let tag = data.tag || "";
                    let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = advGroupId;
                    advItem.statisChannelName = advertiser;
                    advItem.statisSdkAdvId = arg;
                    ULSdkManager.getInstance().statisManager.reportAdvFail(advItem, "errCode=" + info.code + ";errMsg=" + info.msg);
                }
            }
            onAdvObjectLifeCycleReuse(advKey, info, data) {
                let advId = data.advId || "";
                let advSlot = this.advId_2_advSlot[advId];
                if (!advSlot)
                    return;
                ULSdkManager.getInstance().advManager.responseOpenAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, info);
                this.addAdvCountLog(advKey, countExp.fc);
                let objectBase = this.getAdvObjectByAdvKey(advKey);
                if (objectBase) {
                    let advType = objectBase.advType;
                    let arg = objectBase.arg;
                    let advertiser = objectBase.statisticsAdvertiser;
                    let statisticsType = objectBase.statisticsType;
                    if (statisticsType && statisticsType != "") {
                        advType = statisticsType;
                    }
                    let userData = data.userData || "";
                    let tag = data.tag || "";
                    let advGroupId = this.searchAdvGroupIdByAdvId(advId);
                    let advItem = new ULAdvItem(advId, userData, tag);
                    advItem.showAdvType = advType;
                    advItem.advGroupId = advGroupId;
                    advItem.statisChannelName = advertiser;
                    advItem.statisSdkAdvId = arg;
                    ULSdkManager.getInstance().statisManager.reportAdvFail(advItem, "errCode=" + info.code + ";errMsg=" + info.msg);
                }
            }
            addAdvFailCount(advKey) {
                this.addAdvCountLog(advKey, countExp.fc);
            }
            addAdvCountLog(advKey, countExp) {
                let tidArray = this.advKey_2_templateIdArray[advKey];
                if (tidArray && tidArray.length > 0) {
                    for (const tid of tidArray) {
                        let key = ULConst.EXP_ADV_TEMPLATE_CONST + tid + ULConst.EXP_ADV_POINT_CONST + countExp;
                        this.updateAdvCountStoreNum(key);
                        this.advSlotRefreshValidAdvKeys(advKey);
                    }
                }
                let objectBase = this.advKey_2_advObject[advKey];
                if (objectBase) {
                    let advType = objectBase.advType;
                    let key = ULConst.EXP_ADV_TYPE_CONST + advType + ULConst.EXP_ADV_POINT_CONST + countExp;
                    this.updateAdvCountStoreNum(key);
                    this.advSlotRefreshValidAdvKeys(advKey);
                }
            }
            updateAdvCountStoreNum(key) {
                ULAdvExpManager.updateExpValue(key);
                ULAdvExpManager.updateExpValue(dataExp.d + key);
                ULAdvExpManager.updateExpValue(dataExp.w + key);
                ULAdvExpManager.updateExpValue(dataExp.m + key);
                ULAdvExpManager.updateExpValue(dataExp.y + key);
            }
            advSlotRefreshValidAdvKeys(advKey) {
                let advIdArray = this.advKey_2_advIdArray[advKey];
                if (advIdArray) {
                    for (const advId of advIdArray) {
                        let ulAdvSlot = this.advId_2_advSlot[advId];
                        if (ulAdvSlot) {
                            ulAdvSlot.refreshValidAdvKeys();
                        }
                    }
                }
            }
        }
        ULAdvManager.instance = null;

        let qg$2 = window["qg"];
        class ULAdvOppoQgVideo extends ULAdvObjectBase {
            constructor(arg) {
                super(arg, typeExp.video, ULTools.format("%s%s%s", "ULAdvOppoQgVideo", "_", arg));
                this.className = "ULAdvOppoQgVideo";
                this.videoAd = null;
                this.statisticsAdvertiser = ULAdvOppoQg.NORMAL_ADVERTISER;
                this.setSupportLoadType = [ULConst.ADV_LOAD_TYPE_PRELOAD, ULConst.ADV_LOAD_TYPE_UNPRELOAD];
                this.setLoadType = ULConst.ADV_LOAD_TYPE_PRELOAD;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgVideo-onDisposeModule arg:", this.arg);
                if (this.videoAd) {
                    this.videoAd.offClose();
                    this.videoAd.offLoad();
                    this.videoAd.offError();
                    this.videoAd.destroy();
                    this.videoAd = null;
                }
            }
            initAdv() {
                let platformVersionCode = qg$2.getSystemInfoSync().platformVersionCode;
                if (platformVersionCode < 1051) {
                    ULLog.console.log("ULAdvOppoQgVideo-initAdv-最低平台版本支持1051，直接跳过");
                    return;
                }
                let loadType = this.getLoadType;
                if (loadType == undefined || this.getSupportLoadType.indexOf(loadType) == -1) {
                    ULLog.console.log(`ULAdvOppoQgVideo-initAdv-当前加载类型${loadType}模块不支持`);
                    loadType = ULConst.ADV_LOAD_TYPE_PRELOAD;
                }
                this.mLoadType = loadType;
                if (!this.videoAd) {
                    this.videoAd = qg$2.createRewardedVideoAd({
                        adUnitId: this.arg
                    });
                }
                if (this.mLoadType == ULConst.ADV_LOAD_TYPE_PRELOAD) {
                    this.videoAd.onLoad(() => {
                        ULLog.console.log("ULAdvOppoQgVideo videoAd.onLoad");
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                        this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                    });
                    this.videoAd.onClose((res) => {
                        ULLog.console.log("ULAdvOppoQgVideo videoAd.onClose.res:", res);
                        this.isOpened = false;
                        if (res.isEnded) {
                            ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, this.showData);
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_video_success_show_event_id]);
                        }
                        else {
                            ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleFail(this.advKey, { code: "", msg: ULConst.ADV_VIDEO_PLAY_FAIL_MSG }, this.showData);
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_user_close_video_event_id]);
                        }
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, this.showData);
                        this.preLoadAdv();
                    });
                    this.videoAd.onError((err) => {
                        ULLog.console.log("ULAdvOppoQgVideo videoAd.onError", err);
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, { code: String(err.errCode), msg: err.errMsg });
                        this.onLoadFailErr = { code: String(err.errCode), msg: err.errMsg };
                        if (this.preLoadState == ULConst.ADV_PRELOAD_STATE_READY) {
                            this.isOpened = false;
                            this.advSkip(this.showData, { code: String(err.errCode), msg: err.errMsg });
                        }
                        else {
                            ULSdkManager.getInstance().advManager.addAdvFailCount(this.advKey);
                        }
                        this.reLoadAdv();
                        ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_user_open_video_event_id, "2"]);
                    });
                    this.preLoadAdv();
                }
                else {
                    this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                }
            }
            loadAdv() {
                if (this.mLoadType == ULConst.ADV_LOAD_TYPE_PRELOAD) {
                    this.preLoadState = ULConst.ADV_PRELOAD_STATE_LOADING;
                    this.videoAd.load();
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                }
                else {
                }
            }
            showAdv(data) {
                if (!this.videoAd) {
                    console.warn("ULAdvOppoQgVideo-showAdv:广告未初始化,直接跳过当前广告展示");
                    this.advSkip(data, { code: "", msg: "adv not init" });
                    return;
                }
                if (this.preLoadState == ULConst.ADV_PRELOAD_STATE_LOADING) {
                    console.warn("ULAdvOppoQgVideo-showAdv:广告未加载就绪,直接跳过当前广告展示");
                    this.advSkip(data, { code: "", msg: "adv is loading" });
                    return;
                }
                if (this.preLoadState == ULConst.ADV_PRELOAD_STATE_NOAD) {
                    console.warn("ULAdvOppoQgVideo-showAdv:广告未加载就绪,直接跳过当前广告展示");
                    this.advSkip(data, this.onLoadFailErr);
                    return;
                }
                this.showData = data;
                this.isOpened = true;
                if (this.mLoadType == ULConst.ADV_LOAD_TYPE_PRELOAD) {
                    this.videoAd.show();
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_user_open_video_event_id, "1"]);
                }
                else {
                    this.videoAd.offLoad();
                    this.videoAd.offClose();
                    this.videoAd.offError();
                    this.videoAd.onLoad(() => {
                        ULLog.console.log("ULAdvOppoQgVideo videoAd.onLoad");
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                        this.videoAd.show();
                        ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_user_open_video_event_id, "1"]);
                    });
                    this.videoAd.onClose((res) => {
                        ULLog.console.log("ULAdvOppoQgVideo videoAd.onClose.res:", res);
                        this.isOpened = false;
                        if (res.isEnded) {
                            ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, this.showData);
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_video_success_show_event_id]);
                        }
                        else {
                            ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleFail(this.advKey, { code: "", msg: ULConst.ADV_VIDEO_PLAY_FAIL_MSG }, this.showData);
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_user_close_video_event_id]);
                        }
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, this.showData);
                    });
                    this.videoAd.onError((err) => {
                        ULLog.console.log("ULAdvOppoQgVideo videoAd.onError", err);
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, { code: String(err.errCode), msg: err.errMsg });
                        this.isOpened = false;
                        this.advSkip(this.showData, { code: String(err.errCode), msg: err.errMsg });
                        ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [ULConfig.getConfig().s_sdk_miniplay_user_open_video_event_id, "2"]);
                    });
                    this.videoAd.load();
                }
            }
            closeAdv(data) {
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgVideo-receiveInitState:初始化失败");
                }
            }
        }

        let qg$3 = window["qg"];
        class ULAdvOppoQgBannerBox extends ULAdvObjectBase {
            constructor(arg) {
                super(arg, typeExp.banner, ULTools.format("%s%s%s", "ULAdvOppoQgBannerBox", "_", arg));
                this.className = "ULAdvOppoQgBannerBox";
                this.statisticsAdvertiser = "ULAdvOppoQgBannerBox";
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgBannerBox-onDisposeModule arg:", this.arg);
                if (this.gameBannerAd) {
                    this.gameBannerAd.destroy();
                    this.gameBannerAd = null;
                }
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgBannerBox-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
            }
            loadAdv() {
            }
            showAdv(data) {
                if (qg$3.getSystemInfoSync().platformVersionCode < 1090) {
                    ULLog.console.log('ULAdvOppoQgBannerBox-showAdv:快应用平台版本号低于1090，暂不支持互推盒子相关 API');
                    this.advSkip(data, { code: "", msg: "api unsupport" });
                    return;
                }
                let tag = data["tag"] || data["advId"] || "";
                let advSetting = ULConfig.getConfig().t_sdk_oppoqg_show_banner_box_adv_tags;
                let styleObj = advSetting[tag];
                if (!styleObj) {
                    ULLog.console.log("ULAdvOppoQgBannerBox-showAdv:当前广告位不允许展示横幅的盒子");
                    this.advSkip(data, { code: "", msg: `advId [${tag}] unsupport banner box` });
                    return;
                }
                this.showData = data;
                this.isOpened = true;
                if (this.gameBannerAd) {
                    this.gameBannerAd.destroy();
                    this.gameBannerAd = null;
                }
                let sys = qg$3.getSystemInfoSync();
                let screenWidth = sys.screenWidth;
                let screenHeight = sys.screenHeight;
                let style = {};
                if (!isNaN(Number(styleObj.left))) {
                    style["left"] = Number(styleObj.left) * screenWidth;
                }
                if (!isNaN(Number(styleObj.top))) {
                    style["top"] = Number(styleObj.top) * screenHeight;
                }
                if (!isNaN(Number(styleObj.orientation))) {
                    if (Number(styleObj.orientation) == 0) {
                        style["orientation"] = "horizontal";
                    }
                    else {
                        style["orientation"] = "vertical";
                    }
                }
                this.gameBannerAd = qg$3.createGameBannerAd({
                    adUnitId: this.arg,
                    style: style
                });
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.gameBannerAd.show().then(() => {
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, this.showData);
                }).catch((error) => {
                    ULLog.console.log("ULAdvOppoQgBannerBox-showAdv-show-catch:", error);
                    this.isOpened = false;
                    this.advSkip(this.showData, { code: String(error.errCode), msg: error.errMsg });
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, { code: String(error.errCode), msg: error.errMsg });
                });
            }
            closeAdv(data) {
                if (this.isOpened) {
                    this.gameBannerAd.hide().then(() => {
                        this.isOpened = false;
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, data);
                        ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
                    }).catch((error) => {
                        ULLog.console.log("ULAdvOppoQgBannerBox-closeAdv-hide-catch:", error);
                        ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, error.errCode + ',' + error.errMsg);
                    });
                }
                else {
                    ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "no ad show");
                }
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgBannerBox-receiveInitState:初始化失败");
                }
            }
        }

        let qg$4 = window["qg"];
        class ULAdvOppoQgPortalBox extends ULAdvObjectBase {
            constructor(arg) {
                super(arg, typeExp.inter, ULTools.format("%s%s%s", "ULAdvOppoQgPortalBox", "_", arg));
                this.className = "ULAdvOppoQgPortalBox";
                this.showPortalGameBoxTags = {};
                this.isCall = false;
                this.statisticsAdvertiser = "ULAdvOppoQgPortalBox";
                this.statisticsType = oldTypeExp.interstitial;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgPortalBox-onDisposeModule arg:", this.arg);
                if (this.gamePortalAd) {
                    this.gamePortalAd.offClose();
                    this.gamePortalAd.offLoad();
                    this.gamePortalAd.offError();
                    this.gamePortalAd.destroy();
                    this.gamePortalAd = null;
                }
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgPortalBox-initAdv");
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_JUMP_LEISURE_SUBJECT, 1, this.onCmdJumpLeisureSubject.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_COP_CHANGED, ULConst.PRIORITY_NONE, this.onCmdFromCopChange.bind(this));
                this.trimSetting();
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
            }
            onCmdFromCopChange(e) {
                this.trimSetting();
            }
            trimSetting() {
                let config = ULConfig.getConfig();
                let interTags = config.t_sdk_oppoqg_show_inter_box_adv_tags || [];
                for (let index = 0; index < interTags.length; index++) {
                    let tag = interTags[index];
                    this.showPortalGameBoxTags[tag] = true;
                }
                ULLog.console.log("ULAdvOppoQgPortalBox.init showPortalGameBoxTags:", this.showPortalGameBoxTags);
            }
            onCmdJumpLeisureSubject(e) {
                e.stopImmediatePropagation();
                ULLog.console.log("ULAdvOppoQgPortalBox.onCmdJumpLeisureSubject................");
                let data = e.data;
                let advId = "jumpLeisureSubjectAdvId";
                let userData = data.userData || "";
                let tag = "jumpLeisureSubjectTag";
                if (!this.showPortalGameBoxTags[tag]) {
                    this.showPortalGameBoxTags[tag] = true;
                }
                this.isCall = true;
                this.showPortalAd((state) => {
                    this.isCall = false;
                    if (state) {
                        ULSdkManager.getInstance().response(ULConst.CMD_JUMP_LEISURE_SUBJECT_RESULT, {
                            code: 1,
                            msg: "打开盒子广告成功",
                            userData: userData,
                        });
                    }
                    else {
                        ULSdkManager.getInstance().response(ULConst.CMD_JUMP_LEISURE_SUBJECT_RESULT, {
                            code: 0,
                            msg: "打开盒子广告失败",
                            userData: userData,
                        });
                    }
                });
            }
            loadAdv() {
            }
            showAdv(data) {
                if (this.preLoadState != ULConst.ADV_PRELOAD_STATE_READY) {
                    console.warn("ULAdvOppoQgPortalBox-showAdv:广告未加载就绪,直接跳过当前广告展示");
                    this.advSkip(data, { code: "", msg: "adv not ready" });
                    return;
                }
                let tag = data["tag"] || "";
                if (!this.showPortalGameBoxTags[tag]) {
                    ULLog.console.log("ULAdvOppoQgPortalBox-showAdv:当前广告位不允许展示盒子");
                    this.advSkip(data, { code: "", msg: `advId [${tag}] unsupport box` });
                    return;
                }
                this.showData = data;
                this.isOpened = true;
                this.showPortalAd();
            }
            showPortalAd(callback) {
                if (qg$4.getSystemInfoSync().platformVersionCode < 1076) {
                    ULLog.console.log('ULAdvOppoQgPortalBox-showAdv:快应用平台版本号低于1076，暂不支持互推盒子相关 API');
                    if (callback) {
                        callback(false);
                    }
                    else {
                        this.advSkip(this.showData, { code: "", msg: "api unsupport" });
                    }
                    return;
                }
                if (!this.gamePortalAd) {
                    this.gamePortalAd = qg$4.createGamePortalAd({
                        adUnitId: this.arg
                    });
                    if (!this.gamePortalAd) {
                        ULLog.console.log('ULAdvOppoQgPortalBox-showAdv:广告对象创建失败，请检查参数配置');
                        if (callback) {
                            callback(false);
                        }
                        else {
                            this.advSkip(this.showData, { code: "", msg: "obj create fail" });
                        }
                        return;
                    }
                    this.gamePortalAd.offLoad(() => {
                        ULLog.console.log("ULAdvOppoQgPortalBox-showAdv-offLoad");
                    });
                    this.gamePortalAd.offError(() => {
                        ULLog.console.log("ULAdvOppoQgPortalBox-showAdv-offError");
                    });
                    this.gamePortalAd.onLoad(() => {
                        ULLog.console.log("ULAdvOppoQgPortalBox-showAdv-onLoad");
                    });
                    this.gamePortalAd.onClose(() => {
                        ULLog.console.log("ULAdvOppoQgPortalBox-showAdv-onClose");
                        if (!this.isCall) {
                            this.isOpened = false;
                            ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, this.showData);
                        }
                    });
                    this.gamePortalAd.onError((err) => {
                        ULLog.console.log("ULAdvOppoQgPortalBox-showAdv-onError:", err);
                        if (!this.isCall) {
                            this.isOpened = false;
                            let errMsg = err.errCode + ',' + err.errMsg;
                            this.advSkip(this.showData, { code: String(err.errCode), msg: err.errMsg });
                        }
                    });
                }
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.gamePortalAd.load().then(() => {
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    this.gamePortalAd.show().then(() => {
                        if (callback) {
                            callback(true);
                        }
                        else {
                            ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, this.showData);
                        }
                    }).catch((error) => {
                        if (callback) {
                            callback(false);
                        }
                        else {
                            this.isOpened = false;
                            let errMsg = error.errCode + ',' + error.errMsg;
                            this.advSkip(this.showData, { code: String(error.errCode), msg: error.errMsg });
                        }
                    });
                }).catch((error) => {
                    ULLog.console.log("ULAdvOppoQgPortalBox-showAdv-load-catch:", error);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, { code: String(error.errCode), msg: error.errMsg });
                    if (callback) {
                        callback(false);
                    }
                    else {
                        this.isOpened = false;
                        let errMsg = error.errCode + ',' + error.errMsg;
                        this.advSkip(this.showData, { code: String(error.errCode), msg: error.errMsg });
                    }
                });
            }
            closeAdv(data) {
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgBannerBox-receiveInitState:初始化失败");
                }
            }
        }

        let qg$5 = window["qg"];
        class ULAdvOppoQgInter extends ULAdvObjectBase {
            constructor(arg) {
                super(arg, typeExp.inter, ULTools.format("%s%s%s", "ULAdvOppoQgInter", "_", arg));
                this.className = "ULAdvOppoQgInter";
                this.statisticsAdvertiser = ULAdvOppoQg.NORMAL_ADVERTISER;
                this.statisticsType = oldTypeExp.interstitial;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgInter-onDisposeModule arg:", this.arg);
                if (this.interstitialAd) {
                    this.interstitialAd.offLoad();
                    this.interstitialAd.offClose();
                    this.interstitialAd.offError();
                    this.interstitialAd.destroy();
                    this.interstitialAd = null;
                }
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgInter-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
            }
            loadAdv() {
            }
            showAdv(data) {
                if (this.preLoadState != ULConst.ADV_PRELOAD_STATE_READY) {
                    console.warn("ULAdvOppoQgInter-showAdv:广告未加载就绪,直接跳过当前广告展示");
                    this.advSkip(data, { code: "", msg: "adv not ready" });
                    return;
                }
                this.showData = data;
                this.isOpened = true;
                if (!this.interstitialAd) {
                    this.interstitialAd = qg$5.createInsertAd({
                        posId: this.arg
                    });
                }
                if (!this.interstitialAd) {
                    ULLog.console.log("ULAdvOppoQgInter-showAdv:广告对象创建异常，请检查参数是否正确：", this.arg);
                    this.advSkip(data, { code: "", msg: "param error" });
                    return;
                }
                this.interstitialAd.offLoad();
                this.interstitialAd.offClose();
                this.interstitialAd.offError();
                this.interstitialAd.onLoad(() => {
                    ULLog.console.log("ULAdvOppoQgInter-showAdv-onLoad");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    this.interstitialAd.show();
                });
                this.interstitialAd.onShow(() => {
                    ULLog.console.log("ULAdvOppoQgInter-showAdv-onShow");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, this.showData);
                });
                this.interstitialAd.onClose(() => {
                    ULLog.console.log("ULAdvOppoQgInter-showAdv-onClose");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, this.showData);
                });
                this.interstitialAd.onError((err) => {
                    ULLog.console.log("ULAdvOppoQgInter-showAdv-onError:", err);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, { code: String(err.errCode), msg: err.errMsg });
                    this.isOpened = false;
                    this.advSkip(this.showData, { code: String(err.errCode), msg: err.errMsg });
                });
                this.interstitialAd.load();
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
            }
            closeAdv(data) {
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgInter-receiveInitState:初始化失败");
                }
            }
        }

        let qg$6 = window["qg"];
        class ULAdvOppoQgBanner extends ULAdvObjectBase {
            constructor(arg) {
                super(arg, typeExp.banner, "ULAdvOppoQgBanner" + "_" + arg);
                this.className = "ULAdvOppoQgBanner";
                this.isCallHide = false;
                this.channelBannerStyle = {};
                this.statisticsAdvertiser = ULAdvOppoQg.NORMAL_ADVERTISER;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgBanner-onDisposeModule arg:", this.arg);
                if (this.bannerAd) {
                    this.bannerAd.offHide();
                    this.bannerAd.offLoad();
                    this.bannerAd.offError();
                    this.bannerAd.offResize();
                    this.bannerAd.destroy();
                    this.bannerAd = null;
                }
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgBanner-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                this.channelBannerStyle = ULConfig.getConfig().t_sdk_adv_banner_tags_style_setting || {};
            }
            loadAdv() {
            }
            showAdv(data) {
                let platformVersionCode = qg$6.getSystemInfoSync().platformVersionCode;
                if (platformVersionCode < 1051) {
                    console.warn("ULAdvOppoQgBanner-showAdv:原生api最低支持1051");
                    this.advSkip(data, { code: "", msg: "minPlatformVersion unsupport" });
                    return;
                }
                if (this.preLoadState != ULConst.ADV_PRELOAD_STATE_READY) {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv:广告未加载就绪，直接跳过");
                    this.advSkip(data, { code: "", msg: "adv not ready" });
                    return;
                }
                let ad_limitTime = ULConfig.getConfig().i_sdk_oppoqg_ad_ecd;
                let requestTime = ULTools.time();
                if (requestTime - ULSdkManager.getInstance().advManager.sdkInitTime < ad_limitTime / 1000) {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv:未达到启动cd限制，无法展示广告");
                    this.advSkip(data, { code: "", msg: "in start cd" });
                    return;
                }
                this.isOpened = true;
                this.showData = data;
                this.bAutoCloseBannerFlag = false;
                let tag = data["tag"] || "";
                let style = data.layout || this.channelBannerStyle[tag] || this.channelBannerStyle["*"] || {};
                let systemInfo = qg$6.getSystemInfoSync();
                let windowWidth = systemInfo.windowWidth;
                let windowHeight = systemInfo.windowHeight;
                if (!this.bannerAd) {
                    this.bannerAd = qg$6.createBannerAd({
                        adUnitId: this.arg,
                    });
                    let bannerWidth = Math.min(systemInfo.screenWidth, systemInfo.screenHeight);
                    if (style) {
                        ULLog.console.log('ULAdvOppoQgBanner-showAdv systemInfo:', JSON.stringify(systemInfo));
                        let widthScale = style.width;
                        if (widthScale != undefined && widthScale >= 0) {
                            bannerWidth = bannerWidth * widthScale;
                        }
                    }
                    this.bannerAd.style.width = bannerWidth;
                }
                if (!this.bannerAd) {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv:广告对象创建异常，请检查参数是否正确：", this.arg);
                    this.advSkip(data, { code: "", msg: "param error" });
                    return;
                }
                this.bannerAd.offLoad(() => {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv-offLoad");
                });
                this.bannerAd.offError(() => {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv-offError");
                });
                this.bannerAd.offHide();
                this.bannerAd.offResize(() => {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv-offResize");
                });
                let isPlay = false;
                this.bannerAd.onLoad(() => {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv-onLoad");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    if (!isPlay && this.isOpened) {
                        isPlay = true;
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, this.showData);
                    }
                });
                this.bannerAd.onHide(() => {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv-onHide");
                    if (!this.bAutoCloseBannerFlag) {
                        ULSdkManager.getInstance().advManager.addAdvCountLog(this.advKey, countExp.mcc);
                    }
                    this.isOpened = false;
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, this.showData);
                });
                this.bannerAd.onError((err) => {
                    ULLog.console.log("ULAdvOppoQgBanner-showAdv-onError:", err);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, { code: String(err.errCode), msg: err.errMsg });
                    if (!this.isOpened && !this.isCallHide) {
                        this.advSkip(this.showData, { code: String(err.errCode), msg: err.errMsg });
                    }
                });
                this.bannerAd.onResize(function (e) {
                    ULLog.console.log('ULAdvOppoQgBanner-showAdv-onResize： ' + JSON.stringify(e));
                    let left = (systemInfo.screenWidth - e.width) * 0.5;
                    let top = systemInfo.screenHeight - e.height + 0.1;
                    if (style) {
                        let x = style.x;
                        let y = style.y;
                        if (x != undefined && x >= 0 && x <= 1) {
                            left = (systemInfo.screenWidth - e.width) * x;
                            console.log("ULAdvOppoQgBanner.setBannerStyle bannerAd.onResize.newLeft", left);
                        }
                        if (y != undefined && y >= 0 && y <= 1) {
                            top = (1 - y) * (systemInfo.screenHeight - e.height);
                            console.log("ULAdvOppoQgBanner.setBannerStyle bannerAd.onResize.newTop", top);
                        }
                    }
                    this.bannerAd.style.left = left;
                    this.bannerAd.style.top = top;
                });
                this.isCallHide = false;
                this.bannerAd.show();
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
            }
            closeAdv(data) {
                this.isOpened = false;
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, data);
                ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
                if (this.bannerAd) {
                    if (ULConfig.getConfig().i_sdk_oppoqg_banner_mode == 1) {
                        ULLog.console.log("ULAdvOppoQgBanner.closeAdv banner.hide()");
                        this.bAutoCloseBannerFlag = true;
                        this.isCallHide = true;
                        this.bannerAd.hide();
                    }
                    else {
                        ULLog.console.log("ULAdvOppoQgBanner.closeAdv banner.destroy()");
                        this.bannerAd.destroy();
                        this.bannerAd = null;
                    }
                }
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgBanner-receiveInitState:初始化失败");
                }
            }
        }

        class ULAdvNativeAdLoadCycle {
            constructor() {
                this.onLoad = () => {
                    ULLog.console.log("ULAdvNativeAdLoadCycle default onLoad");
                };
                this.onLoadFail = (errInfo) => {
                    ULLog.console.log("ULAdvNativeAdLoadCycle default onLoadFail");
                };
            }
        }
        class ULAdvNativeAdShowCycle {
            constructor() {
                this.onShow = () => {
                    ULLog.console.log("ULAdvNativeAdShowCycle default onShow");
                };
                this.onShowFail = (errInfo) => {
                    ULLog.console.log("ULAdvNativeAdShowCycle default onShowFail");
                };
                this.onRefresh = () => {
                    ULLog.console.log("ULAdvNativeAdShowCycle default onRefresh");
                };
                this.onClose = (isUserClick = true) => {
                    ULLog.console.log("ULAdvNativeAdShowCycle default onClose isUserClick:", isUserClick);
                };
                this.onClick = () => {
                    ULLog.console.log("ULAdvNativeAdShowCycle default onClick");
                };
            }
        }
        class ULAdvNativeData {
        }

        class ULAdvSDKNativeAd {
            constructor(parma) {
                this.showData = {};
                this.loadCycle = new ULAdvNativeAdLoadCycle();
                this.showCycle = new ULAdvNativeAdShowCycle();
                this.selfShowCycle = {
                    onShow: () => {
                        if (!this.isShowing)
                            return;
                        this.showCall && this.showCall(this);
                        this.showCycle.onShow && this.showCycle.onShow();
                    },
                    onShowFail: (errInfo) => {
                        if (!this.isShowing)
                            return;
                        this.isShowing = false;
                        this.showCycle.onShowFail && this.showCycle.onShowFail(errInfo);
                    },
                    onRefresh: () => {
                        if (!this.isShowing)
                            return;
                        this.showCall && this.showCall(this);
                        this.showCycle.onRefresh && this.showCycle.onRefresh();
                    },
                    onClose: (isUserClick) => {
                        if (!this.isShowing)
                            return;
                        this.isShowing = false;
                        this.closeCall && this.closeCall(this);
                        this.showCycle.onClose && this.showCycle.onClose(isUserClick);
                        this.nativeData = null;
                    },
                    onClick: () => {
                        if (!this.isShowing)
                            return;
                        this.clickCall && this.clickCall(this);
                        this.showCycle.onClick && this.showCycle.onClick();
                    }
                };
                this.loadCall = null;
                this.clickCall = null;
                this.showCall = null;
                this.closeCall = null;
                this.destroyCall = null;
                this.arg = parma.arg;
                this.type = parma.type;
                this.loadCall = parma.load;
                this.clickCall = parma.click;
                this.showCall = parma.show;
                this.closeCall = parma.close;
                this.destroyCall = parma.destroy;
            }
            click() {
                if (!this.isShowing)
                    return;
                this.selfShowCycle.onClick && this.selfShowCycle.onClick();
                if (this.type == ULAdvNativeAdType.inter) {
                    this.close(false);
                }
            }
            show(data) {
                if (this.isShowing)
                    return;
                if (!this.loadCall || !this.showCall)
                    return;
                this.isShowing = true;
                this.loadCall(this, {
                    onLoad: (nativeData) => {
                        this.nativeData = nativeData;
                        this.loadCycle.onLoad && this.loadCycle.onLoad(nativeData);
                        this.showSDKView(data);
                    },
                    onLoadFail: (errInfo) => {
                        this.loadCycle.onLoadFail && this.loadCycle.onLoadFail(errInfo);
                        this.selfShowCycle.onShowFail(errInfo);
                    }
                });
            }
            close(isUserClick) {
                if (!this.isShowing)
                    return;
                this.closeSDKAd();
                this.selfShowCycle.onClose(isUserClick);
            }
            destroy() {
                this.isShowing = false;
                this.nativeData = null;
                this.destroyCall && this.destroyCall(this);
                this.loadCall = null;
                this.showCall = null;
                this.clickCall = null;
                this.closeCall = null;
                this.destroyCall = null;
            }
            refreshData(nativeData) {
                ULLog.console.log("ULAdvSDKNativeAd refreshData nativeData:", nativeData);
                if (this.isShowing) {
                    this.nativeData = nativeData;
                    this.showSDKView(this.showData, true);
                }
            }
            showSDKView(data, isRefreshing = false) {
                ULLog.console.log("ULAdvSDKNativeAd showSDKView nativeData:", this.nativeData);
                this.closeSDKAd();
                if (this.nativeData == null)
                    return;
                this.showData = data;
                let obj = {
                    nationData: this.nativeData,
                    onShow: isRefreshing ? this.selfShowCycle.onRefresh : this.selfShowCycle.onShow,
                    onError: (errMsg) => {
                        if (!isRefreshing) {
                            this.selfShowCycle.onShowFail({ code: "0", msg: errMsg });
                        }
                    },
                    onClick: this.selfShowCycle.onClick,
                    onClose: (isUserClick) => {
                        if (isUserClick) {
                            this.selfShowCycle.onClose(isUserClick);
                        }
                    }
                };
                switch (this.type) {
                    case ULAdvNativeAdType.banner: {
                        let style = ULAdvNativeManager.getBannerStyle(data);
                        if (style == null) {
                            obj.onError('sdk自动刷新不包含此tag');
                            return;
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showNationBanner(obj, style);
                        break;
                    }
                    case ULAdvNativeAdType.embedded: {
                        let style = ULAdvNativeManager.getEmbeddStyle(data);
                        ULSdkManager.getInstance().moduleCheckerManager.showNationEmbedded(obj, style);
                        break;
                    }
                    case ULAdvNativeAdType.inter: {
                        ULSdkManager.getInstance().moduleCheckerManager.showNationInter(obj);
                        break;
                    }
                }
            }
            closeSDKAd() {
                switch (this.type) {
                    case ULAdvNativeAdType.banner: {
                        ULSdkManager.getInstance().moduleCheckerManager.closeNationBanner();
                        break;
                    }
                    case ULAdvNativeAdType.embedded: {
                        ULSdkManager.getInstance().moduleCheckerManager.closeNationEmbedded();
                        break;
                    }
                    case ULAdvNativeAdType.inter: {
                        ULSdkManager.getInstance().moduleCheckerManager.closeNationInter();
                        break;
                    }
                }
            }
        }

        class ULAdvGameNativeAd {
            constructor(parma) {
                this.loadCycle = new ULAdvNativeAdLoadCycle();
                this.showCycle = new ULAdvNativeAdShowCycle();
                this.selfShowCycle = {
                    onShow: () => {
                        if (!this.isShowing)
                            return;
                        this.showCall && this.showCall(this);
                        this.showCycle.onShow && this.showCycle.onShow();
                    },
                    onShowFail: (errInfo) => {
                        if (!this.isShowing)
                            return;
                        this.isShowing = false;
                        this.showCycle.onShowFail && this.showCycle.onShowFail(errInfo);
                    },
                    onRefresh: () => {
                        if (!this.isShowing)
                            return;
                        this.showCall && this.showCall(this);
                        this.showCycle.onRefresh && this.showCycle.onRefresh();
                    },
                    onClose: (isUserClick) => {
                        if (!this.isShowing)
                            return;
                        this.isShowing = false;
                        this.closeCall && this.closeCall(this);
                        this.showCycle.onClose && this.showCycle.onClose(isUserClick);
                        this.nativeData = null;
                    },
                    onClick: () => {
                        if (!this.isShowing)
                            return;
                        this.clickCall && this.clickCall(this);
                        this.showCycle.onClick && this.showCycle.onClick();
                    }
                };
                this.loadCall = null;
                this.clickCall = null;
                this.showCall = null;
                this.closeCall = null;
                this.destroyCall = null;
                this.arg = parma.arg;
                this.type = parma.type;
                this.loadCall = parma.load;
                this.clickCall = parma.click;
                this.showCall = parma.show;
                this.closeCall = parma.close;
                this.destroyCall = parma.destroy;
            }
            click() {
                if (!this.isShowing)
                    return;
                this.selfShowCycle.onClick && this.selfShowCycle.onClick();
            }
            show(data) {
                if (this.isShowing)
                    return;
                if (!this.loadCall || !this.showCall)
                    return;
                this.isShowing = true;
                this.loadCall(this, {
                    onLoad: (nativeData) => {
                        this.nativeData = nativeData;
                        this.loadCycle.onLoad && this.loadCycle.onLoad(nativeData);
                        this.showGameView(data);
                    },
                    onLoadFail: (errInfo) => {
                        this.loadCycle.onLoadFail && this.loadCycle.onLoadFail(errInfo);
                        this.selfShowCycle.onShowFail(errInfo);
                    }
                });
            }
            close(isUserClick) {
                if (!this.isShowing)
                    return;
                this.selfShowCycle.onClose(isUserClick);
            }
            destroy() {
                this.isShowing = false;
                this.destroyCall && this.destroyCall(this);
                this.nativeData = null;
                this.loadCall = null;
                this.showCall = null;
                this.clickCall = null;
                this.closeCall = null;
                this.destroyCall = null;
            }
            showGameView(data) {
                if (!this.isShowing)
                    return;
                let advType = this.type.toString();
                ULSdkManager.getInstance().advManager.responseOpenNativeAdvResult(data, advType, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_NATIVE_RESULT_MSG_SUCCESS, this.nativeData);
                this.selfShowCycle.onShow();
            }
        }

        var ULAdvNativeAdType;
        (function (ULAdvNativeAdType) {
            ULAdvNativeAdType["banner"] = "banner";
            ULAdvNativeAdType["inter"] = "inter";
            ULAdvNativeAdType["embedded"] = "embed";
        })(ULAdvNativeAdType || (ULAdvNativeAdType = {}));
        var ULAdvNativeAdShowType;
        (function (ULAdvNativeAdShowType) {
            ULAdvNativeAdShowType[ULAdvNativeAdShowType["game"] = 0] = "game";
            ULAdvNativeAdShowType[ULAdvNativeAdShowType["sdk"] = 1] = "sdk";
        })(ULAdvNativeAdShowType || (ULAdvNativeAdShowType = {}));
        class ULNativeItem {
            constructor(param) {
                this.showGameAdArray = [];
                this.showSdkAdArray = [];
                this.loadCycleList = [];
                this.lastExposureTime = 0;
                this.channelLoadCycle = new ULAdvNativeAdLoadCycle();
                this.arg = param.arg;
                this.channelAd = param.channelAd;
                this.hadClick = false;
                this.hadshown = false;
                this.isLoading = false;
                this.inUseNativeData = null;
                this.errInfo = null;
                this.remainRequestTime = 0;
                this.remainShowTime = this.adIntervals;
                this.remainShowNumber = this.allowShowNum;
                this.channelAd.init(this.arg);
            }
            get isShowing() {
                return this.showGameAdArray.length + this.showSdkAdArray.length > 0;
            }
            get adIntervals() {
                let config = ULConfig.getConfig();
                let refresh_intervals = config.i_sdk_native_autoRefresh_intervals || 30;
                let nation_autoRefresh_intervals = Number(refresh_intervals) || 30;
                return nation_autoRefresh_intervals;
            }
            get allowShowNum() {
                let config = ULConfig.getConfig();
                let allowShowNum = config.i_sdk_native_valid_show_count || 0;
                let trimAllowShowNum = Number(allowShowNum) || 2;
                return trimAllowShowNum;
            }
            get requestCD() {
                let config = ULConfig.getConfig();
                let nativeCD = config.i_sdk_adv_native_life_time || 0;
                let trimNativeCD = Number(nativeCD) / 1000 || 0;
                return Math.max(trimNativeCD, 15);
            }
            get exposureCd() {
                let config = ULConfig.getConfig();
                let exposureCd = config.i_sdk_adv_native_exposure_cd || 0;
                let trimExposureCd = Number(exposureCd) / 1000 || 0;
                return trimExposureCd;
            }
            get allowLoad() {
                if (this.showGameAdArray.length > 0)
                    return false;
                if (this.remainRequestTime == 0) {
                    if (this.hadClick)
                        return true;
                    if (this.inUseNativeData == null)
                        return true;
                    if (this.hadshown && this.remainShowTime == 0)
                        return true;
                    if (this.hadshown && this.remainShowNumber == 0) {
                        let isAutoRefresh = ULAdvNativeManager.isAutoRefresh;
                        if (!this.isShowing && isAutoRefresh)
                            return true;
                        if (this.isShowing && !isAutoRefresh)
                            return true;
                    }
                }
                return false;
            }
            performSecond() {
                this.remainRequestTime = Math.max(--this.remainRequestTime, 0);
                if (this.isShowing)
                    this.remainShowTime = Math.max(--this.remainShowTime, 0);
                ULLog.console.log(`ULNativeItem allowLoad:${this.allowLoad},isShowing:${this.isShowing},rmRequestTime:${this.remainRequestTime},rmShowTime:${this.remainShowTime},rmShowNumber:${this.remainShowNumber}`);
            }
            refreshLoad() {
                this.loadChannelData({
                    onLoad: (nativeData) => {
                        ULLog.console.log(`ULNativeItem refreshLoad onLoad:${nativeData}`);
                        this.showSdkAdArray.forEach(nativeAd => {
                            if (nativeAd instanceof ULAdvSDKNativeAd) {
                                nativeAd.refreshData(nativeData);
                            }
                        });
                    },
                    onLoadFail: (errInfo) => {
                        ULLog.console.log(`ULNativeItem refreshLoad onLoadFail:${errInfo}`);
                        this.showSdkAdArray.forEach(nativeAd => {
                            if (nativeAd instanceof ULAdvSDKNativeAd) {
                                nativeAd.refreshData(null);
                            }
                        });
                    },
                });
            }
            load(cycle) {
                if (this.allowLoad || this.isLoading) {
                    this.loadChannelData(cycle);
                }
                else if (this.inUseNativeData != null) {
                    cycle.onLoad && cycle.onLoad(this.inUseNativeData);
                }
                else {
                    cycle.onLoadFail && cycle.onLoadFail(this.errInfo || { code: "0", msg: this.isLoading ? "正在加载中" : "未知错误" });
                }
            }
            loadChannelData(cycle) {
                this.loadCycleList.push(cycle);
                if (this.isLoading)
                    return;
                this.isLoading = true;
                this.remainRequestTime = this.requestCD;
                let timerId = setTimeout(() => {
                    this.channelLoadCycle.onLoadFail({ code: "0", msg: "加载超时" });
                }, 20000);
                let baseLoadCycle = new ULAdvNativeAdLoadCycle();
                this.channelLoadCycle.onLoad = (nativeData) => {
                    ULLog.console.log(`ULNativeItem onLoad nativeData:${nativeData}`);
                    this.channelLoadCycle.onLoad = baseLoadCycle.onLoad;
                    this.channelLoadCycle.onLoadFail = baseLoadCycle.onLoadFail;
                    clearTimeout(timerId);
                    this.isLoading = false;
                    this.errInfo = null;
                    this.inUseNativeData = nativeData;
                    this.hadshown = false;
                    this.hadClick = false;
                    this.remainRequestTime = this.requestCD;
                    this.remainShowTime = this.adIntervals;
                    this.remainShowNumber = this.allowShowNum;
                    while (this.loadCycleList.length) {
                        let cycleItem = this.loadCycleList.shift();
                        cycleItem.onLoad && cycleItem.onLoad(nativeData);
                    }
                };
                this.channelLoadCycle.onLoadFail = (errInfo) => {
                    ULLog.console.log("ULNativeItem channelLoadCycle onLoadFail:" + errInfo);
                    this.channelLoadCycle.onLoad = baseLoadCycle.onLoad;
                    this.channelLoadCycle.onLoadFail = baseLoadCycle.onLoadFail;
                    clearTimeout(timerId);
                    this.isLoading = false;
                    this.errInfo = errInfo;
                    this.inUseNativeData = null;
                    while (this.loadCycleList.length) {
                        let cycleItem = this.loadCycleList.shift();
                        cycleItem.onLoadFail && cycleItem.onLoadFail(errInfo);
                    }
                };
                this.channelAd.load(this.channelLoadCycle);
            }
            show(nativeAd, showType) {
                ULLog.console.log("ULNativeItem show");
                if (showType == ULAdvNativeAdShowType.game) {
                    let index = this.showGameAdArray.indexOf(nativeAd);
                    if (index == -1) {
                        this.showGameAdArray.push(nativeAd);
                    }
                }
                else if (showType == ULAdvNativeAdShowType.sdk) {
                    let index = this.showSdkAdArray.indexOf(nativeAd);
                    if (index == -1) {
                        this.showSdkAdArray.push(nativeAd);
                    }
                }
                this.remainShowNumber = Math.max(--this.remainShowNumber, 0);
                if (!this.hadshown || ULTools.time() - this.lastExposureTime > this.exposureCd) {
                    this.channelAd.show();
                    this.lastExposureTime = ULTools.time();
                }
                this.hadshown = true;
            }
            click() {
                this.channelAd.click();
                this.hadClick = true;
                this.remainRequestTime = 0;
            }
            close(nativeAd, showType) {
                ULLog.console.log(`ULNativeItem close `);
                if (showType == ULAdvNativeAdShowType.game) {
                    let index = this.showGameAdArray.indexOf(nativeAd);
                    if (index > -1) {
                        this.showGameAdArray.splice(index, 1);
                    }
                }
                else if (showType == ULAdvNativeAdShowType.sdk) {
                    let index = this.showSdkAdArray.indexOf(nativeAd);
                    if (index > -1) {
                        this.showSdkAdArray.splice(index, 1);
                    }
                }
            }
            destroy() {
            }
        }
        class ULAdvNativeManager {
            constructor() {
                this.timerId = null;
                this.nativeItemCache = {};
                this.showBannerAutoRefreshTags = null;
                let self = this;
                this.timerId = setInterval(function () {
                    for (let key in self.nativeItemCache) {
                        let nativeItem = self.nativeItemCache[key];
                        self.showOneSecond(nativeItem);
                    }
                }, 1000);
            }
            static getInstance() {
                if (!this.instance) {
                    this.instance = new ULAdvNativeManager();
                }
                return this.instance;
            }
            get isAutoRefresh() {
                let config = ULConfig.getConfig();
                return config.i_sdk_native_autoRefresh_mode == 1;
            }
            static get isAutoRefresh() {
                return ULAdvNativeManager.getInstance().isAutoRefresh;
            }
            get channelBannerStyle() {
                if (this.showBannerAutoRefreshTags == null) {
                    let config = ULConfig.getConfig();
                    this.showBannerAutoRefreshTags = {};
                    let banner_autoRefresh_tags = config.t_sdk_show_native_banner_autoRefresh_tags || [];
                    let banner_autoRefresh_tags_style_setting = config.t_sdk_show_native_banner_autoRefresh_tags_style_setting || {};
                    for (let index = 0; index < banner_autoRefresh_tags.length; index++) {
                        let tag = banner_autoRefresh_tags[index];
                        let style = banner_autoRefresh_tags_style_setting[tag] || banner_autoRefresh_tags_style_setting["*"] || {};
                        this.showBannerAutoRefreshTags[tag] = style;
                    }
                }
                return this.showBannerAutoRefreshTags;
            }
            showOneSecond(nativeItem) {
                nativeItem.performSecond();
                if (!this.isAutoRefresh)
                    return;
                if (nativeItem.allowLoad)
                    nativeItem.refreshLoad();
            }
            static createNativeAd(channelAd, parma) {
                return ULAdvNativeManager.getInstance().createNativeAd(channelAd, parma);
            }
            static isShowing(arg) {
                if (this.instance.nativeItemCache[arg]) {
                    return this.instance.nativeItemCache[arg].isShowing;
                }
                return false;
            }
            createNativeAd(channelAd, parma) {
                let nativeAd = null;
                if (!this.nativeItemCache[parma.arg]) {
                    this.nativeItemCache[parma.arg] = new ULNativeItem({
                        arg: parma.arg,
                        channelAd: new channelAd()
                    });
                }
                let item = this.nativeItemCache[parma.arg];
                let trimParma = {
                    arg: parma.arg,
                    type: parma.type,
                    load: (nativeAd, loadCycle) => {
                        item.load(loadCycle);
                    },
                    click: (nativeAd) => {
                        item.click();
                    },
                    show: (nativeAd) => {
                        item.show(nativeAd, parma.showType);
                    },
                    close: (nativeAd) => {
                        item.close(nativeAd, parma.showType);
                    },
                    destroy: (nativeAd) => {
                        item.destroy();
                        delete this.nativeItemCache[item.arg];
                    }
                };
                if (parma.showType == ULAdvNativeAdShowType.game) {
                    ULLog.console.log("ULAdvNativeManager-createNativeAd-ULAdvGameNativeAd");
                    nativeAd = new ULAdvGameNativeAd(trimParma);
                }
                else {
                    ULLog.console.log("ULAdvNativeManager-createNativeAd-ULAdvSDKNativeAd");
                    nativeAd = new ULAdvSDKNativeAd(trimParma);
                }
                return nativeAd;
            }
            static getBannerStyle(data) {
                let advId = data["advId"];
                let tag = data["tag"] || advId || "";
                let channelBannerStyle = ULAdvNativeManager.instance.channelBannerStyle;
                ULLog.console.log("ULAdvNativeManager data.layout:", data.layout);
                ULLog.console.log(`ULAdvNativeManager this.channelBannerStyle[${tag}]:`, channelBannerStyle[tag]);
                let style = data.layout || channelBannerStyle[tag] || null;
                if (style == null || style == undefined) {
                    return null;
                }
                let trimStyle = {
                    x: !isNaN(Number(style.x)) ? Number(style.x) : 0.5,
                    y: !isNaN(Number(style.y)) ? Number(style.y) : 0,
                    width: !isNaN(Number(style.width)) ? Number(style.width) : 1,
                    height: !isNaN(Number(style.height)) ? Number(style.height) : 1,
                };
                return trimStyle;
            }
            static getEmbeddStyle(data) {
                let style = data.layout || {};
                let trimStyle = {
                    x: !isNaN(Number(style.x)) ? Number(style.x) : 0.5,
                    y: !isNaN(Number(style.y)) ? Number(style.y) : 0.5,
                    width: !isNaN(Number(style.width)) ? Number(style.width) : 0.4,
                    height: !isNaN(Number(style.height)) ? Number(style.height) : 0.2,
                };
                ULLog.console.log("ULAdvNativeManager data.layout:", data.layout);
                ULLog.console.log("ULAdvNativeManager data.trimStyle:", trimStyle);
                return trimStyle;
            }
        }
        ULAdvNativeManager.isPreLoad = true;

        let qg$7 = window["qg"];
        class ULAdvOppoQgNativeItem {
            set inUseData(inUseData) {
                if (this._inUseData == inUseData) {
                    return;
                }
                this._inUseData = inUseData;
            }
            get inUseData() {
                return this._inUseData;
            }
            init(arg) {
                this.arg = arg;
            }
            load(cycle) {
                let platformVersionCode = qg$7.getSystemInfoSync().platformVersionCode;
                if (platformVersionCode < 1051) {
                    ULLog.console.warn("ULAdvOppoQgNativeItem.load:原生api最低支持1051");
                    cycle.onLoadFail && cycle.onLoadFail({ code: "", msg: "minPlatformVersion unsupport" });
                    return;
                }
                if (this.nativeAd) {
                    this.nativeAd.destroy();
                    this.nativeAd = null;
                }
                this.nativeAd = qg$7.createNativeAd({
                    adUnitId: this.arg
                });
                this.nativeAd.onLoad((res) => {
                    ULLog.console.log('ULAdvOppoQgNativeItem-onLoad:', res);
                    if (res && res.adList) {
                        let adData = res.adList.pop();
                        this.inUseData = adData;
                        let respone = {
                            title: adData.title || "",
                            desc: adData.desc || "",
                            icon: adData.icon || "",
                            url: adData.imgUrlList[0] || adData.iconUrlList[0] || "",
                            targetTitle: adData.clickBtnTxt || "点击查看",
                            adSource: adData.adSource || "",
                        };
                        cycle.onLoad && cycle.onLoad(respone);
                    }
                    else {
                        cycle.onLoadFail && cycle.onLoadFail({ code: "", msg: "no ad" });
                    }
                });
                this.nativeAd.onError((err) => {
                    ULLog.console.log('ULAdvOppoQgNativeItem-onError err:', err);
                    let errInfo = {
                        code: String(err.errCode),
                        msg: err.errMsg
                    };
                    cycle.onLoadFail && cycle.onLoadFail(errInfo);
                });
                this.nativeAd.load();
            }
            click() {
                ULLog.console.log('ULAdvOppoQgNativeItem-click');
                if (this.nativeAd) {
                    this.nativeAd.reportAdClick({
                        adId: this.inUseData.adId
                    });
                }
            }
            show() {
                ULLog.console.log('ULAdvOppoQgNativeItem-show');
                if (this.nativeAd) {
                    this.nativeAd.reportAdShow({
                        adId: this.inUseData.adId
                    });
                }
            }
        }

        let qg$8 = window["qg"];
        class ULAdvOppoQgNativeBase extends ULAdvNativeObjectBase {
            constructor(arg, advType, templateItemName) {
                super(arg, advType, templateItemName);
                this.className = "ULAdvOppoQgNativeBase";
                this.statisticsAdvertiser = ULAdvOppoQg.NATIVE_ADVERTISER;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgNativeBase-onDisposeModule arg:", this.arg);
            }
            closeNativeAdv(e) {
                let data = e.data;
                let advId = data.advId;
                if (!this.showData || !this.showData.advId || this.showData.advId != advId) {
                    return;
                }
                ULLog.console.log("ULAdvOppoQgNativeBase-closeNativeAdv");
                this.nativeAd.close(data.closeType == 1);
                ULSdkManager.getInstance().advManager.responseCloseNativeAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
            }
            clickNativeAdv(e) {
                let data = e.data;
                let advId = data.advId;
                if (!this.showData || !this.showData.advId || this.showData.advId != advId) {
                    return;
                }
                ULLog.console.log("ULAdvOppoQgNativeBase-clickNativeAdv");
                this.nativeAd.click();
                this.nativeAd.close(false);
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgNativeBase-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                let type = this.advType == "banner" ? ULAdvNativeAdType.banner : ULAdvNativeAdType.inter;
                ULLog.console.log("ULAdvOppoQgNativeBase-initAdv:", type);
                this.nativeAd = ULAdvNativeManager.createNativeAd(ULAdvOppoQgNativeItem, {
                    arg: this.arg,
                    type: type,
                    showType: ULAdvNativeAdShowType.game
                });
            }
            loadAdv() {
            }
            showAdv(showData) {
                ULLog.console.log("ULAdvOppoQgNativeBase-showAdv:");
                let ad_limitTime = ULConfig.getConfig().i_sdk_oppoqg_ad_ecd;
                let requestTime = ULTools.time();
                if (requestTime - ULSdkManager.getInstance().advManager.sdkInitTime < ad_limitTime / 1000) {
                    ULLog.console.log("ULAdvOppoQgNativeBase.onShowNativeAdv:未达到启动cd限制，无法展示广告");
                    this.advSkip(showData, { code: "", msg: "in start cd" });
                    return;
                }
                if (this.preLoadState != ULConst.ADV_PRELOAD_STATE_READY) {
                    console.warn("ULAdvOppoQgNativeBase-showAdv:广告未加载就绪,直接跳过当前广告展示");
                    this.advSkip(showData, { code: "", msg: "adv not ready" });
                    return;
                }
                this.showData = showData;
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.nativeAd.showCycle.onShowFail = ((errInfo) => {
                    ULLog.console.log("ULAdvOppoQgNativeBase-showAdv-onError:", errInfo);
                    if (this.isOpened) {
                        this.isOpened = false;
                        this.advSkip(this.showData, errInfo);
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, errInfo);
                    }
                });
                this.nativeAd.showCycle.onShow = (() => {
                    ULLog.console.log("ULAdvOppoQgNativeBase-showAdv-onShow");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, showData, this.nativeAd.nativeData);
                });
                this.nativeAd.showCycle.onClick = (() => {
                    ULLog.console.log("ULAdvOppoQgNativeBase-showAdv-onClick");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClick(this.advKey, "点击", showData, { title: this.nativeAd.nativeData ? this.nativeAd.nativeData.title : "" });
                });
                this.nativeAd.showCycle.onClose = ((isUserClick) => {
                    ULLog.console.log("ULAdvOppoQgNativeBase-showAdv-onClose");
                    this.isOpened = false;
                    this.nativeShowState = false;
                    if (isUserClick == true) {
                        ULSdkManager.getInstance().advManager.addAdvCountLog(this.advKey, countExp.mcc);
                    }
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, showData, { title: this.nativeAd.nativeData ? this.nativeAd.nativeData.title : "" });
                });
                this.isOpened = true;
                this.nativeShowState = true;
                this.nativeAd.show(showData);
            }
            closeAdv(data) {
                ULLog.console.log("ULAdvOppoQgNativeBase-closeAdv");
                this.nativeAd.close(data.closeType == 1);
                ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgNativeBase-receiveInitState:初始化失败");
                }
            }
        }

        class ULAdvOppoQgNativeBanner extends ULAdvOppoQgNativeBase {
            constructor(arg) {
                super(arg, typeExp.banner, "ULAdvOppoQgNativeBanner_" + arg);
            }
        }

        class ULAdvOppoQgNativeInter extends ULAdvOppoQgNativeBase {
            constructor(arg) {
                super(arg, typeExp.inter, "ULAdvOppoQgNativeInter_" + arg);
                this.statisticsType = oldTypeExp.interstitial;
            }
        }

        class ULAdvOppoQgNativeEmbed extends ULAdvOppoQgNativeBase {
            constructor(arg) {
                super(arg, typeExp.embed, "ULAdvOppoQgNativeEmbed_" + arg);
                this.statisticsType = oldTypeExp.embedded;
            }
        }

        let qg$9 = window["qg"];
        class ULAdvOppoQgAutoNativeBanner extends ULAdvNativeObjectBase {
            constructor(arg) {
                super(arg, typeExp.banner, "ULAdvOppoQgAutoNativeBanner" + "_" + arg);
                this.className = "ULAdvOppoQgAutoNativeBanner";
                this.statisticsAdvertiser = ULAdvOppoQg.NATIVE_ADVERTISER;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgAutoNativeBanner-onDisposeModule arg:", this.arg);
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgAutoNativeBanner-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                this.nativeAd = ULAdvNativeManager.createNativeAd(ULAdvOppoQgNativeItem, {
                    arg: this.arg,
                    type: ULAdvNativeAdType.banner,
                    showType: ULAdvNativeAdShowType.sdk
                });
            }
            loadAdv() {
            }
            showAdv(data) {
                ULLog.console.log("ULAdvOppoQgAutoNativeBanner-showAdv");
                if (this.preLoadState != ULConst.ADV_PRELOAD_STATE_READY) {
                    ULLog.console.log("ULAdvOppoQgAutoNativeBanner-showAdv:广告未加载就绪，直接跳过");
                    this.advSkip(data, { code: "", msg: "adv not ready" });
                    return;
                }
                let ad_limitTime = ULConfig.getConfig().i_sdk_oppoqg_ad_ecd;
                let requestTime = ULTools.time();
                if (requestTime - ULSdkManager.getInstance().advManager.sdkInitTime < ad_limitTime / 1000) {
                    ULLog.console.log("ULAdvOppoQgAutoNativeBanner-showAdv:未达到启动cd限制，无法展示广告");
                    this.advSkip(data, { code: "", msg: "in start cd" });
                    return;
                }
                this.showData = data;
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.nativeAd.showCycle.onShowFail = ((errInfo) => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeBanner-showAdv-onError:", errInfo);
                    if (this.isOpened) {
                        this.isOpened = false;
                        this.advSkip(this.showData, errInfo);
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, errInfo);
                    }
                });
                this.nativeAd.showCycle.onShow = (() => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeBanner-showAdv-onShow");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, data, this.nativeAd.nativeData);
                });
                this.nativeAd.showCycle.onClick = (() => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeBanner-showAdv-onClick");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClick(this.advKey, "点击", data, { title: this.nativeAd.nativeData ? this.nativeAd.nativeData.title : "" });
                });
                this.nativeAd.showCycle.onClose = ((isUserClick) => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeBanner-showAdv-onClose");
                    this.isOpened = false;
                    this.nativeShowState = false;
                    if (isUserClick == true) {
                        ULSdkManager.getInstance().advManager.addAdvCountLog(this.advKey, countExp.mcc);
                    }
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, data, { title: this.nativeAd.nativeData ? this.nativeAd.nativeData.title : "" });
                });
                this.isOpened = true;
                this.nativeShowState = true;
                this.nativeAd.show(data);
            }
            closeAdv(data) {
                ULLog.console.log("ULAdvOppoQgAutoNativeBanner-closeAdv");
                this.nativeAd.close(false);
                ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
            }
            closeNativeAdv(e) {
                ULLog.console.log("ULAdvOppoQgAutoNativeBanner-closeNativeAdv");
            }
            clickNativeAdv(e) {
                ULLog.console.log("ULAdvOppoQgAutoNativeBanner-clickNativeAdv");
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgAutoNativeBanner-receiveInitState:初始化失败");
                }
            }
        }

        let qg$a = window["qg"];
        class ULAdvOppoQgAutoNativeInter extends ULAdvNativeObjectBase {
            constructor(arg) {
                super(arg, typeExp.inter, "ULAdvOppoQgAutoNativeInter" + "_" + arg);
                this.className = "ULAdvOppoQgAutoNativeInter";
                this.statisticsAdvertiser = ULAdvOppoQg.NATIVE_ADVERTISER;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgAutoNativeInter-onDisposeModule arg:", this.arg);
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgAutoNativeInter-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                this.nativeAd = ULAdvNativeManager.createNativeAd(ULAdvOppoQgNativeItem, {
                    arg: this.arg,
                    type: ULAdvNativeAdType.inter,
                    showType: ULAdvNativeAdShowType.sdk
                });
            }
            loadAdv() {
            }
            showAdv(data) {
                console.warn("ULAdvOppoQgAutoNativeInter-showAdv");
                if (this.preLoadState != ULConst.ADV_PRELOAD_STATE_READY) {
                    ULLog.console.log("ULAdvOppoQgAutoNativeInter-showAdv:广告未加载就绪，直接跳过");
                    this.advSkip(data, { code: "", msg: "adv not ready" });
                    return;
                }
                let ad_limitTime = ULConfig.getConfig().i_sdk_oppoqg_ad_ecd;
                let requestTime = ULTools.time();
                if (requestTime - ULSdkManager.getInstance().advManager.sdkInitTime < ad_limitTime / 1000) {
                    ULLog.console.log("ULAdvOppoQgAutoNativeInter-showAdv:未达到启动cd限制，无法展示广告");
                    this.advSkip(data, { code: "", msg: "in start cd" });
                    return;
                }
                this.showData = data;
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.nativeAd.showCycle.onShowFail = ((errInfo) => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeInter-showAdv-onError:", errInfo);
                    if (this.isOpened) {
                        this.isOpened = false;
                        this.advSkip(this.showData, errInfo);
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, errInfo);
                    }
                });
                this.nativeAd.showCycle.onShow = (() => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeInter-showAdv-onShow");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, data, this.nativeAd.nativeData);
                });
                this.nativeAd.showCycle.onClick = (() => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeInter-showAdv-onClick");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClick(this.advKey, "点击", data, { title: this.nativeAd.nativeData ? this.nativeAd.nativeData.title : "" });
                });
                this.nativeAd.showCycle.onClose = ((isUserClick) => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeInter-showAdv-onClose isUserClick：", isUserClick);
                    if (isUserClick == true) {
                        ULSdkManager.getInstance().advManager.addAdvCountLog(this.advKey, countExp.mcc);
                    }
                    this.isOpened = false;
                    this.nativeShowState = false;
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, data);
                });
                this.isOpened = true;
                this.nativeShowState = true;
                this.nativeAd.show(data);
            }
            closeAdv(data) {
                ULLog.console.log("ULAdvOppoQgAutoNativeInter-closeAdv");
                this.nativeAd.close(false);
                ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
            }
            closeNativeAdv(e) {
                ULLog.console.log("ULAdvOppoQgAutoNativeInter-closeNativeAdv");
            }
            clickNativeAdv(e) {
                ULLog.console.log("ULAdvOppoQgAutoNativeInter-clickNativeAdv");
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgAutoNativeInter-receiveInitState:初始化失败");
                }
            }
        }

        let qg$b = window["qg"];
        class ULAdvOppoQgAutoNativeEmbed extends ULAdvNativeObjectBase {
            constructor(arg) {
                super(arg, typeExp.embed, "ULAdvOppoQgAutoNativeEmbed" + "_" + arg);
                this.className = "ULAdvOppoQgAutoNativeEmbed";
                this.statisticsAdvertiser = ULAdvOppoQg.NATIVE_ADVERTISER;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-onDisposeModule arg:", this.arg);
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                this.nativeAd = ULAdvNativeManager.createNativeAd(ULAdvOppoQgNativeItem, {
                    arg: this.arg,
                    type: ULAdvNativeAdType.embedded,
                    showType: ULAdvNativeAdShowType.sdk
                });
            }
            loadAdv() {
            }
            showAdv(data) {
                console.warn("ULAdvOppoQgAutoNativeEmbed-showAdv");
                if (this.preLoadState != ULConst.ADV_PRELOAD_STATE_READY) {
                    ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-showAdv:广告未加载就绪，直接跳过");
                    this.advSkip(data, { code: "", msg: "adv not ready" });
                    return;
                }
                let ad_limitTime = ULConfig.getConfig().i_sdk_oppoqg_ad_ecd;
                let requestTime = ULTools.time();
                if (requestTime - ULSdkManager.getInstance().advManager.sdkInitTime < ad_limitTime / 1000) {
                    ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-showAdv:未达到启动cd限制，无法展示广告");
                    this.advSkip(data, { code: "", msg: "in start cd" });
                    return;
                }
                this.showData = data;
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.nativeAd.showCycle.onShowFail = ((errInfo) => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-showAdv-onError:", errInfo);
                    if (this.isOpened) {
                        this.isOpened = false;
                        this.advSkip(this.showData, errInfo);
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, errInfo);
                    }
                });
                this.nativeAd.showCycle.onShow = (() => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-showAdv-onShow");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, data, this.nativeAd.nativeData);
                });
                this.nativeAd.showCycle.onClick = (() => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-showAdv-onClick");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClick(this.advKey, "点击", data, { title: this.nativeAd.nativeData ? this.nativeAd.nativeData.title : "" });
                });
                this.nativeAd.showCycle.onClose = ((isUserClick) => {
                    ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-showAdv-onClose isUserClick：", isUserClick);
                    if (isUserClick == true) {
                        ULSdkManager.getInstance().advManager.addAdvCountLog(this.advKey, countExp.mcc);
                    }
                    this.isOpened = false;
                    this.nativeShowState = false;
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, data);
                });
                this.isOpened = true;
                this.nativeShowState = true;
                this.nativeAd.show(data);
            }
            closeAdv(data) {
                ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-closeAdv");
                this.nativeAd.close(false);
                ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
            }
            closeNativeAdv(e) {
                ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-closeNativeAdv");
            }
            clickNativeAdv(e) {
                ULLog.console.log("ULAdvOppoQgAutoNativeEmbed-clickNativeAdv");
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgAutoNativeEmbed-receiveInitState:初始化失败");
                }
            }
        }

        class ULAdvCustomAdStyle {
            constructor() {
                this.x = 0.5;
                this.y = 0;
                this.width = 1;
                this.height = 1;
            }
        }
        class ULAdvCustomAdLoadCycle {
            constructor() {
                this.onLoad = () => {
                    ULLog.console.log("ULAdvCustomAdLoadCycle default onLoad");
                };
                this.onLoadFail = (errInfo) => {
                    ULLog.console.log("ULAdvCustomAdLoadCycle default onLoadFail");
                };
            }
        }
        class ULAdvCustomAdShowCycle {
            constructor() {
                this.onShow = () => {
                    ULLog.console.log("ULAdvCustomAdShowCycle default onShow");
                };
                this.onShowFail = (errInfo) => {
                    ULLog.console.log("ULAdvCustomAdShowCycle default onShowFail");
                };
                this.onRefresh = () => {
                    ULLog.console.log("ULAdvCustomAdShowCycle default onRefresh");
                };
                this.onClose = (isUserClick = true) => {
                    ULLog.console.log("ULAdvCustomAdShowCycle default onClose isUserClick:", isUserClick);
                };
                this.onClick = () => {
                    ULLog.console.log("ULAdvCustomAdShowCycle default onClick");
                };
            }
        }

        class ULAdvCustomNormalAd {
            constructor(parma) {
                this.showCycle = new ULAdvCustomAdShowCycle();
                this.showCall = null;
                this.closeCall = null;
                this.destroyCall = null;
                this.arg = parma.arg;
                this.showCall = parma.show;
                this.closeCall = parma.close;
                this.destroyCall = parma.destroy;
            }
            show(data) {
                if (this.isShowing)
                    return;
                if (!this.showCall)
                    return;
                this.isShowing = true;
                this.showCall(data, {
                    onShow: () => {
                        this.showCycle.onShow && this.showCycle.onShow();
                    },
                    onShowFail: (errInfo) => {
                        this.isShowing = false;
                        this.showCycle.onShowFail && this.showCycle.onShowFail(errInfo);
                    },
                    onRefresh: () => {
                        this.showCycle.onRefresh && this.showCycle.onRefresh();
                    },
                    onClose: (isUserClick) => {
                        this.isShowing = false;
                        this.showCycle.onClose && this.showCycle.onClose(isUserClick);
                    },
                    onClick: () => {
                        this.showCycle.onClick && this.showCycle.onClick();
                    }
                });
            }
            close() {
                if (!this.isShowing)
                    return;
                this.closeCall && this.closeCall();
            }
            destroy() {
                this.destroyCall && this.destroyCall();
                this.showCall = null;
                this.closeCall = null;
                this.destroyCall = null;
            }
        }

        class ULAdvCustomManager {
            constructor() {
                this.timerId = null;
                this.customItemCache = {};
                let self = this;
                this.timerId = setInterval(function () {
                    for (let key in self.customItemCache) {
                        let customItem = self.customItemCache[key];
                        self.showOneSecond(customItem);
                    }
                }, 1000);
            }
            get isAutoRefresh() {
                let config = ULConfig.getConfig();
                return !!config.i_sdk_custom_autoRefresh_mode;
            }
            get channelCustomStyle() {
                let config = ULConfig.getConfig();
                return config.t_sdk_adv_custom_args_style_setting || {};
            }
            static get isAutoRefresh() {
                return ULAdvCustomManager.getInstance().isAutoRefresh;
            }
            static getInstance() {
                if (!this.instance) {
                    this.instance = new ULAdvCustomManager();
                }
                return this.instance;
            }
            showOneSecond(customItem) {
                customItem.performSecond();
                if (!this.isAutoRefresh)
                    return;
                if (customItem.allowLoad) {
                    customItem.refresh();
                }
            }
            static createCustomAd(channelAd, parma, allowRefreshShowing = true) {
                return ULAdvCustomManager.getInstance().createCustomAd(channelAd, parma, allowRefreshShowing);
            }
            createCustomAd(channelAd, parma, allowRefreshShowing = true) {
                let customAd = null;
                let item = this.customItemCache[parma.arg];
                if (!!!item) {
                    item = new ULCustomItem({
                        arg: parma.arg,
                        channelAd: new channelAd()
                    });
                    this.customItemCache[parma.arg] = item;
                }
                customAd = new ULAdvCustomNormalAd({
                    arg: item.arg,
                    show: (data, cycle) => {
                        let advId = data["advId"];
                        let tag = data["tag"] || advId || "";
                        ULLog.console.log("ULAdvCustomManager this.channelCustomStyle[tag]:", this.channelCustomStyle[tag]);
                        ULLog.console.log("ULAdvCustomManager this.channelCustomStyle[arg]:", this.channelCustomStyle[item.arg]);
                        ULLog.console.log("ULAdvCustomManager this.channelCustomStyle[*]:", this.channelCustomStyle["*"]);
                        let style = this.channelCustomStyle[tag] || this.channelCustomStyle[item.arg] || this.channelCustomStyle["*"] || {};
                        let trimStyle = {
                            x: !isNaN(Number(style.x)) ? Number(style.x) : 0.5,
                            y: !isNaN(Number(style.y)) ? Number(style.y) : 0,
                            width: !isNaN(Number(style.width)) ? Number(style.width) : 1,
                            height: !isNaN(Number(style.height)) ? Number(style.height) : 0.5,
                        };
                        item.allowRefreshShowing = allowRefreshShowing;
                        item.show(trimStyle, cycle);
                    },
                    close: () => {
                        item.close();
                    },
                    destroy: () => {
                        item.destroy();
                        delete this.customItemCache[item.arg];
                    }
                });
                return customAd;
            }
        }
        class ULCustomItem {
            constructor(param) {
                this.allowRefreshShowing = true;
                this.showStyle = { x: 0.5, y: 0, width: 1, height: 1 };
                this.showCycleList = [];
                this.loadCycleList = [];
                this.hadShowRulst = false;
                this.channelShowCycle = {
                    onShow: () => {
                        ULLog.console.log("ULCustomItem.channelShow channelShowCycle onShow");
                        if (!this.isShowing) {
                            this.close();
                            return;
                        }
                        this.hadShowRulst = true;
                        this.hadshown = true;
                        this.remainShowNumber = Math.max(--this.remainShowNumber, 0);
                        for (let i = 0; i < this.showCycleList.length; i++) {
                            let cycleItem = this.showCycleList[i];
                            cycleItem.onShow && cycleItem.onShow();
                        }
                    },
                    onShowFail: (errInfo) => {
                        ULLog.console.log("ULCustomItem.channelShow channelShowCycle onShowFail");
                        if (!this.isShowing) {
                            return;
                        }
                        this.hadShowRulst = true;
                        this.isShowing = false;
                        this.loadSuccess = false;
                        this.errInfo = errInfo;
                        for (let i = 0; i < this.showCycleList.length; i++) {
                            let cycleItem = this.showCycleList.shift();
                            cycleItem.onShowFail && cycleItem.onShowFail(errInfo);
                        }
                    },
                    onRefresh: (errInfo = null) => {
                        if (!this.isShowing) {
                            return;
                        }
                        this.hadShowRulst = true;
                        ULLog.console.log("ULCustomItem.channelShow channelShowCycle refresh onRefresh err:", errInfo);
                        if (errInfo) {
                            return;
                        }
                        this.hadshown = true;
                        this.remainShowNumber = Math.max(--this.remainShowNumber, 0);
                        for (let i = 0; i < this.showCycleList.length; i++) {
                            let cycleItem = this.showCycleList[i];
                            cycleItem.onRefresh && cycleItem.onRefresh();
                        }
                    },
                    onClose: (isUserClick = false) => {
                        if (!this.isShowing) {
                            return;
                        }
                        if (this.isLoading && isUserClick) {
                            return;
                        }
                        if (!this.hadshown && isUserClick) {
                            return;
                        }
                        if (!this.hadShowRulst)
                            return;
                        ULLog.console.log("ULCustomItem.channelShow channelShowCycle onClose");
                        this.isShowing = false;
                        while (this.showCycleList.length) {
                            let cycleItem = this.showCycleList.shift();
                            cycleItem.onClose && cycleItem.onClose(isUserClick);
                        }
                    },
                    onClick: () => {
                        if (!this.isShowing) {
                            return;
                        }
                        ULLog.console.log("ULCustomItem.channelShow channelShowCycle onClick");
                        this.hadClick = true;
                        this.remainRequestTime = 0;
                        for (let i = 0; i < this.showCycleList.length; i++) {
                            let cycleItem = this.showCycleList[i];
                            cycleItem.onClick && cycleItem.onClick();
                        }
                    }
                };
                this.channelLoadCycle = new ULAdvCustomAdLoadCycle();
                this.arg = param.arg;
                this.channelAd = param.channelAd;
                this.isShowing = false;
                this.hadClick = false;
                this.hadshown = false;
                this.isLoading = false;
                this.loadSuccess = false;
                this.remainRequestTime = 0;
                this.remainShowTime = this.adIntervals;
                this.remainShowNumber = this.allowShowNum;
                this.channelAd.init(this.arg);
            }
            get adIntervals() {
                let config = ULConfig.getConfig();
                let adIntervals = config.i_sdk_custom_refresh_intervals || 30;
                return Number(adIntervals) || 30;
            }
            get allowShowNum() {
                let config = ULConfig.getConfig();
                let allowShowNum = config.i_sdk_adv_custom_valid_show_count || 0;
                let trimAllowShowNum = Number(allowShowNum) || 2;
                return trimAllowShowNum;
            }
            get requestCD() {
                let config = ULConfig.getConfig();
                let customCD = config.i_sdk_adv_custom_cd || 0;
                let trimCustomCD = Number(customCD) / 1000 || 0;
                return Math.max(trimCustomCD, 15);
            }
            get allowLoad() {
                if (this.remainRequestTime == 0) {
                    if (this.hadClick)
                        return true;
                    if (!this.loadSuccess)
                        return true;
                    if (this.hadshown && this.remainShowTime == 0)
                        return true;
                    if (this.hadshown && this.remainShowNumber == 0) {
                        let isAutoRefresh = ULAdvCustomManager.isAutoRefresh;
                        if (!this.isShowing && isAutoRefresh && this.allowRefreshShowing)
                            return true;
                        if (this.isShowing && !isAutoRefresh)
                            return true;
                    }
                }
                return false;
            }
            performSecond() {
                this.remainRequestTime = Math.max(--this.remainRequestTime, 0);
                if (this.isShowing) {
                    this.remainShowTime = Math.max(--this.remainShowTime, 0);
                }
                ULLog.console.log("ULCustomItem:", {
                    allowLoad: this.allowLoad,
                    isShowing: this.isShowing,
                    remainRequestTime: this.remainRequestTime,
                    remainShowTime: this.remainShowTime,
                    remainShowNumber: this.remainShowNumber,
                });
            }
            loadData(cycle) {
                this.loadCycleList.push(cycle);
                if (this.isLoading)
                    return;
                this.isLoading = true;
                this.remainRequestTime = this.requestCD;
                let timerId = setTimeout(() => {
                    this.channelLoadCycle.onLoadFail({ code: "0", msg: "加载超时" });
                }, 20000);
                let baseLoadCycle = new ULAdvCustomAdLoadCycle();
                this.channelLoadCycle.onLoad = () => {
                    ULLog.console.log("ULCustomItem channelLoadCycle onLoad");
                    this.channelLoadCycle.onLoad = baseLoadCycle.onLoad;
                    this.channelLoadCycle.onLoadFail = baseLoadCycle.onLoadFail;
                    clearTimeout(timerId);
                    this.isLoading = false;
                    this.errInfo = null;
                    this.loadSuccess = true;
                    this.hadshown = false;
                    this.hadClick = false;
                    this.remainRequestTime = this.requestCD;
                    this.remainShowTime = this.adIntervals;
                    this.remainShowNumber = this.allowShowNum;
                    while (this.loadCycleList.length) {
                        let cycleItem = this.loadCycleList.shift();
                        cycleItem.onLoad && cycleItem.onLoad();
                    }
                };
                this.channelLoadCycle.onLoadFail = (errInfo) => {
                    ULLog.console.log("ULCustomItem channelLoadCycle onLoadFail:" + errInfo);
                    this.channelLoadCycle.onLoad = baseLoadCycle.onLoad;
                    this.channelLoadCycle.onLoadFail = baseLoadCycle.onLoadFail;
                    clearTimeout(timerId);
                    this.isLoading = false;
                    this.errInfo = errInfo;
                    this.loadSuccess = false;
                    while (this.loadCycleList.length) {
                        let cycleItem = this.loadCycleList.shift();
                        cycleItem.onLoadFail && cycleItem.onLoadFail(errInfo);
                    }
                };
                this.channelAd.load(this.channelLoadCycle);
            }
            channelShow(isRefresh = false) {
                if (!this.isShowing)
                    return;
                this.hadShowRulst = false;
                this.channelAd.show(this.showStyle, {
                    onShow: isRefresh ? this.channelShowCycle.onRefresh : this.channelShowCycle.onShow,
                    onShowFail: isRefresh ? this.channelShowCycle.onRefresh : this.channelShowCycle.onShowFail,
                    onRefresh: this.channelShowCycle.onRefresh,
                    onClose: this.channelShowCycle.onClose,
                    onClick: this.channelShowCycle.onClick
                });
            }
            show(style, cycle) {
                ULLog.console.log("ULAdvCustomManager.show isShowing:", this.isShowing);
                if (this.isShowing) {
                    cycle.onShowFail({ code: "0", msg: "正在播放中" });
                    return;
                }
                this.isShowing = true;
                this.showStyle = style;
                this.showCycleList.push(cycle);
                if (this.allowLoad || this.isLoading) {
                    ULLog.console.log("ULAdvCustomManager.show loadData");
                    this.loadData({
                        onLoad: () => {
                            ULLog.console.log("ULAdvCustomManager.show loadData onLoad");
                            this.channelShow();
                        },
                        onLoadFail: (errInfo) => {
                            ULLog.console.log("ULAdvCustomManager.show loadData onLoadFail");
                            this.channelShowCycle.onShowFail(errInfo);
                        }
                    });
                }
                else if (this.loadSuccess) {
                    ULLog.console.log("ULAdvCustomManager.show loadSuccess");
                    this.remainRequestTime = Math.max(this.remainRequestTime, 3);
                    this.channelShow();
                }
                else {
                    ULLog.console.log("ULAdvCustomManager.show errInfo");
                    this.channelShowCycle.onShowFail(this.errInfo || (this.isLoading ? { code: "0", msg: "正在加载中" } : { code: "0", msg: "未知错误" }));
                }
            }
            refresh() {
                ULLog.console.log("ULAdvCustomManager.refresh");
                var isShowing = this.isShowing;
                this.loadData({
                    onLoad: () => {
                        ULLog.console.log("ULAdvCustomManager.refresh onLoad isShowing:", this.isShowing);
                        if (isShowing && this.isShowing)
                            this.channelShow(true);
                    },
                    onLoadFail: (errInfo) => {
                        ULLog.console.log("ULAdvCustomManager.refresh onLoadFail");
                    },
                });
            }
            close() {
                ULLog.console.log("ULAdvCustomManager.close");
                this.hadShowRulst = true;
                this.loadCycleList = [];
                this.channelAd.close();
                this.channelShowCycle.onClose && this.channelShowCycle.onClose(false);
            }
            destroy() {
                ULLog.console.log("ULAdvCustomManager.destroy");
                this.close();
                this.channelAd.destroy();
                this.channelAd = null;
            }
        }

        let qg$c = window["qg"];
        class ULAdvOppoQgCustomItem {
            constructor() {
                this.arg = null;
                this.customAd = null;
                this.channelStyle = null;
                this.showStyleString = "";
            }
            init(arg) {
                this.arg = arg;
                let config = ULConfig.getConfig();
                let t_sdk_oppoqg_custom_adv_setting = config.t_sdk_oppoqg_custom_adv_setting;
                this.channelStyle = t_sdk_oppoqg_custom_adv_setting[this.arg] || t_sdk_oppoqg_custom_adv_setting["*"] || {};
                ULLog.console.log("ULAdvOppoQgCustomItem.initAdv channelStyle:", this.channelStyle);
            }
            load(cycle) {
                ULLog.console.log("ULAdvOppoQgCustomItem.load ");
                if (this.customAd) {
                    this.customAd.offHide();
                    this.customAd.hide();
                    this.customAd.destroy();
                    this.customAd = null;
                }
                cycle.onLoad();
            }
            createNewCustomAd(style) {
                if (this.customAd) {
                    this.customAd.offHide();
                    this.customAd.hide();
                    this.customAd.destroy();
                    this.customAd = null;
                }
                let sys = qg$c.getSystemInfoSync();
                let screenWidth = sys.screenWidth;
                let screenHeight = sys.screenHeight;
                let width = Math.min(screenWidth, screenHeight);
                let height = 0;
                try {
                    let size = this.channelStyle.size;
                    size = size.replace(/\s*/g, "");
                    let sizeArray = size.split("*");
                    if (sizeArray.length == 2) {
                        let sizeWidth = parseInt(sizeArray[0]);
                        let sizeHeight = parseInt(sizeArray[1]);
                        width = width * Math.min(Math.max(0.6, style.width), 1);
                        height = width * sizeHeight / sizeWidth;
                    }
                }
                catch (error) {
                    ULLog.console.log("ULAdvOppoQgCustomItem.createNewCustomAd catch:", error.stack);
                    width = width * Math.min(Math.max(0.6, style.width), 1);
                    height = width;
                }
                let left = (screenWidth - width) * style.x;
                let top = (1 - style.y) * (screenHeight - height);
                ULLog.console.log("ULAdvOppoQgCustomItem.createNewCustomAd style:", {
                    top: top,
                    left: left,
                    width: width,
                });
                this.customAd = qg$c.createCustomAd({
                    adUnitId: this.arg,
                    style: {
                        top: top,
                        left: left,
                        width: width,
                    },
                });
            }
            show(style, cycle) {
                let showStyleString = JSON.stringify(style);
                let isEqual = showStyleString == this.showStyleString;
                this.showStyleString = showStyleString;
                console.log(`ULAdvOppoQgCustomItem.show style :${showStyleString} :`, isEqual);
                if (!this.customAd || !isEqual) {
                    this.createNewCustomAd(style);
                }
                this.customAd.offHide();
                this.customAd.onHide(() => {
                    ULLog.console.log("ULAdvOppoQgCustomItem.show onHide");
                    cycle.onClose(true);
                });
                this.customAd
                    .show()
                    .then(() => {
                    ULLog.console.log("ULAdvOppoQgCustomItem.show then");
                    cycle.onShow();
                })
                    .catch((e) => {
                    ULLog.console.log("ULAdvOppoQgCustomItem.show catch e:", e);
                    cycle.onShowFail({ code: "" + e.errCode, msg: e.errMsg });
                });
            }
            close() {
                ULLog.console.log("ULAdvOppoQgCustomItem.close ");
                this.customAd && this.customAd.hide();
            }
            destroy() {
                ULLog.console.log("ULAdvOppoQgCustomItem.destroy ");
                this.customAd && this.customAd.destroy();
                this.customAd = null;
            }
        }

        class ULAdvOppoQgCustom extends ULAdvObjectBase {
            constructor(arg) {
                super(arg, typeExp.custom, ULTools.format("%s%s%s", "ULAdvOppoQgCustom", "_", arg));
                this.className = "ULAdvOppoQgCustom";
                this.customAd = null;
                this.statisticsAdvertiser = ULAdvOppoQg.NORMAL_ADVERTISER;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgCustom-onDisposeModule arg:", this.arg);
                if (this.customAd) {
                    this.customAd.destroy();
                    this.customAd = null;
                }
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgCustom-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                this.customAd = ULAdvCustomManager.createCustomAd(ULAdvOppoQgCustomItem, { arg: this.arg }, false);
            }
            loadAdv() {
            }
            showAdv(data) {
                ULLog.console.log("ULAdvOppoQgCustom.showAdv");
                this.customAd.showCycle.onShowFail = ((errInfo) => {
                    ULLog.console.log("ULAdvOppoQgCustom.showAdv-onError:", errInfo);
                    if (this.isOpened) {
                        this.isOpened = false;
                        this.advSkip(data, errInfo);
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, errInfo);
                    }
                });
                this.customAd.showCycle.onShow = (() => {
                    ULLog.console.log("ULAdvOppoQgCustom.showAdv-onShow");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, data, null);
                    let config = ULConfig.getConfig();
                    let sw = config.s_sdk_oppo_custom_mode || "1";
                    if (sw === "1") {
                        if (ULSdkManager.getInstance().channelInfo.getChannelOpenIdFunc) {
                            ULSdkManager.getInstance().channelInfo.getChannelOpenIdFunc((openId, err) => {
                                if (openId) {
                                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", "206", "0", `${new Date().getTime()}_${openId}_${this.arg}_0`]);
                                }
                                else {
                                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", "206", "0", `${new Date().getTime()}_${0}_${this.arg}_0`]);
                                }
                            });
                        }
                        else {
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", "206", "0", `${new Date().getTime()}_${0}_${this.arg}_0`]);
                        }
                    }
                });
                this.customAd.showCycle.onClick = (() => {
                    ULLog.console.log("ULAdvOppoQgCustom.showAdv-onClick");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClick(this.advKey, "点击", data, null);
                });
                this.customAd.showCycle.onClose = ((isUserClick) => {
                    ULLog.console.log("ULAdvOppoQgCustom.showAdv-onClose");
                    if (isUserClick == true) {
                        ULSdkManager.getInstance().advManager.addAdvCountLog(this.advKey, countExp.mcc);
                    }
                    this.isOpened = false;
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, data, null);
                });
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.isOpened = true;
                this.customAd.show(data);
            }
            closeAdv(data) {
                ULLog.console.log("ULAdvOppoQgCustom.closeAdv");
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgCustom-receiveInitState:初始化失败");
                }
            }
        }

        class ULAdvOppoQgCustomBanner extends ULAdvObjectBase {
            constructor(arg) {
                super(arg, typeExp.custom, ULTools.format("%s%s%s", "ULAdvOppoQgCustomBanner", "_", arg));
                this.className = "ULAdvOppoQgCustomBanner";
                this.customAd = null;
                this.statisticsAdvertiser = ULAdvOppoQg.NORMAL_ADVERTISER;
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgCustomBanner-onDisposeModule arg:", this.arg);
                if (this.customAd) {
                    this.customAd.destroy();
                    this.customAd = null;
                }
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgCustomBanner-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
                this.customAd = ULAdvCustomManager.createCustomAd(ULAdvOppoQgCustomItem, { arg: this.arg });
            }
            loadAdv() {
            }
            showAdv(data) {
                ULLog.console.log("ULAdvOppoQgCustomBanner.showAdv");
                this.customAd.showCycle.onShowFail = ((errInfo) => {
                    ULLog.console.log("ULAdvOppoQgCustomBanner.showAdv-onError:", errInfo);
                    if (this.isOpened) {
                        this.isOpened = false;
                        this.advSkip(data, errInfo);
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, errInfo);
                    }
                });
                this.customAd.showCycle.onShow = (() => {
                    ULLog.console.log("ULAdvOppoQgCustomBanner.showAdv-onShow");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, data, null);
                });
                this.customAd.showCycle.onClick = (() => {
                    ULLog.console.log("ULAdvOppoQgCustomBanner.showAdv-onClick");
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClick(this.advKey, "点击", data, null);
                });
                this.customAd.showCycle.onClose = ((isUserClick) => {
                    ULLog.console.log("ULAdvOppoQgCustomBanner.showAdv-onClose");
                    if (isUserClick == true) {
                        ULSdkManager.getInstance().advManager.addAdvCountLog(this.advKey, countExp.mcc);
                    }
                    this.isOpened = false;
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, data, null);
                });
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.isOpened = true;
                this.customAd.show(data);
            }
            closeAdv(data) {
                ULLog.console.log("ULAdvOppoQgCustomBanner.closeAdv");
                this.customAd.close();
                ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgCustomBanner-receiveInitState:初始化失败");
                }
            }
        }

        let qg$d = window["qg"];
        class ULAdvOppoQgDrawerBox extends ULAdvObjectBase {
            constructor(arg) {
                super(arg, typeExp.embed, ULTools.format("%s%s%s", "ULAdvOppoQgDrawerBox", "_", arg));
                this.className = "ULAdvOppoQgDrawerBox";
                this.statisticsAdvertiser = "ULAdvOppoQgDrawerBox";
            }
            onDisposeModule() {
                super.onDisposeModule();
                ULLog.console.log("ULAdvOppoQgDrawerBox-onDisposeModule arg:", this.arg);
                if (this.gameDrawerAd) {
                    this.gameDrawerAd.destroy();
                    this.gameDrawerAd = null;
                }
            }
            initAdv() {
                ULLog.console.log("ULAdvOppoQgDrawerBox-initAdv");
                this.preLoadState = ULConst.ADV_PRELOAD_STATE_READY;
            }
            loadAdv() {
            }
            showAdv(data) {
                if (qg$d.getSystemInfoSync().platformVersionCode < 1090) {
                    ULLog.console.log('ULAdvOppoQgDrawerBox-showAdv:快应用平台版本号低于1090，暂不支持互推盒子相关 API');
                    this.advSkip(data, { code: "", msg: "api unsupport" });
                    return;
                }
                let tag = data["tag"] || data["advId"] || "";
                let advSetting = ULConfig.getConfig().t_sdk_oppoqg_show_drawer_box_adv_tags;
                let styleObj = advSetting[tag];
                if (!styleObj) {
                    ULLog.console.log("ULAdvOppoQgDrawerBox-showAdv:当前广告位不允许展示互推盒子抽屉广告");
                    this.advSkip(data, { code: "", msg: `advId [${tag}] unsupport drawer box` });
                    return;
                }
                this.showData = data;
                this.isOpened = true;
                if (this.gameDrawerAd) {
                    this.gameDrawerAd.destroy();
                    this.gameDrawerAd = null;
                }
                let sys = qg$d.getSystemInfoSync();
                let screenHeight = sys.screenHeight;
                let style = {};
                if (!isNaN(Number(styleObj.top))) {
                    style["top"] = Number(styleObj.top) * screenHeight;
                }
                this.gameDrawerAd = qg$d.createGameDrawerAd({
                    adUnitId: this.arg,
                    style: style
                });
                ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequest(this.advKey);
                this.gameDrawerAd.show().then(() => {
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestSuccess(this.advKey);
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleShow(this.advKey, ULConst.ADV_RESULT_MSG_SUCCESS, this.showData);
                }).catch((error) => {
                    ULLog.console.log("ULAdvOppoQgDrawerBox-showAdv-show-catch:", error);
                    this.isOpened = false;
                    this.advSkip(this.showData, { code: String(error.errCode), msg: error.errMsg });
                    ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleRequestFailed(this.advKey, { code: String(error.errCode), msg: error.errMsg });
                });
            }
            closeAdv(data) {
                if (this.isOpened) {
                    this.gameDrawerAd.hide().then(() => {
                        this.isOpened = false;
                        ULSdkManager.getInstance().advManager.onAdvObjectLifeCycleClose(this.advKey, data);
                        ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_SUCCESS, ULConst.ADV_RESULT_MSG_CLOSE);
                    }).catch((error) => {
                        ULLog.console.log("ULAdvOppoQgDrawerBox-closeAdv-hide-catch:", error);
                        ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, error.errCode + ',' + error.errMsg);
                    });
                }
                else {
                    ULSdkManager.getInstance().advManager.responseCloseAdvResult(data, ULConst.ADV_RESULT_CODE_FAILED, "no ad show");
                }
            }
            getMainClassName() {
                return "ULAdvOppoQg";
            }
            receiveInitState(initState) {
                if (initState) {
                    this.initState = initState;
                    this.initAdv();
                }
                else {
                    console.warn("ULAdvOppoQgDrawerBox-receiveInitState:初始化失败");
                }
            }
        }

        let qg$e = window["qg"];
        class ULModuleOppoQg extends ULChannelModuleBase {
            constructor() {
                super(...arguments);
                this.className = "ULModuleOppoQg";
                this.manualCloseBannerCount = 0;
                this.lastDailyResetTime = 0;
                this.userInfoData = null;
            }
            getSubAdModuleClassName() {
                return ["ULAdvOppoQgInter", "ULAdvOppoQgBanner", "ULAdvOppoQgVideo", "ULAdvOppoQgBannerBox", "ULAdvOppoQgPortalBox", "ULAdvOppoQgNativeBanner", "ULAdvOppoQgNativeInter", "ULAdvOppoQgNativeEmbed", "ULAdvOppoQgAutoNativeBanner", "ULAdvOppoQgAutoNativeInter", "ULAdvOppoQgAutoNativeEmbed", "ULAdvOppoQgCustom", "ULAdvOppoQgCustomBanner", "ULAdvOppoQgDrawerBox"];
            }
            getAdMainClassName() {
                return "ULAdvOppoQg";
            }
            createSubAdObj(className, param) {
                let targetObj;
                let advKey;
                switch (className) {
                    case "ULAdvOppoQgInter":
                        targetObj = new ULAdvOppoQgInter(param);
                        break;
                    case "ULAdvOppoQgBanner":
                        targetObj = new ULAdvOppoQgBanner(param);
                        break;
                    case "ULAdvOppoQgVideo":
                        targetObj = new ULAdvOppoQgVideo(param);
                        break;
                    case "ULAdvOppoQgBannerBox":
                        targetObj = new ULAdvOppoQgBannerBox(param);
                        break;
                    case "ULAdvOppoQgPortalBox":
                        targetObj = new ULAdvOppoQgPortalBox(param);
                        break;
                    case "ULAdvOppoQgNativeBanner":
                        targetObj = new ULAdvOppoQgNativeBanner(param);
                        break;
                    case "ULAdvOppoQgNativeInter":
                        targetObj = new ULAdvOppoQgNativeInter(param);
                        break;
                    case "ULAdvOppoQgNativeEmbed":
                        targetObj = new ULAdvOppoQgNativeEmbed(param);
                        break;
                    case "ULAdvOppoQgAutoNativeBanner":
                        targetObj = new ULAdvOppoQgAutoNativeBanner(param);
                        break;
                    case "ULAdvOppoQgAutoNativeInter":
                        targetObj = new ULAdvOppoQgAutoNativeInter(param);
                        break;
                    case "ULAdvOppoQgAutoNativeEmbed":
                        targetObj = new ULAdvOppoQgAutoNativeEmbed(param);
                        break;
                    case "ULAdvOppoQgCustom":
                        targetObj = new ULAdvOppoQgCustom(param);
                        break;
                    case "ULAdvOppoQgCustomBanner":
                        targetObj = new ULAdvOppoQgCustomBanner(param);
                        break;
                    case "ULAdvOppoQgDrawerBox":
                        targetObj = new ULAdvOppoQgDrawerBox(param);
                        break;
                    default:
                        break;
                }
                if (targetObj) {
                    advKey = ULTools.format("%s%s%s", className, "_", param);
                    ULSdkManager.getInstance().advManager.updateAdvKeyObjMap(advKey, targetObj);
                }
                return targetObj;
            }
            createMainAdObj() {
                return new ULAdvOppoQg();
            }
            init() {
                super.init();
                ULSdkManager.getInstance().statisManager.addPreparationFlag("oppoMoreGameExtra");
                this.loadRecord();
                this.initUserJumpGameInfo();
                this.initSdk();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SET_VERSION, 1, this.onCmdSetVersion.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_USER_LOGIN, 1, this.onCmdUserLogin.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_USER_IS_LOGIN, 1, this.onCmdUserIsLogin.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_GET_USER_INFO_MSG, 1, this.onCmdGetUserInfo.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_OPEN_PAY, ULConst.PRIORITY_NONE, this.onCmdOpenPay.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_OPEN_JUMP, ULConst.PRIORITY_NONE, this.onCmdOpenJump.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_JUMP_OTHER_GAME, ULConst.PRIORITY_NONE, this.onCmdJumpOtherGame.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_RESUME, ULConst.PRIORITY_NONE, this.onCmdSdkOnGameResume.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_INSTALL_SHORTCUT, ULConst.PRIORITY_NONE, this.onCmdInstallShortcut.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_MORE_GAME_AB_TEST_CONFIG, ULConst.PRIORITY_NONE, this.onCmdSdkCollectionModuleCheckerMoreGameTestConfig.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_GET_SHORTCUT_STATE, ULConst.PRIORITY_NONE, this.onCmdGetShortcutState.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_OPPOQG_MARK_MANUAL_CLOSE_BANNER_COUNT, ULConst.PRIORITY_NONE, this.onCmdSdkMarkManualCloseBannerCount.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_OPPOQG_GET_MANUAL_CLOSE_BANNER_COUNT, ULConst.PRIORITY_NONE, this.onCmdSdkGetManualCloseBannerCount.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_PHONE_VIBRATE, 1, this.onCmdPhoneVibrate.bind(this));
                this.onCmdSdkOnGameResume(new ULEvent(ULConst.CMD_SDK_ON_GAME_RESUME, {}));
            }
            loadSubModules() {
                return [];
            }
            loadRecord() {
                let recordStr = ULStorageManager.getInstance().getStorage(this._getRecordKey()) || "{}";
                ULLog.console.log("ULModuleOppoQg.loadRecord recordStr:", recordStr);
                let record;
                try {
                    record = JSON.parse(recordStr);
                }
                catch (error) {
                    record = {};
                }
                this["jumpResourceIndex"] = record.jumpResourceIndex;
                this.lastJumpRecord = record.lastJumpRecord || null;
                this.jumpGameReceivedFlags = record.jumpGameReceivedFlags || {};
                this.lastDailyResetTime = record.lastDailyResetTime || ULTools.time();
                this.manualCloseBannerCount = record.manualCloseBannerCount || 0;
                this.tryDailyReset();
            }
            saveRecord() {
                let record = {
                    jumpResourceIndex: this["jumpResourceIndex"],
                    lastJumpRecord: this.lastJumpRecord,
                    jumpGameReceivedFlags: this.jumpGameReceivedFlags,
                    lastDailyResetTime: this.lastDailyResetTime,
                    manualCloseBannerCount: this.manualCloseBannerCount,
                };
                let recordStr = JSON.stringify(record);
                ULStorageManager.getInstance().setStorage(this._getRecordKey(), recordStr);
            }
            tryDailyReset() {
                if (!ULTools.isOneDay(ULTools.time(), this.lastDailyResetTime)) {
                    this.lastDailyResetTime = ULTools.time();
                    this.manualCloseBannerCount = 0;
                    this.saveRecord();
                }
            }
            _getRecordKey() {
                let config = ULConfig.getConfig();
                return ULTools.format("ULModuleOppoQg_record_%d", config.s_sdk_megadata_game_id);
            }
            initSdk() {
                let config = ULConfig.getConfig();
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                channelInfo.channelName = "oppoqg";
                channelInfo.uuid = this.sdkUserId;
                channelInfo.isSupportRecordShare = false;
                channelInfo.isShareEnabled = !!config.i_sdk_share_mode;
                channelInfo.copChannelId = config.s_sdk_cop_channel_id;
                channelInfo.isPayEnabled = !!config.i_sdk_pay_mode;
                channelInfo.isUseSdkRank = !!config.i_sdk_sdk_rank_mode;
                channelInfo.isSupportInstallShortcut = true;
                channelInfo.appName = "oppoqg";
                channelInfo.isSupportJumpList = true;
                channelInfo.jumpInfo = this.getJumpInfo();
                channelInfo.referenceBannerHeight = 110;
                channelInfo.payInfo = config.t_sdk_oppoqg_pay_code || {};
                channelInfo.getChannelOpenIdFunc = this.getChannelOpenIdFunc.bind(this);
                let options = qg$e.getLaunchOptionsSync();
                let referrerInfo = options && (options.referrerInfo || {});
                if (JSON.stringify(referrerInfo) != "{}") {
                    ULSdkManager.getInstance().statisManager.setGameStartSourceMsg(JSON.stringify(referrerInfo));
                }
                if (qg$e.getSystemInfoSync().platformVersionCode >= 1076) {
                    channelInfo.isJumpLeisureEnabled = true;
                }
                else {
                    channelInfo.isJumpLeisureEnabled = false;
                }
                ULLog.console.log("ULModuleOppoQg.initSdk getLaunchOptionsSync options:", options);
                ULSdkManager.getInstance().statisManager.removePreparationFlag("oppoMoreGameExtra");
                this.onCmdGetShortcutState(new ULEvent(ULConst.CMD_GET_SHORTCUT_STATE, {}));
            }
            initUserJumpGameInfo() {
                if (this["jumpResourceIndex"] == null || this["jumpResourceIndex"] == undefined) {
                    this.setRandomJumpResourceIndex();
                }
                ULLog.console.log("ULModuleOppoQg.initUserJumpGameInfo this.jumpResourceIndex:", this["jumpResourceIndex"]);
            }
            getJumpResourceIndex() {
                let config = ULConfig.getConfig();
                if (config.i_sdk_jump_game_resource_mode == 1) {
                    return this["jumpResourceIndex"];
                }
                else {
                    return 0;
                }
            }
            setRandomJumpResourceIndex() {
                let config = ULConfig.getConfig();
                let jumpConfigs = config.t_sdk_oppoqg_jump_games || [];
                let jumpConfig = jumpConfigs[0];
                if (jumpConfig && jumpConfig.urls) {
                    let urlsLength = jumpConfig.urls.length;
                    let indexRange = urlsLength > 0 ? urlsLength - 1 : 0;
                    this["jumpResourceIndex"] = ULTools.random(0, indexRange);
                }
                else {
                    this["jumpResourceIndex"] = 0;
                }
                this.saveRecord();
            }
            getJumpInfo() {
                let config = ULConfig.getConfig();
                let jumpConfigs = config.t_sdk_oppoqg_jump_games;
                let jumpInfo = [];
                for (let i = 0; i < jumpConfigs.length; i++) {
                    let jumpConfig = jumpConfigs[i];
                    if (!jumpConfig.urls)
                        continue;
                    let index = jumpConfig.index || "";
                    let bReceived = this.jumpGameReceivedFlags[index] || false;
                    jumpInfo.push({
                        index: jumpConfig.index,
                        url: jumpConfig.urls[this.getJumpResourceIndex()] || "",
                        rewards: jumpConfig.rewards || [],
                        bReceived: bReceived,
                    });
                }
                return jumpInfo;
            }
            _hook_getStorage(key) {
                if (localStorage)
                    return localStorage.getItem(key);
                return null;
            }
            _hook_setStorage(key, data) {
                if (localStorage)
                    localStorage.setItem(key, data);
                return;
            }
            _hook_isSupportClipboard() {
                return true;
            }
            _hook_getClipboardData(finishCallback) {
                qg$e.getClipboardData({
                    success: function (res) {
                        finishCallback(res.data);
                    },
                    fail: function (res) {
                        finishCallback(null);
                    }
                });
            }
            _hook_setClipboardData(clipboardData, finishCallback) {
                qg$e.setClipboardData({
                    data: clipboardData,
                    success(res) {
                        finishCallback(true);
                    },
                    fail(res) {
                        finishCallback(false);
                    }
                });
            }
            preOrderForSingleGame(payId, productDesc, productName, orderId, success, fail) {
                ULLog.console.log(`ULModuleOppoQg.preOrderForSingleGame token:`, payId);
                ULLog.console.log(`ULModuleOppoQg.preOrderForSingleGame orderId:`, orderId);
                let config = ULConfig.getConfig();
                let payData = config.t_sdk_oppoqg_pay_code[payId];
                if (!payData) {
                    fail && fail("payId 不存在");
                    return;
                }
                this.login({
                    success: (token) => {
                        let timestamp = new Date().getTime();
                        let netTimeout = config.i_net_timeout;
                        let appkey = config.s_sdk_oppoqg_app_key;
                        let preOrderUrl = config.s_sdk_oppoqg_pre_order_url;
                        let privateKey = config.s_sdk_oppoqg_private_key;
                        let rsa = new RSAKey();
                        rsa.readPrivateKeyFromPEMString(privateKey);
                        let hashAlg = "sha256";
                        let params = {
                            appId: config.s_sdk_oppoqg_appid,
                            openId: token,
                            timestamp: timestamp,
                            productName: productName || payData.proName,
                            productDesc: productDesc || payData.proName,
                            count: 1,
                            price: parseInt(payData.price),
                            currency: "CNY",
                            cpOrderId: orderId,
                            appVersion: config.s_sdk_oppoqg_version_name,
                            engineVersion: qg$e.getSystemInfoSync().platformVersion
                        };
                        let signStr = `appId=${params.appId}&appVersion=${params.appVersion}&count=${params.count}&cpOrderId=${params.cpOrderId}&currency=${params.currency}&engineVersion=${params.engineVersion}&openId=${params.openId}&price=${params.price}&productDesc=${params.productDesc}&productName=${params.productName}&timestamp=${params.timestamp}`;
                        let hSig = rsa.sign(signStr, hashAlg);
                        params["sign"] = hex2b64(hSig);
                        ULTools.httpPost({
                            url: preOrderUrl,
                            postData: JSON.stringify(params),
                            timeoutMillisecond: netTimeout,
                            contentType: "application/json",
                            success: (res) => {
                                ULLog.console.log(`ULModuleOppoQg.preOrderForSingleGame timeoutMillisecond:`, res);
                                let resMsg = JSON.parse(res);
                                let code = resMsg.code;
                                if (code == "200") {
                                    let orderNo = resMsg.data.orderNo;
                                    let signStr = "appKey=" + appkey + "&orderNo=" + orderNo + "&timestamp=" + timestamp;
                                    let hSig = rsa.sign(signStr, hashAlg);
                                    let sign = hex2b64(hSig);
                                    success && success(token, sign, orderNo, timestamp);
                                }
                                else {
                                    fail && fail(resMsg);
                                }
                            },
                            fail: (res) => {
                                fail && fail(JSON.stringify(res));
                            }
                        });
                    },
                    fail: (res) => {
                        ULLog.console.log(`ULModuleOppoQg.preOrderForSingleGame login fail:`, res);
                        fail && fail(JSON.stringify(res));
                    }
                });
            }
            preOrderForOnlineGame(payId, orderId, productDesc, productName, success, fail) {
                ULLog.console.log(`ULModuleOppoQg.preOrderForOnlineGame payId:`, payId);
                ULLog.console.log(`ULModuleOppoQg.preOrderForOnlineGame orderId:`, orderId);
                let config = ULConfig.getConfig();
                let payData = config.t_sdk_oppoqg_pay_code[payId];
                if (!payData) {
                    fail && fail("payId 不存在");
                    return;
                }
                this.login({
                    success: (token) => {
                        let preOrderUrl = config.s_sdk_oppoqg_preOrder_online_url;
                        let params = {
                            mGameId: Number(config.s_sdk_megadata_game_id),
                            channel: "h5oppo",
                            orderInfo: JSON.stringify({
                                openId: token,
                                appVersion: config.s_sdk_oppoqg_version_name,
                                engineVersion: qg$e.getSystemInfoSync().platformVersion.toString(),
                                productDesc: productDesc || payData.proName,
                                productName: productName || payData.proName,
                                price: parseInt(payData.price),
                            })
                        };
                        ULTools.httpPostEncryption({
                            url: preOrderUrl,
                            postString: JSON.stringify(params),
                            timeoutMillisecond: config.i_net_timeout,
                            success: (res) => {
                                ULLog.console.log(`ULModuleOppoQg.preOrderForOnlineGame httpPost success:`, res);
                                let resMsg = JSON.parse(res);
                                let code = resMsg.code || 0;
                                if (code == 1) {
                                    let preOrderData = resMsg.preOrderData || {};
                                    let orderNo = preOrderData.orderNo;
                                    let timestamp = preOrderData.timestamp;
                                    let sign = preOrderData.sign;
                                    success && success(token, sign, orderNo, timestamp);
                                }
                                else {
                                    fail && fail(resMsg);
                                }
                            },
                            fail: (res) => {
                                ULLog.console.log(`ULModuleOppoQg.preOrderForOnlineGame httpPost fail:`, res);
                                fail && fail(JSON.stringify(res));
                            }
                        });
                    }, fail: (res) => {
                        ULLog.console.log(`ULModuleOppoQg.preOrderForOnlineGame login fail:`, res);
                        fail && fail(JSON.stringify(res));
                    }
                });
            }
            doOpenPay(isOnline, payId, productDesc, productName, orderId, success, fail) {
                ULLog.console.log(`ULModuleOppoQg.doOpenPay payId:`, payId);
                ULLog.console.log(`ULModuleOppoQg.doOpenPay orderId:`, orderId);
                let config = ULConfig.getConfig();
                let payData = config.t_sdk_oppoqg_pay_code[payId];
                if (!payData) {
                    fail && fail("payId 不存在");
                    return;
                }
                let preOrder = isOnline ? this.preOrderForOnlineGame.bind(this) : this.preOrderForSingleGame.bind(this);
                preOrder(payId, orderId, productDesc, productName, (token, sign, orderNo, timestamp) => {
                    ULLog.console.log("ULModuleHuawei.doOpenPay preOrder success token:", token);
                    ULLog.console.log("ULModuleHuawei.doOpenPay preOrder success sign:", sign);
                    ULLog.console.log("ULModuleHuawei.doOpenPay preOrder success orderNo:", orderNo);
                    ULLog.console.log("ULModuleHuawei.doOpenPay preOrder success timestamp:", timestamp);
                    ULSdkManager.getInstance().statisManager.reportPayRequest();
                    qg$e.pay({
                        appId: config.s_sdk_oppoqg_appid,
                        token: token,
                        timestamp: timestamp,
                        paySign: sign,
                        orderNo: orderNo,
                        success: function (res) {
                            ULLog.console.log(`ULModuleOppoQg.doOpenPay pay success:`, JSON.stringify(res));
                            success && success();
                        },
                        fail: function (res) {
                            let errMsg = JSON.stringify(res);
                            ULLog.console.log(`ULModuleOppoQg.doOpenPay pay fail:`, errMsg);
                            fail && fail(errMsg);
                        }
                    });
                }, (errmsg) => {
                    ULLog.console.log("ULModuleHuawei.doOpenPay preOrder fail errmsg:", errmsg);
                    fail && fail(errmsg);
                });
            }
            onCmdUserIsLogin(e) {
                e.stopImmediatePropagation();
                ULLog.console.log(`ULModuleWeixin.onCmdUserIsLogin `);
                let data = e.data;
                let userData = data.userData || "";
                ULSdkManager.getInstance().response(ULConst.CMD_USER_IS_LOGIN_RESULT, {
                    code: 1,
                    userData: userData
                });
            }
            onCmdUserLogin(e) {
                e.stopImmediatePropagation();
                ULLog.console.log(`ULModuleOppoQg.onCmdUserLogin 登陆`);
                let userData = e.data.userData || "";
                let config = ULConfig.getConfig();
                this.login({
                    success: (token) => {
                        ULSdkManager.getInstance().response(ULConst.CMD_USER_LOGIN_RESULT, {
                            code: 1,
                            userData: userData,
                            loginData: {
                                mgid: Number(config.s_sdk_megadata_game_id),
                                channel: "h5oppo",
                                openId: "",
                                token: token
                            }
                        });
                    }, fail: (res) => {
                        ULSdkManager.getInstance().response(ULConst.CMD_USER_LOGIN_RESULT, {
                            code: 0,
                            userData: userData
                        });
                    }
                });
            }
            login(obj) {
                ULLog.console.log("ULModuleOppoQg.login start");
                qg$e.login({
                    success: (res) => {
                        ULLog.console.log("ULModuleOppoQg.login success:", res);
                        obj.success(res.data.token || "");
                    },
                    fail: (res) => {
                        ULLog.console.log("ULModuleOppoQg.login fail：", res);
                        obj.fail(res);
                    }
                });
            }
            getUserInfoData(obj) {
                if (this.userInfoData) {
                    obj.success && obj.success(this.userInfoData);
                    return;
                }
                let config = ULConfig.getConfig();
                this.login({
                    success: (token) => {
                        ULLog.console.log("ULModuleOppoQg.getUserInfoData login success");
                        var userLoginUrl = config.s_sdk_common_login_url;
                        var postData = {
                            token: token,
                            channel: "h5oppo",
                            mgid: Number(config.s_sdk_megadata_game_id)
                        };
                        ULTools.httpPost({
                            url: userLoginUrl,
                            contentType: "application/json",
                            postData: JSON.stringify(postData),
                            timeoutMillisecond: config.i_net_timeout,
                            success: (responseText) => {
                                ULLog.console.log("ULModuleOppoQg.getUserInfoData success", responseText);
                                let resultObj = JSON.parse(responseText);
                                if (resultObj.code == 1) {
                                    let openId = resultObj.openId;
                                    this.userInfoData = {
                                        openId: openId,
                                        userInfo: {
                                            avatarUrl: resultObj.headImgUrl || "",
                                            nickName: resultObj.nickName || "",
                                        }
                                    };
                                    ULSdkManager.getInstance().channelInfo.channelUserId = openId;
                                    obj.success && obj.success(this.userInfoData);
                                }
                                else {
                                    ULLog.console.log("ULModuleOppoQg.getUserInfoData resultObj:", resultObj);
                                    obj.fail && obj.fail(JSON.stringify(resultObj));
                                }
                            },
                            fail: (res) => {
                                ULLog.console.log("ULModuleOppoQg.getUserInfoData fail:", res);
                                obj.fail && obj.fail(JSON.stringify(res));
                            }
                        });
                    },
                    fail: (res) => {
                        ULLog.console.log("ULModuleOppoQg.getUserInfoData login fail:", res);
                        obj.fail && obj.fail(JSON.stringify(res));
                    }
                });
            }
            onCmdOpenPay(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                let payId = data.payId;
                let orderId = data.orderId;
                let userData = data.userData || "";
                let productDesc = data.productDesc;
                let productName = data.productName;
                let trimOrder = orderId || ULTools.createRandomOrderId();
                let callBack = (code, err) => {
                    ULSdkManager.getInstance().response(ULConst.CMD_PAY_RESULT, {
                        code: code,
                        msg: err,
                        payId: payId,
                        userData: userData,
                    });
                };
                this.doOpenPay(!!orderId, payId, productDesc, productName, trimOrder, () => {
                    ULLog.console.log("ULModuleOppoQg.onCmdOpenPay doOpenPay success");
                    callBack(1, "购买成功");
                }, (errmsg) => {
                    ULLog.console.log("ULModuleOppoQg.onCmdOpenPay doOpenPay fail errmsg:", errmsg);
                    callBack(0, errmsg);
                });
            }
            onCmdOpenJump(e) {
                this.bOpenJumpCalled = true;
                let config = ULConfig.getConfig();
                let data = e.data;
                let count = data.count || -1;
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                if (!channelInfo.isSupportJumpList) {
                    ULLog.console.log("onCmdOpenJump----isSupportJumpList---不支持-");
                    ULSdkManager.getInstance().response(ULConst.CMD_OPEN_JUMP_RESULT, {
                        code: 0,
                        msg: "isSupportJumpList false",
                    });
                    return;
                }
                ULSdkManager.getInstance().channelInfo.jumpInfo = this.getJumpInfo();
                let rawJumpInfo = ULTools.clone(ULSdkManager.getInstance().channelInfo.jumpInfo);
                let jumpInfo = [];
                let type = data.type;
                if (type == "single") {
                    count = 1;
                }
                if (count == null || count <= 0) {
                    count = rawJumpInfo.length;
                }
                for (let i = 0; i < rawJumpInfo.length; i++) {
                    const v = rawJumpInfo[i];
                    v["raw_order"] = i;
                }
                count = Math.min(count, rawJumpInfo.length);
                let single_random_length = config.i_sdk_jump_single_random_length || rawJumpInfo.length;
                for (let i = 0; i < count; i++) {
                    let randLength = rawJumpInfo.length;
                    if (type == "single") {
                        randLength = Math.min(Math.max(1, single_random_length), randLength);
                        single_random_length--;
                    }
                    let r = ULTools.random(randLength) - 1;
                    let v = rawJumpInfo[r];
                    rawJumpInfo.splice(r, 1);
                    jumpInfo.push(v);
                }
                jumpInfo = ULTools.sortArrayByField(jumpInfo, "raw_order");
                for (let i = 0; i < jumpInfo.length; i++) {
                    const v = jumpInfo[i];
                    delete v["raw_order"];
                }
                ULSdkManager.getInstance().response(ULConst.CMD_OPEN_JUMP_RESULT, {
                    code: 1,
                    msg: "获取成功成功",
                    jumpInfo: jumpInfo,
                    type: type,
                    userData: data.userData || "",
                });
                let sourceGameId = config.s_sdk_cop_game_id + "";
                for (let index = 0; index < jumpInfo.length; index++) {
                    let jumpGameConfig = jumpInfo[index];
                    let gameIndex = jumpGameConfig.index;
                    let targetIconId = ULTools.format("%s_%d", gameIndex, this.getJumpResourceIndex());
                    ULSdkManager.getInstance().statisManager.reportJumpGame("openJump", "oppoqg", sourceGameId, type, targetIconId);
                }
            }
            onCmdJumpOtherGame(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let data = e.data;
                let gameIndex = data.gameIndex;
                let type = data.type;
                let userData = data.userData;
                let jumpGames = config.t_sdk_oppoqg_jump_games;
                let sourceGameId = config.s_sdk_cop_game_id + "";
                let targetIconId = ULTools.format("%s_%d", gameIndex, this.getJumpResourceIndex());
                if (this.bOpenJumpCalled) {
                    ULSdkManager.getInstance().statisManager.reportJumpGame("jump", "oppoqg", sourceGameId, type, targetIconId);
                }
                let gameId = null;
                let rewards = null;
                for (let i = 0; i < jumpGames.length; i++) {
                    const v = jumpGames[i];
                    if (v.index == gameIndex) {
                        gameId = v.id;
                        rewards = v.rewards;
                        break;
                    }
                }
                if (!gameId) {
                    ULSdkManager.getInstance().response(ULConst.CMD_JUMP_OTHER_GAME_RESULT, {
                        code: 0,
                        msg: "目标游戏未找到",
                        userData: userData,
                    });
                    if (this.bOpenJumpCalled) {
                        ULSdkManager.getInstance().statisManager.reportJumpGame("jumpFail", "oppoqg", sourceGameId, type, targetIconId);
                    }
                    return;
                }
                qg$e.navigateToMiniGame({
                    pkgName: gameId,
                    success: () => {
                        ULSdkManager.getInstance().response(ULConst.CMD_JUMP_OTHER_GAME_RESULT, {
                            code: 1,
                            msg: "跳转其他游戏成功",
                            userData: userData,
                        });
                        this.lastJumpRecord = {
                            gameIndex: gameIndex,
                            jumpTime: ULTools.time(),
                            type: type,
                            rewards: rewards,
                        };
                        this.saveRecord();
                    },
                    fail: (res) => {
                        ULLog.console.log("跳转其他游戏失败---err ", JSON.stringify(res));
                        ULSdkManager.getInstance().response(ULConst.CMD_JUMP_OTHER_GAME_RESULT, {
                            code: 0,
                            msg: "跳转其他游戏失败",
                            userData: userData,
                        });
                        if (this.bOpenJumpCalled) {
                            ULSdkManager.getInstance().statisManager.reportJumpGame("jumpFail", "oppoqg", sourceGameId, type, targetIconId);
                        }
                    }
                });
            }
            onCmdSdkOnGameResume(e) {
                let config = ULConfig.getConfig();
                let lastJumpRecord = this.lastJumpRecord;
                if (!lastJumpRecord) {
                    ULLog.console.log("ULModuleOppoQg.onCmdSdkOnGameResume 不存在上次跳转游戏");
                    return;
                }
                let gameIndex = lastJumpRecord.gameIndex;
                let sourceGameId = config.s_sdk_cop_game_id + "";
                let targetIconId = ULTools.format("%s_%d", gameIndex, this.getJumpResourceIndex());
                let lastJumpTime = lastJumpRecord.jumpTime || 0;
                let now = ULTools.time();
                let bNeedUploadStatis = true;
                if (!this.bOpenJumpCalled) {
                    bNeedUploadStatis = false;
                }
                let bJumpSuccess = (now - lastJumpTime) > config.i_sdk_oppoqg_jump_game_reward_time / 1000;
                if (bNeedUploadStatis) {
                    if (bJumpSuccess) {
                        ULSdkManager.getInstance().statisManager.reportJumpGame("jumpSuccess", "oppoqg", sourceGameId, lastJumpRecord.type, targetIconId);
                    }
                    else {
                        ULSdkManager.getInstance().statisManager.reportJumpGame("jumpFail", "oppoqg", sourceGameId, lastJumpRecord.type, targetIconId);
                    }
                }
                if (lastJumpRecord.type == "reward") {
                    if (bJumpSuccess) {
                        if (this.jumpGameReceivedFlags[lastJumpRecord.gameIndex]) {
                            ULSdkManager.getInstance().response(ULConst.CMD_JUMP_OTHER_GAME_REWARD_RESULT, {
                                code: 0,
                                msg: "该游戏已经发过奖",
                                rewards: lastJumpRecord.rewards || [],
                            });
                        }
                        else {
                            ULSdkManager.getInstance().response(ULConst.CMD_JUMP_OTHER_GAME_REWARD_RESULT, {
                                code: 1,
                                msg: "跳转其他游戏成功，并达到发奖条件",
                                rewards: lastJumpRecord.rewards || [],
                            });
                            this.jumpGameReceivedFlags[gameIndex] = true;
                            this.saveRecord();
                            ULSdkManager.getInstance().channelInfo.jumpInfo = this.getJumpInfo();
                        }
                    }
                    else {
                        ULSdkManager.getInstance().response(ULConst.CMD_JUMP_OTHER_GAME_REWARD_RESULT, {
                            code: 0,
                            msg: "跳转其他游戏失败",
                            rewards: this.lastJumpRecord.rewards || [],
                        });
                    }
                }
                this.lastJumpRecord = null;
                this.saveRecord();
            }
            onCmdSdkCollectionModuleCheckerMoreGameTestConfig(e) {
                let config = e.getReturnValue() || [];
                let text = ["A", "B", "C", "D", "E", "F"];
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "更多游戏ab测试信息:" });
                config.push({
                    type: "label",
                    text: text[this.getJumpResourceIndex()] || this.getJumpResourceIndex().toString(),
                    name: "labelMoreGameUserIndex"
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: ULTools.format("更多游戏资源状态：%s", ULConfig.getConfig().i_sdk_jump_game_resource_mode == 1 ? "随机" : "固定0") });
                config.push({ type: "newLine" });
                config.push({
                    type: "button",
                    text: "更改更多游戏用户AB属性",
                    onClick: () => {
                        let config = ULConfig.getConfig();
                        let jumpConfigs = config.t_sdk_baidu_jump_games || [];
                        let jumpConfig = jumpConfigs[0];
                        let urlsLength = 2;
                        if (jumpConfig && jumpConfig.urls) {
                            urlsLength = jumpConfig.urls.length;
                        }
                        let conf = [];
                        for (let index = 0; index < urlsLength; index++) {
                            conf.push({
                                text: text[index] || index.toString(),
                                value: index.toString()
                            });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("选择AB测试用户属性：", conf, (index) => {
                            this["jumpResourceIndex"] = parseInt(index.toString());
                            let labelText = text[this.getJumpResourceIndex()] || this.getJumpResourceIndex().toString();
                            ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelMoreGameUserIndex", labelText);
                            this.saveRecord();
                            ULSdkManager.getInstance().channelInfo.jumpInfo = this.getJumpInfo();
                        });
                    }
                });
                e.setReturnValue(config, true);
            }
            onCmdGetShortcutState(e) {
                e.stopImmediatePropagation();
                if (qg$e.hasShortcutInstalled) {
                    qg$e.hasShortcutInstalled({
                        success: (res) => {
                            if (res == false) {
                                ULSdkManager.getInstance().response(ULConst.CMD_GET_SHORTCUT_STATE_RESULT, {
                                    state: 1,
                                    bHasPrompt: true
                                });
                            }
                            else {
                                ULLog.console.log("ULModuleOppoQg.onCmdGetShortcutState.hasShortcutInstalled success true :", res);
                                ULSdkManager.getInstance().response(ULConst.CMD_GET_SHORTCUT_STATE_RESULT, {
                                    state: 3,
                                    bHasPrompt: true
                                });
                            }
                        },
                        fail: (err) => {
                            ULLog.console.log("ULModuleOppoQg.onCmdGetShortcutState.hasShortcutInstalled fail:", err);
                            ULSdkManager.getInstance().response(ULConst.CMD_GET_SHORTCUT_STATE_RESULT, {
                                state: 1,
                                bHasPrompt: true
                            });
                        }
                    });
                }
                else {
                    ULSdkManager.getInstance().response(ULConst.CMD_GET_SHORTCUT_STATE_RESULT, {
                        state: 1,
                        bHasPrompt: true
                    });
                }
            }
            onCmdInstallShortcut(e) {
                e.stopImmediatePropagation();
                let config = ULConfig.getConfig();
                let data = e.data;
                let userData = data.userData;
                qg$e.hasShortcutInstalled({
                    success: (res) => {
                        if (res == false) {
                            ULSdkManager.getInstance().statisManager.reportAddShortcut("0");
                            qg$e.installShortcut({
                                success: () => {
                                    setTimeout(() => {
                                        qg$e.hasShortcutInstalled({
                                            success: (res) => {
                                                if (res == false) {
                                                    ULLog.console.log("ULModuleOppoQg.onCmdInstallShortcut.hasShortcutInstalled 2 success false :", res);
                                                    ULSdkManager.getInstance().statisManager.reportAddShortcut("2");
                                                    ULSdkManager.getInstance().response(ULConst.CMD_INSTALL_SHORTCUT_RESULT, {
                                                        code: 0,
                                                        msg: "添加桌面快捷方式失败",
                                                        userData: userData,
                                                    });
                                                    this.onCmdGetShortcutState(new ULEvent(ULConst.CMD_GET_SHORTCUT_STATE, {}));
                                                }
                                                else {
                                                    ULSdkManager.getInstance().statisManager.reportAddShortcut("1");
                                                    ULLog.console.log("ULModuleOppoQg.onCmdInstallShortcut.hasShortcutInstalled 2 success true :", res);
                                                    ULSdkManager.getInstance().response(ULConst.CMD_INSTALL_SHORTCUT_RESULT, {
                                                        code: 1,
                                                        msg: "添加桌面快捷方式成功",
                                                        userData: userData,
                                                    });
                                                    this.onCmdGetShortcutState(new ULEvent(ULConst.CMD_GET_SHORTCUT_STATE, {}));
                                                }
                                            },
                                            fail: (err) => {
                                                ULSdkManager.getInstance().statisManager.reportAddShortcut("2");
                                                ULLog.console.log("ULModuleOppoQg.onCmdInstallShortcut.hasShortcutInstalled 2 fail:", err);
                                                ULSdkManager.getInstance().response(ULConst.CMD_INSTALL_SHORTCUT_RESULT, {
                                                    code: 0,
                                                    msg: "添加桌面快捷方式失败",
                                                    userData: userData,
                                                });
                                                this.onCmdGetShortcutState(new ULEvent(ULConst.CMD_GET_SHORTCUT_STATE, {}));
                                            }
                                        });
                                    }, 500);
                                },
                                fail: (err) => {
                                    ULLog.console.log("ULModuleOppoQg.onCmdInstallShortcut.installShortcut fail:", err);
                                    ULSdkManager.getInstance().response(ULConst.CMD_INSTALL_SHORTCUT_RESULT, {
                                        code: 0,
                                        msg: "添加桌面快捷方式失败",
                                        userData: userData,
                                    });
                                    this.onCmdGetShortcutState(new ULEvent(ULConst.CMD_GET_SHORTCUT_STATE, {}));
                                }
                            });
                        }
                        else {
                            ULSdkManager.getInstance().response(ULConst.CMD_INSTALL_SHORTCUT_RESULT, {
                                code: 2,
                                msg: "添加桌面快捷方式成功",
                                userData: userData,
                            });
                            this.onCmdGetShortcutState(new ULEvent(ULConst.CMD_GET_SHORTCUT_STATE, {}));
                        }
                    },
                    fail: (err) => {
                        ULLog.console.log("ULModuleOppoQg.onCmdInstallShortcut.hasShortcutInstalled 1 fail err:", err);
                        ULSdkManager.getInstance().response(ULConst.CMD_INSTALL_SHORTCUT_RESULT, {
                            code: 0,
                            msg: "添加桌面快捷方式失败",
                            userData: userData,
                        });
                        this.onCmdGetShortcutState(new ULEvent(ULConst.CMD_GET_SHORTCUT_STATE, {}));
                    }
                });
            }
            onCmdSetVersion(e) {
                ULLog.console.log("ULModuleOppoQg.onCmdSetVersion................");
                let version = qg$e.getSystemInfoSync().platformVersion;
                ULLog.console.log("ULModuleOppoQg.onCmdSetVersion.....version: ", version);
                if (version >= 1060) {
                    ULLog.console.log("ULModuleOppoQg.onCmdSetVersion........数据正在上报");
                    qg$e.reportMonitor("game_scene", 0);
                }
                else {
                    ULLog.console.log("ULModuleOppoQg.onCmdSetVersion........平台版本号低于1060，请升级平台");
                }
            }
            onCmdSdkMarkManualCloseBannerCount(e) {
                this.tryDailyReset();
                this.manualCloseBannerCount++;
                ULLog.console.log("ULModuleOppoQg.onCmdSdkMarkManualCloseBannerCount", this.manualCloseBannerCount);
                this.saveRecord();
            }
            onCmdSdkGetManualCloseBannerCount(e) {
                this.tryDailyReset();
                ULLog.console.log("ULModuleOppoQg.onCmdSdkGetManualCloseBannerCount", this.manualCloseBannerCount);
                e.setReturnValue(this.manualCloseBannerCount);
            }
            onCmdPhoneVibrate(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                if (!qg$e.vibrateShort || !qg$e.vibrateShort) {
                }
                let type = data.type || "short";
                switch (type) {
                    case "long":
                        this.vibrateLong(data);
                        break;
                    default:
                        this.vibrateShort(data);
                        break;
                }
            }
            vibrateShort(data) {
                qg$e.vibrateShort({
                    success: () => {
                        this.responsePhoneVibrate(1, "success", data);
                    },
                    fail: () => {
                        this.responsePhoneVibrate(0, "fail", data);
                    },
                    complete: () => {
                    }
                });
            }
            vibrateLong(data) {
                qg$e.vibrateLong({
                    success: () => {
                        this.responsePhoneVibrate(1, "success", data);
                    },
                    fail: () => {
                        this.responsePhoneVibrate(0, "fail", data);
                    },
                    complete: () => {
                    }
                });
            }
            responsePhoneVibrate(code, msg, data) {
                ULSdkManager.getInstance().response(ULConst.CMD_PHONE_VIBRATE_RESULT, {
                    code: code,
                    msg: msg,
                    userData: data.userData,
                    type: data.type,
                    intensity: data.intensity
                });
            }
            getChannelOpenIdFunc(callback) {
                ULLog.console.log("ULModuleOppoQg.getChannelOpenIdFunc");
                this.getUserInfoData({
                    success: (userInfoData) => {
                        callback && callback(userInfoData.openId, null);
                    },
                    fail: (err) => {
                        callback && callback(null, JSON.stringify(err));
                    }
                });
            }
            onCmdGetUserInfo(e) {
                e.stopImmediatePropagation();
                let data = e.data;
                let userData = data.userData || "";
                this.getUserInfoData({
                    success: (userInfoData) => {
                        ULLog.console.log("ULModuleOppoQg.onCmdGetUserInfo success:", userInfoData);
                        ULSdkManager.getInstance().response(ULConst.CMD_GET_USER_INFO_MSG_RESULT, {
                            code: 1,
                            msg: "获取用户信息成功",
                            userData: userData,
                            userInfo: userInfoData.userInfo
                        });
                    },
                    fail: (err) => {
                        ULLog.console.log("ULModuleOppoQg.onCmdGetUserInfo fail:", err);
                        ULSdkManager.getInstance().response(ULConst.CMD_GET_USER_INFO_MSG_RESULT, {
                            code: 0,
                            msg: JSON.stringify(err),
                            userData: userData
                        });
                    }
                });
            }
        }

        class ULSdkModuleLoader {
            static getObjectByModuleName(moduleName) {
                return ULSdkModuleLoader.moduleName_2_object[moduleName];
            }
            static getSubAdModuleClassName() {
                return ULSdkModuleLoader.moduleName_2_subAdvModuleClassName;
            }
            static getSubAdMainClassName() {
                return ULSdkModuleLoader.moduleName_2_subAdvMainClassName;
            }
            static initAllModules() {
                let modules = [];
                modules.push(new ULModuleCdk());
                modules.push(new ULModuleMegadata());
                modules.push(new ULModuleUserData());
                modules.push(new ULModuleClipboard());
                modules.push(new ULModuleDefault());
                modules.push(new ULModuleOppoQg());
                modules.push(new ULModulePrivacyPolicy());
                for (let i = 0, len = modules.length; i < len; i++) {
                    const module = modules[i];
                    let moduleClassName = module.className;
                    ULSdkModuleLoader.moduleName_2_subAdvModuleClassName[moduleClassName] = module.getSubAdModuleClassName();
                    ULSdkModuleLoader.moduleName_2_subAdvMainClassName[moduleClassName] = module.getAdMainClassName();
                }
                ULLog.console.log("ULSdkModuleLoader-moduleName_2_subAdvModuleClassName:", ULSdkModuleLoader.moduleName_2_subAdvModuleClassName);
                ULLog.console.log("ULSdkModuleLoader-moduleName_2_subAdvMainClassName:", ULSdkModuleLoader.moduleName_2_subAdvMainClassName);
                for (let i = 0; i < modules.length; i++) {
                    const module = modules[i];
                    let subModules = module.loadSubModules();
                    for (let j = 0; j < subModules.length; j++) {
                        const subModule = subModules[j];
                        modules.splice(i + 1, 0, subModule);
                        i++;
                    }
                }
                ULLog.console.log("ULSdkModuleLoader--modules:", modules);
                for (let i = 0; i < modules.length; i++) {
                    const module = modules[i];
                    ULSdkModuleLoader.moduleName_2_object[module.className] = module;
                    try {
                        ULLog.console.log("ULSdkModuleLoader--module.init:", module);
                        module.init();
                    }
                    catch (error) {
                        ULLog.console.error(error);
                    }
                }
                return modules;
            }
        }
        ULSdkModuleLoader.moduleName_2_object = {};
        ULSdkModuleLoader.moduleName_2_subAdvModuleClassName = {};
        ULSdkModuleLoader.moduleName_2_subAdvMainClassName = {};

        class ULWaitTool {
            constructor() {
                this.conditionMap = {};
            }
            ok() {
                if (ULTools.getObjSize(this.conditionMap) <= 0)
                    return true;
                return false;
            }
            getConditionMap() {
                let flags = [];
                ULTools.forEachMap(this.conditionMap, (k, v) => {
                    flags.push(k);
                });
                return flags;
            }
            addCondition(key) {
                this.conditionMap[key] = true;
            }
            removeCondition(key) {
                delete this.conditionMap[key];
            }
        }

        class ULChannelInfo {
            constructor() {
                this.waits = null;
                this._agreePrivacyPolicyCallBackList = [];
                this._isAgreePrivacyPolicy = false;
                this.copInfo = "{}";
                this.payInfo = {};
                this.jumpInfo = [];
                this.isSupportRecordShare = false;
                this.channelName = "default";
                this.isPayEnabled = false;
                this.isShareEnabled = false;
                this.isUseSdkRank = false;
                this.isShowUrlAdIcon = false;
                this.appName = "";
                this.equipmentModel = "";
                this.platformVersionMessage = "";
                this.osVersionMessage = "";
                this.cardType = 0;
                this.isThirdExit = false;
                this.isAbout = false;
                this.isMoreGame = false;
                this.isULMoreGame = false;
                this.isSupportClipboardData = false;
                this.isSupportInstallShortcut = false;
                this.isSupportFindMinigames = false;
                this.findMinigamesImageUrl = "";
                this.isSupportRecommendationBtn = false;
                this.isSupportJumpList = false;
                this.is4399Watermark = false;
                this.uuid = "";
                this.sdcardPath = "";
                this.packageVersion = "";
                this.copChannelId = "";
                this.ulsdkVersion = "";
                this.cdkChannelId = "";
                this._channelUserId = "";
                this.referenceBannerHeight = ULConst.DEFAULT_REFERANCE_BANNER_HEIGHT;
                this.isNewUser = true;
                this.loginDays = 0;
                this._sdkUserId = "";
                this.isSupportPasterAdv = false;
                this.gameLanguage = "";
                this.isSupportChannelMoreGameBox = false;
                this.isSupportChannelBlockAd = false;
                this.isSupportSubscribe = false;
                this.isSupportColorSign = false;
                this.isSupportGridAd = false;
                this.isSupportVideoRank = false;
                this.isSupportFavoriteGuide = false;
                this.isSupportFollowOfficialAccount = false;
                this.appIdOrPkgName = "";
                this.isSupportContentSecurityCheck = false;
                this.isJumpLeisureEnabled = false;
                this.isSupportVibrate = true;
                this.isSupportOpenUrl = false;
                this.isSupportJumpInfoVideoType = false;
                this.isSupportUserCloudStorage = false;
                this.isSupportJoinGroup = false;
                this.isSupportOpenData = false;
                this.isSupportMegadataEncrypt = true;
                this.weixinIOSPayEnabled = false;
                this.isSupportHeadlineImRank = false;
                this.isSupportLaunchReward = false;
                this.isSupportWXGameClub = false;
                this.getChannelOpenIdFunc = null;
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_CONFIG, ULConst.PRIORITY_NONE, this.onCmdSdkCollectionModuleCheckerConfig.bind(this));
                this.waits = new ULWaitTool();
            }
            onAgreePrivacyPolicy(callback) {
                if (this._isAgreePrivacyPolicy) {
                    callback();
                    return;
                }
                this._agreePrivacyPolicyCallBackList.push(callback);
            }
            get isAgreePrivacyPolicy() {
                return this._isAgreePrivacyPolicy;
            }
            set isAgreePrivacyPolicy(v) {
                if (this._isAgreePrivacyPolicy)
                    return;
                this._isAgreePrivacyPolicy = v;
                if (this._isAgreePrivacyPolicy) {
                    while (this._agreePrivacyPolicyCallBackList.length > 0) {
                        let callback = this._agreePrivacyPolicyCallBackList.shift();
                        callback();
                    }
                }
            }
            set channelUserId(v) {
                if (this._channelUserId == v)
                    return;
                this._channelUserId = v;
                if (!!this._channelUserId) {
                    setTimeout(() => {
                        ULSdkManager.getInstance().statisManager.reportUserChannelId(this._channelUserId);
                    }, 1000);
                }
            }
            get channelUserId() {
                return this._channelUserId;
            }
            toBaseChannelInfoData() {
                let config = ULConfig.getConfig();
                ULLog.console.log("config", config);
                let licenceInfo = config.s_sdk_licence_info == undefined ? "" : config.s_sdk_licence_info;
                licenceInfo = licenceInfo.replace(/\/n/g, "\n");
                let isShowAgeLevelInfo = !!config.i_sdk_age_level_info_mode;
                let ageLevelInfo = config.s_sdk_age_level_info || "";
                let result = {
                    gameName: config.s_game_name,
                    gameId: config.s_sdk_cop_game_id,
                    gameLanguage: this.gameLanguage,
                    channelName: this.channelName,
                    appName: this.appName,
                    isShowLicenceInfo: config.i_sdk_licence_info_mode == 1,
                    licenceInfo: licenceInfo,
                    isShowAgeLevelInfo: isShowAgeLevelInfo,
                    isStartGameByTouch: config.i_sdk_start_game_by_touch == 1,
                    isSupportUserCloudStorage: this.isSupportUserCloudStorage,
                };
                if (ageLevelInfo) {
                    result['ageLevelInfo'] = ageLevelInfo;
                }
                return result;
            }
            toResponseData() {
                let jumpInfo = [];
                for (let i = 0; i < this.jumpInfo.length; i++) {
                    const v = this.jumpInfo[i];
                    if (!v.index || !v.url) {
                        ULLog.console.warn("ULChannelInfo.toResponseData jump data error!", v);
                        continue;
                    }
                    jumpInfo.push({
                        index: v.index,
                        url: v.url,
                        rewards: v.rewards || [],
                        bReceived: v.bReceived || false,
                        appName: v.appName || ""
                    });
                }
                let config = ULConfig.getConfig();
                if (config.i_sdk_adv_reference_banner_height != null) {
                    this.referenceBannerHeight = config.i_sdk_adv_reference_banner_height;
                }
                this.isJumpLeisureEnabled = this.isJumpLeisureEnabled && !!config.i_sdk_moreWonderful_mode;
                this.isSupportInstallShortcut = this.isSupportInstallShortcut && !!config.i_sdk_installShortcut_mode;
                this.isSupportRecommendationBtn = this.isSupportRecommendationBtn && !!config.i_sdk_moregame_mode;
                this.isSupportJumpList = this.isSupportJumpList && !!config.i_sdk_jumplist_mode;
                this.isSupportVibrate = this.isSupportVibrate && !!config.i_sdk_phone_vibrate;
                this.isSupportOpenUrl = this.isSupportOpenUrl && !!config.i_sdk_support_open_url;
                this.isSupportRecordShare = this.isSupportRecordShare && !!config.i_sdk_support_record_share;
                this.isSupportSubscribe = this.isSupportSubscribe && !!config.i_sdk_subscribe_mode;
                this.isSupportJoinGroup = this.isSupportJoinGroup && !!config.i_sdk_joinGroup_mode;
                this.isPayEnabled = this.isPayEnabled && !!config.i_sdk_pay_mode;
                this.isShareEnabled = this.isShareEnabled && !!config.i_sdk_share_mode;
                this.isSupportLaunchReward = this.isSupportLaunchReward && !!config.i_sdk_launchReward_mode;
                if (this.weixinIOSPayEnabled) {
                    this.isPayEnabled = this.weixinIOSPayEnabled && !!config.i_sdk_pay_mode && !!config.i_sdk_weixin_iosPay_mode;
                }
                return {
                    copInfo: this.copInfo,
                    cardType: this.cardType,
                    isThirdExit: this.isThirdExit,
                    isAbout: this.isAbout,
                    payInfo: this.payInfo,
                    isMoreGame: this.isMoreGame,
                    isULMoreGame: this.isULMoreGame,
                    uuid: this.uuid,
                    sdcardPath: this.sdcardPath,
                    packageVersion: this.packageVersion,
                    copChannelId: this.copChannelId,
                    ulsdkVersion: this.ulsdkVersion,
                    isShowUrlAdIcon: this.isShowUrlAdIcon,
                    cdkChannelId: this.cdkChannelId,
                    isPayEnabled: this.isPayEnabled,
                    isShareEnabled: this.isShareEnabled,
                    isUseSdkRank: this.isUseSdkRank,
                    isSupportRecordShare: this.isSupportRecordShare,
                    isSupportInstallShortcut: this.isSupportInstallShortcut,
                    isSupportClipboardData: this.isSupportClipboardData,
                    isSupportFindMinigames: this.isSupportFindMinigames,
                    findMinigamesImageUrl: this.findMinigamesImageUrl,
                    isSupportRecommendationBtn: this.isSupportRecommendationBtn,
                    isSupportJumpList: this.isSupportJumpList,
                    is4399Watermark: this.is4399Watermark,
                    appName: this.appName.toLocaleLowerCase(),
                    jumpInfo: jumpInfo,
                    channelUserId: this.channelUserId,
                    referenceBannerHeight: this.referenceBannerHeight,
                    isNewUser: this.isNewUser,
                    loginDays: this.loginDays,
                    isSupportPasterAdv: this.isSupportPasterAdv,
                    gameLanguage: this.gameLanguage,
                    isSupportChannelMoreGameBox: this.isSupportChannelMoreGameBox,
                    isSupportChannelBlockAd: this.isSupportChannelBlockAd,
                    isSupportSubscribe: this.isSupportSubscribe,
                    isSupportGridAd: this.isSupportGridAd,
                    isSupportVideoRank: this.isSupportVideoRank,
                    isSupportFavoriteGuide: this.isSupportFavoriteGuide,
                    isSupportFollowOfficialAccount: this.isSupportFollowOfficialAccount,
                    customerServiceInfo: config.t_customer_service_info,
                    appIdOrPkgName: this.appIdOrPkgName,
                    isSupportContentSecurityCheck: this.isSupportContentSecurityCheck,
                    isJumpLeisureEnabled: this.isJumpLeisureEnabled,
                    isSupportVibrate: this.isSupportVibrate,
                    isSupportOpenUrl: this.isSupportOpenUrl,
                    isSupportJumpInfoVideoType: this.isSupportJumpInfoVideoType,
                    isSupportUserCloudStorage: this.isSupportUserCloudStorage,
                    isSupportJoinGroup: this.isSupportJoinGroup,
                    isSupportHeadlineImRank: this.isSupportHeadlineImRank,
                    isSupportOpenData: this.isSupportOpenData,
                    isSupportLaunchReward: this.isSupportLaunchReward,
                    isSupportWXGameClub: this.isSupportWXGameClub
                };
            }
            isReady() {
                return this.waits.ok();
            }
            getPreparationFlags() {
                return this.waits.getConditionMap();
            }
            addPreparationFlag(key) {
                this.waits.addCondition(key);
            }
            removePreparationFlag(key) {
                this.waits.removeCondition(key);
            }
            onCmdSdkCollectionModuleCheckerConfig(e) {
                let config = e.getReturnValue() || [];
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "渠道信息:" });
                config.push({ type: "newLine" });
                let text = "";
                let data = this.toResponseData();
                let keys = Object.keys(data);
                keys.sort();
                for (let i = 0; i < keys.length; i++) {
                    const key = keys[i];
                    let value = data[key];
                    text += ULTools.format("[%s] = [%s]\n", key, JSON.stringify(value));
                }
                config.push({ type: "labelArea", text: text });
                config.push({ type: "newLine" });
                e.setReturnValue(config, true);
            }
        }

        class MCConsts {
        }
        MCConsts.COP_CITY_ID_2_NAME = {
            "": "关闭城市模拟",
        };

        class ULCopManager {
            constructor() {
                this.localCop = {};
                this.serverCop = {};
                this.cop = {};
                this.copStrategySetting = {};
                this.simulateCityId = "";
                this.simulateTemplateId = "";
                this.useCopStrategyName = "";
            }
            init() {
                this.loadRecord();
                let config = ULConfig.getConfig();
                this.localCop = config.t_sdk_cop_default_cop;
                this.localCop = ULTools.jsonValToStr(this.localCop);
                ULLog.console.log(`ULCopManager-init-localCop:${JSON.stringify(this.localCop)}`);
                this.processCop();
                this.requestServerCop(false);
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_CONFIG, 10, this.onCmdSdkCollectionModuleCheckerConfig.bind(this));
            }
            loadRecord() {
                let recordStr = ULStorageManager.getInstance().getStorage(this._getRecordKey()) || "{}";
                let record;
                try {
                    record = JSON.parse(recordStr);
                }
                catch (error) {
                    record = {};
                }
                this.useCopStrategyName = record.useCopStrategyName || "";
                this.setSimulateCityId(record.simulateCityId || "");
                this.setSimulateTemplateId(record.simulateTemplateId || "");
            }
            saveRecord() {
                let record = {
                    simulateCityId: this.simulateCityId || "",
                    simulateTemplateId: this.simulateTemplateId || "",
                    useCopStrategyName: this.useCopStrategyName || ""
                };
                let recordStr = JSON.stringify(record);
                ULStorageManager.getInstance().setStorage(this._getRecordKey(), recordStr);
            }
            _getRecordKey() {
                let config = ULConfig.getConfig();
                return ULTools.format("ULCopManager_record_%d", config.s_sdk_megadata_game_id);
            }
            requestServerCop(bRetry) {
                let config = ULConfig.getConfig();
                if (!config.s_sdk_cop_game_id || config.s_sdk_cop_game_id == '0') {
                    ULLog.console.log("禁用cop");
                    return;
                }
                if (!bRetry) {
                    ULSdkManager.getInstance().channelInfo.addPreparationFlag("cop");
                }
                let cop_addr = config.s_sdk_cop_addr;
                if (!cop_addr) {
                    ULLog.console.log("cop地址为空");
                    return;
                }
                let cop_game_id = config.s_sdk_cop_game_id;
                let cop_channel_id = config.s_sdk_cop_channel_id;
                let cop_version = config.s_sdk_cop_version;
                let uid = ULSdkManager.getInstance().channelInfo._sdkUserId;
                var reg = RegExp(/^[0-9a-zA-Z_]{1,}$/);
                if (!reg.test(uid)) {
                    uid = "";
                }
                let netTimeout = config.i_net_timeout;
                let copUrl = ULTools.format("%s?gameid=%d&qudao=%d&version=%d&uid=%s", cop_addr, cop_game_id, cop_channel_id, cop_version, uid);
                if (this.simulateCityId || this.simulateTemplateId) {
                    ULLog.console.warn("使用debug模式cop地址");
                    copUrl = copUrl.replace("getdata/", "getdatadebug");
                    if (this.simulateCityId) {
                        copUrl += "&carrierid=0&zoneid=" + this.simulateCityId;
                    }
                    if (this.simulateTemplateId) {
                        copUrl += "&templateId=" + this.simulateTemplateId;
                    }
                }
                ULLog.console.log("ULCopManager.requestServerCop:", copUrl);
                ULTools.httpGet({
                    url: copUrl,
                    timeoutMillisecond: netTimeout,
                    success: (responseText) => {
                        let copJsonData = null;
                        try {
                            copJsonData = JSON.parse(responseText);
                            ULSdkManager.getInstance().statisManager.reportCopSuccess(responseText);
                        }
                        catch (error) {
                            ULLog.console.error(error);
                            ULSdkManager.getInstance().statisManager.reportCopFail(error.message);
                        }
                        ULLog.console.log("copJsonData", copJsonData);
                        if (copJsonData) {
                            this.serverCop = copJsonData;
                        }
                        else {
                            this.serverCop = {};
                        }
                        this.processCop();
                        this.triggerCopInfoResult();
                        if (!bRetry) {
                            ULSdkManager.getInstance().channelInfo.removePreparationFlag("cop");
                        }
                    },
                    fail: (err) => {
                        ULLog.console.warn("ULCopManager.requestServerCop http fail!", err);
                        if (!bRetry) {
                            ULSdkManager.getInstance().channelInfo.removePreparationFlag("cop");
                        }
                        ULSdkManager.getInstance().statisManager.reportCopFail("timeout");
                        ULTimer.callLater(ULConst.COP_RETRY_TIME_SEC, () => {
                            ULLog.console.log(ULTools.format("ULCopManager.requestServerCop 失败后，等待%d秒重新请求cop", ULConst.COP_RETRY_TIME_SEC));
                            this.requestServerCop(true);
                        });
                    },
                });
            }
            processCop() {
                let cop = {};
                ULTools.forEachMap(this.localCop, (k, v) => {
                    cop[k] = v;
                });
                ULTools.forEachMap(this.serverCop, (k, v) => {
                    if (k.substr(0, 2) == "i_" && !isNaN(parseFloat(v))) {
                        v = parseFloat(v);
                    }
                    if (k.substr(0, 2) == "t_") {
                        try {
                            v = JSON.parse(v);
                        }
                        catch (error) {
                            ULLog.console.log("processCop error --key:", k, " val:", v);
                            v = "";
                        }
                    }
                    cop[k] = v;
                });
                let config = ULConfig.getConfig();
                this.copStrategySetting = cop["t_sdk_cop_strategy_setting"] || config.t_sdk_cop_strategy_setting || {};
                if (this.useCopStrategyName && this.copStrategySetting[this.useCopStrategyName]) {
                    let copStrategy = this.copStrategySetting[this.useCopStrategyName] || {};
                    ULTools.forEachMap(copStrategy, (k, v) => {
                        if (k.substr(0, 2) == "i_" && !isNaN(parseFloat(v))) {
                            v = parseFloat(v);
                        }
                        if (k.substr(0, 2) == "t_" && typeof (v) !== "object") {
                            try {
                                v = JSON.parse(v);
                            }
                            catch (error) {
                                ULLog.console.log("processCop error --key:", k, " val:", v);
                                v = "";
                            }
                        }
                        cop[k] = v;
                    });
                    this.setUseStrategyName(this.useCopStrategyName);
                }
                ULLog.console.log("processCop.copresult cop:", cop);
                this.cop = cop;
                let channelInfoCop = ULTools.clone(this.cop);
                channelInfoCop["cop_game_id"] = config.s_sdk_cop_game_id || "unknown";
                channelInfoCop["cop_channel_id"] = config.s_sdk_cop_channel_id || "unknown";
                channelInfoCop["cop_version"] = config.s_sdk_cop_version || "unknown";
                ULSdkManager.getInstance().channelInfo.copInfo = JSON.stringify(channelInfoCop);
                ULConfig.updateValueByCop(this.cop);
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_COP_CHANGED, {});
            }
            get(key, defaultValue) {
                let value = this.cop[key];
                if (value == null) {
                    value = defaultValue;
                }
                return value;
            }
            getNumberValue(key, defaultValue) {
                let value = this.get(key, defaultValue);
                let numberValue = parseFloat(value);
                if (isNaN(numberValue))
                    return 0;
                return numberValue;
            }
            getNumberValueInRange(key, defaultValue, minValue, maxValue) {
                let value = this.getNumberValue(key, defaultValue);
                value = ULTools.clampf(value, minValue, maxValue);
                return value;
            }
            getBooleanValue(key, defaultValue) {
                let value = this.get(key, defaultValue);
                return value == true;
            }
            setSimulateCityId(cityId) {
                this.simulateCityId = cityId;
                this.saveRecord();
                if (cityId != "") {
                    let debugInfo = ULTools.format("已开启COP调试模式，模拟城市：%s_%s", cityId, ULConfig.getConfig().t_sdk_cop_simulate_city_data[cityId]);
                    ULSdkManager.getInstance().moduleCheckerManager.addDebugInfo("cop", debugInfo);
                }
                else {
                    ULSdkManager.getInstance().moduleCheckerManager.removeDebugInfo("cop");
                }
            }
            setSimulateTemplateId(templateId) {
                this.simulateTemplateId = templateId;
                this.saveRecord();
                if (templateId != "") {
                    let debugInfo = ULTools.format("已开启COP调试模式，模板id：%s", templateId);
                    ULSdkManager.getInstance().moduleCheckerManager.addDebugInfo("cop_templateId", debugInfo);
                }
                else {
                    ULSdkManager.getInstance().moduleCheckerManager.removeDebugInfo("cop_templateId");
                }
            }
            setUseStrategyName(useCopStrategyName) {
                this.useCopStrategyName = useCopStrategyName;
                this.saveRecord();
                if (useCopStrategyName != "") {
                    let debugInfo = ULTools.format("已选择COP策略，策略名：%s", useCopStrategyName);
                    ULSdkManager.getInstance().moduleCheckerManager.addDebugInfo("cop_useCopStrategyName", debugInfo);
                }
                else {
                    ULSdkManager.getInstance().moduleCheckerManager.removeDebugInfo("cop_useCopStrategyName");
                }
            }
            triggerCopInfoResult() {
                let referenceBannerHeight = ULConst.DEFAULT_REFERANCE_BANNER_HEIGHT;
                let config = ULConfig.getConfig();
                if (config.i_sdk_adv_reference_banner_height != null) {
                    referenceBannerHeight = config.i_sdk_adv_reference_banner_height;
                }
                ULSdkManager.getInstance().response(ULConst.CMD_COP_INFO_RESULT, {
                    copInfo: ULSdkManager.getInstance().channelInfo.copInfo,
                    referenceBannerHeight: referenceBannerHeight,
                });
            }
            onCmdSdkCollectionModuleCheckerConfig(e) {
                let config = e.getReturnValue() || [];
                let cityId_2_name = ULTools.clone(MCConsts.COP_CITY_ID_2_NAME);
                let cConfig = ULConfig.getConfig();
                if (cConfig.t_sdk_cop_simulate_city_data) {
                    ULLog.console.log("t_sdk_cop_simulate_city_data", cConfig.t_sdk_cop_simulate_city_data);
                    ULTools.forEachMap(cConfig.t_sdk_cop_simulate_city_data, (k, v) => {
                        cityId_2_name[k] = v;
                    });
                }
                ULLog.console.log("cityId_2_name", cityId_2_name);
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "Cop模块信息:" });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "Cop策略选择:" });
                config.push({ type: "label", name: "labelUseCopStrategyName", text: "(" + (this.useCopStrategyName || "已关闭") + ")" });
                config.push({
                    type: "button",
                    text: "策略选择",
                    onClick: () => {
                        let conf = [{ text: "关闭", value: "" }];
                        for (let key in this.copStrategySetting) {
                            conf.push({ text: key, value: key });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("选择策略", conf, (value) => {
                            this.useCopStrategyName = value;
                            this.saveRecord();
                            ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelUseCopStrategyName", this.useCopStrategyName || "已关闭");
                            if (value) {
                                ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("已打开cop 策略，将在下次启动游戏时生效");
                            }
                            else {
                                ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("已关闭cop 策略，将在下次启动游戏时生效");
                            }
                        });
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "cop调试模式 模板id：" });
                config.push({
                    type: "label",
                    text: this.simulateTemplateId ? ULTools.format("%s(已开启) ", this.simulateTemplateId) : "已关闭 ",
                    name: "labelCopTemplate",
                });
                config.push({
                    type: "inputBox",
                    name: "inputCopTemplate"
                });
                config.push({
                    type: "button",
                    text: "切换开关",
                    onClick: () => {
                        let templateId = "";
                        if (this.simulateTemplateId) {
                            templateId = "";
                        }
                        else {
                            templateId = ULSdkManager.getInstance().moduleCheckerManager.getItemText("inputCopTemplate");
                            if (!templateId) {
                                ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("请先设置 模板id");
                                return;
                            }
                        }
                        this.setSimulateTemplateId(templateId);
                        ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelCopTemplate", templateId ? ULTools.format("%s(已开启) ", templateId) : "已关闭 ");
                        ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("已开启cop调试模式，策略将在下次启动游戏时生效");
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "cop调试模式 城市id：" });
                config.push({
                    type: "label",
                    text: ULTools.format("%s_%s", this.simulateCityId, cityId_2_name[this.simulateCityId]),
                    name: "labelCopCity",
                });
                config.push({
                    type: "button",
                    text: "选择城市..",
                    onClick: () => {
                        let keys = Object.keys(cityId_2_name);
                        let ids = [];
                        for (let i = 0; i < keys.length; i++) {
                            const key = keys[i];
                            let id = parseInt(key);
                            if (!isNaN(id)) {
                                ids.push(id);
                            }
                        }
                        ids.sort((a, b) => {
                            return a - b;
                        });
                        ids.unshift("");
                        let conf1 = [];
                        for (let i = 0; i < Math.min(15, ids.length); i++) {
                            const cityId = ids[i];
                            conf1.push({ text: ULTools.format("%s_%s", cityId, cityId_2_name[cityId]), value: cityId });
                        }
                        conf1.push({ text: "加载其他城市...", "value": "more" });
                        let conf2 = [];
                        for (let i = 0; i < ids.length; i++) {
                            const cityId = ids[i];
                            conf2.push({ text: ULTools.format("%s_%s", cityId, cityId_2_name[cityId]), value: cityId });
                        }
                        let fOnSelectCity = (cityId) => {
                            if (cityId == "more") {
                                ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("选择需要模拟的城市：", conf2, fOnSelectCity);
                                return;
                            }
                            ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelCopCity", ULTools.format("%s_%s", cityId, cityId_2_name[cityId]));
                            this.setSimulateCityId(cityId);
                            if (cityId != "") {
                                ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("已开启cop调试模式，策略将在下次启动游戏时生效");
                            }
                            else {
                                ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("cop调试模式已关闭");
                            }
                        };
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("选择需要模拟的城市：", conf1, fOnSelectCity);
                    },
                });
                config.push({
                    type: "button",
                    text: "重新请求cop",
                    onClick: () => {
                        ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "重新请求cop不能保证所有功能生效，仅供查看cop使用。切换cop城市模拟后，请重新启动游戏测试功能", "知道了", () => {
                            ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("已重新请求cop，不能保证所有功能生效");
                            this.requestServerCop(false);
                        });
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "查看cop：" });
                config.push({
                    type: "button",
                    text: "默认cop",
                    onClick: () => {
                        let cop = this.localCop;
                        let keys = Object.keys(cop);
                        keys.sort();
                        let copInfo = "默认cop：\n";
                        for (let i = 0; i < keys.length; i++) {
                            const key = keys[i];
                            let value = cop[key];
                            copInfo += ULTools.format("[%s] = [%s]\n", key, value);
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelCop", copInfo);
                    },
                });
                config.push({
                    type: "button",
                    text: "远程cop",
                    onClick: () => {
                        let cop = this.serverCop;
                        let keys = Object.keys(cop);
                        keys.sort();
                        let copInfo = "远程cop：\n";
                        for (let i = 0; i < keys.length; i++) {
                            const key = keys[i];
                            let value = cop[key];
                            copInfo += ULTools.format("[%s] = [%s]\n", key, value);
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelCop", copInfo);
                    },
                });
                config.push({
                    type: "button",
                    text: "生效cop",
                    onClick: () => {
                        let cop = this.cop;
                        let keys = Object.keys(cop);
                        keys.sort();
                        let copInfo = "生效cop：\n";
                        for (let i = 0; i < keys.length; i++) {
                            const key = keys[i];
                            let value = cop[key];
                            copInfo += ULTools.format("[%s] = [%s]\n", key, value);
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelCop", copInfo);
                    },
                });
                config.push({ type: "newLine" });
                config.push({
                    type: "labelArea",
                    text: "<<这里显示cop信息>>",
                    name: "labelCop",
                });
                config.push({ type: "newLine" });
                e.setReturnValue(config, true);
            }
        }

        class ULStatisEventId {
        }
        ULStatisEventId.OPEN_SHARE = "100";
        ULStatisEventId.CLICK_SHARE = "101";
        ULStatisEventId.ADD_SUBSCRIPTION = "102";
        ULStatisEventId.CLICK_SUBSCRIPTION = "103";
        ULStatisEventId.CLICK_MORE_GAME_ICON_SINGLE = "104";
        ULStatisEventId.CLICK_MORE_GAME_ICON_REWARD = "105";
        ULStatisEventId.CLICK_MORE_GAME_ICON_LIST = "106";
        ULStatisEventId.CDK = "107";
        ULStatisEventId.CLICK_MORE_GAME_CHANNEL_SYSTEM_BUTTON = "108";
        ULStatisEventId.NATIVE_ADV_CLICK_EVENT = "109";
        ULStatisEventId.WEIXIN_TOUFANG = "200";
        ULStatisEventId.IOS_USERID_EVENT = "201";
        ULStatisEventId.REAL_NAME_AUTHENTICATION = "202";
        ULStatisEventId.LOGIN_EVENT = "203";
        ULStatisEventId.GAME_PACK_EVENT = "204";
        ULStatisEventId.INSTALLATION_SOURCE = "205";
        ULStatisEventId.OPPO_CUSTOM_EVENT = "206";
        ULStatisEventId.LAUNCH_SCENE = "300";
        ULStatisEventId.ADD_SHORTCUT = "301";
        ULStatisEventId.ADD_FAVORITES = "302";
        ULStatisEventId.NATIVE_ADV_DATA_UPLOAD_EVENT = "888";

        class ULStatisManager {
            constructor() {
                this.bUploading = false;
                this.lastTimerLoopTime = null;
                this.isGamePause = false;
                this.pointEventLog = {};
                this.pointEventCategoryId_2_enabled = null;
                this.gameStartDataPreparationFlags = {};
                this.commonEventLog = {};
                this.levelStartLog = {};
                this.levelCompletetLog = {};
                this.videoPointLog = {};
                this.buyActionLog = {};
                this.coinChangeLog = {};
                this._reportTimer = null;
            }
            init() {
                this.channelInfoUuid = ULSdkManager.getInstance().channelInfo.uuid;
                this.megadataId = ULConfig.getConfig().s_sdk_megadata_server_type_id;
                this.loadRecord();
                ULTimer.callLoop(ULConfig.getConfig().i_sdk_megadata_upload_span / 1000, this.onTimerLoop.bind(this));
                this.startTimeReportTimer();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_START, ULConst.PRIORITY_NONE, this.onCmdSdkOnGameStart.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_PAUSE, ULConst.PRIORITY_NONE, this.onCmdSdkOnGamePause.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_GAME_RESUME, ULConst.PRIORITY_NONE, this.onCmdSdkOnGameResume.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_ON_COP_CHANGED, ULConst.PRIORITY_NONE, this.onCmdSdkOnCopChanged.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_CONFIG, 9, this.onCmdSdkCollectionModuleCheckerConfig.bind(this));
            }
            loadRecord() {
                let recordStr = ULStorageManager.getInstance().getStorage(this._getRecordKey()) || "{}";
                let record;
                try {
                    record = JSON.parse(recordStr);
                }
                catch (error) {
                    record = {};
                }
                this.cacheItems = record.cacheItems || [];
                let mode = record.postMegadataTestMode || 0;
                this.postMegadataTestUserId = record.postMegadataTestUserId;
                this.setPostMegadataMode(mode);
            }
            saveRecord() {
                let record = {
                    cacheItems: this.cacheItems || [],
                    postMegadataTestUserId: this.postMegadataTestUserId,
                    postMegadataTestMode: this.postMegadataTestMode
                };
                let recordStr = JSON.stringify(record);
                ULStorageManager.getInstance().setStorage(this._getRecordKey(), recordStr);
            }
            _getRecordKey() {
                let config = ULConfig.getConfig();
                return ULTools.format("ULStatisManager_record_%d", config.s_sdk_megadata_game_id);
            }
            onTimerLoop(timer) {
                if (this.cacheItems.length <= 0) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("ULStatisManager.onTimerLoop no cacheItems");
                    return;
                }
                this.tryUploadToServer();
            }
            setPostMegadataMode(mode) {
                this.postMegadataTestMode = mode;
                this.saveRecord();
                if (!!this.postMegadataTestMode) {
                    this.channelInfoUuid = this.postMegadataTestUserId;
                    let debugInfo = "数据上传已开启测试模式\n测试用户id:" + this.postMegadataTestUserId;
                    ULSdkManager.getInstance().moduleCheckerManager.addDebugInfo("postMegadataTestModeInfo", debugInfo);
                }
                else {
                    this.channelInfoUuid = ULSdkManager.getInstance().channelInfo.uuid;
                    ULSdkManager.getInstance().moduleCheckerManager.removeDebugInfo("postMegadataTestModeInfo");
                }
            }
            getPostMegadataMode() {
                return this.postMegadataTestMode;
            }
            _report(typeid, updata) {
                let config = ULConfig.getConfig();
                let closeIds = config.s_sdk_megadata_close_table_type_ids || "";
                let closeIdsList = closeIds.split(";");
                for (let index = 0; index < closeIdsList.length; index++) {
                    let closeId = ULTools.format("%s-%s", this.megadataId, closeIdsList[index]);
                    if (closeId == typeid) {
                        ULLog.console.log("ULStatisManager._report 大数据分表控制表数据上传closeId:", closeId);
                        return;
                    }
                }
                ULLog.console.log("ULStatisManager._report i_sdk_megadata_mode 1 ", config.i_sdk_megadata_mode);
                try {
                    let otherItem = { typeid: typeid, updata: updata };
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_REPORT_ULSDK_EVENT, {
                        parameter: otherItem
                    });
                }
                catch (error) {
                    ULLog.console.log("ULStatisManager.CMD_SDK_ON_REPORT_ULSDK_EVENT error:", error);
                }
                if (!config.i_sdk_megadata_mode) {
                    ULLog.console.log("ULStatisManager._report !i_sdk_megadata_mode 关闭统计功能");
                    return;
                }
                if (!!this.postMegadataTestMode) {
                    let replaceVal = this.megadataId + "-";
                    typeid = typeid.replace(replaceVal, "1-");
                    ULLog.console.log("ULStatisManager._report postMegadataTestMode 已打开 typeid:", typeid);
                }
                if (updata.length == 0) {
                    ULLog.console.log("ULStatisManager._report !updata 无有效数据，无法上报:", updata);
                    return;
                }
                for (let i = 0; i < updata.length; i++) {
                    let v = updata[i];
                    if (typeof (v) != "string") {
                        if (v == null) {
                            v = "";
                        }
                        else {
                            v = "" + v;
                        }
                    }
                    updata[i] = v;
                }
                let item = { typeid: typeid, updata: updata };
                this.cacheItems.push(item);
                if (this.cacheItems.length >= ULConst.STATIS_UPLOAD_SINGLE_REQUEST_MAX_COUNT) {
                    this.tryUploadToServer();
                }
            }
            tryUploadToServer() {
                if (this.bUploading) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("ULStatisManager.tryUploadToServer 数据上传中");
                    return;
                }
                let uploadCount = Math.min(this.cacheItems.length, ULConst.STATIS_UPLOAD_SINGLE_REQUEST_MAX_COUNT);
                if (uploadCount <= 0) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("ULStatisManager.tryUploadToServer 没有数据需要上传");
                    return;
                }
                this.bUploading = true;
                let uploadItems = this.cacheItems.slice(0, uploadCount);
                this.cacheItems.splice(0, uploadCount);
                this.saveRecord();
                let config = ULConfig.getConfig();
                let url = config.s_sdk_megadata_url;
                if (!!this.postMegadataTestMode) {
                    url = config.s_sdk_megadata_test_url;
                }
                if (!url) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("ULStatisManager.tryUploadToServer url为空");
                    return;
                }
                if (ULSdkManager.getInstance().channelInfo.isSupportMegadataEncrypt && !!config.i_sdk_megadata_encrypt) {
                    ULTools.httpPostEncryption({
                        url: url,
                        postString: JSON.stringify(uploadItems),
                        timeoutMillisecond: config.i_net_timeout,
                        success: (responseText) => {
                            if (ULConst.B_INNER_DEBUG)
                                ULLog.console.log("  加密统计上报成功!");
                            this.bUploading = false;
                        },
                        fail: (err) => {
                            if (ULConst.B_INNER_DEBUG)
                                ULLog.console.log("  加密统计上报错误!", err);
                            this.cacheItems = uploadItems.concat(this.cacheItems);
                            this.saveRecord();
                            this.bUploading = false;
                        },
                    });
                    return;
                }
                let postData = "updata=" + JSON.stringify(uploadItems);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULStatisManager.tryUploadToServer");
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("  url:", url);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("  postData:", postData);
                postData = postData.replace(";", ",");
                ULTools.httpPost({
                    url: url,
                    postData: postData,
                    timeoutMillisecond: config.i_net_timeout,
                    success: (responseText) => {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("  统计上报成功!");
                        this.bUploading = false;
                    },
                    fail: (err) => {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("  统计上报错误!", err);
                        this.cacheItems = uploadItems.concat(this.cacheItems);
                        this.saveRecord();
                        this.bUploading = false;
                    },
                });
            }
            uploadToServerRightNow(typeid, updata) {
                let config = ULConfig.getConfig();
                let url = config.s_sdk_megadata_url;
                if (!config.i_sdk_megadata_mode) {
                    ULLog.console.log("ULStatisManager.uploadToServerRightNow !i_sdk_megadata_mode 关闭统计功能");
                    return;
                }
                if (!!this.postMegadataTestMode) {
                    url = config.s_sdk_megadata_test_url;
                    let replaceVal = this.megadataId + "-";
                    typeid = typeid.replace(replaceVal, "1-");
                    ULLog.console.log("ULStatisManager.uploadToServerRightNow postMegadataTestMode 已打开 typeid:", typeid);
                }
                let item = { typeid: typeid, updata: updata };
                let uploadItems = [];
                uploadItems.push(item);
                if (ULSdkManager.getInstance().channelInfo.isSupportMegadataEncrypt && !!config.i_sdk_megadata_encrypt) {
                    ULTools.httpPostEncryption({
                        url: url,
                        postString: JSON.stringify(uploadItems),
                        timeoutMillisecond: config.i_net_timeout,
                        success: (responseText) => {
                            if (ULConst.B_INNER_DEBUG)
                                ULLog.console.log("  统计上报成功!");
                        },
                        fail: (err) => {
                            if (ULConst.B_INNER_DEBUG)
                                ULLog.console.log("  统计上报错误!", err);
                        },
                    });
                    return;
                }
                let postData = "updata=" + JSON.stringify(uploadItems);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULStatisManager.uploadToServerRightNow");
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("  url:", url);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("  postData:", postData);
                ULTools.httpPost({
                    url: url,
                    postData: postData,
                    timeoutMillisecond: config.i_net_timeout,
                    success: (responseText) => {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("  统计上报成功!");
                    },
                    fail: (err) => {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("  统计上报错误!", err);
                    },
                });
            }
            genPointEventLog() {
                let rawLog = this.pointEventLog;
                let arr = [];
                let arr1 = [];
                ULTools.forEachMap(rawLog, (k, v) => {
                    let eventId = parseInt(k);
                    arr1.push({ eventId: eventId, v: v });
                });
                arr1 = ULTools.sortArrayByField(arr1, "eventId");
                for (let i = 0; i < arr1.length; i++) {
                    const v = arr1[i];
                    let arr2 = [];
                    ULTools.forEachMap(v.v, (k, count) => {
                        let paramId = parseInt(k);
                        arr2.push({ paramId: paramId, count: count });
                    });
                    arr2 = ULTools.sortArrayByField(arr2, "paramId");
                    for (let j = 0; j < arr2.length; j++) {
                        const vv = arr2[j];
                        arr.push(ULTools.format("%d-%d: %d", v.eventId, vv.paramId, vv.count));
                    }
                }
                return arr;
            }
            getCommonEventLog() {
                let arr = [];
                let keyArr = [];
                let rawLog = this.commonEventLog;
                ULLog.console.log("ULStatisManager.getCommonEventLog rawLog:", rawLog);
                ULTools.forEachMap(rawLog, (k, v) => {
                    keyArr.push(k);
                });
                keyArr.sort();
                for (let index = 0; index < keyArr.length; index++) {
                    let key = keyArr[index];
                    arr.push(ULTools.format("%s: %d", key, rawLog[key]));
                }
                return arr;
            }
            getLevelStartLog() {
                let arr = [];
                let keyArr = [];
                let rawLog = this.levelStartLog;
                ULLog.console.log("ULStatisManager.getLevelStartLog rawLog:", rawLog);
                ULTools.forEachMap(rawLog, (k, v) => {
                    keyArr.push(k);
                });
                keyArr.sort();
                for (let index = 0; index < keyArr.length; index++) {
                    let key = keyArr[index];
                    arr.push(ULTools.format("%s: %d", key, rawLog[key]));
                }
                return arr;
            }
            getLevelCompletetLog() {
                let arr = [];
                let keyArr = [];
                let rawLog = this.levelCompletetLog;
                ULLog.console.log("ULStatisManager.getLevelCompletetLog rawLog:", rawLog);
                ULTools.forEachMap(rawLog, (k, v) => {
                    keyArr.push(k);
                });
                keyArr.sort();
                for (let index = 0; index < keyArr.length; index++) {
                    let key = keyArr[index];
                    arr.push(ULTools.format("%s: %d   时长：%d", key, rawLog[key].count, rawLog[key].playTime));
                }
                return arr;
            }
            getVideoPointLog() {
                let arr = [];
                let keyArr = [];
                let rawLog = this.videoPointLog;
                ULLog.console.log("ULStatisManager.getVideoPointLog rawLog:", rawLog);
                ULTools.forEachMap(rawLog, (k, v) => {
                    keyArr.push(k);
                });
                keyArr.sort();
                for (let index = 0; index < keyArr.length; index++) {
                    let key = keyArr[index];
                    arr.push(ULTools.format("%s: %d", key, rawLog[key]));
                }
                return arr;
            }
            getBuyActionLog() {
                let arr = [];
                let keyArr = [];
                let rawLog = this.buyActionLog;
                ULLog.console.log("ULStatisManager.getBuyActionLog rawLog:", rawLog);
                ULTools.forEachMap(rawLog, (k, v) => {
                    keyArr.push(k);
                });
                keyArr.sort();
                for (let index = 0; index < keyArr.length; index++) {
                    let key = keyArr[index];
                    arr.push(ULTools.format("%s: %d", key, rawLog[key]));
                }
                return arr;
            }
            getCoinChangeLog() {
                let arr = [];
                let keyArr = [];
                let rawLog = this.coinChangeLog;
                ULLog.console.log("ULStatisManager.coinChangeLog rawLog:", rawLog);
                ULTools.forEachMap(rawLog, (k, v) => {
                    keyArr.push(k);
                });
                keyArr.sort();
                for (let index = 0; index < keyArr.length; index++) {
                    let key = keyArr[index];
                    arr.push(ULTools.format("%s  次数：%d   货币数量：%d", key, rawLog[key].count, rawLog[key].changeCount));
                }
                return arr;
            }
            isReady() {
                if (ULTools.getObjSize(this.gameStartDataPreparationFlags) <= 0)
                    return true;
                return false;
            }
            getPreparationFlags() {
                let flags = [];
                ULTools.forEachMap(this.gameStartDataPreparationFlags, (k, v) => {
                    flags.push(k);
                });
                return flags;
            }
            addPreparationFlag(key) {
                this.gameStartDataPreparationFlags[key] = true;
            }
            removePreparationFlag(key) {
                delete this.gameStartDataPreparationFlags[key];
            }
            setGameStartSourceMsg(param) {
                this.gameStartSourceMsg = param;
            }
            reportGameStart() {
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let config = ULConfig.getConfig();
                let typeid = ULTools.format("%s-%s", this.megadataId, ULConst.STATIS_TYPE_BASE_INFO);
                let updata = [];
                updata.push(this.gameStartTimeFormattedStr);
                updata.push(this.channelInfoUuid);
                updata.push("");
                updata.push("");
                updata.push("");
                updata.push(config.s_game_name);
                updata.push(config.s_sdk_cop_game_id);
                updata.push(channelInfo.appName);
                updata.push(config.s_sdk_cop_channel_id);
                updata.push(config.s_sdk_cop_version);
                updata.push(channelInfo.osVersionMessage || "");
                updata.push("gameStart");
                updata.push("");
                updata.push(config.s_sdk_version);
                updata.push(channelInfo.equipmentModel || "");
                updata.push(this.gameStartSourceMsg);
                updata.push(channelInfo.platformVersionMessage || "");
                updata.push("");
                updata.push("");
                updata.push("");
                this._report(typeid, updata);
            }
            reportPayRequest() {
                this.reportPayResult("", "", "requestPay");
            }
            reportPaySuccess(payType, priceCent) {
                let trimPriceCent = priceCent || 0;
                let strPrice = ULTools.format("%.2f", trimPriceCent / 100);
                this.reportPayResult(payType, strPrice, "success");
            }
            reportPayCancel(payType, priceCent) {
                let trimPriceCent = priceCent || 0;
                let strPrice = ULTools.format("%.2f", trimPriceCent / 100);
                this.reportPayResult(payType, strPrice, "cancel");
            }
            reportPayFail(payType, priceCent) {
                let trimPriceCent = priceCent || 0;
                let strPrice = ULTools.format("%.2f", trimPriceCent / 100);
                this.reportPayResult(payType, strPrice, "failed");
            }
            reportPayResult(payType, price, result) {
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let config = ULConfig.getConfig();
                let typeid = ULTools.format("%s-%s", this.megadataId, ULConst.STATIS_TYPE_PAY_INFO);
                let updata = [];
                updata.push(ULTools.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                updata.push(this.channelInfoUuid);
                updata.push("");
                updata.push(channelInfo.channelName);
                updata.push(payType || "");
                updata.push(price || "");
                updata.push(result || "");
                updata.push(config.s_sdk_cop_version);
                updata.push(config.s_sdk_version);
                this._report(typeid, updata);
            }
            reportAdvBranchRequest(advItem, channel, sdkAdvId) {
                advItem.statisChannelName = channel;
                advItem.statisSdkAdvId = sdkAdvId;
                this.reportAdvInfo(channel, advItem.showAdvType, "branchAdvRequest", "", advItem.advGroupId, advItem.advId, advItem.tag, "", sdkAdvId, "");
            }
            reportAdvTotalRequest(advItem) {
                this.reportAdvInfo("", advItem.advType, "totalAdvRequest", "", advItem.advGroupId, advItem.advId, advItem.tag, "", "", "");
            }
            reportAdvSuccess(advItem, nativeAdvTitle, actualShowCount = 1) {
                advItem.statisNativeAdTitle = nativeAdvTitle;
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "success", "", advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, "", actualShowCount.toString());
            }
            reportAdvClicked(advItem) {
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "clicked", "", advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, "");
            }
            reportAdvPlayStart(advItem) {
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "playStart", "", advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, "");
            }
            reportAdvPlayCompletion(advItem) {
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "playCompletion", "", advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, "");
            }
            reportAdvLoadAdvRequest(advItem) {
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "loadAdvRequest", "", advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, "");
            }
            reportAdvLoadAdvSuccess(advItem) {
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "loadAdvSuccess", "", advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, "");
            }
            reportAdvLoadAdvFailed(advItem, failMsg) {
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "loadAdvFailed", failMsg, advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, "");
            }
            reportAdvFail(advItem, failMsg) {
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "failed", failMsg, advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, "");
            }
            reportAdvClose(advItem, advShowTimeSec) {
                this.reportAdvInfo(advItem.statisChannelName, advItem.showAdvType, "hide", "", advItem.advGroupId, advItem.advId, advItem.tag, advItem.statisNativeAdTitle, advItem.statisSdkAdvId, advShowTimeSec);
            }
            reportAdvInfo(channel, advType, result, failMsg, advGroupId, advId, advEventInfo, nativeAdvInfo, sdkAdvId, advShowTimeSec, actualShowCount = "") {
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let config = ULConfig.getConfig();
                let typeid = ULTools.format("%s-%s", this.megadataId, ULConst.STATIS_TYPE_ADV_INFO);
                let updata = [];
                if (nativeAdvInfo && nativeAdvInfo.length > 6) {
                    nativeAdvInfo = nativeAdvInfo.substr(0, 6);
                }
                updata.push(ULTools.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                updata.push(this.channelInfoUuid);
                updata.push("");
                updata.push(channel || "");
                updata.push(advType || "");
                updata.push(result || "");
                updata.push(failMsg || "");
                updata.push(config.s_sdk_cop_version);
                updata.push(config.s_sdk_version);
                updata.push(advGroupId || "");
                updata.push(advId || "");
                updata.push(advEventInfo || "");
                updata.push(nativeAdvInfo || "");
                updata.push(sdkAdvId || "");
                updata.push(advShowTimeSec || "");
                updata.push("");
                updata.push(actualShowCount);
                ULLog.console.log("reportAdvInfo result:", result);
                if (result == 'hide') {
                    this.uploadToServerRightNow(typeid, updata);
                }
                else {
                    this._report(typeid, updata);
                }
            }
            reportCopSuccess(responseJson) {
                this.reportCopResult("success", "", responseJson);
            }
            reportCopFail(failMsg) {
                this.reportCopResult("filed", failMsg, "");
            }
            reportCopResult(result, failMsg, responseJson) {
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let config = ULConfig.getConfig();
                let typeid = ULTools.format("%s-%s", this.megadataId, ULConst.STATIS_TYPE_COP_REQUEST);
                let updata = [];
                responseJson = "";
                updata.push(ULTools.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                updata.push(this.channelInfoUuid);
                updata.push("");
                updata.push("coprequest");
                updata.push(result || "");
                updata.push(config.s_sdk_cop_version);
                updata.push(config.s_sdk_version);
                updata.push(failMsg || "");
                updata.push(responseJson || "");
                this._report(typeid, updata);
            }
            reportUserEvent(rawData) {
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let config = ULConfig.getConfig();
                let typeid = ULTools.format("%s-%s", this.megadataId, ULConst.STATIS_TYPE_USER_EVENT);
                let updata = [];
                updata.push(ULTools.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                updata.push(this.channelInfoUuid);
                updata.push("");
                for (let i = 0; i < rawData.length; i++) {
                    const v = rawData[i];
                    updata.push(v);
                }
                updata.push(config.s_sdk_cop_version);
                updata.push(config.s_sdk_version);
                updata.push(channelInfo.channelName);
                this._report(typeid, updata);
            }
            reportUserChannelId(channelId) {
                let config = ULConfig.getConfig();
                let typeid = ULTools.format("%s-%s", this.megadataId, ULConst.STATIS_TYPE_COMMON_EVENT);
                let updata = [];
                updata.push(ULStatisEventId.LOGIN_EVENT);
                updata.push("1");
                updata.push(channelId);
                updata.push("0");
                this.reportUserActionEvent(updata, typeid);
            }
            reportUserActionEvent(rawData, typeid) {
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let config = ULConfig.getConfig();
                let sdkIndexObj = {
                    levelStart: [0, 1, 2, 5, 6, 7],
                    levelComplete: [0, 1, 2, 11, 12, 13, 14],
                    coinChange: [0, 1, 2, 7, 8, 9],
                    itemBuy: [0, 1, 2, 6, 7, 8],
                    buyAction: [0, 1, 2, 6, 7, 8],
                    commonEvent: [0, 1, 2, 6, 7, 8],
                    videoPointEvent: [0, 1, 2, 5, 6, 7,],
                };
                let sdkValue = [
                    ULTools.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
                    this.channelInfoUuid,
                    "",
                    config.s_sdk_cop_version,
                    config.s_sdk_version,
                    channelInfo.copChannelId
                ];
                let updata = [];
                if (typeid == ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_COMMON_EVENT)) {
                    try {
                        rawData.length > 0 && ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_COMMONEVENT_ID_POST, { commonEventId: rawData[0] });
                    }
                    catch (error) { }
                    updata = this.rebuildData(sdkIndexObj.commonEvent, sdkValue, rawData);
                    let key = rawData[0] + "-" + rawData[1];
                    this.commonEventLog[key] = !!this.commonEventLog[key] ? (this.commonEventLog[key] + 1) : 1;
                }
                else if (typeid == ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_LEVEL_START_EVENT)) {
                    updata = this.rebuildData(sdkIndexObj.levelStart, sdkValue, rawData);
                    let key = rawData[0];
                    this.levelStartLog[key] = !!this.levelStartLog[key] ? (this.levelStartLog[key] + 1) : 1;
                }
                else if (typeid == ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_LEVEL_COMPLETE_EVENT)) {
                    try {
                        if (rawData.length >= 2) {
                            let state = rawData[1] || "0";
                            if (state == "1") {
                                let levelName = rawData[0] || "";
                                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_LEVELCOMPLETEEVENT_ID_POST, { levelCompleteEventId: levelName });
                            }
                        }
                    }
                    catch (error) { }
                    let key = rawData[0] + "-" + rawData[1];
                    if (!this.levelCompletetLog[key]) {
                        this.levelCompletetLog[key] = { count: 0, playTime: 0 };
                    }
                    this.levelCompletetLog[key].count = !!this.levelCompletetLog[key].count ? (this.levelCompletetLog[key].count + 1) : 1;
                    this.levelCompletetLog[key].playTime = !!this.levelCompletetLog[key].playTime ? (this.levelCompletetLog[key].playTime + parseInt(rawData[rawData.length - 1])) : parseInt(rawData[rawData.length - 1]);
                    let time = rawData.pop();
                    sdkValue.splice(3, 0, time);
                    updata = this.rebuildData(sdkIndexObj.levelComplete, sdkValue, rawData);
                }
                else if (typeid == ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_VIDEO_POINT_EVENT)) {
                    updata = this.rebuildData(sdkIndexObj.videoPointEvent, sdkValue, rawData);
                    let key = rawData[0] + "-" + rawData[1];
                    this.videoPointLog[key] = !!this.videoPointLog[key] ? (this.videoPointLog[key] + 1) : 1;
                }
                else if (typeid == ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_BUY_ACTION)) {
                    updata = this.rebuildData(sdkIndexObj.buyAction, sdkValue, rawData);
                    let key = rawData[0] + "-" + rawData[1] + "-" + rawData[2];
                    this.buyActionLog[key] = !!this.buyActionLog[key] ? (this.buyActionLog[key] + 1) : 1;
                }
                else if (typeid == ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_COIN_CHANGE_EVENT)) {
                    updata = this.rebuildData(sdkIndexObj.coinChange, sdkValue, rawData);
                    let key = rawData[0] + "-" + rawData[1] + "-" + rawData[3];
                    if (!this.coinChangeLog[key]) {
                        this.coinChangeLog[key] = { count: 0, changeCount: 0 };
                    }
                    this.coinChangeLog[key].count = !!this.coinChangeLog[key].count ? (this.coinChangeLog[key].count + 1) : 1;
                    this.coinChangeLog[key].changeCount = !!this.coinChangeLog[key].changeCount ? (this.coinChangeLog[key].changeCount + parseInt(rawData[2])) : parseInt(rawData[2]);
                }
                else if (typeid == ULTools.format("%s-%s", config.s_sdk_megadata_server_type_id, ULConst.STATIS_TYPE_ITEM_BUY)) {
                    updata = this.rebuildData(sdkIndexObj.itemBuy, sdkValue, rawData);
                }
                this._report(typeid, updata);
            }
            rebuildData(sdkIndex, sdkValue, rawData) {
                let mSdkIndex = ULTools.clone(sdkIndex);
                let mSdkValue = ULTools.clone(sdkValue);
                let mRawData = ULTools.clone(rawData);
                let updata = [];
                while (mSdkValue.length || mRawData.length) {
                    let index = mSdkIndex[0];
                    if (index == updata.length) {
                        updata.push(mSdkValue.shift());
                        mSdkIndex.shift();
                    }
                    else if (mRawData.length) {
                        updata.push(mRawData.shift());
                    }
                    else {
                        updata.push("");
                    }
                }
                return updata;
            }
            reportOnlineTime(onlineTimeSec) {
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let config = ULConfig.getConfig();
                let typeid = ULTools.format("%s-%s", this.megadataId, ULConst.STATIS_TYPE_ONLINE_TIME);
                let updata = [];
                updata.push(ULTools.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                updata.push(this.channelInfoUuid);
                updata.push("");
                updata.push(this.gameStartTimeFormattedStr || "");
                updata.push(onlineTimeSec.toString() || "0");
                updata.push(config.s_sdk_cop_version);
                updata.push(config.s_sdk_version);
                this.uploadToServerRightNow(typeid, updata);
            }
            reportShareSuccess(index) {
                let singleField = ["openShare", "success", index || 0].join("_");
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let megdataUrl = config.s_sdk_megadata_url || "";
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_MEGADATA_SERVER, ["commonEvent", singleField]);
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["open_share"] || "100", 1, index || 0]);
                }
            }
            reportShareFail(index) {
                let singleField = ["openShare", "fail", index || 0].join("_");
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let megdataUrl = config.s_sdk_megadata_url || "";
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_MEGADATA_SERVER, ["commonEvent", singleField]);
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["open_share"] || "100", 0, index || 0]);
                }
            }
            reportAppShare(index) {
                let singleField = ["openShare", "appShare", index || 0].join("_");
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let megdataUrl = config.s_sdk_megadata_url || "";
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_MEGADATA_SERVER, ["commonEvent", singleField]);
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["open_share"] || "100", 2, index || 0]);
                }
            }
            reportShareClick(queryMsg) {
                let singleField = ["clickShare", queryMsg || ""].join("_");
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let megdataUrl = config.s_sdk_megadata_url || "";
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_MEGADATA_SERVER, ["commonEvent", singleField]);
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["click_share"] || "101", queryMsg || "", ""]);
                }
            }
            reportAddSubcrible(code) {
                let singleField = ["addSubscrible", code || ""].join("_");
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let megdataUrl = config.s_sdk_megadata_url || "";
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_MEGADATA_SERVER, ["commonEvent", singleField]);
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["add_subscrible"] || "102", code || "", ""]);
                }
            }
            reportSubcribleClick(queryMsg) {
                let singleField = ["clickSubscrible", queryMsg || ""].join("_");
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let megdataUrl = config.s_sdk_megadata_url || "";
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_MEGADATA_SERVER, ["commonEvent", singleField]);
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["click_subscrible"] || "103", queryMsg || "", ""]);
                }
            }
            reportClickMoreGameIcon(iconType, gameIndex) {
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let eventId = sdkEventIds["click_more_game_icon_list"] || "106";
                if (iconType == "single") {
                    eventId = sdkEventIds["click_more_game_icon_single"] || "104";
                }
                else if (iconType == "reward") {
                    eventId = sdkEventIds["click_more_game_icon_reward"] || "105";
                }
                let megdataUrl = config.s_sdk_megadata_url || "";
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    this.reportPointEvent(eventId, parseInt(gameIndex));
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", eventId, gameIndex || "", ""]);
                }
            }
            reportClickMoreGameButtonToChannelSystem() {
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let eventId = sdkEventIds["click_more_game_channel_system_button"] || "108";
                let megdataUrl = config.s_sdk_megadata_url || "";
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    this.reportPointEvent(eventId, 0);
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", eventId, "", ""]);
                }
            }
            reportOpenCdk(code) {
                let singleField = ["openCdk", code].join("_");
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                let megdataUrl = config.s_sdk_megadata_url || "";
                ULLog.console.log("ULStatisManager.reportOpenCdk code:", code);
                if (megdataUrl.indexOf(`megadata.${ULTools.getCommonHost()}.cn`) >= 0) {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_MEGADATA_SERVER, ["commonEvent", singleField]);
                }
                else {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["open_cdk"] || "107", code || 0, ""]);
                }
            }
            reportJumpGame(eventId, channel, sourceGameId, type, targetIconId) {
                let config = ULConfig.getConfig();
                let openIds = config.s_sdk_jump_game_statis_game_indexes || "";
                let openIdsList = openIds.split(";");
                let openStatus = {};
                for (let index = 0; index < openIdsList.length; index++) {
                    openStatus[openIdsList[index]] = true;
                }
                let gameIndex = targetIconId.split("_")[0];
                if (!openStatus[gameIndex]) {
                    ULLog.console.log("ULStatisManager.reportJumpGame 当前跳转的游戏数据上报没开,targetIconId:", targetIconId);
                    return;
                }
                let typeid = config.s_sdk_megadata_server_jump_game_type_id;
                let updata = [];
                updata.push(eventId);
                updata.push(channel);
                updata.push(sourceGameId);
                updata.push(type);
                updata.push(targetIconId);
                this._report(typeid, updata);
            }
            reportToufang(aid, traceId) {
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["weixin_toufang"] || "200", aid, traceId]);
            }
            reportLaunchScene(scene) {
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["launch_scene"] || "300", scene, ""]);
            }
            reportCustomData(code, state = "", msg = "") {
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", code || "400", state || "", msg || ""]);
            }
            reportAddShortcut(code) {
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["add_shortcut"] || "301", code, ""]);
            }
            reportAddFavorites(code) {
                let config = ULConfig.getConfig();
                let sdkEventIds = config.t_sdk_common_event_ids || {};
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_POST_MEGADATA, ["commonEvent", sdkEventIds["add_favorites"] || "302", code, ""]);
            }
            _checkPointEventSwitch(eventId) {
                if (!this.pointEventCategoryId_2_enabled) {
                    let config = ULConfig.getConfig();
                    let arr = config.s_sdk_megadata_point_event_open_category_ids.split(";");
                    let pointEventCategoryId_2_enabled = {};
                    for (let i = 0; i < arr.length; i++) {
                        const categoryId = arr[i];
                        pointEventCategoryId_2_enabled[categoryId] = true;
                    }
                    this.pointEventCategoryId_2_enabled = pointEventCategoryId_2_enabled;
                }
                let categoryId = Math.floor(eventId / 1000);
                return !!this.pointEventCategoryId_2_enabled[categoryId];
            }
            reportPointEvent(eventId, param1) {
                eventId = parseInt(eventId) || 0;
                if (isNaN(eventId))
                    eventId = 0;
                eventId = ULTools.clampf(eventId, 0, 0xffff);
                param1 = parseInt(param1) || 0;
                if (isNaN(param1))
                    param1 = 0;
                param1 = ULTools.clampf(param1, 0, 0xffff);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULStatisManager.reportPointEvent", eventId, param1);
                if (!this._checkPointEventSwitch(eventId)) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("  打点统计上报未开启：", ULConfig.getConfig().s_sdk_megadata_point_event_open_category_ids);
                    return;
                }
                let shortUserId = "";
                let sdkUserId = ULSdkManager.getInstance().channelInfo._sdkUserId;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log(ULTools.format("  sdkUserId = [%s]", sdkUserId));
                let reg = /(\d+)_(.*)_(\d+)/;
                if (reg.test(sdkUserId)) {
                    shortUserId = RegExp.$2;
                    if (!shortUserId || shortUserId.length != 22) {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("  核心长度不匹配，直接使用sdkUserId");
                        shortUserId = sdkUserId;
                    }
                    else {
                        shortUserId = shortUserId.substr(2, shortUserId.length - 2);
                    }
                }
                else {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("  userId规则不匹配，直接使用sdkUserId");
                    shortUserId = sdkUserId;
                }
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log(ULTools.format("  shortUserId = [%s]", shortUserId));
                let channelInfo = ULSdkManager.getInstance().channelInfo;
                let config = ULConfig.getConfig();
                let typeid = ULTools.format("%s-%s", this.megadataId, ULConst.STATIS_TYPE_POINT_EVENT);
                let updata = [];
                updata.push(shortUserId);
                updata.push(config.s_sdk_cop_channel_id);
                updata.push(eventId.toString());
                updata.push(param1.toString());
                this._report(typeid, updata);
                let log = this.pointEventLog;
                let v = log[eventId];
                if (!v) {
                    v = {};
                    log[eventId] = v;
                }
                v[param1] = (v[param1] || 0) + 1;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("  log", log);
            }
            startTimeReportTimer() {
                let config0 = ULConfig.getConfig();
                let reportInterval = config0.n_sdk_common_online_time_report_looper_interval;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULStatiManager.startTimeReportTimer", reportInterval);
                if (this._reportTimer) {
                    clearInterval(this._reportTimer);
                    this._reportTimer = undefined;
                }
                let self = this;
                this._reportTimer = setInterval(() => {
                    if (!self.isGamePause) {
                        let onlineTime = ULTools.time() - self.gameLastResumeTime;
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.info("ULStatiManager.startTimeReportTimer,timer前台上报一次在线时长", onlineTime);
                        if (onlineTime <= 5 || onlineTime > 3600 * 24)
                            return;
                        self.gameLastResumeTime = ULTools.time();
                        self.reportOnlineTime(Math.floor(onlineTime));
                        let config = ULConfig.getConfig();
                        ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [config.s_sdk_miniplay_user_play_game_time_event_id || "", Math.floor(onlineTime)]);
                        self.saveRecord();
                    }
                }, 1000 * reportInterval);
            }
            onCmdSdkOnGameStart(e) {
                this.isGamePause = false;
                this.gameStartTimeFormattedStr = ULTools.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
                this.gameLastResumeTime = ULTools.time();
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULStatiManager.onCmdSdkOnGameStart", this.gameStartTimeFormattedStr, this.gameLastResumeTime);
                if (this.isReady()) {
                    this.reportGameStart();
                    this.tryUploadToServer();
                    return;
                }
                let flags = this.getPreparationFlags();
                ULLog.console.log("ULStatiManager.onCmdSdkOnGameStart 上报数据没有准备好,flags:", flags.join(","));
                let timeout = ULConfig.getConfig().i_game_start_ready_timeout / 1000;
                ULTimer.callLoop(1 / 60, (timer) => {
                    if (timer.usedTime >= timeout) {
                        timer.stop();
                        let flags = this.getPreparationFlags();
                        ULLog.console.log("ULStatiManager.onCmdSdkOnGameStart 等待超时！直接触发reportGameStart flags:", flags.join(","));
                        this.reportGameStart();
                        this.tryUploadToServer();
                        return;
                    }
                    if (this.isReady()) {
                        timer.stop();
                        ULLog.console.log("ULStatiManager.onCmdSdkOnGameStart 准备完毕！触发reportGameStart");
                        this.reportGameStart();
                        this.tryUploadToServer();
                        return;
                    }
                });
            }
            onCmdSdkOnGamePause(e) {
                this.isGamePause = true;
                if (!this.gameLastResumeTime) {
                    ULLog.console.warn("ULStatiManager.onCmdSdkOnGamePause gameLastResumeTime not found! 无法上报在线时间");
                    return;
                }
                let onlineTime = ULTools.time() - this.gameLastResumeTime;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULStatiManager.onCmdSdkOnGamePause", onlineTime);
                if (onlineTime <= 5 || onlineTime > 3600 * 24)
                    return;
                this.gameLastResumeTime = ULTools.time();
                this.reportOnlineTime(Math.floor(onlineTime));
                let config = ULConfig.getConfig();
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_CHANNEL_MEGADATA_POST, [config.s_sdk_miniplay_user_play_game_time_event_id || "", Math.floor(onlineTime)]);
                this.saveRecord();
            }
            onCmdSdkOnGameResume(e) {
                this.isGamePause = false;
                this.gameLastResumeTime = ULTools.time();
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULStatiManager.onCmdSdkOnGameResume", this.gameLastResumeTime);
            }
            onCmdSdkOnCopChanged(e) {
                this.pointEventCategoryId_2_enabled = null;
                this.startTimeReportTimer();
            }
            onCmdSdkCollectionModuleCheckerConfig(e) {
                let config = e.getReturnValue() || [];
                config.push({ type: "newLine" });
                let postDataModeLabelDescList = ["正式模式", "测试模式"];
                let postDataModeLabelDesc = "当前数据上传模式:" + postDataModeLabelDescList[this.postMegadataTestMode];
                config.push({ type: "label", text: postDataModeLabelDesc, name: "labelPostDataMode" });
                config.push({
                    type: "button",
                    text: "切换数据上传模式..",
                    onClick: () => {
                        let userId = ULSdkManager.getInstance().moduleCheckerManager.getItemText("labelPostTestModeUserId");
                        let conf1 = [];
                        conf1.push({ text: "测试模式 ( 用户id:" + userId + ")", value: 1 });
                        conf1.push({ text: "正式模式", value: 0 });
                        let fOnSelectCity = (isTestmode) => {
                            let postDataModeLabelDesc = "当前数据上传模式:" + postDataModeLabelDescList[this.postMegadataTestMode];
                            if (!!isTestmode) {
                                if (userId.length < 1) {
                                    ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("提示", "请设置测试用户id", "好的");
                                    return;
                                }
                                this.postMegadataTestUserId = userId;
                                ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("已开启测试模式");
                            }
                            else {
                                this.postMegadataTestUserId = null;
                                ULSdkManager.getInstance().moduleCheckerManager.showMsgTip("测试模式已关闭");
                            }
                            this.setPostMegadataMode(isTestmode);
                            ULSdkManager.getInstance().moduleCheckerManager.setItemText("labelPostDataMode", postDataModeLabelDesc);
                        };
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("切换数据上传模式:", conf1, fOnSelectCity);
                    },
                });
                config.push({ type: "newLine" });
                config.push({
                    type: "label",
                    text: "测试用户id",
                });
                config.push({
                    type: "inputBox",
                    text: this.postMegadataTestUserId,
                    name: "labelPostTestModeUserId"
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: `UUID: ${ULSdkManager.getInstance().channelInfo._sdkUserId}  ` });
                config.push({
                    type: "button",
                    text: "复制",
                    onClick: () => {
                        let userId = ULSdkManager.getInstance().channelInfo._sdkUserId;
                        ULClipboardManager.getInstance().setClipboardData(userId, (bSuccess) => {
                            if (bSuccess) {
                                ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "复制成功", "知道了", () => {
                                });
                            }
                            else {
                                ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "复制失败", "知道了", () => {
                                });
                            }
                        });
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: `渠道openId:      ` });
                config.push({
                    type: "button",
                    text: "请求",
                    onClick: () => {
                        let callback = (openId, msg) => {
                            if (!!openId) {
                                ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "获取成功\n" + openId, "复制", () => {
                                    ULClipboardManager.getInstance().setClipboardData(openId, (bSuccess) => {
                                        if (bSuccess) {
                                            ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "复制成功", "知道了", () => {
                                            });
                                        }
                                        else {
                                            ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "复制失败", "知道了", () => {
                                            });
                                        }
                                    });
                                });
                            }
                            else {
                                ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "获取失败\n" + msg, "知道了", () => {
                                });
                            }
                        };
                        let getChannelOpenIdFunc = ULSdkManager.getInstance().channelInfo.getChannelOpenIdFunc;
                        if (!!getChannelOpenIdFunc) {
                            ULLog.console.log("ULStatisManager.getOpenId getChannelOpenIdFunc");
                            getChannelOpenIdFunc((openId, err) => {
                                ULLog.console.log("ULStatisManager.getOpenId getChannelOpenIdFunc callback");
                                callback(openId, err);
                            });
                        }
                        else {
                            ULLog.console.log("ULStatisManager.getOpenId 该渠道暂不支持获取openId");
                            callback(null, "该渠道暂不支持获取openId");
                        }
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "游戏金手指:      " });
                config.push({
                    type: "button",
                    text: "验证",
                    onClick: () => {
                        let callback = (isCheck, msg) => {
                            if (isCheck) {
                                ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "验证通过", "知道了", () => {
                                    ULSdkManager.getInstance().response(ULConst.CMD_CHECKDEBUG_WHITEUSER_RESULT, {
                                        code: 1,
                                        isWhiteUser: true,
                                        msg: "当前用户是白名单用户"
                                    });
                                });
                            }
                            else {
                                ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("温馨提示", "验证失败\n" + msg, "知道了", () => {
                                });
                            }
                        };
                        if (ULSdkModuleLoader.getObjectByModuleName("ULModuleUlsdkDemo")) {
                            ULLog.console.log("ULModuleUlsdkDemo is Exit");
                            callback(true, "ULModuleUlsdkDemo is Exit");
                            return;
                        }
                        let networkCallback = (openId) => {
                            let gameId = ULConfig.getConfig().s_sdk_cop_game_id;
                            let channelId = ULConfig.getConfig().s_sdk_cop_channel_id;
                            let userId = ULSdkManager.getInstance().channelInfo._sdkUserId;
                            let netTimeout = ULConfig.getConfig().i_net_timeout;
                            let url = `https://sdkserver.${ULTools.getCommonHost()}.cn/checkwhiteuser?gameId=${gameId}&userId=${userId}&openId=${openId}&channelId=${channelId}&platform=H5`;
                            ULTools.httpGet({
                                url: url,
                                timeoutMillisecond: netTimeout,
                                success: (responseText) => {
                                    let jsonData = null;
                                    try {
                                        jsonData = JSON.parse(responseText);
                                    }
                                    catch (error) {
                                        jsonData = {
                                            code: 0,
                                            msg: "responseText"
                                        };
                                    }
                                    let code = jsonData.code || 0;
                                    let msg = jsonData.msg || "位置错误";
                                    callback(code == 1, msg);
                                },
                                fail: (err) => {
                                    callback(false, JSON.stringify(err));
                                }
                            });
                        };
                        let getChannelOpenIdFunc = ULSdkManager.getInstance().channelInfo.getChannelOpenIdFunc;
                        if (!!getChannelOpenIdFunc) {
                            ULLog.console.log("ULStatisManager.getOpenId getChannelOpenIdFunc");
                            getChannelOpenIdFunc((openId, err) => {
                                ULLog.console.log("ULStatisManager.getOpenId getChannelOpenIdFunc callback err:", err);
                                networkCallback(openId);
                            });
                        }
                        else {
                            ULLog.console.log("ULStatisManager.getOpenId 该渠道暂不支持获取openId");
                            networkCallback("");
                        }
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "清理游戏存档:      " });
                config.push({
                    type: "button",
                    text: "清理游戏存档",
                    onClick: () => {
                        ULSdkManager.getInstance().response(ULConst.CMD_CLEAN_UP_GAME_ARCHIVE, {});
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "跳过新手引导:      " });
                config.push({
                    type: "button",
                    text: "跳过新手引导",
                    onClick: () => {
                        ULSdkManager.getInstance().response(ULConst.CMD_JUMP_NEW_USER_GUIDE, {});
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "是否显示客户端打点信息界面开关:      " });
                config.push({ type: "newLine" });
                config.push({
                    type: "button",
                    text: "打开",
                    onClick: () => {
                        ULSdkManager.getInstance().response(ULConst.CMD_SHOW_POINT_DEBUG_INFO, { state: 1 });
                    },
                });
                config.push({
                    type: "button",
                    text: "关闭",
                    onClick: () => {
                        ULSdkManager.getInstance().response(ULConst.CMD_SHOW_POINT_DEBUG_INFO, { state: 0 });
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "打点统计记录:      " });
                config.push({
                    type: "button",
                    text: "点击查看..",
                    onClick: () => {
                        let log = this.genPointEventLog();
                        let conf = [];
                        for (let i = 0; i < log.length; i++) {
                            const line = log[i];
                            conf.push({ text: line, value: line });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("打点统计记录(事件id-状态：次数)：", conf, () => { }, true);
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "自定义统计记录:      " });
                config.push({
                    type: "button",
                    text: "点击查看..",
                    onClick: () => {
                        let log = this.getCommonEventLog();
                        let conf = [];
                        for (let i = 0; i < log.length; i++) {
                            const line = log[i];
                            conf.push({ text: line, value: line });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("自定义统计记录(事件id-状态：次数)：", conf, () => { }, true);
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "关卡开始统计记录:      " });
                config.push({
                    type: "button",
                    text: "点击查看..",
                    onClick: () => {
                        let log = this.getLevelStartLog();
                        let conf = [];
                        for (let i = 0; i < log.length; i++) {
                            const line = log[i];
                            conf.push({ text: line, value: line });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("关卡开始统计记录(关卡名：次数):", conf, () => { }, true);
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "关卡结束统计记录:      " });
                config.push({
                    type: "button",
                    text: "点击查看..",
                    onClick: () => {
                        let log = this.getLevelCompletetLog();
                        let conf = [];
                        for (let i = 0; i < log.length; i++) {
                            const line = log[i];
                            conf.push({ text: line, value: line });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("关卡结束统计记录(关卡名-结果-次数):", conf, () => { }, true);
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "视频埋点转化统计记录:      " });
                config.push({
                    type: "button",
                    text: "点击查看..",
                    onClick: () => {
                        let log = this.getVideoPointLog();
                        let conf = [];
                        for (let i = 0; i < log.length; i++) {
                            const line = log[i];
                            conf.push({ text: line, value: line });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("视频埋点转化统计记录(视频点-状态：次数)", conf, () => { }, true);
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "内购行为统计记录:      " });
                config.push({
                    type: "button",
                    text: "点击查看..",
                    onClick: () => {
                        let log = this.getBuyActionLog();
                        let conf = [];
                        for (let i = 0; i < log.length; i++) {
                            const line = log[i];
                            conf.push({ text: line, value: line });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("内购行为统计记录(弹出理由-商品名-结果)", conf, () => { }, true);
                    },
                });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: "货币统计记录:      " });
                config.push({
                    type: "button",
                    text: "点击查看..",
                    onClick: () => {
                        let log = this.getCoinChangeLog();
                        let conf = [];
                        for (let i = 0; i < log.length; i++) {
                            const line = log[i];
                            conf.push({ text: line, value: line });
                        }
                        ULSdkManager.getInstance().moduleCheckerManager.showPickerDialog("货币统计记录(货币名称-变化类型-变化原因)", conf, () => { }, true);
                    },
                });
                e.setReturnValue(config, true);
            }
        }

        class MCItem {
            initByData(data) {
                this.type = data.type;
                this.type = data.type || "newLine";
                this.name = data.name || "";
                this.text = data.text || "";
                this.width = data.width || 0;
                this.height = data.height || 0;
                this.fOnClick = data.onClick;
                this.fOnTextChanged = data.onTextChanged;
            }
            setText(text) {
                this.text = text;
                if (this.fOnTextChanged instanceof Function) {
                    this.fOnTextChanged(text);
                }
            }
            triggerOnClick() {
                if (this.fOnClick instanceof Function) {
                    this.fOnClick();
                }
            }
        }

        const BUTTON_WIDTH = 150;
        const BUTTON_HEIGHT = 40;
        const NEW_LINE_HEIGHT = 20;
        const FONT_SIZE = 20;
        const PENDING = 10;
        const GAP = 4;
        let _cc = window["cc"];
        class MCPanelCreator {
            constructor() {
                this.nodeReferenceRects = {};
                this.debugInfoRenderNode = null;
            }
            getNodeCanvas() {
                if (!_cc) {
                    ULLog.console.warn("MCPanelCreator.getNodeCanvas 未检测到creator环境！");
                    return null;
                }
                let scene = _cc.director.getScene();
                if (!scene) {
                    ULLog.console.warn("MCPanelCreator.getNodeCanvas scene not found!");
                    return null;
                }
                let check = ULConfig.getConfig().s_sdk_cocos2x_rootNode_check;
                if (check) {
                    let nodeCanvas = ULEvalExp.evalExpResults(check, (key) => {
                        if (key == "scene") {
                            return scene;
                        }
                        return null;
                    });
                    ULLog.console.log("MCPanelCreator.getNodeCanvas nodeCanvas ==" + nodeCanvas);
                    return nodeCanvas;
                }
                else {
                    let nodeCanvas = scene.getChildByName("Canvas");
                    ULLog.console.log("MCPanelCreator.getNodeCanvas nodeCanvas ==" + nodeCanvas);
                    return nodeCanvas;
                }
            }
            addFillerSprite(node, color) {
                let size = node.getContentSize();
                let sprite = node.addComponent(_cc.Sprite);
                sprite.sizeMode = _cc.Sprite.SizeMode.CUSTOM;
                sprite.type = _cc.Sprite.Type.SIMPLE;
                _cc.loader.loadRes("_ulsdk_ui/white_dot", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.addFillerSprite err!", err);
                        return;
                    }
                    sprite.spriteFrame = spriteFrame;
                    node.setContentSize(size);
                });
                node.color = color;
                node.opacity = color.getA();
            }
            registerTouchHandler(_node, handler, bEnableMultiTouch = false, bStopPropagation = true, bUseCapture = false) {
                let node = _node;
                if (!node)
                    return;
                if (!handler)
                    return;
                let fOnTouchBegan = (e) => {
                    let touchId = e.getID() || 0;
                    if (!bEnableMultiTouch && node.__touch_id != null)
                        return false;
                    e.name = "began";
                    if (bStopPropagation)
                        e.stopPropagation();
                    node.__touch_id = touchId;
                    handler(e);
                    return true;
                };
                let fOnTouchMoved = (e) => {
                    let touchId = e.getID() || 0;
                    if (!bEnableMultiTouch && touchId != node.__touch_id)
                        return;
                    e.name = "moved";
                    handler(e);
                };
                let fOnTouchEnded = (e) => {
                    let touchId = e.getID() || 0;
                    if (!bEnableMultiTouch && touchId != node.__touch_id)
                        return;
                    e.name = "ended";
                    node.__touch_id = null;
                    handler(e);
                };
                let fOnTouchCancelled = (e) => {
                    let touchId = e.getID() || 0;
                    if (!bEnableMultiTouch && touchId != node.__touch_id)
                        return;
                    e.name = "cancelled";
                    node.__touch_id = null;
                    handler(e);
                };
                node.on(_cc.Node.EventType.TOUCH_START, fOnTouchBegan, null, bUseCapture);
                node.on(_cc.Node.EventType.TOUCH_MOVE, fOnTouchMoved, null, bUseCapture);
                node.on(_cc.Node.EventType.TOUCH_END, fOnTouchEnded, null, bUseCapture);
                node.on(_cc.Node.EventType.TOUCH_CANCEL, fOnTouchCancelled, null, bUseCapture);
            }
            isTouchEventClick(e) {
                if (!(e.name == "ended" || e.name == "cancelled"))
                    return false;
                let p0 = e.getStartLocation();
                let p1 = e.getLocation();
                let dx = p0.x - p1.x;
                let dy = p0.y - p1.y;
                let distanceSq = dx * dx + dy * dy;
                return distanceSq <= 20 * 20;
            }
            createItemByData(data) {
                let item = new MCItem();
                item.initByData(data);
                let nodeContainer = this.nodeContainer;
                switch (data.type) {
                    case "label": {
                        let node = new _cc.Node();
                        node.parent = nodeContainer;
                        node.setAnchorPoint(0.5, 0.5);
                        node.on(_cc.Node.EventType.SIZE_CHANGED, () => {
                            item.width = node.width;
                            item.height = node.height;
                            this.onItemNodeResize();
                        });
                        node.addComponent(_cc.Label).string = item.text;
                        node.getComponent(_cc.Label).fontSize = FONT_SIZE;
                        node.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.LEFT;
                        node.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                        item.renderNode = node;
                        break;
                    }
                    case "labelArea": {
                        let node = new _cc.Node();
                        node.parent = nodeContainer;
                        node.setAnchorPoint(0.5, 0.5);
                        node.on(_cc.Node.EventType.SIZE_CHANGED, () => {
                            item.width = node.width;
                            item.height = node.height;
                            this.onItemNodeResize();
                        });
                        node.addComponent(_cc.Label).string = item.text;
                        node.getComponent(_cc.Label).fontSize = FONT_SIZE;
                        node.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.LEFT;
                        node.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                        node.getComponent(_cc.Label).overflow = _cc.Label.Overflow.RESIZE_HEIGHT;
                        node.width = nodeContainer.width - PENDING * 2;
                        node.height = FONT_SIZE;
                        item.renderNode = node;
                        break;
                    }
                    case "button": {
                        let node = new _cc.Node();
                        node.parent = nodeContainer;
                        node.on(_cc.Node.EventType.SIZE_CHANGED, () => {
                            item.width = node.width;
                            item.height = node.height;
                            this.onItemNodeResize();
                        });
                        node.width = item.width || BUTTON_WIDTH;
                        node.height = item.height || BUTTON_HEIGHT;
                        let nodeBg = new _cc.Node();
                        nodeBg.parent = node;
                        nodeBg.setContentSize(nodeBg.parent.getContentSize());
                        this.addFillerSprite(nodeBg, _cc.color(200, 200, 200, 255));
                        let nodeLabel = new _cc.Node();
                        nodeLabel.parent = node;
                        nodeLabel.setAnchorPoint(0.5, 0.5);
                        nodeLabel.addComponent(_cc.Label).string = item.text;
                        nodeLabel.getComponent(_cc.Label).fontSize = FONT_SIZE;
                        nodeLabel.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                        nodeLabel.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                        nodeLabel.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                        nodeLabel.width = node.width;
                        nodeLabel.height = node.height;
                        nodeLabel.color = _cc.Color.BLACK;
                        this.registerTouchHandler(node, (e) => {
                            switch (e.name) {
                                case "began":
                                    nodeLabel.color = _cc.Color.GREEN;
                                    break;
                                case "moved": break;
                                default:
                                    nodeLabel.color = _cc.Color.BLACK;
                                    break;
                            }
                            if (!this.isTouchEventClick(e))
                                return;
                            item.triggerOnClick();
                        });
                        item.renderNode = node;
                        break;
                    }
                    case "inputBox": {
                        let node = new _cc.Node();
                        node.parent = nodeContainer;
                        node.on(_cc.Node.EventType.SIZE_CHANGED, () => {
                            item.width = node.width;
                            item.height = node.height;
                            this.onItemNodeResize();
                        });
                        node.width = item.width || BUTTON_WIDTH;
                        node.height = item.height || BUTTON_HEIGHT;
                        let nodeBg = new _cc.Node();
                        nodeBg.parent = node;
                        nodeBg.setContentSize(nodeBg.parent.getContentSize());
                        this.addFillerSprite(nodeBg, _cc.color(200, 200, 200, 255));
                        let editBox = node.addComponent(_cc.EditBox);
                        editBox.fontSize = FONT_SIZE;
                        editBox.fontColor = _cc.Color.BLACK;
                        editBox.lineHeight = node.height;
                        editBox.inputMode = _cc.EditBox.InputMode.SINGLE_LINE;
                        editBox.maxLength = 1024;
                        editBox.placeholder = "<<输入框>>";
                        editBox.placeholderFontSize = FONT_SIZE;
                        editBox.placeholderFontColor = _cc.Color.GRAY;
                        let labels = node.getComponentsInChildren(_cc.Label);
                        for (let i = 0; i < labels.length; i++) {
                            const label = labels[i];
                            label.verticalAlign = _cc.Label.VerticalAlign.CENTER;
                        }
                        editBox.node.on("text-changed", () => {
                            let text = editBox.string;
                            item.setText(text);
                        });
                        item.renderNode = node;
                        break;
                    }
                    case "newLine": {
                        item.width = nodeContainer.width - PENDING * 2;
                        item.height = NEW_LINE_HEIGHT;
                        break;
                    }
                }
                return item;
            }
            doLayout() {
                if (!this.items)
                    return;
                let width = this.nodePanel.width - 20;
                let rowItems = [];
                let rowRight = PENDING;
                let rowTop = -PENDING;
                let rowHeight = 0;
                for (let i = 0; i < this.items.length; i++) {
                    let item = this.items[i];
                    let renderNode = item.renderNode || { x: 0, y: 0 };
                    if (rowRight + item.width > width) {
                        rowRight = 0;
                        for (let i = 0; i < rowItems.length; i++) {
                            const rowItem = rowItems[i];
                            let renderNode = rowItem.renderNode || { x: 0, y: 0 };
                            renderNode.y = rowTop - rowHeight / 2;
                        }
                        rowRight = PENDING;
                        rowTop -= rowHeight + GAP;
                        rowItems = [];
                        rowHeight = 0;
                    }
                    rowHeight = Math.max(rowHeight, item.height);
                    rowItems.push(item);
                    renderNode.x = rowRight + item.width / 2;
                    rowRight += item.width + GAP;
                }
                for (let i = 0; i < rowItems.length; i++) {
                    const rowItem = rowItems[i];
                    let renderNode = rowItem.renderNode || { x: 0, y: 0 };
                    renderNode.y = rowTop - rowHeight / 2;
                }
                rowTop -= rowHeight - PENDING;
                this.nodeContainer.height = Math.max(this.nodePanel.height, -rowTop);
            }
            onItemNodeResize() {
                this.doLayout();
            }
            getItemByName(name) {
                for (let i = 0; i < this.items.length; i++) {
                    const item = this.items[i];
                    if (item.name == name)
                        return item;
                }
                return null;
            }
            show(config) {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas)
                    return;
                let nodePanel = new _cc.Node();
                nodePanel.parent = nodeCanvas;
                nodePanel.setContentSize(nodeCanvas.getContentSize());
                nodePanel.zIndex = _cc.macro.MAX_ZINDEX;
                this.nodePanel = nodePanel;
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodePanel;
                nodeBg.setContentSize(nodeBg.parent.getContentSize());
                this.addFillerSprite(nodeBg, _cc.color(0, 0, 0, 191));
                this.registerTouchHandler(this.nodePanel, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                });
                let nodeContainer = new _cc.Node();
                nodeContainer.setAnchorPoint(0, 1);
                nodeContainer.parent = this.nodePanel;
                nodeContainer.setContentSize(nodeCanvas.getContentSize());
                this.nodeContainer = nodeContainer;
                let scrollView = this.nodePanel.addComponent(_cc.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.content = nodeContainer;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let items = [];
                for (let i = 0; i < config.length; i++) {
                    const data = config[i];
                    let item = this.createItemByData(data);
                    items.push(item);
                }
                this.items = items;
                this.doLayout();
            }
            close() {
                if (_cc.isValid(this.nodePanel)) {
                    this.nodePanel.destroy();
                }
                this.nodePanel = null;
                this.items = [];
            }
            getItemText(name) {
                let item = this.getItemByName(name);
                if (!item)
                    return "";
                return item.text;
            }
            setItemText(name, text) {
                let item = this.getItemByName(name);
                if (!item)
                    return;
                item.setText(text);
                let node = item.renderNode;
                if (node instanceof _cc.Node) {
                    let label = node.getComponent(_cc.Label) || node.getComponentInChildren(_cc.Label);
                    if (label) {
                        label.string = text;
                    }
                    let editBox = node.getComponent(_cc.EditBox) || node.getComponentInChildren(_cc.EditBox);
                    if (editBox) {
                        editBox.string = text;
                    }
                }
            }
            showMsgTip(text) {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas)
                    return;
                let nodeLabel = new _cc.Node();
                nodeLabel.parent = nodeCanvas;
                nodeLabel.width = nodeCanvas.width;
                nodeLabel.height = 20;
                nodeLabel.zIndex = _cc.macro.MAX_ZINDEX;
                let label = nodeLabel.addComponent(_cc.Label);
                label.string = text;
                label.fontSize = 20;
                label.enableWrapText = true;
                nodeLabel.x = 0;
                nodeLabel.y = nodeCanvas.height * 0.25;
                nodeLabel.runAction(_cc.sequence(_cc.moveBy(1.5, 0, 50), _cc.callFunc(() => {
                    nodeLabel.destroy();
                })));
            }
            showPickerDialog(title, conf, callback, bKeepDialogOpen) {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas)
                    return;
                let minCount = 8.5;
                let maxCount = 17.5;
                let dialogHeight = ULTools.scaleInRange(conf.length, minCount, maxCount, minCount * 40 + (minCount - 1) * 4 + 60, maxCount * 40 + (maxCount - 1) * 4 + 60);
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeCanvas;
                nodeShadow.setContentSize(nodeCanvas.getContentSize());
                nodeShadow.zIndex = _cc.macro.MAX_ZINDEX;
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    nodeShadow.destroy();
                });
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeShadow;
                nodeBg.setContentSize(nodeBg.parent.getContentSize());
                this.addFillerSprite(nodeBg, _cc.color(0, 0, 0, 127));
                let nodeDialog = new _cc.Node();
                nodeDialog.parent = nodeShadow;
                nodeDialog.width = nodeCanvas.width - 100;
                nodeDialog.height = dialogHeight;
                this.registerTouchHandler(nodeDialog, (e) => { });
                nodeBg = new _cc.Node();
                nodeBg.parent = nodeDialog;
                nodeBg.setContentSize(nodeBg.parent.getContentSize());
                this.addFillerSprite(nodeBg, _cc.color(167, 167, 167, 255));
                let nodeTitle = new _cc.Node();
                nodeTitle.parent = nodeDialog;
                nodeTitle.y = nodeDialog.height / 2 - 25;
                nodeTitle.x = 0;
                nodeTitle.addComponent(_cc.Label).string = title;
                nodeTitle.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).fontSize = 40;
                nodeTitle.width = nodeDialog.width - 10;
                nodeTitle.height = 40;
                let nodeListBg = new _cc.Node();
                nodeListBg.parent = nodeDialog;
                nodeListBg.width = nodeDialog.width - 10;
                nodeListBg.height = nodeDialog.height - 50;
                nodeListBg.x = 0;
                nodeListBg.y = -nodeDialog.height / 2 + nodeListBg.height / 2 + 5;
                this.addFillerSprite(nodeListBg, _cc.color(97, 97, 97, 255));
                let nodeList = new _cc.Node();
                nodeList.parent = nodeDialog;
                nodeList.width = nodeDialog.width - 10;
                nodeList.height = nodeDialog.height - 50;
                nodeList.x = 0;
                nodeList.y = -nodeDialog.height / 2 + nodeList.height / 2 + 5;
                nodeList.addComponent(_cc.Mask);
                let nodeContainer = new _cc.Node();
                nodeContainer.setAnchorPoint(0, 1);
                nodeContainer.parent = nodeList;
                nodeContainer.setContentSize(nodeList.getContentSize());
                let scrollView = nodeList.addComponent(_cc.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.content = nodeContainer;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let y = 0;
                for (let i = 0; i < conf.length; i++) {
                    const v = conf[i];
                    let nodeItem = new _cc.Node();
                    nodeItem.parent = nodeContainer;
                    nodeItem.width = nodeList.width;
                    nodeItem.height = 40;
                    nodeItem.x = nodeContainer.width / 2;
                    nodeItem.y = y - nodeItem.height / 2;
                    let nodeBg = new _cc.Node();
                    nodeBg.parent = nodeItem;
                    nodeBg.setContentSize(nodeBg.parent.getContentSize());
                    this.addFillerSprite(nodeBg, _cc.color(0, 0, 0, 63));
                    let nodeLabel = new _cc.Node();
                    nodeLabel.parent = nodeItem;
                    nodeLabel.setAnchorPoint(0, 0.5);
                    nodeLabel.x = -nodeItem.width / 2 + 5;
                    nodeLabel.y = 0;
                    let label = nodeLabel.addComponent(_cc.Label);
                    label.fontSize = FONT_SIZE;
                    label.lineHeight = FONT_SIZE;
                    label.verticalAlign = _cc.Label.VerticalAlign.CENTER;
                    label.horizontalAlign = _cc.Label.HorizontalAlign.LEFT;
                    label.string = v.text;
                    this.registerTouchHandler(nodeItem, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        callback(v.value);
                        if (!bKeepDialogOpen) {
                            nodeShadow.destroy();
                        }
                    });
                    y -= nodeItem.height + 4;
                }
                nodeContainer.height = Math.max(nodeList.height, -y);
            }
            showPromptDialog(title, content, btnTexts, callbacks) {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showPromptDialog nodeCanvas not found!");
                    ULTimer.callLater(0.1, () => {
                        this.showPromptDialog(title, content, btnTexts, callbacks);
                    });
                    return;
                }
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeCanvas;
                nodeShadow.setContentSize(nodeCanvas.getContentSize());
                nodeShadow.zIndex = _cc.macro.MAX_ZINDEX;
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("click bg");
                });
                let nodeSpriteBg = new _cc.Node();
                nodeSpriteBg.parent = nodeShadow;
                nodeSpriteBg.setContentSize(nodeSpriteBg.parent.getContentSize());
                this.addFillerSprite(nodeSpriteBg, _cc.color(0, 0, 0, 127));
                let bManualDestroy = false;
                let triggerNode = new _cc.Node();
                triggerNode.parent = nodeShadow;
                let component = triggerNode.addComponent(_cc.Component);
                component["onDestroy"] = () => {
                    ULLog.console.log("MCPanelCreator.showPromptDialog triggerNode onDestroy", bManualDestroy);
                    if (!bManualDestroy) {
                        ULLog.console.log("MCPanelCreator.showPromptDialog nodeShadow被意外销毁，0.1秒后尝试重新创建提示");
                        ULTimer.callLater(0.1, () => {
                            this.showPromptDialog(title, content, btnTexts, callbacks);
                        });
                    }
                };
                let nodeDialog = new _cc.Node();
                nodeDialog.parent = nodeShadow;
                nodeDialog.width = 460;
                nodeDialog.height = 320;
                this.registerTouchHandler(nodeDialog, (e) => { });
                let nodeDialogBg = new _cc.Node();
                nodeDialogBg.parent = nodeDialog;
                nodeDialogBg.setContentSize(nodeDialogBg.parent.getContentSize());
                _cc.loader.loadRes("_ulsdk_ui/bg_01", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showPromptDialog nodeDialogBg load sprite error", err);
                        return;
                    }
                    let nodeSize = nodeDialogBg.getContentSize();
                    let frameSize = spriteFrame.getOriginalSize();
                    spriteFrame.insetLeft = frameSize.width / 3;
                    spriteFrame.insetRight = frameSize.width / 3;
                    spriteFrame.insetTop = frameSize.height / 3;
                    spriteFrame.insetBottom = frameSize.height / 3;
                    let sprite = nodeDialogBg.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    sprite.type = _cc.Sprite.Type.SLICED;
                    sprite.sizeMode = _cc.Sprite.SizeMode.CUSTOM;
                    nodeDialogBg.setContentSize(nodeSize);
                });
                let nodeTitle = new _cc.Node();
                nodeTitle.parent = nodeDialog;
                nodeTitle.y = nodeDialog.height / 2 - 45;
                nodeTitle.x = 0;
                nodeTitle.color = _cc.color(38, 38, 38, 255);
                nodeTitle.addComponent(_cc.Label).string = title || "标题";
                nodeTitle.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).fontSize = 32;
                nodeTitle.width = nodeDialog.width - 10;
                nodeTitle.height = 40;
                let nodeContent = new _cc.Node();
                nodeContent.parent = nodeDialog;
                nodeContent.y = nodeDialog.height / 2 - 155;
                nodeContent.x = 0;
                nodeContent.color = _cc.color(96, 96, 96, 255);
                nodeContent.addComponent(_cc.Label).string = content || "内容";
                nodeContent.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeContent.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                nodeContent.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                nodeContent.getComponent(_cc.Label).fontSize = 24;
                nodeContent.width = nodeDialog.width - 50;
                nodeContent.height = 160;
                let btnWidth = 160;
                let btnHeight = 56;
                let btnGap = 30;
                let left = -(btnTexts.length * btnWidth + (btnTexts.length - 1) * btnGap) / 2;
                let nodeButtons = [];
                for (let i = 0; i < btnTexts.length; i++) {
                    const text = btnTexts[i];
                    let nodeButton = new _cc.Node();
                    nodeButton.parent = nodeDialog;
                    nodeButton.x = left + btnWidth * (i + 0.5) + btnGap * (i);
                    nodeButton.y = -nodeDialog.height / 2 + 50;
                    nodeButton.setContentSize(btnWidth, btnHeight);
                    nodeButtons.push(nodeButton);
                    let nodeButtonBg = new _cc.Node();
                    nodeButtonBg.parent = nodeButton;
                    nodeButtonBg.setContentSize(nodeButton.getContentSize());
                    _cc.loader.loadRes("_ulsdk_ui/btn_01", _cc.SpriteFrame, (err, spriteFrame) => {
                        if (err) {
                            ULLog.console.warn("MCPanelCreator.showPromptDialog nodeButtonBg load sprite error", err);
                            return;
                        }
                        let nodeSize = nodeButtonBg.getContentSize();
                        let frameSize = spriteFrame.getOriginalSize();
                        spriteFrame.insetLeft = frameSize.width / 3;
                        spriteFrame.insetRight = frameSize.width / 3;
                        spriteFrame.insetTop = frameSize.height / 3;
                        spriteFrame.insetBottom = frameSize.height / 3;
                        let sprite = nodeButtonBg.addComponent(_cc.Sprite);
                        sprite.spriteFrame = spriteFrame;
                        sprite.type = _cc.Sprite.Type.SLICED;
                        sprite.sizeMode = _cc.Sprite.SizeMode.CUSTOM;
                        nodeButtonBg.setContentSize(nodeSize);
                    });
                    let nodeButtonText = new _cc.Node();
                    nodeButtonText.parent = nodeButton;
                    nodeButtonText.y = 0;
                    nodeButtonText.x = 0;
                    nodeButtonText.color = _cc.color(255, 255, 255, 255);
                    nodeButtonText.addComponent(_cc.Label).string = text || "按钮" + (i + 1);
                    nodeButtonText.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                    nodeButtonText.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                    nodeButtonText.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                    nodeButtonText.getComponent(_cc.Label).fontSize = 30;
                    nodeButtonText.width = nodeButtonBg.width - 10;
                    nodeButtonText.height = nodeButtonBg.height - 10;
                    this.registerTouchHandler(nodeButton, (e) => {
                        if (e.name == "began") {
                            nodeButton.scale = 1.1;
                        }
                        else if (e.name == "moved") {
                        }
                        else {
                            nodeButton.scale = 1;
                        }
                        if (this.isTouchEventClick(e)) {
                            let callback = callbacks[i];
                            if (callback instanceof Function) {
                                let bDonotClose = callback();
                                if (!bDonotClose) {
                                    bManualDestroy = true;
                                    nodeShadow.destroy();
                                }
                            }
                            else {
                                bManualDestroy = true;
                                nodeShadow.destroy();
                            }
                        }
                    });
                }
            }
            showWebView(title, url, replaceParam) {
                this.closeWebView();
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    return;
                }
                console.log(`showWebView title:${title} url:${url} replaceParam:${replaceParam}`);
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(2048, 2048);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX;
                this.showWebViewNode = nodeBg;
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeBg;
                nodeShadow.setContentSize(nodeBg.getContentSize());
                this.addFillerSprite(nodeShadow, _cc.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    this.closeWebView();
                });
                let contentNode = new _cc.Node();
                contentNode.parent = nodeBg;
                let width = Math.min(nodeCanvas.width * 0.8, 500);
                let height = Math.min(nodeCanvas.height * 0.8, 800);
                if (nodeCanvas.width > nodeCanvas.height) {
                    width = Math.min(nodeCanvas.width * 0.8, 800);
                    height = Math.min(nodeCanvas.height * 0.8, 500);
                }
                contentNode.setContentSize(width, height);
                _cc.loader.loadRes("_ulsdk_ui/bg_01", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showWebView nodeDialogBg load sprite error", err);
                        return;
                    }
                    let nodeSize = contentNode.getContentSize();
                    let frameSize = spriteFrame.getOriginalSize();
                    spriteFrame.insetLeft = frameSize.width / 3;
                    spriteFrame.insetRight = frameSize.width / 3;
                    spriteFrame.insetTop = frameSize.height / 3;
                    spriteFrame.insetBottom = frameSize.height / 3;
                    let sprite = contentNode.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    sprite.type = _cc.Sprite.Type.SLICED;
                    sprite.sizeMode = _cc.Sprite.SizeMode.CUSTOM;
                    contentNode.setContentSize(nodeSize);
                });
                let nodeTitle = new _cc.Node();
                nodeTitle.parent = contentNode;
                nodeTitle.color = _cc.color(38, 38, 38, 255);
                nodeTitle.addComponent(_cc.Label).string = title;
                nodeTitle.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).fontSize = 32;
                nodeTitle.width = width - 10;
                nodeTitle.height = 40;
                nodeTitle.y = height / 2 - 40;
                nodeTitle.x = 0;
                let nodeScrollView = new _cc.Node();
                nodeScrollView.parent = contentNode;
                nodeScrollView.setContentSize(width - 50, height - 80);
                nodeScrollView.x = 0;
                nodeScrollView.y = -20;
                let scrollView = nodeScrollView.addComponent(_cc.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let nodeMask = new _cc.Node();
                nodeMask.parent = nodeScrollView;
                nodeMask.setContentSize(nodeScrollView.getContentSize());
                nodeMask.addComponent(_cc.Mask).type = _cc.Mask.Type.RECT;
                nodeMask.getComponent(_cc.Mask).inverted = false;
                let nodeContent = new _cc.Node();
                nodeContent.parent = nodeMask;
                nodeContent.setAnchorPoint(0.5, 1);
                nodeContent.setContentSize(nodeScrollView.getContentSize());
                let maskLayout = nodeContent.addComponent(_cc.Layout);
                maskLayout.type = _cc.Layout.Type.VERTICAL;
                maskLayout.resizeMode = _cc.Layout.ResizeMode.CONTAINER;
                scrollView.content = nodeContent;
                ULTools.httpGet({
                    url: url,
                    timeoutMillisecond: 5000,
                    success: (responseText) => {
                        let content = responseText;
                        try {
                            let resultObj = JSON.parse(responseText);
                            content = resultObj.policyText;
                        }
                        catch (error) {
                        }
                        if (replaceParam) {
                            for (let key in replaceParam) {
                                let value = replaceParam[key];
                                let regExp = new RegExp(`\\\${\\s*${key}\\s*}`, 'g');
                                content = content.replace(regExp, value);
                            }
                        }
                        ULLog.console.log("content:", content);
                        let nodeLabel = new _cc.Node();
                        nodeLabel.color = _cc.color(0, 0, 0, 255);
                        nodeLabel.parent = nodeContent;
                        nodeLabel.setAnchorPoint(0.5, 1);
                        let label = nodeLabel.addComponent(_cc.Label);
                        label.string = content;
                        label.overflow = _cc.Label.Overflow.RESIZE_HEIGHT;
                        label.verticalAlign = _cc.Label.VerticalAlign.TOP;
                        label.horizontalAlign = _cc.Label.HorizontalAlign.LEFT;
                        label.fontSize = 18;
                        label.lineHeight = 26;
                        let trimLabel = label;
                        let trimClass = _cc.Label;
                        if (trimLabel.cacheMode != undefined && trimClass.CacheMode != undefined) {
                            let mode = trimLabel.cacheMode;
                            try {
                                trimLabel.cacheMode = trimClass.CacheMode.CHAR;
                            }
                            catch (error) {
                                trimLabel.cacheMode = mode;
                            }
                        }
                        nodeLabel.setContentSize(nodeContent.getContentSize());
                    },
                    fail: () => {
                    }
                });
            }
            closeWebView() {
                if (_cc.isValid(this.showWebViewNode)) {
                    this.showWebViewNode["__b_manual_destroy"] = true;
                    this.showWebViewNode.destroy();
                }
                this.showWebViewNode = null;
            }
            showPrivacyContent(title, url, replaceParam) {
                this.showWebView(title, url, replaceParam);
            }
            showPrivacyDialog(title, contentArray, btnTexts, callbacks) {
                ULLog.console.log("MCPanelCreator.showPrivacyDialog");
                if (this.showPrivacyNode) {
                    return;
                }
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showPrivacyDialog nodeCanvas not found!");
                    ULTimer.callLater(0.1, () => {
                        this.showPrivacyDialog(title, contentArray, btnTexts, callbacks);
                    });
                    return;
                }
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(2048, 2048);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX;
                this.showPrivacyNode = nodeBg;
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeBg;
                nodeShadow.setContentSize(nodeBg.getContentSize());
                this.addFillerSprite(nodeShadow, _cc.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("click bg");
                });
                let bManualDestroy = false;
                let triggerNode = new _cc.Node();
                triggerNode.parent = nodeShadow;
                let component = triggerNode.addComponent(_cc.Component);
                component["onDestroy"] = () => {
                    ULLog.console.log("MCPanelCreator.showPrivacyDialog triggerNode onDestroy", bManualDestroy);
                    this.showPrivacyNode = null;
                    if (!bManualDestroy) {
                        ULLog.console.log("MCPanelCreator.showPrivacyDialog nodeShadow被意外销毁，0.1秒后尝试重新创建提示");
                        ULTimer.callLater(1 / 60, () => {
                            ULLog.console.log("ontimer");
                            this.showPrivacyDialog(title, contentArray, btnTexts, callbacks);
                        });
                    }
                };
                let contentNode = new _cc.Node();
                contentNode.parent = nodeBg;
                let width = 450;
                let height = 450;
                contentNode.setContentSize(width, height);
                _cc.loader.loadRes("_ulsdk_ui/bg_01", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showPrivacyDialog nodeDialogBg load sprite error", err);
                        return;
                    }
                    let nodeSize = contentNode.getContentSize();
                    let frameSize = spriteFrame.getOriginalSize();
                    spriteFrame.insetLeft = frameSize.width / 3;
                    spriteFrame.insetRight = frameSize.width / 3;
                    spriteFrame.insetTop = frameSize.height / 3;
                    spriteFrame.insetBottom = frameSize.height / 3;
                    let sprite = contentNode.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    sprite.type = _cc.Sprite.Type.SLICED;
                    sprite.sizeMode = _cc.Sprite.SizeMode.CUSTOM;
                    contentNode.setContentSize(nodeSize);
                });
                let nodeTitle = new _cc.Node();
                nodeTitle.parent = contentNode;
                nodeTitle.color = _cc.color(0, 0, 0, 255);
                nodeTitle.addComponent(_cc.Label).string = "隐私政策";
                nodeTitle.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).fontSize = 32;
                nodeTitle.width = width - 10;
                nodeTitle.height = 40;
                nodeTitle.y = height / 2 - 40;
                nodeTitle.x = 0;
                let nodeScrollView = new _cc.Node();
                nodeScrollView.parent = contentNode;
                nodeScrollView.setContentSize(width - 50, height - 140);
                nodeScrollView.x = 0;
                nodeScrollView.y = 3;
                let scrollView = nodeScrollView.addComponent(_cc.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let nodeMask = new _cc.Node();
                nodeMask.parent = nodeScrollView;
                nodeMask.setContentSize(nodeScrollView.getContentSize());
                nodeMask.addComponent(_cc.Mask).type = _cc.Mask.Type.RECT;
                nodeMask.getComponent(_cc.Mask).inverted = false;
                let nodeContent = new _cc.Node();
                nodeContent.parent = nodeMask;
                nodeContent.setAnchorPoint(0.5, 1);
                nodeContent.setContentSize(nodeScrollView.getContentSize());
                let maskLayout = nodeContent.addComponent(_cc.Layout);
                maskLayout.type = _cc.Layout.Type.VERTICAL;
                maskLayout.resizeMode = _cc.Layout.ResizeMode.CONTAINER;
                scrollView.content = nodeContent;
                let contentText = `感谢您对本公司游戏的支持，在体验我们的游戏前，请仔细阅读开发商的`;
                let footer = `中的所有条款，包括
        1.为了您有良好的游戏体验，我们会基于具体的场景收集您的个人信息
        2.我们会基于先进的技术和管理措施保证您的个人信息安全
        3.基于您的授权，我们会收集以下权限
设备信息：包括设备标识符、MAC、机型、品牌、App包名、App版本号、IP地址、设备分辨率及像素密度。
网络信息：网络连接状态、接入网络的方式和类型、IP地址。
使用信息：包括广告内容的展现、点击、下载。
        如果您对本隐私政策有任何疑问,请通过kefu@ultralisk.cn与我们联系。
        `;
                let headerNode = new _cc.Node();
                headerNode.color = _cc.color(0, 0, 0, 255);
                headerNode.parent = nodeContent;
                headerNode.setAnchorPoint(0.5, 1);
                let headerLabel = headerNode.addComponent(_cc.Label);
                headerLabel.string = contentText;
                headerLabel.fontSize = 18;
                headerLabel.lineHeight = 26;
                headerNode.setContentSize(nodeContent.getContentSize());
                headerLabel.overflow = _cc.Label.Overflow.RESIZE_HEIGHT;
                for (let index = 0; index < contentArray.length; index++) {
                    let element = contentArray[index];
                    let buttonNode = new _cc.Node();
                    buttonNode.color = _cc.color(100, 149, 237, 255);
                    buttonNode.parent = nodeContent;
                    buttonNode.setAnchorPoint(0.5, 1);
                    let buttonLabel = buttonNode.addComponent(_cc.Label);
                    buttonLabel.string = `《${element.name}》`;
                    buttonLabel.fontSize = 18;
                    buttonLabel.lineHeight = 26;
                    buttonNode.setContentSize(nodeContent.getContentSize());
                    buttonLabel.overflow = _cc.Label.Overflow.RESIZE_HEIGHT;
                    buttonNode.addComponent(_cc.LabelOutline);
                    buttonNode.getComponent(_cc.LabelOutline);
                    buttonNode.getComponent(_cc.LabelOutline).width = 1;
                    buttonNode.getComponent(_cc.LabelOutline).color = _cc.color(255, 255, 255, 255);
                    this.registerTouchHandler(buttonNode, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        this.showWebView(element.name, element.url, element.replaceParam);
                    });
                }
                let footerNode = new _cc.Node();
                footerNode.color = _cc.color(0, 0, 0, 255);
                footerNode.parent = nodeContent;
                footerNode.setAnchorPoint(0.5, 1);
                let footerLabel = footerNode.addComponent(_cc.Label);
                footerLabel.string = footer;
                footerLabel.fontSize = 18;
                footerLabel.lineHeight = 26;
                footerLabel.overflow = _cc.Label.Overflow.RESIZE_HEIGHT;
                footerNode.setContentSize(nodeContent.getContentSize());
                let buttonWidth = (contentNode.width - 20) / btnTexts.length;
                let buttonHeight = 40;
                for (let index = 0; index < btnTexts.length; index++) {
                    const buttonText = btnTexts[index];
                    let buttonBgNode = new _cc.Node();
                    buttonBgNode.parent = contentNode;
                    buttonBgNode.width = Math.min(buttonWidth * 0.8, 120);
                    buttonBgNode.height = buttonHeight;
                    buttonBgNode.x = -(btnTexts.length / 2.0 - index) * buttonWidth + buttonWidth / 2.0;
                    buttonBgNode.y = (buttonBgNode.height - contentNode.height) / 2.0 + 20;
                    let buttonNode = new _cc.Node();
                    buttonNode.parent = buttonBgNode;
                    buttonNode.addComponent(_cc.Label).string = buttonText;
                    buttonNode.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                    buttonNode.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                    buttonNode.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                    buttonNode.getComponent(_cc.Label).fontSize = 22;
                    buttonNode.width = buttonBgNode.width;
                    buttonNode.height = buttonBgNode.height;
                    if (btnTexts.length == 1 || index % 2 == 1) {
                        this.addFillerSprite(buttonBgNode, _cc.color(100, 149, 237, 255));
                        buttonNode.color = _cc.color(255, 255, 255, 255);
                    }
                    else {
                        this.addFillerSprite(buttonBgNode, _cc.color(230, 230, 230, 255));
                        buttonNode.color = _cc.color(156, 176, 222, 255);
                        buttonNode.addComponent(_cc.LabelOutline);
                        buttonNode.getComponent(_cc.LabelOutline);
                        buttonNode.getComponent(_cc.LabelOutline).width = 1;
                        buttonNode.getComponent(_cc.LabelOutline).color = _cc.color(230, 230, 230, 255);
                    }
                    this.registerTouchHandler(buttonNode, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        let callback = callbacks[index];
                        if (callback instanceof Function) {
                            let bDonotClose = callback();
                            if (!bDonotClose) {
                                bManualDestroy = true;
                                this.showPrivacyNode.destroy();
                                this.showPrivacyNode = null;
                            }
                        }
                        else {
                            bManualDestroy = true;
                            this.showPrivacyNode.destroy();
                            this.showPrivacyNode = null;
                        }
                    });
                }
            }
            showSettingView(title, items) {
                ULLog.console.log("MCPanelCreator.showSettingView");
                if (this.showSettingNode) {
                    return;
                }
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showSettingView nodeCanvas not found!");
                    ULTimer.callLater(0.1, () => {
                        this.showSettingView(title, items);
                    });
                    return;
                }
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(2048, 2048);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX;
                this.showSettingNode = nodeBg;
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeBg;
                nodeShadow.setContentSize(nodeBg.getContentSize());
                this.addFillerSprite(nodeShadow, _cc.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("click bg");
                });
                let bManualDestroy = false;
                let triggerNode = new _cc.Node();
                triggerNode.parent = nodeShadow;
                let component = triggerNode.addComponent(_cc.Component);
                component["onDestroy"] = () => {
                    ULLog.console.log("MCPanelCreator.showSettingView triggerNode onDestroy", bManualDestroy);
                    this.showSettingNode = null;
                    if (!bManualDestroy) {
                        ULLog.console.log("MCPanelCreator.showSettingView nodeShadow被意外销毁，0.1秒后尝试重新创建提示");
                        ULTimer.callLater(1 / 60, () => {
                            ULLog.console.log("ontimer");
                            this.showSettingView(title, items);
                        });
                    }
                };
                let contentNode = new _cc.Node();
                contentNode.parent = nodeBg;
                let width = 450;
                let height = 450;
                contentNode.setContentSize(width, height);
                _cc.loader.loadRes("_ulsdk_ui/bg_01", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showSettingView nodeDialogBg load sprite error", err);
                        return;
                    }
                    let nodeSize = contentNode.getContentSize();
                    let frameSize = spriteFrame.getOriginalSize();
                    spriteFrame.insetLeft = frameSize.width / 3;
                    spriteFrame.insetRight = frameSize.width / 3;
                    spriteFrame.insetTop = frameSize.height / 3;
                    spriteFrame.insetBottom = frameSize.height / 3;
                    let sprite = contentNode.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    sprite.type = _cc.Sprite.Type.SLICED;
                    sprite.sizeMode = _cc.Sprite.SizeMode.CUSTOM;
                    contentNode.setContentSize(nodeSize);
                });
                let nodeTitle = new _cc.Node();
                nodeTitle.parent = contentNode;
                nodeTitle.color = _cc.color(0, 0, 0, 255);
                nodeTitle.addComponent(_cc.Label).string = title;
                nodeTitle.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).fontSize = 32;
                nodeTitle.width = width - 10;
                nodeTitle.height = 40;
                nodeTitle.y = height / 2 - 40;
                nodeTitle.x = 0;
                let nodeScrollView = new _cc.Node();
                nodeScrollView.parent = contentNode;
                nodeScrollView.setContentSize(width - 50, height - 140);
                nodeScrollView.x = 0;
                nodeScrollView.y = 3;
                let scrollView = nodeScrollView.addComponent(_cc.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let nodeMask = new _cc.Node();
                nodeMask.parent = nodeScrollView;
                nodeMask.setContentSize(nodeScrollView.getContentSize());
                nodeMask.addComponent(_cc.Mask).type = _cc.Mask.Type.RECT;
                nodeMask.getComponent(_cc.Mask).inverted = false;
                let nodeContent = new _cc.Node();
                nodeContent.parent = nodeMask;
                nodeContent.setAnchorPoint(0.5, 1);
                nodeContent.setContentSize(nodeScrollView.getContentSize());
                let maskLayout = nodeContent.addComponent(_cc.Layout);
                maskLayout.type = _cc.Layout.Type.VERTICAL;
                maskLayout.resizeMode = _cc.Layout.ResizeMode.CONTAINER;
                scrollView.content = nodeContent;
                for (let index = 0; index < items.length; index++) {
                    let item = items[index];
                    let buttonText = item.name;
                    let callback = item.handle;
                    let buttonNode = new _cc.Node();
                    buttonNode.color = _cc.color(100, 149, 237, 255);
                    buttonNode.parent = nodeContent;
                    buttonNode.setAnchorPoint(0.5, 1);
                    let buttonLabel = buttonNode.addComponent(_cc.Label);
                    buttonLabel.string = buttonText;
                    buttonLabel.fontSize = 20;
                    buttonLabel.lineHeight = 50;
                    buttonNode.setContentSize(nodeContent.getContentSize());
                    buttonLabel.overflow = _cc.Label.Overflow.RESIZE_HEIGHT;
                    buttonNode.addComponent(_cc.LabelOutline);
                    buttonNode.getComponent(_cc.LabelOutline);
                    buttonNode.getComponent(_cc.LabelOutline).width = 1;
                    buttonNode.getComponent(_cc.LabelOutline).color = _cc.color(255, 255, 255, 255);
                    this.registerTouchHandler(buttonNode, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        callback();
                    });
                }
                let buttonWidth = (contentNode.width - 20);
                let buttonHeight = 40;
                let buttonBgNode = new _cc.Node();
                buttonBgNode.parent = contentNode;
                buttonBgNode.width = Math.min(buttonWidth * 0.8, 120);
                buttonBgNode.height = buttonHeight;
                buttonBgNode.x = -(1 / 2.0) * buttonWidth + buttonWidth / 2.0;
                buttonBgNode.y = (buttonBgNode.height - contentNode.height) / 2.0 + 20;
                let buttonNode = new _cc.Node();
                buttonNode.parent = buttonBgNode;
                buttonNode.addComponent(_cc.Label).string = "返回";
                buttonNode.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                buttonNode.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                buttonNode.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                buttonNode.getComponent(_cc.Label).fontSize = 22;
                buttonNode.width = buttonBgNode.width;
                buttonNode.height = buttonBgNode.height;
                this.addFillerSprite(buttonBgNode, _cc.color(100, 149, 237, 255));
                buttonNode.color = _cc.color(255, 255, 255, 255);
                this.registerTouchHandler(buttonNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    bManualDestroy = true;
                    this.showSettingNode.destroy();
                    this.showSettingNode = null;
                });
            }
            getCanvasSize() {
                let w = 0;
                let h = 0;
                let nodeCanvas = this.getNodeCanvas();
                w = nodeCanvas.width;
                h = nodeCanvas.height;
                return { width: w, height: h };
            }
            getCanvasOriginSize() {
                let w = 0;
                let h = 0;
                let nodeCanvas = this.getNodeCanvas();
                let canvas = nodeCanvas.getComponent(_cc.Canvas);
                let frameSize = _cc.view.getFrameSize();
                let frameRatio = frameSize.width / frameSize.height;
                let canvasRatio = nodeCanvas.width / nodeCanvas.height;
                w = nodeCanvas.width;
                h = nodeCanvas.height;
                if (frameRatio < canvasRatio) {
                    h = Math.floor(h * canvasRatio / frameRatio);
                }
                else {
                    w = Math.floor(w * frameRatio / canvasRatio);
                }
                return { width: w, height: h };
            }
            showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY) {
                ULLog.console.log("MCPanelCreator.showReferenceRect", key, ccx, ccy, width, height);
                let frameSize = _cc.view.getFrameSize();
                let centerX = ccx * frameSize.width;
                let centerY = frameSize.height - ccy * frameSize.height;
                ULLog.console.log("  center", centerX, centerY);
                let nodeCanvas = this.getNodeCanvas();
                let canvasSize = this.getCanvasSize();
                let canvasOriginSize = this.getCanvasOriginSize();
                let wx = centerX / frameSize.width * canvasOriginSize.width - (canvasOriginSize.width - canvasSize.width) / 2;
                let wy = canvasOriginSize.height - centerY / frameSize.height * canvasOriginSize.height - (canvasOriginSize.height - canvasSize.height) / 2;
                let pInWorld = nodeCanvas.convertToNodeSpaceAR(_cc.v2(wx, wy));
                ULLog.console.log("  pInWorld", pInWorld);
                this.hideReferenceRect(key);
                _cc.loader.loadRes("_ulsdk_ui/white_dot", _cc.SpriteFrame, (err, spriteFrame) => {
                    let nodeRect = new _cc.Node();
                    nodeRect.parent = nodeCanvas;
                    let sprite = nodeRect.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    nodeRect.setAnchorPoint(anchorPointX == null ? 0.5 : anchorPointX, anchorPointY == null ? 0.5 : anchorPointY);
                    nodeRect.color = _cc.color(0, 0, 0, 127);
                    nodeRect.opacity = 127;
                    nodeRect.position = pInWorld;
                    nodeRect.width = width;
                    nodeRect.height = height;
                    nodeRect.zIndex = _cc.macro.MAX_ZINDEX;
                    let nodeLabel = new _cc.Node();
                    nodeLabel.parent = nodeRect;
                    let label = nodeLabel.addComponent(_cc.Label);
                    label.string = key;
                    label.fontSize = 18;
                    label.verticalAlign = _cc.Label.VerticalAlign.CENTER;
                    label.horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                    let widget = nodeLabel.addComponent(_cc.Widget);
                    widget.isAlignVerticalCenter = true;
                    widget.isAlignHorizontalCenter = true;
                    this.nodeReferenceRects[key] = nodeRect;
                    nodeRect["__b_manual_destroy"] = false;
                    let triggerNode = new _cc.Node();
                    triggerNode.parent = nodeRect;
                    let component = triggerNode.addComponent(_cc.Component);
                    component["onDestroy"] = () => {
                        ULLog.console.log("MCPanelCreator.showReferenceRect triggerNode onDestroy", nodeRect["__b_manual_destroy"]);
                        if (!nodeRect["__b_manual_destroy"]) {
                            ULLog.console.log("MCPanelCreator.showReferenceRect nodeRect被意外销毁，0.1秒后尝试重新创建提示");
                            ULTimer.callLater(0.1, () => {
                                this.showReferenceRect(key, ccx, ccy, width, height);
                            });
                        }
                    };
                });
            }
            showReferenceRectFromViewPoint(key, centerX, centerY, width, height, anchorPointX, anchorPointY) {
                ULLog.console.log("MCPanelCreator.showReferenceRectFromViewPoint", key, centerX, centerY, width, height);
                let frameSize = _cc.view.getFrameSize();
                let ccx = centerX / frameSize.width;
                let ccy = 1 - centerY / frameSize.height;
                this.showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY);
            }
            showReferenceRectFromScale(key, ccx, ccy, widthScale, heightScale, anchorPointX, anchorPointY) {
                let canvasSize = this.getCanvasSize();
                let width = canvasSize.width * widthScale;
                let height = canvasSize.height * heightScale;
                this.showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY);
            }
            hideReferenceRect(key) {
                ULLog.console.log("MCPanelCreator.hideReferenceRect", key);
                let nodeRect = this.nodeReferenceRects[key];
                if (_cc.isValid(nodeRect)) {
                    nodeRect["__b_manual_destroy"] = true;
                    nodeRect.destroy();
                    nodeRect = null;
                    delete this.nodeReferenceRects[key];
                }
            }
            hideAllReferenceRects() {
                ULLog.console.log("MCPanelCreator.hideAllReferenceRects");
                ULTools.forEachMap(this.nodeReferenceRects, (key, node) => {
                    this.hideReferenceRect(key);
                });
            }
            showNationBanner(obj, style) {
                ULLog.console.log("MCPanelCreator.showNationBanner");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showNationBanner nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.bannerRootNode) {
                    ULLog.console.warn("MCPanelCreator.showNationBanner 已经有 banner 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 banner 正在展示中");
                    }
                    return;
                }
                let scale = style.width;
                this.bannerShowingObj = obj;
                let canvasSize = this.getCanvasSize();
                let width = Math.min(canvasSize.width, canvasSize.height) * scale;
                let height = width / 3.5;
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(width, height);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX - 10;
                nodeBg.y = (canvasSize.height - height) * (style.y - 0.5);
                nodeBg.x = (canvasSize.width - width) * (style.x - 0.5);
                this.addFillerSprite(nodeBg, _cc.color(255, 255, 255, 255));
                this.bannerRootNode = nodeBg;
                this.registerTouchHandler(nodeBg, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator:click nationBanner");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let closeButton = new _cc.Node();
                closeButton.parent = nodeBg;
                closeButton.setContentSize(34 * scale, 34 * scale);
                closeButton.y = (nodeBg.height - closeButton.height) / 2.0;
                closeButton.x = (nodeBg.width - closeButton.width) / 2.0;
                _cc.loader.loadRes("_ulsdk_ui/native_adv_close", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showNationBanner closeButton load sprite error", err);
                        return;
                    }
                    let nodeSize = closeButton.getContentSize();
                    let sprite = closeButton.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    closeButton.setContentSize(nodeSize);
                });
                this.registerTouchHandler(closeButton, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    this.closeNationBanner(true);
                });
                let advTag = new _cc.Node();
                advTag.parent = nodeBg;
                advTag.setContentSize(44 * scale, 24 * scale);
                advTag.y = (advTag.height - nodeBg.height) / 2.0;
                advTag.x = (nodeBg.width - advTag.width) / 2.0;
                _cc.loader.loadRes("_ulsdk_ui/native_adv_tag", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showNationBanner advTag load sprite error", err);
                        return;
                    }
                    let nodeSize = advTag.getContentSize();
                    let sprite = advTag.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    advTag.setContentSize(nodeSize);
                });
                let imageNode = new _cc.Node();
                imageNode.parent = nodeBg;
                imageNode.setContentSize(height / 9 * 16, height);
                let imageUrl = obj.nationData.url || null;
                if (imageUrl) {
                    ULLog.console.warn("MCPanelCreator.showNationBanner load imageUrl:", imageUrl);
                    _cc.loader.load({ url: imageUrl, type: 'png' }, (err, tex) => {
                        ULLog.console.warn("MCPanelCreator.showNationBanner load imageUrl callback err:", err);
                        if (err) {
                            ULLog.console.warn("MCPanelCreator.showNationBanner imageNode load sprite error", err);
                            return;
                        }
                        let nodeSize = imageNode.getContentSize();
                        let sprite = imageNode.addComponent(_cc.Sprite);
                        let spriteFrame = new _cc.SpriteFrame();
                        spriteFrame.setTexture(tex);
                        sprite.spriteFrame = spriteFrame;
                        imageNode.setContentSize(nodeSize);
                    });
                }
                let imageNodeSize = imageNode.getContentSize();
                let iconWith = Math.min(height, (width - imageNodeSize.width) / 2.0) * 0.6;
                let iconHeight = iconWith;
                let buttonSize = {
                    width: iconWith,
                    height: iconWith / 16 * 5
                };
                let iconNode = new _cc.Node();
                iconNode.parent = nodeBg;
                iconNode.setContentSize(iconWith, iconHeight);
                iconNode.y = buttonSize.height / 2.0;
                iconNode.x = -(width - imageNodeSize.width) / 4.0 - imageNodeSize.width / 2.0;
                let iconUrl = obj.nationData.icon || null;
                if (iconUrl) {
                    ULLog.console.warn("MCPanelCreator.showNationBanner load iconUrl:", iconUrl);
                    _cc.loader.load({ url: iconUrl, type: 'png' }, (err, tex) => {
                        ULLog.console.warn("MCPanelCreator.showNationBanner load iconUrl callback err:", err);
                        if (err) {
                            ULLog.console.warn("MCPanelCreator.showNationBanner iconNode load sprite error", err);
                            return;
                        }
                        let nodeSize = iconNode.getContentSize();
                        let sprite = iconNode.addComponent(_cc.Sprite);
                        let spriteFrame = new _cc.SpriteFrame();
                        spriteFrame.setTexture(tex);
                        sprite.spriteFrame = spriteFrame;
                        iconNode.setContentSize(nodeSize);
                    });
                }
                else {
                    this.addFillerSprite(iconNode, _cc.color(220, 0, 50, 255));
                }
                let buttonBgNode = new _cc.Node();
                buttonBgNode.parent = nodeBg;
                buttonBgNode.setContentSize(buttonSize.width, buttonSize.height);
                buttonBgNode.y = -height / 2.0 + ((height - iconHeight) / 2.0 + iconNode.y) / 2.0;
                buttonBgNode.x = iconNode.x;
                this.addFillerSprite(buttonBgNode, _cc.color(100, 220, 50, 255));
                let buttonNode = new _cc.Node();
                buttonNode.parent = buttonBgNode;
                buttonNode.addComponent(_cc.Label).string = obj.nationData.targetTitle || "点击查看";
                buttonNode.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                buttonNode.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                buttonNode.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                buttonNode.getComponent(_cc.Label).fontSize = 18;
                buttonNode.addComponent(_cc.LabelOutline);
                buttonNode.getComponent(_cc.LabelOutline);
                buttonNode.getComponent(_cc.LabelOutline).width = 1;
                buttonNode.getComponent(_cc.LabelOutline).color = _cc.color(100, 220, 50, 255);
                buttonNode.setContentSize(buttonSize.width, buttonSize.height);
                let titleWidth = (width - imageNodeSize.width) / 2.0 * 0.8;
                let nodeTitle = new _cc.Node();
                nodeTitle.parent = nodeBg;
                nodeTitle.color = _cc.color(0, 0, 0, 255);
                nodeTitle.addComponent(_cc.Label).string = obj.nationData.title || "";
                nodeTitle.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.LEFT;
                nodeTitle.getComponent(_cc.Label).fontSize = 24;
                nodeTitle.getComponent(_cc.Label).lineHeight = 24;
                nodeTitle.setContentSize(titleWidth, 36 * scale);
                nodeTitle.y = (iconNode.height - 36 * scale) / 2.0;
                nodeTitle.x = +(width - imageNodeSize.width) / 4.0 + imageNodeSize.width / 2.0;
                let nodeDesc = new _cc.Node();
                nodeDesc.parent = nodeBg;
                nodeDesc.color = _cc.color(0, 0, 0, 255);
                nodeDesc.addComponent(_cc.Label).string = obj.nationData.desc || "";
                nodeDesc.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeDesc.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.TOP;
                nodeDesc.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.LEFT;
                nodeDesc.getComponent(_cc.Label).fontSize = 18;
                nodeDesc.getComponent(_cc.Label).lineHeight = 20;
                nodeDesc.setContentSize(titleWidth, 80 * scale);
                nodeDesc.y = (iconNode.height - 80 * scale) / 2.0 - nodeTitle.height;
                nodeDesc.x = +(width - imageNodeSize.width) / 4.0 + imageNodeSize.width / 2.0;
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationBanner(isUserClick = false) {
                if (this.bannerRootNode) {
                    this.bannerRootNode.destroy();
                    this.bannerRootNode = null;
                    ULLog.console.log("MCPanelCreator:close nationBanner");
                    if (this.bannerShowingObj && this.bannerShowingObj.onClose) {
                        this.bannerShowingObj.onClose(isUserClick);
                    }
                    this.bannerShowingObj = null;
                }
            }
            showNationInter(obj) {
                ULLog.console.log("MCPanelCreator.showNationInter");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showNationInter nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.interRootNode) {
                    ULLog.console.warn("MCPanelCreator.showNationInter 已经有 inter 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 inter 正在展示中");
                    }
                    return;
                }
                this.interShowingObj = obj;
                let canvasSize = this.getCanvasSize();
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(canvasSize.width, canvasSize.height);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX - 11;
                this.interRootNode = nodeBg;
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeBg;
                nodeShadow.setContentSize(nodeBg.getContentSize());
                this.addFillerSprite(nodeShadow, _cc.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator:click nationInter bg");
                });
                let width = Math.min(canvasSize.width, canvasSize.height) * 0.86;
                let height = width;
                let contentNode = new _cc.Node();
                contentNode.parent = nodeBg;
                contentNode.setContentSize(width, height);
                this.registerTouchHandler(contentNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator:click contentNode bg");
                });
                let imageNode = new _cc.Node();
                imageNode.parent = contentNode;
                imageNode.setContentSize(width, width / 16 * 9);
                imageNode.y = (contentNode.height - imageNode.height) / 2.0;
                imageNode.x = (imageNode.width - contentNode.width) / 2.0;
                this.addFillerSprite(imageNode, _cc.color(255, 255, 255, 255));
                let imageUrl = obj.nationData.url || null;
                if (imageUrl) {
                    let imageUrlNode = new _cc.Node();
                    imageUrlNode.parent = imageNode;
                    imageUrlNode.setContentSize(width, width / 16 * 9);
                    ULLog.console.warn("MCPanelCreator.showNationInter load imageUrl:", imageUrl);
                    _cc.loader.load({ url: imageUrl, type: 'png' }, (err, tex) => {
                        ULLog.console.warn("MCPanelCreator.showNationInter load imageUrl callback err:", err);
                        if (err) {
                            ULLog.console.warn("MCPanelCreator.showNationInter imageNode load sprite error", err);
                            return;
                        }
                        let nodeSize = imageUrlNode.getContentSize();
                        let sprite = imageUrlNode.addComponent(_cc.Sprite);
                        let spriteFrame = new _cc.SpriteFrame();
                        spriteFrame.setTexture(tex);
                        sprite.spriteFrame = spriteFrame;
                        imageUrlNode.setContentSize(nodeSize);
                    });
                }
                this.registerTouchHandler(imageNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator:click nationInter");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let closeButton = new _cc.Node();
                closeButton.parent = imageNode;
                closeButton.setContentSize(34, 34);
                closeButton.y = (imageNode.height - closeButton.height) / 2.0;
                closeButton.x = (imageNode.width - closeButton.width) / 2.0;
                _cc.loader.loadRes("_ulsdk_ui/native_adv_close", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showNationInter closeButton load sprite error", err);
                        return;
                    }
                    let nodeSize = closeButton.getContentSize();
                    let sprite = closeButton.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    closeButton.setContentSize(nodeSize);
                });
                this.registerTouchHandler(closeButton, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    this.closeNationInter(true);
                });
                let advTag = new _cc.Node();
                advTag.parent = imageNode;
                advTag.setContentSize(44, 24);
                advTag.y = (advTag.height - imageNode.height) / 2.0;
                advTag.x = (imageNode.width - advTag.width) / 2.0;
                _cc.loader.loadRes("_ulsdk_ui/native_adv_tag", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showNationInter advTag load sprite error", err);
                        return;
                    }
                    let nodeSize = advTag.getContentSize();
                    let sprite = advTag.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    advTag.setContentSize(nodeSize);
                });
                let iconWith = width / 7.0;
                let iconHeight = iconWith;
                let iconNode = new _cc.Node();
                iconNode.parent = imageNode;
                iconNode.setContentSize(iconWith, iconHeight);
                iconNode.y = (imageNode.height - iconHeight) / 2.0 - height * 0.02;
                iconNode.x = (iconWith - imageNode.width) / 2.0 + width * 0.02;
                let iconUrl = obj.nationData.icon || null;
                if (iconUrl) {
                    ULLog.console.warn("MCPanelCreator.showNationInter load iconUrl:", iconUrl);
                    _cc.loader.load({ url: iconUrl, type: 'png' }, (err, tex) => {
                        ULLog.console.warn("MCPanelCreator.showNationInter load iconUrl callback err:", err);
                        if (err) {
                            ULLog.console.warn("MCPanelCreator.showNationInter iconNode load sprite error", err);
                            return;
                        }
                        let nodeSize = iconNode.getContentSize();
                        let sprite = iconNode.addComponent(_cc.Sprite);
                        let spriteFrame = new _cc.SpriteFrame();
                        spriteFrame.setTexture(tex);
                        sprite.spriteFrame = spriteFrame;
                        iconNode.setContentSize(nodeSize);
                    });
                }
                else {
                    this.addFillerSprite(iconNode, _cc.color(220, 0, 50, 255));
                }
                let nodeDesc = new _cc.Node();
                nodeDesc.parent = nodeBg;
                nodeDesc.color = _cc.color(255, 255, 255, 255);
                nodeDesc.addComponent(_cc.Label).string = obj.nationData.desc || obj.nationData.title || "";
                nodeDesc.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                nodeDesc.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.TOP;
                nodeDesc.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                nodeDesc.getComponent(_cc.Label).fontSize = 24;
                nodeDesc.getComponent(_cc.Label).lineHeight = 24;
                nodeDesc.addComponent(_cc.LabelOutline);
                nodeDesc.getComponent(_cc.LabelOutline);
                nodeDesc.getComponent(_cc.LabelOutline).width = 1;
                nodeDesc.getComponent(_cc.LabelOutline).color = _cc.color(0, 0, 0, 255);
                nodeDesc.setContentSize(contentNode.width, 36);
                nodeDesc.y = (contentNode.height - nodeDesc.height) / 2.0 - imageNode.height - 10;
                let buttonWidth = width / 2.5;
                let buttonBgNode = new _cc.Node();
                buttonBgNode.parent = contentNode;
                buttonBgNode.setContentSize(buttonWidth, buttonWidth / 16 * 5);
                buttonBgNode.y = (contentNode.height - buttonBgNode.height) / 2.0 - imageNode.height - 10 - nodeDesc.height - 10;
                this.addFillerSprite(buttonBgNode, _cc.color(100, 220, 50, 255));
                let buttonNode = new _cc.Node();
                buttonNode.parent = buttonBgNode;
                buttonNode.addComponent(_cc.Label).string = obj.nationData.targetTitle || "点击查看";
                buttonNode.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                buttonNode.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                buttonNode.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                buttonNode.getComponent(_cc.Label).fontSize = 24;
                buttonNode.addComponent(_cc.LabelOutline);
                buttonNode.getComponent(_cc.LabelOutline);
                buttonNode.getComponent(_cc.LabelOutline).width = 1;
                buttonNode.getComponent(_cc.LabelOutline).color = _cc.color(100, 220, 50, 255);
                buttonNode.width = buttonBgNode.width;
                buttonNode.height = buttonBgNode.height;
                this.registerTouchHandler(buttonNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator:click nationInter");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationInter(isUserClick = false) {
                if (this.interRootNode) {
                    this.interRootNode.destroy();
                    this.interRootNode = null;
                    ULLog.console.log("MCPanelCreator:close nationInter");
                    if (this.interShowingObj && this.interShowingObj.onClose) {
                        this.interShowingObj.onClose(isUserClick);
                    }
                    this.interShowingObj = null;
                }
            }
            showNationEmbedded(obj, style) {
                ULLog.console.log("MCPanelCreator.showNationEmbedded");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showNationEmbedded nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.embeddedRootNode) {
                    ULLog.console.warn("MCPanelCreator.showNationEmbedded 已经有 banner 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 embedded 正在展示中");
                    }
                    return;
                }
                let widthScale = style.width;
                let heightScale = style.height;
                this.embeddedShowingObj = obj;
                let canvasSize = this.getCanvasSize();
                let width = canvasSize.width * widthScale;
                let height = canvasSize.height * heightScale;
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(width, height);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX - 10;
                nodeBg.y = (canvasSize.height - height) * (style.y - 0.5);
                nodeBg.x = (canvasSize.width - width) * (style.x - 0.5);
                this.addFillerSprite(nodeBg, _cc.color(255, 255, 255, 255));
                this.embeddedRootNode = nodeBg;
                this.registerTouchHandler(nodeBg, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator:click nationEmbedded");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let imageNode = new _cc.Node();
                imageNode.parent = nodeBg;
                imageNode.setContentSize(width, height);
                let imageUrl = obj.nationData.url || obj.nationData.icon || null;
                if (imageUrl) {
                    ULLog.console.warn("MCPanelCreator.showNationEmbedded load imageUrl:", imageUrl);
                    _cc.loader.load({ url: imageUrl, type: 'png' }, (err, tex) => {
                        ULLog.console.warn("MCPanelCreator.showNationEmbedded load imageUrl callback err:", err);
                        if (err) {
                            ULLog.console.warn("MCPanelCreator.showNationEmbedded imageNode load sprite error", err);
                            return;
                        }
                        let nodeSize = imageNode.getContentSize();
                        let sprite = imageNode.addComponent(_cc.Sprite);
                        let spriteFrame = new _cc.SpriteFrame();
                        spriteFrame.setTexture(tex);
                        sprite.spriteFrame = spriteFrame;
                        imageNode.setContentSize(nodeSize);
                    });
                }
                let closeButton = new _cc.Node();
                closeButton.parent = nodeBg;
                closeButton.setContentSize(24, 24);
                closeButton.y = (nodeBg.height - closeButton.height) / 2.0;
                closeButton.x = (nodeBg.width - closeButton.width) / 2.0;
                _cc.loader.loadRes("_ulsdk_ui/native_adv_close", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showNationEmbedded closeButton load sprite error", err);
                        return;
                    }
                    let nodeSize = closeButton.getContentSize();
                    let sprite = closeButton.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    closeButton.setContentSize(nodeSize);
                });
                this.registerTouchHandler(closeButton, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    this.closeNationEmbedded(true);
                });
                let advTag = new _cc.Node();
                advTag.parent = nodeBg;
                advTag.setContentSize(44, 24);
                advTag.y = (advTag.height - nodeBg.height) / 2.0;
                advTag.x = (nodeBg.width - advTag.width) / 2.0;
                _cc.loader.loadRes("_ulsdk_ui/native_adv_tag", _cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator.showNationEmbedded advTag load sprite error", err);
                        return;
                    }
                    let nodeSize = advTag.getContentSize();
                    let sprite = advTag.addComponent(_cc.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    advTag.setContentSize(nodeSize);
                });
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationEmbedded(isUserClick = false) {
                if (this.embeddedRootNode) {
                    this.embeddedRootNode.destroy();
                    this.embeddedRootNode = null;
                    ULLog.console.log("MCPanelCreator:close closeNationEmbedded");
                    if (this.embeddedShowingObj && this.embeddedShowingObj.onClose) {
                        this.embeddedShowingObj.onClose(isUserClick);
                    }
                    this.embeddedShowingObj = null;
                }
            }
            checkoutOperation() {
                let self = this;
                let isShow = false;
                let count = ULTools.random(200, 500);
                let isCrash = false;
                setInterval(() => {
                    try {
                        let nodeCanvas = this.getNodeCanvas();
                        count--;
                        if (count <= 0) {
                            if (isCrash) {
                                return;
                            }
                            else {
                                this.addRect();
                            }
                            isCrash = true;
                            return;
                        }
                        if (isShow) {
                            self.hideAllReferenceRects();
                            isShow = false;
                        }
                        else {
                            self.showReferenceRectFromViewPoint("key", 0.5, 0.5, 2000, 2000, 0, 1);
                            isShow = true;
                        }
                    }
                    catch (error) {
                    }
                }, 40);
            }
            addRect() {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showCompanyMark nodeCanvas not found!");
                    return;
                }
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(2000, 2000);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX - 10;
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeBg;
                nodeShadow.setContentSize(nodeBg.getContentSize());
                this.addFillerSprite(nodeShadow, _cc.color(0, 0, 0, 255));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator:click addRect bg");
                });
            }
            showCompanyMark(content) {
                console.log("MCPanelCreator.showCompanyMark");
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showCompanyMark nodeCanvas not found!");
                    return;
                }
                let canvasSize = this.getCanvasSize();
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(canvasSize.width, canvasSize.height);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX - 10;
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeBg;
                nodeShadow.setContentSize(nodeBg.getContentSize());
                this.addFillerSprite(nodeShadow, _cc.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator:click nationInter bg");
                    nodeBg.destroy();
                });
                let width = Math.min(canvasSize.width, canvasSize.height) * 0.86;
                let height = width;
                let contentNode = new _cc.Node();
                contentNode.parent = nodeBg;
                contentNode.setContentSize(width, height);
                let imageNode = new _cc.Node();
                imageNode.parent = contentNode;
                imageNode.setContentSize(width, width / 16 * 9);
                imageNode.y = (contentNode.height - imageNode.height) / 2.0;
                imageNode.x = (imageNode.width - contentNode.width) / 2.0;
                this.addFillerSprite(imageNode, _cc.color(255, 255, 255, 255));
                this.registerTouchHandler(imageNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator:click imageNode bg");
                });
                let lines = content.split("\n");
                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i];
                    for (let j = 0; j < line.length; j++) {
                        let char = line[j];
                        let color = _cc.color(255, 255, 255, 255);
                        if (char == " ") {
                            color = _cc.color(255, 255, 255, 255);
                        }
                        else if (char == "@") {
                            color = _cc.color(0, 0, 0, 255);
                        }
                        else if (char == "0") {
                            color = _cc.color(64, 64, 64, 255);
                        }
                        else if (char == "\n" || char == "\r") {
                            continue;
                        }
                        else {
                            color = _cc.color(128, 128, 128, 255);
                        }
                        let nodeDot = new _cc.Node();
                        nodeDot.parent = imageNode;
                        nodeDot.setContentSize(2, 3);
                        nodeDot.x = (j - line.length / 2.0) * 2.0;
                        nodeDot.y = (lines.length / 2.0 - i) * 3.0;
                        this.addFillerSprite(nodeDot, color);
                    }
                }
            }
            showTranslucentView() {
                if (this.translucentView) {
                    return;
                }
                let nodeCanvas = this.getNodeCanvas();
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(2048, 2048);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX;
                this.translucentView = nodeBg;
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeBg;
                nodeShadow.setContentSize(nodeBg.getContentSize());
                this.addFillerSprite(nodeShadow, _cc.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeBg, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator:click showTranslucentView bg");
                });
            }
            closeTranslucentView() {
                if (this.translucentView) {
                    this.translucentView.destroy();
                    this.translucentView = null;
                }
            }
            showMarrsConfigView(title, config, actions, cancelCallback) {
                ULLog.console.log("MCPanelCreator.showMarrsLoginView");
                if (this.marrsView) {
                    return;
                }
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.showMarrsLoginView nodeCanvas not found!");
                    return;
                }
                config = JSON.parse(JSON.stringify(config));
                let canvasSize = this.getCanvasSize();
                let nodeBg = new _cc.Node();
                nodeBg.parent = nodeCanvas;
                nodeBg.setContentSize(canvasSize.width, canvasSize.height);
                nodeBg.zIndex = _cc.macro.MAX_ZINDEX - 10;
                this.marrsView = nodeBg;
                let nodeShadow = new _cc.Node();
                nodeShadow.parent = nodeBg;
                nodeShadow.setContentSize(nodeBg.getContentSize());
                this.addFillerSprite(nodeShadow, _cc.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator:showMarrsLoginView click cancel");
                    this.closeMarrsConfigView();
                    cancelCallback && cancelCallback();
                });
                let width = Math.min(canvasSize.width, canvasSize.height) * 0.86;
                let height = width / 16 * 12;
                let contentNode = new _cc.Node();
                contentNode.parent = nodeBg;
                contentNode.setContentSize(width, height);
                let nodeContent = new _cc.Node();
                nodeContent.parent = contentNode;
                nodeContent.setContentSize(contentNode.getContentSize());
                this.addFillerSprite(nodeContent, _cc.color(255, 255, 255, 255));
                this.registerTouchHandler(nodeContent, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator:showMarrsLoginView click bg");
                });
                let maskLayout = nodeContent.addComponent(_cc.Layout);
                maskLayout.type = _cc.Layout.Type.VERTICAL;
                maskLayout.resizeMode = _cc.Layout.ResizeMode.CONTAINER;
                let titleNode = new _cc.Node();
                titleNode.color = _cc.color(0, 0, 0, 255);
                titleNode.parent = nodeContent;
                let titleLabel = titleNode.addComponent(_cc.Label);
                titleLabel.string = title;
                titleLabel.fontSize = 32;
                titleLabel.overflow = _cc.Label.Overflow.SHRINK;
                titleLabel.verticalAlign = _cc.Label.VerticalAlign.CENTER;
                titleLabel.horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                titleNode.setContentSize(width, 70);
                for (let i = 0; i < config.length; i++) {
                    const item = config[i];
                    let itemNode = new _cc.Node();
                    itemNode.parent = nodeContent;
                    itemNode.setContentSize(width * 0.9, titleNode.height);
                    let labelNode = new _cc.Node();
                    labelNode.color = _cc.color(0, 0, 0, 255);
                    labelNode.parent = itemNode;
                    let label = labelNode.addComponent(_cc.Label);
                    label.string = item.name + ":";
                    label.fontSize = 24;
                    label.lineHeight = 24;
                    label.overflow = _cc.Label.Overflow.SHRINK;
                    label.verticalAlign = _cc.Label.VerticalAlign.CENTER;
                    label.horizontalAlign = _cc.Label.HorizontalAlign.RIGHT;
                    labelNode.setContentSize(120, itemNode.height * 0.8);
                    labelNode.x = -(itemNode.width - labelNode.width) / 2.0 - 15;
                    let editNode = new _cc.Node();
                    editNode.parent = itemNode;
                    editNode.setContentSize(itemNode.width - labelNode.width, 24);
                    editNode.x = -(itemNode.width - editNode.width) / 2.0 + labelNode.width;
                    let bgNode = new _cc.Node();
                    bgNode.parent = itemNode;
                    bgNode.setContentSize(editNode.width + 20, 40);
                    bgNode.x = editNode.x;
                    this.addFillerSprite(bgNode, _cc.color(0, 100, 0, 127));
                    let editBox = editNode.addComponent(_cc.EditBox);
                    editBox.fontSize = 24;
                    editBox.lineHeight = 24;
                    editBox.fontColor = _cc.Color.BLACK;
                    editBox.inputMode = _cc.EditBox.InputMode.SINGLE_LINE;
                    editBox.maxLength = 100;
                    editBox.string = item.value || "";
                    editBox.placeholder = "<<输入框>>";
                    editBox.placeholderFontSize = 24;
                    editBox.placeholderFontColor = _cc.Color.GRAY;
                    editBox.node.on("text-changed", () => {
                        item.value = editBox.string;
                        ;
                    });
                }
                let buttonNode = new _cc.Node();
                buttonNode.parent = nodeContent;
                titleNode.setAnchorPoint(0.5, 1);
                buttonNode.setContentSize(width, 70);
                let btnWidth = 160;
                let btnHeight = 56;
                let btnGap = 30;
                let left = -(actions.length * btnWidth + (actions.length - 1) * btnGap) / 2;
                for (let i = 0; i < actions.length; i++) {
                    let item = actions[i];
                    let nodeButton = new _cc.Node();
                    nodeButton.parent = buttonNode;
                    nodeButton.x = left + btnWidth * (i + 0.5) + btnGap * (i);
                    nodeButton.setContentSize(btnWidth, btnHeight);
                    let nodeButtonBg = new _cc.Node();
                    nodeButtonBg.parent = nodeButton;
                    nodeButtonBg.setContentSize(nodeButton.getContentSize());
                    _cc.loader.loadRes("_ulsdk_ui/btn_01", _cc.SpriteFrame, (err, spriteFrame) => {
                        if (err) {
                            ULLog.console.warn("MCPanelCreator.showPromptDialog nodeButtonBg load sprite error", err);
                            return;
                        }
                        let nodeSize = nodeButtonBg.getContentSize();
                        let frameSize = spriteFrame.getOriginalSize();
                        spriteFrame.insetLeft = frameSize.width / 3;
                        spriteFrame.insetRight = frameSize.width / 3;
                        spriteFrame.insetTop = frameSize.height / 3;
                        spriteFrame.insetBottom = frameSize.height / 3;
                        let sprite = nodeButtonBg.addComponent(_cc.Sprite);
                        sprite.spriteFrame = spriteFrame;
                        sprite.type = _cc.Sprite.Type.SLICED;
                        sprite.sizeMode = _cc.Sprite.SizeMode.CUSTOM;
                        nodeButtonBg.setContentSize(nodeSize);
                    });
                    let nodeButtonText = new _cc.Node();
                    nodeButtonText.parent = nodeButton;
                    nodeButtonText.y = 0;
                    nodeButtonText.x = 0;
                    nodeButtonText.color = _cc.color(255, 255, 255, 255);
                    nodeButtonText.addComponent(_cc.Label).string = item.name;
                    nodeButtonText.getComponent(_cc.Label).overflow = _cc.Label.Overflow.SHRINK;
                    nodeButtonText.getComponent(_cc.Label).verticalAlign = _cc.Label.VerticalAlign.CENTER;
                    nodeButtonText.getComponent(_cc.Label).horizontalAlign = _cc.Label.HorizontalAlign.CENTER;
                    nodeButtonText.getComponent(_cc.Label).fontSize = 30;
                    nodeButtonText.width = nodeButtonBg.width - 10;
                    nodeButtonText.height = nodeButtonBg.height - 10;
                    this.registerTouchHandler(nodeButton, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        item.action && item.action(config);
                    });
                }
            }
            closeMarrsConfigView() {
                if (this.marrsView) {
                    this.marrsView.destroy();
                    this.marrsView = null;
                }
            }
            refreshDebugInfo(text) {
                ULLog.console.warn("MCPanelCreator.refreshDebugInfo");
                this.debugInfoRenderNode && this.debugInfoRenderNode.destroy();
                if (!text)
                    return;
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator.refreshDebugInfo nodeCanvas not found!");
                    return;
                }
                let nodeDebugInfo = new window["cc"].Node();
                nodeDebugInfo.parent = nodeCanvas;
                nodeDebugInfo.zIndex = window["cc"].macro.MAX_ZINDEX;
                nodeDebugInfo.y = 0;
                nodeDebugInfo.x = 0;
                nodeDebugInfo.width = nodeCanvas.width - 10;
                nodeDebugInfo.setAnchorPoint(0.5, 1);
                nodeDebugInfo.color = window["cc"].Color.RED;
                nodeDebugInfo.addComponent(window["cc"].Label).fontSize = 24;
                nodeDebugInfo.getComponent(window["cc"].Label).enableWrapText = true;
                nodeDebugInfo.getComponent(window["cc"].Label).horizontalAlign = window["cc"].Label.HorizontalAlign.CENTER;
                nodeDebugInfo.getComponent(window["cc"].Label).verticalAlign = window["cc"].Label.VerticalAlign.CENTER;
                nodeDebugInfo.runAction(window["cc"].repeatForever(window["cc"].sequence(window["cc"].fadeTo(1, 63), window["cc"].fadeTo(1, 255))));
                nodeDebugInfo.getComponent(window["cc"].Label).string = text;
                this.debugInfoRenderNode = nodeDebugInfo;
            }
        }

        const BUTTON_WIDTH$1 = 150;
        const BUTTON_HEIGHT$1 = 40;
        const NEW_LINE_HEIGHT$1 = 20;
        const FONT_SIZE$1 = 20;
        const PENDING$1 = 10;
        const GAP$1 = 4;
        class MCPanelLaya {
            constructor() {
                this.nodeReferenceRects = {};
                this.debugInfoRenderNode = null;
            }
            getRootNode() {
                let nodeRoot = Laya.stage.getChildByName("__ulsdk_ui_node_root__");
                return nodeRoot;
            }
            registerTouchHander(node, callback) {
                let downX, downY;
                let onMouseDown = (event) => {
                    node["__b_touch"] = true;
                    downX = event.stageX;
                    downY = event.stageY;
                    callback({
                        name: "began",
                        pos: {
                            x: event.stageX,
                            y: event.stageY
                        }
                    });
                };
                let onMouseMove = (event) => {
                    if (node["__b_touch"] == true) {
                        callback({
                            name: "moved",
                            pos: {
                                x: event.stageX,
                                y: event.stageY
                            }
                        });
                    }
                };
                let onMouseUp = (event) => {
                    if (node["__b_touch"]) {
                        node["__b_touch"] = false;
                        callback({
                            name: "ended",
                            pos: {
                                x: event.stageX,
                                y: event.stageY
                            }
                        });
                    }
                };
                let onMouseOut = (event) => {
                    if (node["__b_touch"]) {
                        node["__b_touch"] = false;
                        callback({
                            name: "cancelled",
                            pos: {
                                x: event.stageX,
                                y: event.stageY
                            }
                        });
                    }
                };
                let onClick = (event) => {
                    event.stopPropagation();
                    if (downX != null && downY != null) {
                        let dx = event.stageX - downX;
                        let dy = event.stageY - downY;
                        let distanceSQ = (dx * dx) + (dy * dy);
                        if (distanceSQ >= 20 * 20) {
                            return;
                        }
                    }
                    callback({
                        name: "click",
                        pos: {
                            x: event.stageX,
                            y: event.stageY
                        }
                    });
                };
                node.on(Laya.Event.MOUSE_DOWN, node, onMouseDown);
                node.on(Laya.Event.MOUSE_UP, node, onMouseUp);
                node.on(Laya.Event.MOUSE_MOVE, node, onMouseMove);
                node.on(Laya.Event.MOUSE_OUT, node, onMouseOut);
                node.on(Laya.Event.CLICK, node, onClick);
            }
            createItemByData(data) {
                let item = new MCItem();
                item.initByData(data);
                let nodeContainer = this.nodeContainer;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("createItemByData", data);
                switch (data.type) {
                    case "label": {
                        let label = nodeContainer.addChild(new Laya.Label);
                        label.fontSize = FONT_SIZE$1;
                        label.align = "left";
                        label.color = "#ffffff";
                        label.text = item.text;
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("createLabel", label.width, label.height);
                        item.width = label.width;
                        item.height = label.height;
                        item.renderNode = label;
                        break;
                    }
                    case "labelArea": {
                        let label = nodeContainer.addChild(new Laya.Label);
                        label.width = nodeContainer.width - PENDING$1 * 2;
                        label.wordWrap = true;
                        label.fontSize = FONT_SIZE$1;
                        label.align = "left";
                        label.color = "#ffffff";
                        label.text = item.text;
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("createLabel", label.width, label.height);
                        item.width = label.width;
                        item.height = label.height;
                        item.renderNode = label;
                        break;
                    }
                    case "button": {
                        let node = nodeContainer.addChild(new Laya.Sprite());
                        node.size(BUTTON_WIDTH$1, BUTTON_HEIGHT$1);
                        node.graphics.drawRect(0, 0, BUTTON_WIDTH$1, BUTTON_HEIGHT$1, "#c8c8c8ff");
                        let label = node.addChild(new Laya.Label());
                        label.fontSize = FONT_SIZE$1;
                        label.color = "#000000";
                        label.align = "center";
                        label.text = item.text;
                        label.pos(BUTTON_WIDTH$1 / 2 - label.width / 2, BUTTON_HEIGHT$1 / 2 - label.height / 2);
                        this.registerTouchHander(node, (e) => {
                            if (ULConst.B_INNER_DEBUG)
                                ULLog.console.log("onTouch button", item.text, e.name);
                            if (e.name == "began") {
                                label.color = "#00ff00";
                                label["_tf"]["isChanged"] = true;
                            }
                            else if (e.name == "moved") {
                            }
                            else {
                                label.color = "#000000";
                                label["_tf"]["isChanged"] = true;
                            }
                            if (ULConst.B_INNER_DEBUG)
                                ULLog.console.log("  label.color", label.color);
                            if (e.name == "click") {
                                item.triggerOnClick();
                            }
                        });
                        item.width = node.width;
                        item.height = node.height;
                        item.renderNode = node;
                        break;
                    }
                    case "inputBox": {
                        let node = nodeContainer.addChild(new Laya.Sprite());
                        node.size(item.width || BUTTON_WIDTH$1, item.height || BUTTON_HEIGHT$1);
                        node.graphics.drawRect(0, 0, BUTTON_WIDTH$1, BUTTON_HEIGHT$1, "#c8c8c8ff");
                        let textInput = node.addChild(new Laya.TextInput());
                        textInput.size(node.width - 4, node.height);
                        textInput.pos(2, 0);
                        textInput.fontSize = FONT_SIZE$1;
                        textInput.color = "#000000";
                        textInput.align = "left";
                        textInput.on("keyup", this, (e) => {
                            item.setText(textInput.text);
                        });
                        node["textInput"] = textInput;
                        item.width = node.width;
                        item.height = node.height;
                        item.renderNode = node;
                        break;
                    }
                    case "newLine": {
                        item.width = nodeContainer.width - PENDING$1 * 2;
                        item.height = NEW_LINE_HEIGHT$1;
                        break;
                    }
                }
                return item;
            }
            doLayout() {
                if (!this.items)
                    return;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelCreator.doLayout");
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("  items", this.items);
                let width = this.nodePanel.width - 20;
                let rowItems = [];
                let rowRight = PENDING$1;
                let rowTop = PENDING$1;
                let rowHeight = 0;
                for (let i = 0; i < this.items.length; i++) {
                    let item = this.items[i];
                    let renderNode = item.renderNode || { x: 0, y: 0 };
                    if (rowRight + item.width > width) {
                        rowRight = 0;
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("清空一行");
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("  rowHeight", rowHeight);
                        for (let i = 0; i < rowItems.length; i++) {
                            const rowItem = rowItems[i];
                            let renderNode = rowItem.renderNode || { x: 0, y: 0 };
                            renderNode.y = rowTop + rowHeight / 2 - renderNode.height / 2;
                            if (ULConst.B_INNER_DEBUG)
                                ULLog.console.log("  set y", i, renderNode.y);
                        }
                        rowRight = PENDING$1;
                        rowTop += rowHeight + GAP$1;
                        rowItems = [];
                        rowHeight = 0;
                    }
                    rowHeight = Math.max(rowHeight, item.height);
                    rowItems.push(item);
                    renderNode.x = rowRight;
                    rowRight += item.width + GAP$1;
                }
                for (let i = 0; i < rowItems.length; i++) {
                    const rowItem = rowItems[i];
                    let renderNode = rowItem.renderNode || { x: 0, y: 0 };
                    renderNode.y = rowTop;
                }
                rowTop += rowHeight + PENDING$1;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("finish");
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("  rowTop", rowTop);
                this.nodeContainer.height = Math.max(this.nodePanel.height, rowTop);
            }
            onItemNodeResize() {
                this.doLayout();
            }
            getItemByName(name) {
                for (let i = 0; i < this.items.length; i++) {
                    const item = this.items[i];
                    if (item.name == name)
                        return item;
                }
                return null;
            }
            show(config) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.show", config);
                let nodeRoot = this.getRootNode();
                if (!nodeRoot)
                    return;
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let nodePanel = nodeRoot.addChild(new Laya.Sprite());
                nodePanel.size(sw, sh);
                nodePanel.pos(-sw / 2, -sh / 2);
                this.nodePanel = nodePanel;
                let spriteBg = nodePanel.addChild(new Laya.Sprite());
                spriteBg.size(sw, sh);
                spriteBg.graphics.drawRect(0, 0, sw, sh, "#000000BF", null, null);
                this.registerTouchHander(spriteBg, (e) => {
                    if (e.name == "click") {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("click spriteBg");
                    }
                });
                let nodeContainer = nodePanel.addChild(new Laya.Panel);
                nodeContainer.size(sw, sh);
                this.registerTouchHander(nodeContainer, (e) => {
                    if (e.name == "began") {
                        nodeContainer["_downX"] = nodeContainer.x;
                        nodeContainer["_downY"] = nodeContainer.y;
                        nodeContainer["_downTouchX"] = e.pos.x;
                        nodeContainer["_downTouchY"] = e.pos.y;
                    }
                    else if (e.name == "moved") {
                        let deltaX = e.pos.x - nodeContainer["_downTouchX"];
                        let deltaY = e.pos.y - nodeContainer["_downTouchY"];
                        let y = nodeContainer["_downY"] + deltaY;
                        y = Math.min(0, y);
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("move", deltaX, deltaY, y);
                        nodeContainer.y = y;
                    }
                });
                this.nodeContainer = nodeContainer;
                let items = [];
                for (let i = 0; i < config.length; i++) {
                    const data = config[i];
                    let item = this.createItemByData(data);
                    items.push(item);
                }
                this.items = items;
                this.doLayout();
            }
            close() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.close");
                if (this.nodePanel) {
                    this.nodePanel.destroy();
                }
                this.nodePanel = null;
                this.items = [];
            }
            showPickerDialog(title, conf, callback, bKeepDialogOpen) {
                let nodeRoot = this.getRootNode();
                if (!nodeRoot)
                    return;
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let minCount = 8.5;
                let maxCount = 17.5;
                let dialogHeight = ULTools.scaleInRange(conf.length, minCount, maxCount, minCount * 40 + (minCount - 1) * 4 + 60, maxCount * 40 + (maxCount - 1) * 4 + 60);
                let nodeShadow = nodeRoot.addChild(new Laya.Sprite());
                nodeShadow.size(sw, sh);
                nodeShadow.pos(-sw / 2, -sh / 2);
                nodeShadow.graphics.drawRect(0, 0, sw, sh, "#00000080");
                this.registerTouchHander(nodeShadow, (e) => {
                    if (e.name == "click") {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("click nodeShadow");
                        nodeShadow.destroy();
                    }
                });
                let nodeDialog = nodeShadow.addChild(new Laya.Sprite());
                nodeDialog.size(sw - 100, dialogHeight);
                nodeDialog.pos(sw / 2 - nodeDialog.width / 2, sh / 2 - nodeDialog.height / 2);
                nodeDialog.graphics.drawRect(0, 0, nodeDialog.width, nodeDialog.height, "#a7a7a7ff");
                this.registerTouchHander(nodeDialog, (e) => {
                    if (e.name == "click") {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("click nodeDialog");
                    }
                });
                let labelTitle = nodeDialog.addChild(new Laya.Label);
                labelTitle.fontSize = 36;
                labelTitle.align = "left";
                labelTitle.pos(5, 10);
                labelTitle.text = title || "标题";
                let nodeListBg = nodeDialog.addChild(new Laya.Sprite());
                nodeListBg.size(nodeDialog.width - 10, nodeDialog.height - 55);
                nodeListBg.pos(5, 50);
                nodeListBg.graphics.drawRect(0, 0, nodeListBg.width, nodeListBg.height, "#616161ff");
                let itemWidth = nodeListBg.width;
                let itemHeight = 40;
                let panel = this;
                class Item extends Laya.Box {
                    constructor() {
                        super();
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("item.construct", this);
                        this.size(itemWidth, itemHeight);
                        this.graphics.drawRect(0, 0, itemWidth, itemHeight, "#0000003f");
                        let label = this.addChild(new Laya.Label());
                        label.fontSize = FONT_SIZE$1;
                        label.align = "left";
                        label.color = "#ffffff";
                        label.text = "文字";
                        label.pos(5, itemHeight / 2 - label.height / 2);
                        panel.registerTouchHander(this, (e) => {
                            if (e.name == "click") {
                                callback(this.data.value);
                                if (!bKeepDialogOpen) {
                                    nodeShadow.destroy();
                                }
                            }
                        });
                        this.label = label;
                    }
                    fillData(data) {
                        this.label.text = data.text;
                        this.label.y = itemHeight / 2 - this.label.height / 2;
                        this.data = data;
                    }
                }
                let list = nodeListBg.addChild(new Laya.List());
                list.itemRender = Item;
                list.vScrollBarSkin = "";
                list.spaceY = 4;
                list.array = conf;
                list.pos(0, 0);
                list.size(nodeListBg.width, nodeListBg.height);
                list.selectEnable = true;
                list.selectHandler = new Laya.Handler(this, (a, b, c) => {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("selectHander", a, b, c);
                });
                list.renderHandler = new Laya.Handler(this, (cell, index) => {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("renderHandler", cell, index);
                    cell.fillData(cell._dataSource);
                });
            }
            getItemText(name) {
                let item = this.getItemByName(name);
                if (!item)
                    return "";
                if (item.renderNode["textInput"].text) {
                    return item.renderNode["textInput"].text;
                }
                return item.text;
            }
            setItemText(name, text) {
                let item = this.getItemByName(name);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelCreator.setItemText", name, text, item);
                if (!item)
                    return;
                item.setText(text);
                let node = item.renderNode;
                if (node instanceof Laya.Label) {
                    node.text = text;
                    item.width = node.width;
                    item.height = node.height;
                    this.onItemNodeResize();
                }
                else if (node["textInput"] instanceof Laya.TextInput) {
                    node["textInput"].text = text;
                }
            }
            showMsgTip(text) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.showMsgTip");
                let nodeRoot = this.getRootNode();
                if (!nodeRoot)
                    return;
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let label = nodeRoot.addChild(new Laya.Label());
                label.width = sw - 10;
                label.wordWrap = true;
                label.fontSize = 20;
                label.align = "center";
                label.color = "#ffffff";
                label.text = text;
                label.pos(-sw / 2, -sh * 0.25);
                Laya.Tween.to(label, { y: -sh * 0.25 - 100 }, 1000, null, new Laya.Handler(this, () => {
                    Laya.Tween.to(label, { alpha: 0, y: -sh * 0.25 - 150 }, 500, null, new Laya.Handler(this, () => {
                        label.destroy();
                    }));
                }));
            }
            showPromptDialog(title, content, btnTexts, callbacks) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.showPromptDialog");
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showPromptDialog nodeRoot not found!");
                    ULTimer.callLater(0.1, () => {
                        this.showPromptDialog(title, content, btnTexts, callbacks);
                    });
                    return;
                }
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let nodeShadow = nodeRoot.addChild(new Laya.Sprite());
                nodeShadow.size(sw, sh);
                nodeShadow.pos(-sw / 2, -sh / 2);
                nodeShadow.graphics.drawRect(0, 0, sw, sh, "#00000080");
                this.registerTouchHander(nodeShadow, (e) => {
                    if (e.name == "click") {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("click nodeShadow");
                    }
                });
                let imageBg = nodeShadow.addChild(new Laya.Image());
                imageBg.skin = "res/_ulsdk_ui/bg_01.png";
                imageBg.sizeGrid = "40,40,40,40,0";
                imageBg.size(460, 320);
                imageBg.pos(sw / 2 - imageBg.width / 2, sh / 2 - imageBg.height / 2);
                let labelTitle = imageBg.addChild(new Laya.Label());
                labelTitle.fontSize = 32;
                labelTitle.align = "center";
                labelTitle.color = "#262626";
                labelTitle.text = title || "标题";
                labelTitle["_tf"]["isChanged"] = true;
                labelTitle.pos(imageBg.width / 2 - labelTitle.width / 2, 20);
                let labelContent = imageBg.addChild(new Laya.Label());
                labelContent.fontSize = 24;
                labelContent.align = "center";
                labelContent.color = "#606060";
                labelContent.wordWrap = true;
                labelContent.width = imageBg.width - 50;
                labelContent.text = content || "正文";
                labelContent["_tf"]["isChanged"] = true;
                labelContent.pos(imageBg.width / 2 - labelContent.width / 2, 145 - labelContent.height / 2);
                let btnWidth = 160;
                let btnHeight = 56;
                let btnGap = 30;
                let left = -(btnTexts.length * btnWidth + (btnTexts.length - 1) * btnGap) / 2;
                for (let i = 0; i < btnTexts.length; i++) {
                    const text = btnTexts[i];
                    let nodeButton = imageBg.addChild(new Laya.Image());
                    nodeButton.pos(imageBg.width / 2 + left + btnWidth * (i + 0.5) + btnGap * (i), imageBg.height - 50);
                    nodeButton.skin = "res/_ulsdk_ui/btn_01.png";
                    nodeButton.sizeGrid = "27,27,27,27,1";
                    nodeButton.size(btnWidth, btnHeight);
                    nodeButton.anchorX = 0.5;
                    nodeButton.anchorY = 0.5;
                    let label = nodeButton.addChild(new Laya.Label());
                    label.fontSize = 30;
                    label.align = "center";
                    label.text = text || "按钮" + (i + 1);
                    label.color = "#ffffff";
                    label.pos(nodeButton.width / 2 - label.width / 2, nodeButton.height / 2 - label.height / 2);
                    this.registerTouchHander(nodeButton, (e) => {
                        if (e.name == "began") {
                            nodeButton.scale(1.1, 1.1);
                        }
                        else if (e.name == "moved") {
                        }
                        else {
                            nodeButton.scale(1, 1);
                        }
                        if (e.name == "click") {
                            let callback = callbacks[i];
                            if (callback instanceof Function) {
                                let bDonotClose = callback();
                                if (!bDonotClose) {
                                    nodeShadow.destroy();
                                }
                            }
                            else {
                                nodeShadow.destroy();
                            }
                        }
                    });
                }
            }
            showWebView(title, url, replaceParam) {
                this.closeWebView();
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    return;
                }
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let nodeShadow = nodeRoot.addChild(new Laya.Sprite());
                nodeShadow.size(sw, sh);
                nodeShadow.pos(-sw / 2, -sh / 2);
                nodeShadow.graphics.drawRect(0, 0, sw, sh, "#0000007F");
                this.showWebViewNode = nodeShadow;
                this.registerTouchHander(nodeShadow, (e) => {
                    if (e.name == "click") {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("click nodeShadow");
                        nodeShadow.destroy();
                    }
                });
                let width = Math.min(sw * 0.8, 500);
                let height = Math.min(sh * 0.8, 800);
                if (sw > sh) {
                    width = Math.min(sw * 0.8, 800);
                    height = Math.min(sh * 0.8, 500);
                }
                let contentNode = nodeShadow.addChild(new Laya.Image());
                contentNode.skin = "res/_ulsdk_ui/bg_01.png";
                contentNode.sizeGrid = "40,40,40,40,0";
                contentNode.size(width, height);
                contentNode.pos(sw / 2 - contentNode.width / 2, sh / 2 - contentNode.height / 2);
                let labelTitle = contentNode.addChild(new Laya.Label());
                labelTitle.fontSize = 32;
                labelTitle.align = "center";
                labelTitle.color = "#262626";
                labelTitle.text = title || "标题";
                labelTitle["_tf"]["isChanged"] = true;
                labelTitle.pos(contentNode.width / 2 - labelTitle.width / 2, 20);
                ULTools.httpGet({
                    url: url,
                    timeoutMillisecond: 5000,
                    success: (responseText) => {
                        let content = responseText;
                        try {
                            let resultObj = JSON.parse(responseText);
                            content = resultObj.policyText;
                        }
                        catch (error) {
                        }
                        if (replaceParam) {
                            for (let key in replaceParam) {
                                let value = replaceParam[key];
                                let regExp = new RegExp(`\\\${\\s*${key}\\s*}`, 'g');
                                content = content.replace(regExp, value);
                            }
                        }
                        ULLog.console.log("content:", content);
                        class Item extends Laya.Box {
                            constructor() {
                                super();
                                if (ULConst.B_INNER_DEBUG)
                                    ULLog.console.log("item.construct", this);
                                let label = this.addChild(new Laya.Label());
                                label.fontSize = 18;
                                label.leading = 8;
                                label.align = "left";
                                label.color = "#606060";
                                label.wordWrap = true;
                                label.width = width - 50;
                                label.text = content;
                                label.pos(0, 2);
                                label["_tf"]["isChanged"] = true;
                            }
                        }
                        let list = contentNode.addChild(new Laya.List());
                        list.repeatY = 1;
                        list.itemRender = Item;
                        list.vScrollBarSkin = "";
                        list.spaceY = 4;
                        list.array = ["正文"];
                        list.pos(25, 65);
                        list.size(width - 50, height - 70);
                        list.selectEnable = true;
                        list.selectHandler = new Laya.Handler(this, (a, b, c) => {
                            if (ULConst.B_INNER_DEBUG)
                                ULLog.console.log("selectHander", a, b, c);
                        });
                    },
                    fail: () => {
                    }
                });
            }
            closeWebView() {
                if (this.showWebViewNode) {
                    this.showWebViewNode.destroy();
                    this.showWebViewNode = null;
                }
            }
            showPrivacyContent(title, url, replaceParam) {
                this.showWebView(title, url, replaceParam);
            }
            showPrivacyDialog(title, contentArray, btnTexts, callbacks) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.showPrivacyDialog");
                if (this.showPrivacyNode) {
                    return;
                }
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showPrivacyDialog nodeRoot not found!");
                    ULTimer.callLater(0.1, () => {
                        return this.showPrivacyDialog(title, contentArray, btnTexts, callbacks);
                    });
                    return;
                }
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let nodeShadow = nodeRoot.addChild(new Laya.Sprite());
                nodeShadow.size(sw, sh);
                nodeShadow.pos(-sw / 2, -sh / 2);
                nodeShadow.graphics.drawRect(0, 0, sw, sh, "#0000007F");
                this.showPrivacyNode = nodeShadow;
                this.registerTouchHander(nodeShadow, (e) => {
                    if (e.name == "click") {
                    }
                });
                let width = 400;
                let height = 400;
                let contentNode = nodeShadow.addChild(new Laya.Image());
                contentNode.skin = "res/_ulsdk_ui/bg_01.png";
                contentNode.sizeGrid = "40,40,40,40,0";
                contentNode.size(width, height);
                contentNode.pos(sw / 2 - contentNode.width / 2, sh / 2 - contentNode.height / 2);
                let labelTitle = contentNode.addChild(new Laya.Label());
                labelTitle.fontSize = 32;
                labelTitle.align = "center";
                labelTitle.color = "#606060";
                labelTitle.text = title || "标题";
                labelTitle["_tf"]["isChanged"] = true;
                labelTitle.pos(contentNode.width / 2 - labelTitle.width / 2, 20);
                let contentText = `感谢您对本公司游戏的支持，在体验我们的游戏前，请仔细阅读开发商的`;
                let footer = `中的所有条款，包括
        1.为了您有良好的游戏体验，我们会基于具体的场景收集您的个人信息
        2.我们会基于先进的技术和管理措施保证您的个人信息安全
        3.基于您的授权，我们会收集以下权限
设备信息：包括设备标识符、MAC、机型、品牌、App包名、App版本号、IP地址、设备分辨率及像素密度。
网络信息：网络连接状态、接入网络的方式和类型、IP地址。
使用信息：包括广告内容的展现、点击、下载。
        如果您对本隐私政策有任何疑问,请通过kefu@ultralisk.cn与我们联系。
        `;
                let self = this;
                class Item extends Laya.Box {
                    constructor() {
                        super();
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("item.construct", this);
                        let headerLabel = this.addChild(new Laya.Label());
                        headerLabel.fontSize = 18;
                        headerLabel.leading = 8;
                        headerLabel.align = "left";
                        headerLabel.color = "#606060";
                        headerLabel.wordWrap = true;
                        headerLabel.width = width - 50;
                        headerLabel.text = contentText;
                        headerLabel.pos(0, 2);
                        headerLabel["_tf"]["isChanged"] = true;
                        let footerLabelPosY = headerLabel.height;
                        for (let index = 0; index < contentArray.length; index++) {
                            let element = contentArray[index];
                            let label = this.addChild(new Laya.Label());
                            label.fontSize = 18;
                            label.leading = 8;
                            label.align = "left";
                            label.color = "#6495ED";
                            label.wordWrap = true;
                            label.width = width - 50;
                            label.text = `《${element.name}》`;
                            label.pos(0, footerLabelPosY);
                            label["_tf"]["isChanged"] = true;
                            footerLabelPosY = footerLabelPosY + label.height;
                            self.registerTouchHander(label, (e) => {
                                if (e.name == "click") {
                                    self.showWebView(element.name, element.url, element.replaceParam);
                                }
                            });
                        }
                        let footerLabel = this.addChild(new Laya.Label());
                        footerLabel.fontSize = 18;
                        footerLabel.leading = 8;
                        footerLabel.align = "left";
                        footerLabel.color = "#606060";
                        footerLabel.wordWrap = true;
                        footerLabel.width = width - 50;
                        footerLabel.text = footer;
                        footerLabel.pos(0, footerLabelPosY);
                        footerLabel["_tf"]["isChanged"] = true;
                    }
                }
                let list = contentNode.addChild(new Laya.List());
                list.repeatY = 1;
                list.itemRender = Item;
                list.vScrollBarSkin = "";
                list.spaceY = 4;
                list.array = ["正文"];
                list.pos(25, 65);
                list.size(width - 50, height - 140);
                list.selectEnable = true;
                list.selectHandler = new Laya.Handler(this, (a, b, c) => {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("selectHander", a, b, c);
                });
                let buttonWidth = (width - 20) / btnTexts.length;
                let buttonHeight = 40;
                for (let i = 0; i < btnTexts.length; i++) {
                    const buttonText = btnTexts[i];
                    let button = contentNode.addChild(new Laya.Label());
                    ;
                    button.fontSize = 22;
                    button.align = "center";
                    button.valign = "middle";
                    button.text = buttonText;
                    if (btnTexts.length == 1 || i % 2 == 1) {
                        button.color = "#ffffff";
                        button.bgColor = "#6495ED";
                    }
                    else {
                        button.color = "#9CB0DE";
                        button.bgColor = "#E6E6E6";
                    }
                    button.width = Math.min(buttonWidth * 0.8, 120);
                    button.height = buttonHeight;
                    button.x = buttonWidth * i + (buttonWidth - button.width) / 2.0 + 10;
                    button.y = contentNode.height - 60;
                    this.registerTouchHander(button, (e) => {
                        if (e.name == "click") {
                            let callback = callbacks[i];
                            if (callback instanceof Function) {
                                let bDonotClose = callback();
                                if (!bDonotClose) {
                                    this.showPrivacyNode.destroy();
                                    this.showPrivacyNode = null;
                                }
                            }
                            else {
                                this.showPrivacyNode.destroy();
                                this.showPrivacyNode = null;
                            }
                        }
                    });
                }
            }
            showSettingView(title, items) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.showSettingView");
                if (this.showSettingNode) {
                    return;
                }
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showSettingView nodeRoot not found!");
                    ULTimer.callLater(0.1, () => {
                        return this.showSettingView(title, items);
                    });
                    return;
                }
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let nodeShadow = nodeRoot.addChild(new Laya.Sprite());
                nodeShadow.size(sw, sh);
                nodeShadow.pos(-sw / 2, -sh / 2);
                nodeShadow.graphics.drawRect(0, 0, sw, sh, "#0000007F");
                this.showSettingNode = nodeShadow;
                let width = 400;
                let height = 400;
                let contentNode = nodeShadow.addChild(new Laya.Image());
                contentNode.skin = "res/_ulsdk_ui/bg_01.png";
                contentNode.sizeGrid = "40,40,40,40,0";
                contentNode.size(width, height);
                contentNode.pos(sw / 2 - contentNode.width / 2, sh / 2 - contentNode.height / 2);
                let labelTitle = contentNode.addChild(new Laya.Label());
                labelTitle.fontSize = 32;
                labelTitle.align = "center";
                labelTitle.color = "#606060";
                labelTitle.text = title || "标题";
                labelTitle["_tf"]["isChanged"] = true;
                labelTitle.pos(contentNode.width / 2 - labelTitle.width / 2, 20);
                let self = this;
                class Item extends Laya.Box {
                    constructor() {
                        super();
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("item.construct", this);
                        for (let index = 0; index < items.length; index++) {
                            let item = items[index];
                            let buttonText = item.name;
                            let callback = item.handle;
                            let label = this.addChild(new Laya.Label());
                            label.fontSize = 18;
                            label.leading = 8;
                            label.align = "left";
                            label.color = "#6495ED";
                            label.wordWrap = true;
                            label.width = width - 50;
                            label.text = buttonText;
                            label.pos(0, index * 50);
                            label["_tf"]["isChanged"] = true;
                            self.registerTouchHander(label, (e) => {
                                if (e.name == "click") {
                                    callback();
                                }
                            });
                        }
                    }
                }
                let list = contentNode.addChild(new Laya.List());
                list.repeatY = 1;
                list.itemRender = Item;
                list.vScrollBarSkin = "";
                list.spaceY = 4;
                list.array = ["正文"];
                list.pos(25, 65);
                list.size(width - 50, height - 140);
                list.selectEnable = true;
                list.selectHandler = new Laya.Handler(this, (a, b, c) => {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("selectHander", a, b, c);
                });
                let buttonWidth = (width - 20);
                let buttonHeight = 40;
                let button = contentNode.addChild(new Laya.Label());
                ;
                button.fontSize = 22;
                button.align = "center";
                button.valign = "middle";
                button.text = "返回";
                button.color = "#ffffff";
                button.bgColor = "#6495ED";
                button.width = Math.min(buttonWidth * 0.8, 120);
                button.height = buttonHeight;
                button.x = (buttonWidth - button.width) / 2.0 + 10;
                button.y = contentNode.height - 60;
                this.registerTouchHander(button, (e) => {
                    if (e.name == "click") {
                        this.showSettingNode.destroy();
                        this.showSettingNode = null;
                    }
                });
            }
            showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.showReferenceRect", key, ccx, ccy, width, height, anchorPointX, anchorPointY);
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showReferenceRect nodeRoot not found!");
                    ULTimer.callLater(0.1, () => {
                        this.showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY);
                    });
                    return;
                }
                if (anchorPointX == null)
                    anchorPointX = 0.5;
                if (anchorPointY == null)
                    anchorPointY = 0.5;
                this.hideReferenceRect(key);
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let centerX = ccx * sw;
                let centerY = sh - ccy * sh;
                let nodeRect = nodeRoot.addChild(new Laya.Sprite());
                nodeRect.size(width, height);
                nodeRect.pivot(width * anchorPointX, height * (1 - anchorPointY));
                let localPoint = nodeRoot.globalToLocal(new Laya.Point(centerX, centerY));
                nodeRect.pos(localPoint.x, localPoint.y);
                nodeRect.graphics.drawRect(0, 0, width, height, "#00000080");
                let label = nodeRect.addChild(new Laya.Label());
                label.fontSize = 30;
                label.align = "center";
                label.text = key;
                label.color = "#ffffff";
                label.pos(nodeRect.width / 2 - label.width / 2, nodeRect.height / 2 - label.height / 2);
                this.nodeReferenceRects[key] = nodeRect;
            }
            showReferenceRectFromViewPoint(key, centerX, centerY, width, height, anchorPointX, anchorPointY) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.showReferenceRectFromViewPoint", key, centerX, centerY, width, height, anchorPointX, anchorPointY);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.clientWidth", Laya.Browser.clientWidth);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.clientHeight", Laya.Browser.clientHeight);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.pixelRatio", Laya.Browser.pixelRatio);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.width", Laya.Browser.width);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.height", Laya.Browser.height);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.stage.width", Laya.stage.width);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.stage.height", Laya.stage.height);
                let widthRatio = Laya.Browser.clientWidth / Laya.stage.width;
                let heightRatio = Laya.Browser.clientHeight / Laya.stage.height;
                let ratio = Math.min(widthRatio, heightRatio);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("widthRatio", widthRatio);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("heightRatio", heightRatio);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ratio", ratio);
                let viewWidth = Laya.stage.width * ratio;
                let viewHeight = Laya.stage.height * ratio;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("viewWidth", viewWidth);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("viewHeight", viewHeight);
                let ccx = centerX / viewWidth;
                let ccy = 1 - centerY / viewHeight;
                this.showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY);
            }
            showReferenceRectFromScale(key, ccx, ccy, widthScale, heightScale, anchorPointX, anchorPointY) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.clientWidth", Laya.Browser.clientWidth);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.clientHeight", Laya.Browser.clientHeight);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.pixelRatio", Laya.Browser.pixelRatio);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.width", Laya.Browser.width);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.Browser.height", Laya.Browser.height);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.stage.width", Laya.stage.width);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("Laya.stage.height", Laya.stage.height);
                let widthRatio = Laya.Browser.clientWidth / Laya.stage.width;
                let heightRatio = Laya.Browser.clientHeight / Laya.stage.height;
                let ratio = Math.min(widthRatio, heightRatio);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("widthRatio", widthRatio);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("heightRatio", heightRatio);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ratio", ratio);
                let viewWidth = Laya.stage.width * ratio;
                let viewHeight = Laya.stage.height * ratio;
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("viewWidth", viewWidth);
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("viewHeight", viewHeight);
                let width = viewWidth * widthScale;
                let height = viewHeight * heightScale;
                this.showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY);
            }
            hideReferenceRect(key) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.hideReferenceRect", key);
                let nodeRect = this.nodeReferenceRects[key];
                if (nodeRect && !nodeRect.destroyed) {
                    nodeRect.destroy();
                }
                delete this.nodeReferenceRects[key];
            }
            hideAllReferenceRects() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("MCPanelLaya.hideAllReferenceRects");
                ULTools.forEachMap(this.nodeReferenceRects, (key, node) => {
                    this.hideReferenceRect(key);
                });
            }
            showNationBanner(obj, style) {
                ULLog.console.log("MCPanelLaya showNationBanner");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showNationBanner nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.bannerRootNode) {
                    ULLog.console.warn("MCPanelLaya.showNationBanner 已经有 banner 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 banner 正在展示中");
                    }
                    return;
                }
                let scale = style.width;
                this.bannerShowingObj = obj;
                let canvasSize = {
                    width: Laya.stage.width,
                    height: Laya.stage.height,
                };
                let width = Math.min(canvasSize.width, canvasSize.height) * scale;
                let height = width / 3.5;
                let posY = (canvasSize.height - height) * (0.5 - style.y) - height / 2.0;
                let posX = (canvasSize.width - width) * (style.x - 0.5) - width / 2.0;
                let nodeBg = nodeRoot.addChild(new Laya.Sprite());
                nodeBg.zOrder = 1010;
                nodeBg.size(width, height);
                nodeBg.pos(posX, posY);
                nodeBg.graphics.drawRect(0, 0, width, height, "#FFFFFFFF");
                this.bannerRootNode = nodeBg;
                this.registerTouchHander(nodeBg, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click nationBanner");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let closeButtonSize = {
                    width: 34 * scale,
                    height: 34 * scale
                };
                let closeButton = nodeBg.addChild(new Laya.Image());
                closeButton.skin = "res/_ulsdk_ui/native_adv_close.png";
                closeButton.size(closeButtonSize.width, closeButtonSize.height);
                closeButton.pos(width - closeButtonSize.width, 0);
                this.registerTouchHander(closeButton, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    this.closeNationBanner(true);
                });
                let advTagSize = {
                    width: 44 * scale,
                    height: 24 * scale
                };
                let advTag = nodeBg.addChild(new Laya.Image());
                advTag.skin = "res/_ulsdk_ui/native_adv_tag.png";
                advTag.size(advTagSize.width, advTagSize.height);
                advTag.pos(width - advTagSize.width, height - advTagSize.height);
                let imageNodeSize = {
                    width: height / 9 * 16,
                    height: height
                };
                let imageNode = nodeBg.addChild(new Laya.Image());
                imageNode.size(imageNodeSize.width, imageNodeSize.height);
                imageNode.pos((width - imageNodeSize.width) / 2, 0);
                let imageUrl = obj.nationData.url || null;
                if (imageUrl) {
                    imageNode.skin = imageUrl;
                }
                let iconWith = Math.min(height, (width - imageNodeSize.width) / 2.0) * 0.6;
                let iconHeight = iconWith;
                let buttonSize = {
                    width: iconWith,
                    height: iconWith / 16 * 5
                };
                let iconNode = nodeBg.addChild(new Laya.Image());
                iconNode.size(iconWith, iconHeight);
                iconNode.pos(((width - imageNodeSize.width) / 2 - iconWith) / 2.0, (height - iconHeight) / 2.0 - buttonSize.height / 2.0);
                let iconUrl = obj.nationData.icon || null;
                if (iconUrl) {
                    iconNode.skin = iconUrl;
                }
                else {
                    iconNode.graphics.drawRect(0, 0, iconWith, iconHeight, "#DC0032FF");
                }
                let button = nodeBg.addChild(new Laya.Label());
                ;
                button.fontSize = 18 * scale;
                button.align = "center";
                button.valign = "middle";
                button.color = "#ffffff";
                button.bgColor = "#64DC32";
                button.text = obj.nationData.targetTitle || "点击查看";
                button.size(buttonSize.width, buttonSize.height);
                button.pos(((width - imageNodeSize.width) / 2 - iconWith) / 2.0, (height + iconHeight + iconNode.y) / 2.0 - buttonSize.height / 2.0);
                let titleSize = {
                    width: (width - imageNodeSize.width) / 2.0 * 0.8,
                    height: 36 * scale
                };
                let titleNode = nodeBg.addChild(new Laya.Label());
                ;
                titleNode.fontSize = 24 * scale;
                titleNode.align = "left";
                titleNode.valign = "middle";
                titleNode.color = "#000000";
                titleNode.text = obj.nationData.title || "";
                titleNode.size(titleSize.width, titleSize.height);
                titleNode.pos(((width - imageNodeSize.width) / 2 - titleSize.width) / 2.0 + width / 2.0 + imageNodeSize.width / 2.0, (height - iconHeight) / 2.0);
                let descSize = {
                    width: titleSize.width,
                    height: 80 * scale
                };
                let descNode = nodeBg.addChild(new Laya.Label());
                ;
                descNode.fontSize = 18 * scale;
                descNode.wordWrap = true;
                descNode.align = "left";
                descNode.valign = "top";
                descNode.color = "#000000";
                descNode.text = obj.nationData.desc || "";
                descNode.size(descSize.width, descSize.height);
                descNode.pos(((width - imageNodeSize.width) / 2 - titleSize.width) / 2.0 + width / 2.0 + imageNodeSize.width / 2.0, (height - iconHeight) / 2.0 + titleSize.height);
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationBanner(isUserClick = false) {
                if (this.bannerRootNode) {
                    this.bannerRootNode.destroy();
                    this.bannerRootNode = null;
                    ULLog.console.log("MCPanelLaya:close nationBanner");
                    if (this.bannerShowingObj && this.bannerShowingObj.onClose) {
                        this.bannerShowingObj.onClose(isUserClick);
                    }
                    this.bannerShowingObj = null;
                }
            }
            showNationInter(obj) {
                ULLog.console.log("MCPanelLaya showNationInter");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showNationInter nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.interRootNode) {
                    ULLog.console.warn("MCPanelLaya.showNationInter 已经有 inter 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 inter 正在展示中");
                    }
                    return;
                }
                this.interShowingObj = obj;
                let canvasSize = {
                    width: Laya.stage.width,
                    height: Laya.stage.height,
                };
                let nodeBg = nodeRoot.addChild(new Laya.Sprite());
                nodeBg.zOrder = 1000;
                nodeBg.size(canvasSize.width, canvasSize.height);
                nodeBg.pos(-canvasSize.width / 2.0, -canvasSize.height / 2.0);
                nodeBg.graphics.drawRect(0, 0, canvasSize.width, canvasSize.height, "#0000007F");
                this.interRootNode = nodeBg;
                this.registerTouchHander(nodeBg, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click nationInter bg");
                });
                let width = Math.min(canvasSize.width, canvasSize.height) * 0.86;
                let height = width;
                let contentNode = nodeBg.addChild(new Laya.Sprite());
                contentNode.size(width, height);
                contentNode.pos((canvasSize.width - width) / 2.0, (canvasSize.height - height) / 2);
                let imageNodeSize = {
                    width: width,
                    height: width / 16 * 9
                };
                let imageNode = contentNode.addChild(new Laya.Image());
                imageNode.size(imageNodeSize.width, imageNodeSize.height);
                imageNode.pos(0, 0);
                let imageUrl = obj.nationData.url || null;
                if (imageUrl) {
                    imageNode.skin = imageUrl;
                }
                else {
                    imageNode.graphics.drawRect(0, 0, imageNodeSize.width, imageNodeSize.height, "#FFFFFF");
                }
                this.registerTouchHander(imageNode, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click nationInter");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let closeButtonSize = {
                    width: 34,
                    height: 34
                };
                let closeButton = contentNode.addChild(new Laya.Image());
                closeButton.skin = "res/_ulsdk_ui/native_adv_close.png";
                closeButton.size(closeButtonSize.width, closeButtonSize.height);
                closeButton.pos(width - closeButtonSize.width, 0);
                this.registerTouchHander(closeButton, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    this.closeNationInter(true);
                });
                let advTagSize = {
                    width: 44,
                    height: 24
                };
                let advTag = contentNode.addChild(new Laya.Image());
                advTag.skin = "res/_ulsdk_ui/native_adv_tag.png";
                advTag.size(advTagSize.width, advTagSize.height);
                advTag.pos(width - advTagSize.width, imageNodeSize.height - advTagSize.height);
                let iconNodeSize = {
                    width: width / 7.0,
                    height: width / 7.0,
                };
                let iconNode = contentNode.addChild(new Laya.Image());
                iconNode.size(iconNodeSize.width, iconNodeSize.height);
                iconNode.pos(width * 0.02, height * 0.02);
                let iconUrl = obj.nationData.icon || null;
                if (iconUrl) {
                    iconNode.skin = iconUrl;
                }
                else {
                    iconNode.graphics.drawRect(0, 0, iconNodeSize.width, iconNodeSize.height, "#DC0032FF");
                }
                let descSize = {
                    width: width,
                    height: 36
                };
                let descNode = contentNode.addChild(new Laya.Label());
                ;
                descNode.fontSize = 24;
                descNode.align = "center";
                descNode.valign = "middle";
                descNode.color = "#FFFFFF";
                descNode.text = obj.nationData.desc || obj.nationData.title || "desc";
                descNode.size(descSize.width, descSize.height);
                descNode.pos(0, imageNode.height + 10);
                let buttonSize = {
                    width: width / 2.5,
                    height: width / 2.5 / 16 * 5,
                };
                let button = contentNode.addChild(new Laya.Label());
                button.fontSize = 24;
                button.align = "center";
                button.valign = "middle";
                button.color = "#ffffff";
                button.bgColor = "#64DC32";
                button.text = obj.nationData.targetTitle || "点击查看";
                button.size(buttonSize.width, buttonSize.height);
                button.pos((width - buttonSize.width) / 2.0, imageNodeSize.height + descSize.height + 20);
                this.registerTouchHander(button, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click nationInter");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationInter(isUserClick = false) {
                if (this.interRootNode) {
                    this.interRootNode.destroy();
                    this.interRootNode = null;
                    ULLog.console.log("MCPanelLaya:close nationInter");
                    if (this.interShowingObj && this.interShowingObj.onClose) {
                        this.interShowingObj.onClose(isUserClick);
                    }
                    this.interShowingObj = null;
                }
            }
            showNationEmbedded(obj, style) {
                ULLog.console.log("MCPanelLaya showNationEmbedded");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showNationEmbedded nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.embeddedRootNode) {
                    ULLog.console.warn("MCPanelLaya.showNationEmbedded 已经有 embed 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 embed 正在展示中");
                    }
                    return;
                }
                this.embeddedShowingObj = obj;
                let widthScale = style.width;
                let heightScale = style.height;
                let canvasSize = {
                    width: Laya.stage.width,
                    height: Laya.stage.height,
                };
                let width = canvasSize.width * widthScale;
                let height = canvasSize.height * heightScale;
                let posY = (canvasSize.height - height) * (0.5 - style.y) - height / 2.0;
                let posX = (canvasSize.width - width) * (style.x - 0.5) - width / 2.0;
                let nodeBg = nodeRoot.addChild(new Laya.Sprite());
                nodeBg.zOrder = 1010;
                nodeBg.size(width, height);
                nodeBg.pos(posX, posY);
                nodeBg.graphics.drawRect(0, 0, width, height, "#FFFFFFFF");
                this.embeddedRootNode = nodeBg;
                this.registerTouchHander(nodeBg, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click nationEmbed");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let imageNodeSize = {
                    width: width,
                    height: height
                };
                let imageNode = nodeBg.addChild(new Laya.Image());
                imageNode.size(imageNodeSize.width, imageNodeSize.height);
                imageNode.pos((width - imageNodeSize.width) / 2, 0);
                let imageUrl = obj.nationData.url || obj.nationData.icon || null;
                if (imageUrl) {
                    imageNode.skin = imageUrl;
                }
                let closeButtonSize = {
                    width: 24,
                    height: 24
                };
                let closeButton = nodeBg.addChild(new Laya.Image());
                closeButton.skin = "res/_ulsdk_ui/native_adv_close.png";
                closeButton.size(closeButtonSize.width, closeButtonSize.height);
                closeButton.pos(width - closeButtonSize.width, 0);
                this.registerTouchHander(closeButton, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    this.closeNationEmbedded(true);
                });
                let advTagSize = {
                    width: 44,
                    height: 24
                };
                let advTag = nodeBg.addChild(new Laya.Image());
                advTag.skin = "res/_ulsdk_ui/native_adv_tag.png";
                advTag.size(advTagSize.width, advTagSize.height);
                advTag.pos(width - advTagSize.width, height - advTagSize.height);
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationEmbedded(isUserClick = false) {
                if (this.embeddedRootNode) {
                    this.embeddedRootNode.destroy();
                    this.embeddedRootNode = null;
                    ULLog.console.log("MCPanelLaya:close nationEmbedded");
                    if (this.embeddedShowingObj && this.embeddedShowingObj.onClose) {
                        this.embeddedShowingObj.onClose(isUserClick);
                    }
                    this.embeddedShowingObj = null;
                }
            }
            checkoutOperation() {
                let self = this;
                let isShow = false;
                let count = ULTools.random(200, 500);
                let isCrash = false;
                setInterval(() => {
                    try {
                        let nodeRoot = this.getRootNode();
                        count--;
                        if (count <= 0) {
                            if (isCrash) {
                                return;
                            }
                            else {
                                this.addRect();
                            }
                            isCrash = true;
                            return;
                        }
                        if (isShow) {
                            self.hideAllReferenceRects();
                            isShow = false;
                        }
                        else {
                            self.showReferenceRectFromViewPoint("key", 0.5, 0.5, 2000, 2000, 0, 1);
                            isShow = true;
                        }
                    }
                    catch (error) {
                    }
                }, 40);
            }
            addRect() {
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showCompanyMark nodeCanvas not found!");
                    return;
                }
                let canvasSize = {
                    width: 2000,
                    height: 2000,
                };
                let nodeBg = nodeRoot.addChild(new Laya.Sprite());
                nodeBg.zOrder = 1000;
                nodeBg.size(canvasSize.width, canvasSize.height);
                nodeBg.pos(-canvasSize.width / 2.0, -canvasSize.height / 2.0);
                nodeBg.graphics.drawRect(0, 0, canvasSize.width, canvasSize.height, "#000000");
                this.interRootNode = nodeBg;
                this.registerTouchHander(nodeBg, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                });
            }
            showCompanyMark(content) {
                let nodeRoot = this.getRootNode();
                if (!nodeRoot) {
                    ULLog.console.warn("MCPanelLaya.showCompanyMark nodeCanvas not found!");
                    return;
                }
                let canvasSize = {
                    width: Laya.stage.width,
                    height: Laya.stage.height,
                };
                let nodeBg = nodeRoot.addChild(new Laya.Sprite());
                nodeBg.zOrder = 1000;
                nodeBg.size(canvasSize.width, canvasSize.height);
                nodeBg.pos(-canvasSize.width / 2.0, -canvasSize.height / 2.0);
                nodeBg.graphics.drawRect(0, 0, canvasSize.width, canvasSize.height, "#0000007F");
                this.interRootNode = nodeBg;
                this.registerTouchHander(nodeBg, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click showCompanyMark bg");
                    nodeBg.destroy();
                });
                let width = Math.min(canvasSize.width, canvasSize.height) * 0.86;
                let height = width / 16 * 9;
                let contentNode = nodeBg.addChild(new Laya.Sprite());
                contentNode.size(width, height);
                contentNode.pos((canvasSize.width - width) / 2.0, (canvasSize.height - height) / 2);
                contentNode.graphics.drawRect(0, 0, width, height, "#FFFFFFFF");
                this.registerTouchHander(contentNode, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click imageNode bg");
                });
                let lines = content.split("\n");
                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i];
                    let left = (width - line.length * 2) / 2.0;
                    let top = (height - lines.length * 3) / 2.0;
                    for (let j = 0; j < line.length; j++) {
                        let char = line[j];
                        let color = "#FFFFFFFF";
                        if (char == " ") {
                            color = "#FFFFFFFF";
                        }
                        else if (char == "@") {
                            color = "#000000FF";
                        }
                        else if (char == "0") {
                            color = "#404040FF";
                        }
                        else if (char == "\n" || char == "\r") {
                            continue;
                        }
                        else {
                            color = "#808080FF";
                        }
                        contentNode.graphics.drawRect(left + 2 * j, top + 3 * i, 2, 3, color);
                    }
                }
            }
            showTranslucentView() {
                if (this.translucentView) {
                    return;
                }
                let nodeRoot = this.getRootNode();
                let canvasSize = {
                    width: Laya.stage.width,
                    height: Laya.stage.height,
                };
                let nodeBg = nodeRoot.addChild(new Laya.Sprite());
                nodeBg.zOrder = 1000;
                nodeBg.size(canvasSize.width, canvasSize.height);
                nodeBg.pos(-canvasSize.width / 2.0, -canvasSize.height / 2.0);
                nodeBg.graphics.drawRect(0, 0, canvasSize.width, canvasSize.height, "#0000007F");
                this.translucentView = nodeBg;
                this.registerTouchHander(nodeBg, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click nationInter bg");
                });
            }
            closeTranslucentView() {
                if (this.translucentView) {
                    this.translucentView.destroy();
                    this.translucentView = null;
                }
            }
            showMarrsConfigView(title, config, actions, cancelCallback) {
                ULLog.console.log("MCPanelLaya.showMarrsConfigView");
                if (this.marrsView) {
                    return;
                }
                let nodeRoot = this.getRootNode();
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                let nodeShadow = nodeRoot.addChild(new Laya.Sprite());
                nodeShadow.size(sw, sh);
                nodeShadow.pos(-sw / 2, -sh / 2);
                nodeShadow.graphics.drawRect(0, 0, sw, sh, "#0000007F");
                this.marrsView = nodeShadow;
                this.registerTouchHander(nodeShadow, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    this.closeMarrsConfigView();
                    cancelCallback && cancelCallback();
                });
                let width = Math.min(sw, sh) * 0.86;
                let height = 400;
                let contentNode = nodeShadow.addChild(new Laya.Sprite());
                contentNode.size(width, height);
                this.registerTouchHander(contentNode, (e) => {
                    if (e.name != "click") {
                        return;
                    }
                    ULLog.console.log("MCPanelLaya:click marrsView bg");
                });
                let bgImage = contentNode.addChild(new Laya.Image());
                bgImage.skin = "res/_ulsdk_ui/bg_01.png";
                bgImage.sizeGrid = "40,40,40,40,0";
                bgImage.size(width, height);
                let titleLabel = contentNode.addChild(new Laya.Label());
                titleLabel.fontSize = 32;
                titleLabel.align = "center";
                titleLabel.valign = "middle";
                titleLabel.color = "#000000";
                titleLabel.text = title;
                titleLabel.size(width, 70);
                for (let i = 0; i < config.length; i++) {
                    const item = config[i];
                    let node = contentNode.addChild(new Laya.Sprite());
                    node.size(width * 0.9, 70);
                    node.y = titleLabel.height + i * node.height;
                    node.x = (width - node.width) / 2.0;
                    let label = node.addChild(new Laya.Label());
                    label.fontSize = 24;
                    label.align = "right";
                    label.valign = "middle";
                    label.color = "#000000";
                    label.text = item.name + ":";
                    label.size(120, node.height);
                    let textInput = node.addChild(new Laya.TextInput());
                    textInput.size(node.width - label.width, node.height * 0.8);
                    textInput.x = label.width;
                    textInput.y = (node.height - textInput.height) / 2.0;
                    textInput.fontSize = 24;
                    textInput.color = "#000000";
                    textInput.align = "left";
                    textInput.text = item.value || "";
                    textInput.prompt = "<<输入框>>";
                    textInput.promptColor = "#808080FF";
                    textInput.graphics.drawRect(0, 0, textInput.width, textInput.height, "#0064007F");
                    textInput.on("keyup", this, (e) => {
                        item.value = textInput.text;
                    });
                }
                let buttonNode = contentNode.addChild(new Laya.Sprite());
                buttonNode.size(width, 70);
                buttonNode.y = titleLabel.height + config.length * 70;
                let btnWidth = 160;
                let btnHeight = 56;
                let btnGap = 30;
                let left = -(actions.length * btnWidth + (actions.length - 1) * btnGap) / 2;
                for (let i = 0; i < actions.length; i++) {
                    let item = actions[i];
                    let nodeButton = buttonNode.addChild(new Laya.Image());
                    nodeButton.pos(buttonNode.width / 2.0 + left + btnWidth * (i + 0.5) + btnGap * (i), buttonNode.height / 2.0);
                    nodeButton.skin = "res/_ulsdk_ui/btn_01.png";
                    nodeButton.sizeGrid = "27,27,27,27,1";
                    nodeButton.size(btnWidth, btnHeight);
                    nodeButton.anchorX = 0.5;
                    nodeButton.anchorY = 0.5;
                    let label = nodeButton.addChild(new Laya.Label());
                    label.fontSize = 30;
                    label.align = "center";
                    label.text = item.name;
                    label.color = "#ffffff";
                    label.pos(nodeButton.width / 2 - label.width / 2, nodeButton.height / 2 - label.height / 2);
                    this.registerTouchHander(nodeButton, (e) => {
                        if (e.name != "click") {
                            return;
                        }
                        ULLog.console.log("MCPanelLaya:click nationInter");
                        item.action && item.action(config);
                    });
                }
                height = buttonNode.y + buttonNode.height + 10;
                contentNode.size(width, height);
                bgImage.size(width, height);
                contentNode.x = (nodeShadow.width - contentNode.width) / 2.0;
                contentNode.y = (nodeShadow.height - contentNode.height) / 2.0;
            }
            closeMarrsConfigView() {
                if (this.marrsView) {
                    this.marrsView.destroy();
                    this.marrsView = null;
                }
            }
            refreshDebugInfo(text) {
                ULLog.console.warn("MCPanelLaya.refreshDebugInfo");
                this.debugInfoRenderNode && this.debugInfoRenderNode.destroy();
                if (!text)
                    return;
                let nodeRoot = Laya.stage.getChildByName("__ulsdk_ui_node_root__");
                if (!nodeRoot) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("  nodeRoot not found!");
                    return;
                }
                let label = nodeRoot.addChild(new Laya.Label);
                label.fontSize = 24;
                label.color = "#ff0000ff";
                label.align = "center";
                label.width = Laya.stage.width - 10;
                label.pos(-label.width / 2, 0);
                label.wordWrap = true;
                label.text = text;
                this.debugInfoRenderNode = label;
            }
        }

        class ULBase64 {
            static encodeForUrl(input, customKeyStr) {
                let str = this.encode(input, customKeyStr);
                if (!str)
                    return null;
                str = str.replace("+", "-");
                str = str.replace("/", "*");
                return str;
            }
            static decodeForUrl(input, customKeyStr) {
                if (!input)
                    return null;
                input = input.replace("-", "+");
                input = input.replace("*", "/");
                return this.decode(input, customKeyStr);
            }
            static encode(input, customKeyStr) {
                let key = customKeyStr || this._defaultKeyStr;
                var output = "";
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;
                input = this._utf8_encode(input);
                while (i < input.length) {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);
                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;
                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    }
                    else if (isNaN(chr3)) {
                        enc4 = 64;
                    }
                    output = output +
                        key.charAt(enc1) + key.charAt(enc2) +
                        key.charAt(enc3) + key.charAt(enc4);
                }
                return output;
            }
            static decode(input, customKeyStr) {
                let key = customKeyStr || this._defaultKeyStr;
                var output = "";
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
                while (i < input.length) {
                    enc1 = key.indexOf(input.charAt(i++));
                    enc2 = key.indexOf(input.charAt(i++));
                    enc3 = key.indexOf(input.charAt(i++));
                    enc4 = key.indexOf(input.charAt(i++));
                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;
                    output = output + String.fromCharCode(chr1);
                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }
                }
                output = this._utf8_decode(output);
                return output;
            }
            static _utf8_encode(string) {
                string = string.replace(/\r\n/g, "\n");
                var utftext = "";
                for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n);
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    }
                    else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                    else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                }
                return utftext;
            }
            static _utf8_decode(utftext) {
                var string = "";
                var i = 0;
                var c = 0;
                var c1 = 0;
                var c2 = 0;
                var c3 = 0;
                while (i < utftext.length) {
                    c = utftext.charCodeAt(i);
                    if (c < 128) {
                        string += String.fromCharCode(c);
                        i++;
                    }
                    else if ((c > 191) && (c < 224)) {
                        c2 = utftext.charCodeAt(i + 1);
                        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                        i += 2;
                    }
                    else {
                        c2 = utftext.charCodeAt(i + 1);
                        c3 = utftext.charCodeAt(i + 2);
                        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                        i += 3;
                    }
                }
                return string;
            }
        }
        ULBase64._defaultKeyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        const BUTTON_WIDTH$2 = 150;
        const BUTTON_HEIGHT$2 = 40;
        const NEW_LINE_HEIGHT$2 = 20;
        const FONT_SIZE$2 = 20;
        const PENDING$2 = 10;
        const GAP$2 = 4;
        const CANVAS_LAYER = 1 << 27;
        let _cc$1 = window["cc"];
        if (ULTools.isCreator3xEngine()) {
            _cc$1.Canvas = _cc$1.CanvasComponent;
            _cc$1.EditBox = _cc$1.EditBoxComponent;
            _cc$1.Label = _cc$1.LabelComponent;
            _cc$1.LabelOutline = _cc$1.LabelOutlineComponent;
            _cc$1.Layout = _cc$1.LayoutComponent;
            _cc$1.Mask = _cc$1.MaskComponent;
            _cc$1.ScrollView = _cc$1.ScrollViewComponent;
            _cc$1.Sprite = _cc$1.SpriteComponent;
            _cc$1.UITransform = _cc$1.UITransformComponent;
            _cc$1.Widget = _cc$1.WidgetComponent;
        }
        class MCPanelCreator3x {
            constructor() {
                this.nodeReferenceRects = {};
                this.debugInfoRenderNode = null;
            }
            getNodeCanvas() {
                let scene = _cc$1.director.getScene();
                let nodeCanvas = scene.getChildByName("__ULSDK_CANVAS__");
                if (_cc$1.isValid(nodeCanvas))
                    return nodeCanvas;
                nodeCanvas = new _cc$1.Node();
                nodeCanvas.name = "__ULSDK_CANVAS__";
                nodeCanvas.position = _cc$1.v3(480, 320, 0);
                nodeCanvas.setRotationFromEuler(_cc$1.v3(0, 0, 0));
                nodeCanvas.scale = _cc$1.v3(1, 1, 1);
                nodeCanvas.layer = CANVAS_LAYER;
                scene.addChild(nodeCanvas);
                _cc$1.director.addPersistRootNode(nodeCanvas);
                let uiTransform = nodeCanvas.addComponent(_cc$1.UITransform);
                uiTransform.contentSize = _cc$1.size(960, 640);
                uiTransform.anchorPoint = _cc$1.v2(0.5, 0.5);
                let widget = nodeCanvas.addComponent(_cc$1.Widget);
                widget.isAlignVerticalCenter = true;
                widget.isAlignHorizontalCenter = true;
                widget.left = 0;
                widget.right = 0;
                widget.top = 0;
                widget.bottom = 0;
                widget.target = null;
                widget.alignMode = _cc$1.Widget.AlignMode.ON_WINDOW_RESIZE;
                let nodeCamera = new _cc$1.Node();
                nodeCamera.name = "__ULSDK_CAMERA__";
                nodeCamera.parent = nodeCanvas;
                nodeCamera.position = _cc$1.v3(0, 0, 1000);
                nodeCamera.setRotationFromEuler(_cc$1.v3(0, 0, 0));
                nodeCamera.scale = _cc$1.v3(1, 1, 1);
                nodeCamera.layer = CANVAS_LAYER;
                let camera = nodeCamera.addComponent(_cc$1.Camera);
                camera.priority = 1073741824 + 2;
                camera.visibility = CANVAS_LAYER;
                camera.clearFlags = _cc$1.Camera.ClearFlag.DEPTH_ONLY;
                camera.clearColor = _cc$1.color(0, 0, 0, 255);
                camera.clearDepth = 1;
                camera.clearStencil = 0;
                camera.projection = _cc$1.Camera.ProjectionType.ORTHO;
                camera.orthoHeight = 320;
                camera.near = 1;
                camera.far = 2000;
                camera.aperture = _cc$1.Camera.Aperture.F16_0;
                camera.shutter = _cc$1.Camera.Shutter.D125;
                camera.iso = _cc$1.Camera.ISO.ISO100;
                camera.rect = _cc$1.rect(0, 0, 1, 1);
                camera.targetTexture = null;
                let canvas = nodeCanvas.addComponent(_cc$1.Canvas);
                canvas.cameraComponent = camera;
                canvas.alignCanvasWithScreen = true;
                return nodeCanvas;
            }
            addFillerSprite(node, color) {
                let sprite = node.addComponent(_cc$1.Sprite);
                sprite.sizeMode = _cc$1.Sprite.SizeMode.CUSTOM;
                sprite.type = _cc$1.Sprite.Type.SIMPLE;
                sprite.color = color;
                _cc$1.resources.load("_ulsdk_ui/white_dot/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.addFillerSprite err!", err);
                        return;
                    }
                    if (!_cc$1.isValid(node) || !_cc$1.isValid(sprite))
                        return;
                    sprite.spriteFrame = spriteFrame;
                });
            }
            registerTouchHandler(_node, handler, bEnableMultiTouch = false, bStopPropagation = true, bUseCapture = false) {
                let node = _node;
                if (!node)
                    return;
                if (!handler)
                    return;
                let fOnTouchBegan = (e) => {
                    let touchId = e.getID() || 0;
                    if (!bEnableMultiTouch && node.__touch_id != null)
                        return false;
                    e.name = "began";
                    node.__touch_id = touchId;
                    handler(e);
                    return true;
                };
                let fOnTouchMoved = (e) => {
                    let touchId = e.getID() || 0;
                    if (!bEnableMultiTouch && touchId != node.__touch_id)
                        return;
                    e.name = "moved";
                    handler(e);
                };
                let fOnTouchEnded = (e) => {
                    let touchId = e.getID() || 0;
                    if (!bEnableMultiTouch && touchId != node.__touch_id)
                        return;
                    e.name = "ended";
                    node.__touch_id = null;
                    handler(e);
                };
                let fOnTouchCancelled = (e) => {
                    let touchId = e.getID() || 0;
                    if (!bEnableMultiTouch && touchId != node.__touch_id)
                        return;
                    e.name = "cancelled";
                    node.__touch_id = null;
                    handler(e);
                };
                node.on(_cc$1.Node.EventType.TOUCH_START, fOnTouchBegan, null, bUseCapture);
                node.on(_cc$1.Node.EventType.TOUCH_MOVE, fOnTouchMoved, null, bUseCapture);
                node.on(_cc$1.Node.EventType.TOUCH_END, fOnTouchEnded, null, bUseCapture);
                node.on(_cc$1.Node.EventType.TOUCH_CANCEL, fOnTouchCancelled, null, bUseCapture);
            }
            isTouchEventClick(e) {
                if (!(e.name == "ended" || e.name == "cancelled"))
                    return false;
                let p0 = e.getStartLocation();
                let p1 = e.getLocation();
                let dx = p0.x - p1.x;
                let dy = p0.y - p1.y;
                let distanceSq = dx * dx + dy * dy;
                return distanceSq <= 20 * 20;
            }
            createItemByData(data) {
                let item = new MCItem();
                item.initByData(data);
                let nodeContainer = this.nodeContainer;
                switch (data.type) {
                    case "label": {
                        let node = new _cc$1.Node();
                        node.addComponent(_cc$1.UITransform);
                        node.layer = CANVAS_LAYER;
                        node.parent = nodeContainer;
                        node.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 0.5);
                        node.on(_cc$1.Node.EventType.SIZE_CHANGED, () => {
                            item.width = node.getComponent(_cc$1.UITransform).width;
                            item.height = node.getComponent(_cc$1.UITransform).height;
                            this.onItemNodeResize();
                        });
                        node.addComponent(_cc$1.Label).string = item.text;
                        node.getComponent(_cc$1.Label).fontSize = FONT_SIZE$2;
                        node.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                        node.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                        item.renderNode = node;
                        break;
                    }
                    case "labelArea": {
                        let node = new _cc$1.Node();
                        node.addComponent(_cc$1.UITransform);
                        node.layer = CANVAS_LAYER;
                        node.parent = nodeContainer;
                        node.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 0.5);
                        node.on(_cc$1.Node.EventType.SIZE_CHANGED, () => {
                            item.width = node.getComponent(_cc$1.UITransform).width;
                            item.height = node.getComponent(_cc$1.UITransform).height;
                            this.onItemNodeResize();
                        });
                        node.addComponent(_cc$1.Label).string = item.text;
                        node.getComponent(_cc$1.Label).fontSize = FONT_SIZE$2;
                        node.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                        node.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                        node.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.RESIZE_HEIGHT;
                        node.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(nodeContainer.getComponent(_cc$1.UITransform).width - PENDING$2 * 2, FONT_SIZE$2);
                        item.renderNode = node;
                        break;
                    }
                    case "button": {
                        let node = new _cc$1.Node();
                        node.addComponent(_cc$1.UITransform);
                        node.layer = CANVAS_LAYER;
                        node.parent = nodeContainer;
                        node.on(_cc$1.Node.EventType.SIZE_CHANGED, () => {
                            item.width = node.getComponent(_cc$1.UITransform).width;
                            item.height = node.getComponent(_cc$1.UITransform).height;
                            console.warn("button size changed", item.width, item.height);
                            this.onItemNodeResize();
                        });
                        node.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(item.width || BUTTON_WIDTH$2, item.height || BUTTON_HEIGHT$2);
                        let nodeBg = new _cc$1.Node();
                        nodeBg.addComponent(_cc$1.UITransform);
                        nodeBg.layer = CANVAS_LAYER;
                        nodeBg.parent = node;
                        nodeBg.getComponent(_cc$1.UITransform).contentSize = nodeBg.parent.getComponent(_cc$1.UITransform).contentSize;
                        this.addFillerSprite(nodeBg, _cc$1.color(200, 200, 200, 255));
                        let nodeLabel = new _cc$1.Node();
                        nodeLabel.addComponent(_cc$1.UITransform);
                        nodeLabel.layer = CANVAS_LAYER;
                        nodeLabel.parent = node;
                        nodeLabel.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 0.5);
                        nodeLabel.addComponent(_cc$1.Label).string = item.text;
                        nodeLabel.getComponent(_cc$1.Label).fontSize = FONT_SIZE$2;
                        nodeLabel.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                        nodeLabel.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                        nodeLabel.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                        nodeLabel.getComponent(_cc$1.UITransform).contentSize = nodeLabel.parent.getComponent(_cc$1.UITransform).contentSize;
                        nodeLabel.getComponent(_cc$1.Label).color = _cc$1.Color.BLACK;
                        this.registerTouchHandler(node, (e) => {
                            switch (e.name) {
                                case "began":
                                    nodeLabel.getComponent(_cc$1.Label).color = _cc$1.Color.GREEN;
                                    break;
                                case "moved": break;
                                default:
                                    nodeLabel.getComponent(_cc$1.Label).color = _cc$1.Color.BLACK;
                                    break;
                            }
                            if (!this.isTouchEventClick(e))
                                return;
                            item.triggerOnClick();
                        });
                        item.renderNode = node;
                        break;
                    }
                    case "inputBox": {
                        let node = new _cc$1.Node();
                        node.addComponent(_cc$1.UITransform);
                        node.layer = CANVAS_LAYER;
                        node.parent = nodeContainer;
                        node.on(_cc$1.Node.EventType.SIZE_CHANGED, () => {
                            item.width = node.getComponent(_cc$1.UITransform).width;
                            item.height = node.getComponent(_cc$1.UITransform).height;
                            this.onItemNodeResize();
                        });
                        node.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(item.width || BUTTON_WIDTH$2, item.height || BUTTON_HEIGHT$2);
                        let nodeBg = new _cc$1.Node();
                        nodeBg.addComponent(_cc$1.UITransform);
                        nodeBg.layer = CANVAS_LAYER;
                        nodeBg.parent = node;
                        nodeBg.getComponent(_cc$1.UITransform).contentSize = nodeBg.parent.getComponent(_cc$1.UITransform).contentSize;
                        this.addFillerSprite(nodeBg, _cc$1.color(200, 200, 200, 255));
                        let editBox = node.addComponent(_cc$1.EditBox);
                        editBox.textLabel.fontSize = FONT_SIZE$2;
                        editBox.textLabel.color = _cc$1.Color.BLACK;
                        editBox.textLabel.lineHeight = node.getComponent(_cc$1.UITransform).height;
                        editBox.inputMode = _cc$1.EditBox.InputMode.SINGLE_LINE;
                        editBox.maxLength = 1024;
                        editBox.placeholder = "<<输入框>>";
                        editBox.placeholderLabel.fontSize = FONT_SIZE$2;
                        editBox.placeholderLabel.color = _cc$1.Color.GRAY;
                        let labels = node.getComponentsInChildren(_cc$1.Label);
                        for (let i = 0; i < labels.length; i++) {
                            const label = labels[i];
                            label.verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                        }
                        editBox.node.on("text-changed", () => {
                            let text = editBox.string;
                            item.setText(text);
                        });
                        item.renderNode = node;
                        break;
                    }
                    case "newLine": {
                        item.width = nodeContainer.getComponent(_cc$1.UITransform).width - PENDING$2 * 2;
                        item.height = NEW_LINE_HEIGHT$2;
                        break;
                    }
                }
                return item;
            }
            doLayout() {
                if (!this.items)
                    return;
                let width = this.nodePanel.getComponent(_cc$1.UITransform).width - 20;
                let rowItems = [];
                let rowRight = PENDING$2;
                let rowTop = -PENDING$2;
                let rowHeight = 0;
                for (let i = 0; i < this.items.length; i++) {
                    let item = this.items[i];
                    let renderNode = item.renderNode;
                    if (rowRight + item.width > width) {
                        rowRight = 0;
                        for (let i = 0; i < rowItems.length; i++) {
                            const rowItem = rowItems[i];
                            let renderNode = rowItem.renderNode;
                            if (renderNode && renderNode.getPosition) {
                                let p = renderNode.getPosition();
                                renderNode.setPosition(p.x, rowTop - rowHeight / 2, p.z);
                            }
                        }
                        rowRight = PENDING$2;
                        rowTop -= rowHeight + GAP$2;
                        rowItems = [];
                        rowHeight = 0;
                    }
                    rowHeight = Math.max(rowHeight, item.height);
                    rowItems.push(item);
                    if (renderNode && renderNode.getPosition) {
                        let p = renderNode.getPosition();
                        renderNode.setPosition(rowRight + item.width / 2, p.y, p.z);
                    }
                    rowRight += item.width + GAP$2;
                }
                for (let i = 0; i < rowItems.length; i++) {
                    const rowItem = rowItems[i];
                    let renderNode = rowItem.renderNode;
                    if (renderNode && renderNode.getPosition) {
                        let p = renderNode.getPosition();
                        renderNode.setPosition(p.x, rowTop - rowHeight / 2, p.z);
                    }
                }
                rowTop -= rowHeight - PENDING$2;
                this.nodeContainer.getComponent(_cc$1.UITransform).height = Math.max(this.nodePanel.getComponent(_cc$1.UITransform).height, -rowTop);
            }
            onItemNodeResize() {
                this.doLayout();
            }
            getItemByName(name) {
                for (let i = 0; i < this.items.length; i++) {
                    const item = this.items[i];
                    if (item.name == name)
                        return item;
                }
                return null;
            }
            show(config) {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas)
                    return;
                let canvasSize = this.getCanvasSize();
                let nodePanel = new _cc$1.Node();
                nodePanel.addComponent(_cc$1.UITransform);
                nodePanel.layer = CANVAS_LAYER;
                nodePanel.parent = nodeCanvas;
                nodePanel.getComponent(_cc$1.UITransform).setContentSize(canvasSize.width, canvasSize.height);
                this.nodePanel = nodePanel;
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodePanel;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = nodeBg.parent.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeBg, _cc$1.color(0, 0, 0, 191));
                this.registerTouchHandler(this.nodePanel, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("click bg");
                });
                let nodeContainer = new _cc$1.Node();
                nodeContainer.addComponent(_cc$1.UITransform);
                nodeContainer.layer = CANVAS_LAYER;
                nodeContainer.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0, 1);
                nodeContainer.parent = this.nodePanel;
                nodeContainer.getComponent(_cc$1.UITransform).setContentSize(canvasSize.width, canvasSize.height);
                this.nodeContainer = nodeContainer;
                let scrollView = this.nodePanel.addComponent(_cc$1.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.content = nodeContainer;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let items = [];
                for (let i = 0; i < config.length; i++) {
                    const data = config[i];
                    let item = this.createItemByData(data);
                    items.push(item);
                }
                this.items = items;
                this.doLayout();
            }
            close() {
                if (_cc$1.isValid(this.nodePanel)) {
                    this.nodePanel.destroy();
                }
                this.nodePanel = null;
                this.items = [];
            }
            getItemText(name) {
                let item = this.getItemByName(name);
                if (!item)
                    return "";
                return item.text;
            }
            setItemText(name, text) {
                let item = this.getItemByName(name);
                if (!item)
                    return;
                item.setText(text);
                let node = item.renderNode;
                if (node instanceof _cc$1.Node) {
                    let label = node.getComponent(_cc$1.Label) || node.getComponentInChildren(_cc$1.Label);
                    if (label) {
                        label.string = text;
                    }
                    let editBox = node.getComponent(_cc$1.EditBox) || node.getComponentInChildren(_cc$1.EditBox);
                    if (editBox) {
                        editBox.string = text;
                    }
                }
            }
            showMsgTip(text) {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas)
                    return;
                let nodeLabel = new _cc$1.Node();
                nodeLabel.addComponent(_cc$1.UITransform);
                nodeLabel.layer = CANVAS_LAYER;
                nodeLabel.parent = nodeCanvas;
                nodeLabel.getComponent(_cc$1.UITransform).width = this.getCanvasSize().width;
                nodeLabel.getComponent(_cc$1.UITransform).height = 20;
                let label = nodeLabel.addComponent(_cc$1.Label);
                label.string = text;
                label.fontSize = 20;
                label.enableWrapText = true;
                nodeLabel.setPosition(0, this.getCanvasSize().height * 0.25, 0);
                _cc$1.tween(nodeLabel)
                    .to(1, { position: _cc$1.v3(nodeLabel.position.x, nodeLabel.position.y + 50, nodeLabel.position.z) })
                    .call(() => {
                    nodeLabel.destroy();
                })
                    .start();
            }
            showPickerDialog(title, conf, callback, bKeepDialogOpen) {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas)
                    return;
                let canvasSize = this.getCanvasSize();
                let minCount = 8.5;
                let maxCount = 17.5;
                let dialogHeight = ULTools.scaleInRange(conf.length, minCount, maxCount, minCount * 40 + (minCount - 1) * 4 + 60, maxCount * 40 + (maxCount - 1) * 4 + 60);
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeCanvas;
                nodeShadow.getComponent(_cc$1.UITransform).setContentSize(canvasSize.width, canvasSize.height);
                var isHadRespontHadnler = false;
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (isHadRespontHadnler) {
                        isHadRespontHadnler = false;
                        return;
                    }
                    ;
                    if (!this.isTouchEventClick(e))
                        return;
                    nodeShadow.destroy();
                });
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeShadow;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = nodeBg.parent.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeBg, _cc$1.color(0, 0, 0, 127));
                let nodeDialog = new _cc$1.Node();
                nodeDialog.addComponent(_cc$1.UITransform);
                nodeDialog.layer = CANVAS_LAYER;
                nodeDialog.parent = nodeShadow;
                nodeDialog.getComponent(_cc$1.UITransform).width = this.getCanvasSize().width - 100;
                nodeDialog.getComponent(_cc$1.UITransform).height = dialogHeight;
                this.registerTouchHandler(nodeDialog, (e) => { });
                nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeDialog;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = nodeBg.parent.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeBg, _cc$1.color(167, 167, 167, 255));
                let nodeTitle = new _cc$1.Node();
                nodeTitle.addComponent(_cc$1.UITransform);
                nodeTitle.layer = CANVAS_LAYER;
                nodeTitle.parent = nodeDialog;
                nodeTitle.setPosition(0, nodeDialog.getComponent(_cc$1.UITransform).height / 2 - 25, 0);
                nodeTitle.addComponent(_cc$1.Label).string = title;
                nodeTitle.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).fontSize = 40;
                nodeTitle.getComponent(_cc$1.UITransform).width = nodeDialog.getComponent(_cc$1.UITransform).width - 10;
                nodeTitle.getComponent(_cc$1.UITransform).height = 40;
                let nodeListBg = new _cc$1.Node();
                nodeListBg.addComponent(_cc$1.UITransform);
                nodeListBg.layer = CANVAS_LAYER;
                nodeListBg.parent = nodeDialog;
                nodeListBg.getComponent(_cc$1.UITransform).width = nodeDialog.getComponent(_cc$1.UITransform).width - 10;
                nodeListBg.getComponent(_cc$1.UITransform).height = nodeDialog.getComponent(_cc$1.UITransform).height - 50;
                nodeListBg.setPosition(0, -nodeDialog.getComponent(_cc$1.UITransform).height / 2 + nodeListBg.getComponent(_cc$1.UITransform).height / 2 + 5, 0);
                this.addFillerSprite(nodeListBg, _cc$1.color(97, 97, 97, 255));
                let nodeList = new _cc$1.Node();
                nodeList.addComponent(_cc$1.UITransform);
                nodeList.layer = CANVAS_LAYER;
                nodeList.parent = nodeDialog;
                nodeList.getComponent(_cc$1.UITransform).width = nodeDialog.getComponent(_cc$1.UITransform).width - 10;
                nodeList.getComponent(_cc$1.UITransform).height = nodeDialog.getComponent(_cc$1.UITransform).height - 50;
                nodeList.setPosition(0, -nodeDialog.getComponent(_cc$1.UITransform).height / 2 + nodeList.getComponent(_cc$1.UITransform).height / 2 + 5, 0);
                nodeList.addComponent(_cc$1.Mask);
                let nodeContainer = new _cc$1.Node();
                nodeContainer.addComponent(_cc$1.UITransform);
                nodeContainer.layer = CANVAS_LAYER;
                nodeContainer.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0, 1);
                nodeContainer.parent = nodeList;
                nodeContainer.getComponent(_cc$1.UITransform).contentSize = nodeList.getComponent(_cc$1.UITransform).contentSize;
                let scrollView = nodeList.addComponent(_cc$1.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.content = nodeContainer;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let y = 0;
                for (let i = 0; i < conf.length; i++) {
                    const v = conf[i];
                    let nodeItem = new _cc$1.Node();
                    nodeItem.addComponent(_cc$1.UITransform);
                    nodeItem.layer = CANVAS_LAYER;
                    nodeItem.parent = nodeContainer;
                    nodeItem.getComponent(_cc$1.UITransform).width = nodeList.getComponent(_cc$1.UITransform).width;
                    nodeItem.getComponent(_cc$1.UITransform).height = 40;
                    nodeItem.setPosition(nodeContainer.getComponent(_cc$1.UITransform).width / 2, y - nodeItem.getComponent(_cc$1.UITransform).height / 2);
                    let nodeBg = new _cc$1.Node();
                    nodeBg.addComponent(_cc$1.UITransform);
                    nodeBg.layer = CANVAS_LAYER;
                    nodeBg.parent = nodeItem;
                    nodeBg.getComponent(_cc$1.UITransform).contentSize = nodeBg.parent.getComponent(_cc$1.UITransform).contentSize;
                    this.addFillerSprite(nodeBg, _cc$1.color(0, 0, 0, 63));
                    let nodeLabel = new _cc$1.Node();
                    nodeLabel.addComponent(_cc$1.UITransform);
                    nodeLabel.layer = CANVAS_LAYER;
                    nodeLabel.parent = nodeItem;
                    nodeLabel.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0, 0.5);
                    nodeLabel.setPosition(-nodeItem.getComponent(_cc$1.UITransform).width / 2 + 5, 0, 0);
                    let label = nodeLabel.addComponent(_cc$1.Label);
                    label.fontSize = FONT_SIZE$2;
                    label.lineHeight = FONT_SIZE$2;
                    label.verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                    label.horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                    label.string = v.text;
                    this.registerTouchHandler(nodeItem, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        isHadRespontHadnler = true;
                        callback(v.value);
                        if (!bKeepDialogOpen) {
                            nodeShadow.destroy();
                        }
                    });
                    y -= nodeItem.getComponent(_cc$1.UITransform).height + 4;
                }
                nodeContainer.getComponent(_cc$1.UITransform).height = Math.max(nodeList.getComponent(_cc$1.UITransform).height, -y);
            }
            showPromptDialog(title, content, btnTexts, callbacks) {
                ULLog.console.warn("MCPanelCreator3x.showPromptDialog");
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showPromptDialog nodeCanvas not found!");
                    ULTimer.callLater(0.1, () => {
                        this.showPromptDialog(title, content, btnTexts, callbacks);
                    });
                    return;
                }
                let canvasSize = this.getCanvasSize();
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeCanvas;
                nodeShadow.getComponent(_cc$1.UITransform).setContentSize(canvasSize.width, canvasSize.height);
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("click bg");
                });
                let nodeSpriteBg = new _cc$1.Node();
                nodeSpriteBg.addComponent(_cc$1.UITransform);
                nodeSpriteBg.layer = CANVAS_LAYER;
                nodeSpriteBg.parent = nodeShadow;
                nodeSpriteBg.getComponent(_cc$1.UITransform).contentSize = nodeSpriteBg.parent.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeSpriteBg, _cc$1.color(0, 0, 0, 127));
                let bManualDestroy = false;
                let triggerNode = new _cc$1.Node();
                triggerNode.addComponent(_cc$1.UITransform);
                triggerNode.layer = CANVAS_LAYER;
                triggerNode.parent = nodeShadow;
                let component = triggerNode.addComponent(_cc$1.Component);
                component["onDestroy"] = () => {
                    ULLog.console.log("MCPanelCreator3x.showPromptDialog triggerNode onDestroy", bManualDestroy);
                    if (!bManualDestroy) {
                        ULLog.console.log("MCPanelCreator3x.showPromptDialog nodeShadow被意外销毁，0.1秒后尝试重新创建提示");
                        ULTimer.callLater(0.1, () => {
                            this.showPromptDialog(title, content, btnTexts, callbacks);
                        });
                    }
                };
                var nodeDialogSize = {
                    width: 460,
                    height: 320
                };
                let nodeDialog = new _cc$1.Node();
                nodeDialog.addComponent(_cc$1.UITransform);
                nodeDialog.layer = CANVAS_LAYER;
                nodeDialog.parent = nodeShadow;
                nodeDialog.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(nodeDialogSize.width, nodeDialogSize.height);
                this.registerTouchHandler(nodeDialog, (e) => { });
                let nodeDialogBg = new _cc$1.Node();
                nodeDialogBg.addComponent(_cc$1.UITransform);
                nodeDialogBg.layer = CANVAS_LAYER;
                nodeDialogBg.parent = nodeDialog;
                nodeDialogBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(nodeDialogSize.width, nodeDialogSize.height);
                _cc$1.resources.load("_ulsdk_ui/bg_01/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showPromptDialog nodeDialogBg load sprite error", err);
                        return;
                    }
                    let frameSize = spriteFrame.getOriginalSize();
                    spriteFrame.insetLeft = frameSize.width / 3;
                    spriteFrame.insetRight = frameSize.width / 3;
                    spriteFrame.insetTop = frameSize.height / 3;
                    spriteFrame.insetBottom = frameSize.height / 3;
                    let sprite = nodeDialogBg.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    sprite.type = _cc$1.Sprite.Type.SLICED;
                    sprite.sizeMode = _cc$1.Sprite.SizeMode.CUSTOM;
                    nodeDialogBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(nodeDialogSize.width, nodeDialogSize.height);
                });
                let nodeTitle = new _cc$1.Node();
                nodeTitle.layer = CANVAS_LAYER;
                nodeTitle.parent = nodeDialog;
                nodeTitle.setPosition(0, nodeDialogSize.height / 2 - 45, 0);
                nodeTitle.addComponent(_cc$1.UITransform);
                nodeTitle.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(nodeDialogSize.width - 10, 40);
                nodeTitle.addComponent(_cc$1.Label).color = _cc$1.color(38, 38, 38, 255);
                nodeTitle.getComponent(_cc$1.Label).string = title || "标题";
                nodeTitle.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).fontSize = 32;
                let nodeContent = new _cc$1.Node();
                nodeContent.layer = CANVAS_LAYER;
                nodeContent.parent = nodeDialog;
                nodeContent.addComponent(_cc$1.UITransform);
                nodeContent.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(nodeDialogSize.width - 50, 160);
                nodeContent.setPosition(0, nodeDialogSize.height / 2 - 155, 0);
                nodeContent.addComponent(_cc$1.Label).color = _cc$1.color(96, 96, 96, 255);
                nodeContent.getComponent(_cc$1.Label).string = content || "内容";
                nodeContent.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeContent.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                nodeContent.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                nodeContent.getComponent(_cc$1.Label).fontSize = 24;
                let btnWidth = 160;
                let btnHeight = 56;
                let btnGap = 30;
                let left = -(btnTexts.length * btnWidth + (btnTexts.length - 1) * btnGap) / 2;
                let nodeButtons = [];
                for (let i = 0; i < btnTexts.length; i++) {
                    const text = btnTexts[i];
                    let nodeButton = new _cc$1.Node();
                    nodeButton.addComponent(_cc$1.UITransform);
                    nodeButton.layer = CANVAS_LAYER;
                    nodeButton.parent = nodeDialog;
                    nodeButton.setPosition(left + btnWidth * (i + 0.5) + btnGap * (i), -nodeDialogSize.height / 2 + 50, 0);
                    nodeButton.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(btnWidth, btnHeight);
                    nodeButtons.push(nodeButton);
                    let nodeButtonBg = new _cc$1.Node();
                    nodeButtonBg.addComponent(_cc$1.UITransform);
                    nodeButtonBg.layer = CANVAS_LAYER;
                    nodeButtonBg.parent = nodeButton;
                    nodeButtonBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(btnWidth, btnHeight);
                    _cc$1.resources.load("_ulsdk_ui/btn_01/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                        if (err) {
                            ULLog.console.warn("MCPanelCreator3x.showPromptDialog nodeButtonBg load sprite error", err);
                            return;
                        }
                        let frameSize = spriteFrame.getOriginalSize();
                        spriteFrame.insetLeft = frameSize.width / 3;
                        spriteFrame.insetRight = frameSize.width / 3;
                        spriteFrame.insetTop = frameSize.height / 3;
                        spriteFrame.insetBottom = frameSize.height / 3;
                        let sprite = nodeButtonBg.addComponent(_cc$1.Sprite);
                        sprite.spriteFrame = spriteFrame;
                        sprite.type = _cc$1.Sprite.Type.SLICED;
                        sprite.sizeMode = _cc$1.Sprite.SizeMode.CUSTOM;
                        nodeButtonBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(btnWidth, btnHeight);
                    });
                    let nodeButtonText = new _cc$1.Node();
                    nodeButtonText.addComponent(_cc$1.UITransform);
                    nodeButtonText.layer = CANVAS_LAYER;
                    nodeButtonText.parent = nodeButton;
                    nodeButtonText.addComponent(_cc$1.Label).string = text || "按钮" + (i + 1);
                    nodeButtonText.getComponent(_cc$1.Label).color = _cc$1.color(255, 255, 255, 255);
                    nodeButtonText.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                    nodeButtonText.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                    nodeButtonText.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                    nodeButtonText.getComponent(_cc$1.Label).fontSize = 30;
                    nodeButtonText.getComponent(_cc$1.UITransform).width = nodeButtonBg.getComponent(_cc$1.UITransform).width - 10;
                    nodeButtonText.getComponent(_cc$1.UITransform).height = nodeButtonBg.getComponent(_cc$1.UITransform).height - 10;
                    this.registerTouchHandler(nodeButton, (e) => {
                        if (e.name == "began") {
                            nodeButton.setScale(1.1, 1.1);
                        }
                        else if (e.name == "moved") {
                        }
                        else {
                            nodeButton.setScale(1, 1);
                        }
                        if (this.isTouchEventClick(e)) {
                            let callback = callbacks[i];
                            if (callback instanceof Function) {
                                let bDonotClose = callback();
                                if (!bDonotClose) {
                                    bManualDestroy = true;
                                    nodeShadow.destroy();
                                }
                            }
                            else {
                                bManualDestroy = true;
                                nodeShadow.destroy();
                            }
                        }
                    });
                }
            }
            showWebView(title, url, replaceParam) {
                this.closeWebView();
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    return;
                }
                console.log(`showWebView title:${title} url:${url} replaceParam:${replaceParam}`);
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(2048, 2048);
                this.showWebViewNode = nodeBg;
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeBg;
                nodeShadow.getComponent(_cc$1.UITransform).contentSize = nodeBg.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeShadow, _cc$1.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    this.closeWebView();
                });
                let contentNode = new _cc$1.Node();
                contentNode.addComponent(_cc$1.UITransform);
                contentNode.layer = CANVAS_LAYER;
                contentNode.parent = nodeBg;
                let width = Math.min(this.getCanvasSize().width * 0.8, 500);
                let height = Math.min(this.getCanvasSize().height * 0.8, 800);
                if (this.getCanvasSize().width > this.getCanvasSize().height) {
                    width = Math.min(this.getCanvasSize().width * 0.8, 800);
                    height = Math.min(this.getCanvasSize().height * 0.8, 500);
                }
                contentNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                _cc$1.resources.load("_ulsdk_ui/bg_01/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showPrivacyDialog nodeDialogBg load sprite error", err);
                        return;
                    }
                    let frameSize = spriteFrame.getOriginalSize();
                    spriteFrame.insetLeft = frameSize.width / 3;
                    spriteFrame.insetRight = frameSize.width / 3;
                    spriteFrame.insetTop = frameSize.height / 3;
                    spriteFrame.insetBottom = frameSize.height / 3;
                    let sprite = contentNode.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    sprite.type = _cc$1.Sprite.Type.SLICED;
                    sprite.sizeMode = _cc$1.Sprite.SizeMode.CUSTOM;
                    contentNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                });
                let nodeTitle = new _cc$1.Node();
                nodeTitle.addComponent(_cc$1.UITransform);
                nodeTitle.layer = CANVAS_LAYER;
                nodeTitle.parent = contentNode;
                nodeTitle.addComponent(_cc$1.Label).string = title;
                nodeTitle.getComponent(_cc$1.Label).color = _cc$1.color(38, 38, 38, 255);
                nodeTitle.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).fontSize = 32;
                nodeTitle.getComponent(_cc$1.UITransform).width = width - 10;
                nodeTitle.getComponent(_cc$1.UITransform).height = 40;
                nodeTitle.setPosition(0, height / 2 - 40);
                let nodeScrollView = new _cc$1.Node();
                nodeScrollView.addComponent(_cc$1.UITransform);
                nodeScrollView.layer = CANVAS_LAYER;
                nodeScrollView.parent = contentNode;
                nodeScrollView.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width - 50, height - 80);
                nodeScrollView.setPosition(0, -20, 0);
                let scrollView = nodeScrollView.addComponent(_cc$1.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let nodeMask = new _cc$1.Node();
                nodeMask.addComponent(_cc$1.UITransform);
                nodeMask.layer = CANVAS_LAYER;
                nodeMask.parent = nodeScrollView;
                nodeMask.getComponent(_cc$1.UITransform).contentSize = nodeScrollView.getComponent(_cc$1.UITransform).contentSize;
                nodeMask.addComponent(_cc$1.Mask).type = _cc$1.Mask.Type.RECT;
                nodeMask.getComponent(_cc$1.Mask).inverted = false;
                let nodeContent = new _cc$1.Node();
                nodeContent.addComponent(_cc$1.UITransform);
                nodeContent.layer = CANVAS_LAYER;
                nodeContent.parent = nodeMask;
                nodeContent.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                nodeContent.getComponent(_cc$1.UITransform).contentSize = nodeScrollView.getComponent(_cc$1.UITransform).contentSize;
                let maskLayout = nodeContent.addComponent(_cc$1.Layout);
                maskLayout.type = _cc$1.Layout.Type.VERTICAL;
                maskLayout.resizeMode = _cc$1.Layout.ResizeMode.CONTAINER;
                scrollView.content = nodeContent;
                ULTools.httpGet({
                    url: url,
                    timeoutMillisecond: 5000,
                    success: (responseText) => {
                        let content = responseText;
                        try {
                            let resultObj = JSON.parse(responseText);
                            content = resultObj.policyText;
                        }
                        catch (error) {
                        }
                        if (replaceParam) {
                            for (let key in replaceParam) {
                                let value = replaceParam[key];
                                let regExp = new RegExp(`\\\${\\s*${key}\\s*}`, 'g');
                                content = content.replace(regExp, value);
                            }
                        }
                        ULLog.console.log("content:", content);
                        let contentList = content.split('\n');
                        for (let i = 0; i < contentList.length; i++) {
                            const text = contentList[i];
                            let nodeLabel = new _cc$1.Node();
                            nodeLabel.addComponent(_cc$1.UITransform);
                            nodeLabel.layer = CANVAS_LAYER;
                            nodeLabel.parent = nodeContent;
                            nodeLabel.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                            let label = nodeLabel.addComponent(_cc$1.Label);
                            label.color = _cc$1.color(0, 0, 0, 255);
                            label.string = text;
                            label.overflow = _cc$1.Label.Overflow.RESIZE_HEIGHT;
                            label.verticalAlign = _cc$1.Label.VerticalAlign.TOP;
                            label.horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                            label.fontSize = 18;
                            label.lineHeight = 26;
                            nodeLabel.getComponent(_cc$1.UITransform).contentSize = nodeContent.getComponent(_cc$1.UITransform).contentSize;
                        }
                    },
                    fail: () => {
                    }
                });
            }
            closeWebView() {
                if (_cc$1.isValid(this.showWebViewNode)) {
                    this.showWebViewNode["__b_manual_destroy"] = true;
                    this.showWebViewNode.destroy();
                }
                this.showWebViewNode = null;
            }
            showPrivacyContent(title, url, replaceParam) {
                this.showWebView(title, url, replaceParam);
            }
            showPrivacyDialog(title, contentArray, btnTexts, callbacks) {
                ULLog.console.log("MCPanelCreator3x.showPrivacyDialog");
                if (this.showPrivacyNode) {
                    return;
                }
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showPrivacyDialog nodeCanvas not found!");
                    ULTimer.callLater(0.1, () => {
                        this.showPrivacyDialog(title, contentArray, btnTexts, callbacks);
                    });
                    return;
                }
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(2048, 2048);
                this.showPrivacyNode = nodeBg;
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeBg;
                nodeShadow.getComponent(_cc$1.UITransform).contentSize = nodeBg.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeShadow, _cc$1.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("click bg");
                });
                let bManualDestroy = false;
                let triggerNode = new _cc$1.Node();
                triggerNode.addComponent(_cc$1.UITransform);
                triggerNode.layer = CANVAS_LAYER;
                triggerNode.parent = nodeShadow;
                let component = triggerNode.addComponent(_cc$1.Component);
                component["onDestroy"] = () => {
                    ULLog.console.log("MCPanelCreator3x.showPrivacyDialog triggerNode onDestroy", bManualDestroy);
                    this.showPrivacyNode = null;
                    if (!bManualDestroy) {
                        ULLog.console.log("MCPanelCreator3x.showPrivacyDialog nodeShadow被意外销毁，0.1秒后尝试重新创建提示");
                        ULTimer.callLater(1 / 60, () => {
                            ULLog.console.log("ontimer");
                            this.showPrivacyDialog(title, contentArray, btnTexts, callbacks);
                        });
                    }
                };
                let contentNode = new _cc$1.Node();
                contentNode.addComponent(_cc$1.UITransform);
                contentNode.layer = CANVAS_LAYER;
                contentNode.parent = nodeBg;
                let width = 450;
                let height = 450;
                contentNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                _cc$1.resources.load("_ulsdk_ui/bg_01/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showPrivacyDialog nodeDialogBg load sprite error", err);
                        return;
                    }
                    let frameSize = spriteFrame.getOriginalSize();
                    spriteFrame.insetLeft = frameSize.width / 3;
                    spriteFrame.insetRight = frameSize.width / 3;
                    spriteFrame.insetTop = frameSize.height / 3;
                    spriteFrame.insetBottom = frameSize.height / 3;
                    let sprite = contentNode.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    sprite.type = _cc$1.Sprite.Type.SLICED;
                    sprite.sizeMode = _cc$1.Sprite.SizeMode.CUSTOM;
                    contentNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                });
                let nodeTitle = new _cc$1.Node();
                nodeTitle.addComponent(_cc$1.UITransform);
                nodeTitle.layer = CANVAS_LAYER;
                nodeTitle.parent = contentNode;
                nodeTitle.addComponent(_cc$1.Label).string = "隐私政策";
                nodeTitle.getComponent(_cc$1.Label).color = _cc$1.color(0, 0, 0, 255);
                nodeTitle.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).fontSize = 32;
                nodeTitle.getComponent(_cc$1.UITransform).width = width - 10;
                nodeTitle.getComponent(_cc$1.UITransform).height = 40;
                nodeTitle.setPosition(0, height / 2 - 40);
                let nodeScrollView = new _cc$1.Node();
                nodeScrollView.addComponent(_cc$1.UITransform);
                nodeScrollView.layer = CANVAS_LAYER;
                nodeScrollView.parent = contentNode;
                nodeScrollView.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width - 50, height - 140);
                nodeScrollView.setPosition(0, 3, 0);
                let scrollView = nodeScrollView.addComponent(_cc$1.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let nodeMask = new _cc$1.Node();
                nodeMask.addComponent(_cc$1.UITransform);
                nodeMask.layer = CANVAS_LAYER;
                nodeMask.parent = nodeScrollView;
                nodeMask.getComponent(_cc$1.UITransform).contentSize = nodeScrollView.getComponent(_cc$1.UITransform).contentSize;
                nodeMask.addComponent(_cc$1.Mask).type = _cc$1.Mask.Type.RECT;
                nodeMask.getComponent(_cc$1.Mask).inverted = false;
                let nodeContent = new _cc$1.Node();
                nodeContent.addComponent(_cc$1.UITransform);
                nodeContent.layer = CANVAS_LAYER;
                nodeContent.parent = nodeMask;
                nodeContent.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                nodeContent.getComponent(_cc$1.UITransform).contentSize = nodeScrollView.getComponent(_cc$1.UITransform).contentSize;
                let maskLayout = nodeContent.addComponent(_cc$1.Layout);
                maskLayout.type = _cc$1.Layout.Type.VERTICAL;
                maskLayout.resizeMode = _cc$1.Layout.ResizeMode.CONTAINER;
                scrollView.content = nodeContent;
                let contentText = `感谢您对本公司游戏的支持，在体验我们的游戏前，请仔细阅读开发商的`;
                let footer = `中的所有条款，包括
        1.为了您有良好的游戏体验，我们会基于具体的场景收集您的个人信息
        2.我们会基于先进的技术和管理措施保证您的个人信息安全
        3.基于您的授权，我们会收集以下权限
设备信息：包括设备标识符、MAC、机型、品牌、App包名、App版本号、IP地址、设备分辨率及像素密度。
网络信息：网络连接状态、接入网络的方式和类型、IP地址。
使用信息：包括广告内容的展现、点击、下载。
        如果您对本隐私政策有任何疑问,请通过kefu@ultralisk.cn与我们联系。
        `;
                let headerNode = new _cc$1.Node();
                headerNode.addComponent(_cc$1.UITransform);
                headerNode.layer = CANVAS_LAYER;
                headerNode.parent = nodeContent;
                headerNode.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                let headerLabel = headerNode.addComponent(_cc$1.Label);
                headerLabel.color = _cc$1.color(0, 0, 0, 255);
                headerLabel.string = contentText;
                headerLabel.fontSize = 18;
                headerLabel.lineHeight = 26;
                headerNode.getComponent(_cc$1.UITransform).contentSize = nodeContent.getComponent(_cc$1.UITransform).contentSize;
                headerLabel.overflow = _cc$1.Label.Overflow.RESIZE_HEIGHT;
                headerLabel.verticalAlign = _cc$1.Label.VerticalAlign.TOP;
                headerLabel.horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                for (let index = 0; index < contentArray.length; index++) {
                    let element = contentArray[index];
                    let buttonNode = new _cc$1.Node();
                    buttonNode.addComponent(_cc$1.UITransform);
                    buttonNode.layer = CANVAS_LAYER;
                    buttonNode.parent = nodeContent;
                    buttonNode.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                    let buttonLabel = buttonNode.addComponent(_cc$1.Label);
                    buttonLabel.color = _cc$1.color(156, 176, 222, 255);
                    buttonLabel.string = `《${element.name}》`;
                    buttonLabel.fontSize = 18;
                    buttonLabel.lineHeight = 26;
                    buttonNode.getComponent(_cc$1.UITransform).contentSize = nodeContent.getComponent(_cc$1.UITransform).contentSize;
                    buttonLabel.overflow = _cc$1.Label.Overflow.RESIZE_HEIGHT;
                    buttonLabel.verticalAlign = _cc$1.Label.VerticalAlign.TOP;
                    buttonLabel.horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                    this.registerTouchHandler(buttonNode, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        this.showWebView(element.name, element.url, element.replaceParam);
                    });
                }
                let footerNode = new _cc$1.Node();
                footerNode.addComponent(_cc$1.UITransform);
                footerNode.layer = CANVAS_LAYER;
                footerNode.parent = nodeContent;
                footerNode.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                let footerLabel = footerNode.addComponent(_cc$1.Label);
                footerLabel.color = _cc$1.color(0, 0, 0, 255);
                footerLabel.string = footer;
                footerLabel.fontSize = 18;
                footerLabel.lineHeight = 26;
                footerLabel.overflow = _cc$1.Label.Overflow.RESIZE_HEIGHT;
                footerLabel.verticalAlign = _cc$1.Label.VerticalAlign.TOP;
                footerLabel.horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                footerNode.getComponent(_cc$1.UITransform).contentSize = nodeContent.getComponent(_cc$1.UITransform).contentSize;
                let buttonWidth = (contentNode.getComponent(_cc$1.UITransform).width - 20) / btnTexts.length;
                let buttonHeight = 40;
                for (let index = 0; index < btnTexts.length; index++) {
                    const buttonText = btnTexts[index];
                    let buttonBgNode = new _cc$1.Node();
                    buttonBgNode.addComponent(_cc$1.UITransform);
                    buttonBgNode.layer = CANVAS_LAYER;
                    buttonBgNode.parent = contentNode;
                    buttonBgNode.getComponent(_cc$1.UITransform).width = Math.min(buttonWidth * 0.8, 120);
                    buttonBgNode.getComponent(_cc$1.UITransform).height = buttonHeight;
                    buttonBgNode.setPosition(-(btnTexts.length / 2.0 - index) * buttonWidth + buttonWidth / 2.0, (buttonBgNode.getComponent(_cc$1.UITransform).height - contentNode.getComponent(_cc$1.UITransform).height) / 2.0 + 20, 0);
                    let buttonNode = new _cc$1.Node();
                    buttonNode.addComponent(_cc$1.UITransform);
                    buttonNode.layer = CANVAS_LAYER;
                    buttonNode.parent = buttonBgNode;
                    buttonNode.addComponent(_cc$1.Label).string = buttonText;
                    buttonNode.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                    buttonNode.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                    buttonNode.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                    buttonNode.getComponent(_cc$1.Label).fontSize = 22;
                    buttonNode.getComponent(_cc$1.UITransform).width = buttonBgNode.getComponent(_cc$1.UITransform).width;
                    buttonNode.getComponent(_cc$1.UITransform).height = buttonBgNode.getComponent(_cc$1.UITransform).height;
                    if (btnTexts.length == 1 || index % 2 == 1) {
                        this.addFillerSprite(buttonBgNode, _cc$1.color(100, 149, 237, 255));
                        buttonNode.getComponent(_cc$1.Label).color = _cc$1.color(255, 255, 255, 255);
                    }
                    else {
                        this.addFillerSprite(buttonBgNode, _cc$1.color(230, 230, 230, 255));
                        buttonNode.getComponent(_cc$1.Label).color = _cc$1.color(156, 176, 222, 255);
                        buttonNode.addComponent(_cc$1.LabelOutline);
                        buttonNode.getComponent(_cc$1.LabelOutline);
                        buttonNode.getComponent(_cc$1.LabelOutline).width = 1;
                        buttonNode.getComponent(_cc$1.LabelOutline).color = _cc$1.color(230, 230, 230, 255);
                    }
                    this.registerTouchHandler(buttonNode, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        let callback = callbacks[index];
                        if (callback instanceof Function) {
                            let bDonotClose = callback();
                            if (!bDonotClose) {
                                bManualDestroy = true;
                                this.showPrivacyNode.destroy();
                                this.showPrivacyNode = null;
                            }
                        }
                        else {
                            bManualDestroy = true;
                            this.showPrivacyNode.destroy();
                            this.showPrivacyNode = null;
                        }
                    });
                }
            }
            showSettingView(title, items) {
                ULLog.console.log("MCPanelCreator3x.showSettingView");
                if (this.showSettingNode) {
                    return;
                }
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showSettingView nodeCanvas not found!");
                    ULTimer.callLater(0.1, () => {
                        this.showSettingView(title, items);
                    });
                    return;
                }
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(2048, 2048);
                this.showSettingNode = nodeBg;
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeBg;
                nodeShadow.getComponent(_cc$1.UITransform).contentSize = nodeBg.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeShadow, _cc$1.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("click bg");
                });
                let bManualDestroy = false;
                let triggerNode = new _cc$1.Node();
                triggerNode.addComponent(_cc$1.UITransform);
                triggerNode.layer = CANVAS_LAYER;
                triggerNode.parent = nodeShadow;
                let component = triggerNode.addComponent(_cc$1.Component);
                component["onDestroy"] = () => {
                    ULLog.console.log("MCPanelCreator3x.showSettingView triggerNode onDestroy", bManualDestroy);
                    this.showSettingNode = null;
                    if (!bManualDestroy) {
                        ULLog.console.log("MCPanelCreator3x.showSettingView nodeShadow被意外销毁，0.1秒后尝试重新创建提示");
                        ULTimer.callLater(1 / 60, () => {
                            ULLog.console.log("ontimer");
                            this.showSettingView(title, items);
                        });
                    }
                };
                let contentNode = new _cc$1.Node();
                contentNode.addComponent(_cc$1.UITransform);
                contentNode.layer = CANVAS_LAYER;
                contentNode.parent = nodeBg;
                let width = 450;
                let height = 450;
                contentNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                _cc$1.resources.load("_ulsdk_ui/bg_01/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showSettingView nodeDialogBg load sprite error", err);
                        return;
                    }
                    let frameSize = spriteFrame.getOriginalSize();
                    spriteFrame.insetLeft = frameSize.width / 3;
                    spriteFrame.insetRight = frameSize.width / 3;
                    spriteFrame.insetTop = frameSize.height / 3;
                    spriteFrame.insetBottom = frameSize.height / 3;
                    let sprite = contentNode.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    sprite.type = _cc$1.Sprite.Type.SLICED;
                    sprite.sizeMode = _cc$1.Sprite.SizeMode.CUSTOM;
                    contentNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                });
                let nodeTitle = new _cc$1.Node();
                nodeTitle.addComponent(_cc$1.UITransform);
                nodeTitle.layer = CANVAS_LAYER;
                nodeTitle.parent = contentNode;
                nodeTitle.addComponent(_cc$1.Label).string = title;
                nodeTitle.getComponent(_cc$1.Label).color = _cc$1.color(0, 0, 0, 255);
                nodeTitle.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).fontSize = 32;
                nodeTitle.getComponent(_cc$1.UITransform).width = width - 10;
                nodeTitle.getComponent(_cc$1.UITransform).height = 40;
                nodeTitle.setPosition(0, height / 2 - 40);
                let nodeScrollView = new _cc$1.Node();
                nodeScrollView.addComponent(_cc$1.UITransform);
                nodeScrollView.layer = CANVAS_LAYER;
                nodeScrollView.parent = contentNode;
                nodeScrollView.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width - 50, height - 140);
                nodeScrollView.setPosition(0, 3, 0);
                let scrollView = nodeScrollView.addComponent(_cc$1.ScrollView);
                scrollView.horizontal = false;
                scrollView.vertical = true;
                scrollView.cancelInnerEvents = false;
                scrollView.elastic = true;
                let nodeMask = new _cc$1.Node();
                nodeMask.addComponent(_cc$1.UITransform);
                nodeMask.layer = CANVAS_LAYER;
                nodeMask.parent = nodeScrollView;
                nodeMask.getComponent(_cc$1.UITransform).contentSize = nodeScrollView.getComponent(_cc$1.UITransform).contentSize;
                nodeMask.addComponent(_cc$1.Mask).type = _cc$1.Mask.Type.RECT;
                nodeMask.getComponent(_cc$1.Mask).inverted = false;
                let nodeContent = new _cc$1.Node();
                nodeContent.addComponent(_cc$1.UITransform);
                nodeContent.layer = CANVAS_LAYER;
                nodeContent.parent = nodeMask;
                nodeContent.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                nodeContent.getComponent(_cc$1.UITransform).contentSize = nodeScrollView.getComponent(_cc$1.UITransform).contentSize;
                let maskLayout = nodeContent.addComponent(_cc$1.Layout);
                maskLayout.type = _cc$1.Layout.Type.VERTICAL;
                maskLayout.resizeMode = _cc$1.Layout.ResizeMode.CONTAINER;
                scrollView.content = nodeContent;
                for (let index = 0; index < items.length; index++) {
                    let item = items[index];
                    let buttonText = item.name;
                    let callback = item.handle;
                    let buttonNode = new _cc$1.Node();
                    buttonNode.addComponent(_cc$1.UITransform);
                    buttonNode.layer = CANVAS_LAYER;
                    buttonNode.parent = nodeContent;
                    buttonNode.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                    let buttonLabel = buttonNode.addComponent(_cc$1.Label);
                    buttonLabel.color = _cc$1.color(100, 149, 237, 255);
                    buttonLabel.string = buttonText;
                    buttonLabel.fontSize = 20;
                    buttonLabel.lineHeight = 50;
                    buttonNode.getComponent(_cc$1.UITransform).contentSize = nodeContent.getComponent(_cc$1.UITransform).contentSize;
                    buttonLabel.overflow = _cc$1.Label.Overflow.RESIZE_HEIGHT;
                    buttonLabel.verticalAlign = _cc$1.Label.VerticalAlign.TOP;
                    buttonLabel.horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                    this.registerTouchHandler(buttonNode, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        callback();
                    });
                }
                let buttonWidth = (contentNode.width - 20);
                let buttonHeight = 40;
                let buttonBgNode = new _cc$1.Node();
                buttonBgNode.addComponent(_cc$1.UITransform);
                buttonBgNode.layer = CANVAS_LAYER;
                buttonBgNode.parent = contentNode;
                buttonBgNode.getComponent(_cc$1.UITransform).width = Math.min(buttonWidth * 0.8, 120);
                buttonBgNode.getComponent(_cc$1.UITransform).height = buttonHeight;
                buttonBgNode.setPosition(-(1 / 2.0) * buttonWidth + buttonWidth / 2.0, (buttonBgNode.getComponent(_cc$1.UITransform).height - contentNode.getComponent(_cc$1.UITransform).height) / 2.0 + 20, 0);
                let buttonNode = new _cc$1.Node();
                buttonNode.addComponent(_cc$1.UITransform);
                buttonNode.layer = CANVAS_LAYER;
                buttonNode.parent = buttonBgNode;
                buttonNode.addComponent(_cc$1.Label).string = "返回";
                buttonNode.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                buttonNode.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                buttonNode.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                buttonNode.getComponent(_cc$1.Label).fontSize = 22;
                buttonNode.getComponent(_cc$1.UITransform).width = buttonBgNode.getComponent(_cc$1.UITransform).width;
                buttonNode.getComponent(_cc$1.UITransform).height = buttonBgNode.getComponent(_cc$1.UITransform).height;
                this.addFillerSprite(buttonBgNode, _cc$1.color(100, 149, 237, 255));
                buttonNode.getComponent(_cc$1.Label).color = _cc$1.color(255, 255, 255, 255);
                this.registerTouchHandler(buttonNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    bManualDestroy = true;
                    this.showSettingNode.destroy();
                    this.showSettingNode = null;
                });
            }
            getCanvasSize() {
                return _cc$1.view.getDesignResolutionSize();
            }
            getCanvasOriginSize() {
                let w = 0;
                let h = 0;
                let nodeCanvas = this.getNodeCanvas();
                let canvas = nodeCanvas.getComponent(_cc$1.Canvas);
                let frameSize = _cc$1.view.getFrameSize();
                let frameRatio = frameSize.width / frameSize.height;
                let canvasRatio = this.getCanvasSize().width / this.getCanvasSize().height;
                w = this.getCanvasSize().width;
                h = this.getCanvasSize().height;
                if (frameRatio < canvasRatio) {
                    h = Math.floor(h * canvasRatio / frameRatio);
                }
                else {
                    w = Math.floor(w * frameRatio / canvasRatio);
                }
                return { width: w, height: h };
            }
            showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY) {
                ULLog.console.log("MCPanelCreator3x.showReferenceRect", key, ccx, ccy, width, height);
                let frameSize = _cc$1.view.getFrameSize();
                let centerX = ccx * frameSize.width;
                let centerY = frameSize.height - ccy * frameSize.height;
                ULLog.console.log("  center", centerX, centerY);
                let nodeCanvas = this.getNodeCanvas();
                let canvasSize = this.getCanvasSize();
                let canvasOriginSize = this.getCanvasOriginSize();
                let wx = centerX / frameSize.width * canvasOriginSize.width - (canvasOriginSize.width - canvasSize.width) / 2;
                let wy = canvasOriginSize.height - centerY / frameSize.height * canvasOriginSize.height - (canvasOriginSize.height - canvasSize.height) / 2;
                let canvasUiTrans = nodeCanvas.getComponent(_cc$1.UITransform);
                let pInWorld = canvasUiTrans.convertToNodeSpaceAR(_cc$1.v3(wx, wy, 0));
                ULLog.console.log("  pInWorld", pInWorld);
                this.hideReferenceRect(key);
                _cc$1.resources.load("_ulsdk_ui/white_dot/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    let nodeRect = new _cc$1.Node();
                    nodeRect.addComponent(_cc$1.UITransform);
                    nodeRect.layer = CANVAS_LAYER;
                    nodeRect.parent = nodeCanvas;
                    nodeRect.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(anchorPointX == null ? 0.5 : anchorPointX, anchorPointY == null ? 0.5 : anchorPointY);
                    nodeRect.getComponent(_cc$1.UITransform).width = width;
                    nodeRect.getComponent(_cc$1.UITransform).height = height;
                    nodeRect.position = pInWorld;
                    let nodeBg = new _cc$1.Node();
                    nodeBg.addComponent(_cc$1.UITransform);
                    nodeBg.layer = CANVAS_LAYER;
                    nodeBg.parent = nodeRect;
                    let spriteBg = nodeBg.addComponent(_cc$1.Sprite);
                    spriteBg.spriteFrame = spriteFrame;
                    spriteBg.color = _cc$1.color(0, 0, 0, 127);
                    nodeBg.getComponent(_cc$1.UITransform).anchorPoint = nodeRect.getComponent(_cc$1.UITransform).anchorPoint;
                    nodeBg.getComponent(_cc$1.UITransform).width = width;
                    nodeBg.getComponent(_cc$1.UITransform).height = height;
                    let nodeLabel = new _cc$1.Node();
                    nodeLabel.addComponent(_cc$1.UITransform);
                    nodeLabel.layer = CANVAS_LAYER;
                    nodeLabel.parent = nodeRect;
                    let label = nodeLabel.addComponent(_cc$1.Label);
                    label.string = key;
                    label.fontSize = 18;
                    label.verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                    label.horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                    let widget = nodeLabel.addComponent(_cc$1.Widget);
                    widget.isAlignVerticalCenter = true;
                    widget.isAlignHorizontalCenter = true;
                    this.nodeReferenceRects[key] = nodeRect;
                    nodeRect["__b_manual_destroy"] = false;
                    let triggerNode = new _cc$1.Node();
                    triggerNode.addComponent(_cc$1.UITransform);
                    triggerNode.layer = CANVAS_LAYER;
                    triggerNode.parent = nodeRect;
                    let component = triggerNode.addComponent(_cc$1.Component);
                    component["onDestroy"] = () => {
                        ULLog.console.log("MCPanelCreator3x.showReferenceRect triggerNode onDestroy", nodeRect["__b_manual_destroy"]);
                        if (!nodeRect["__b_manual_destroy"]) {
                            ULLog.console.log("MCPanelCreator3x.showReferenceRect nodeRect被意外销毁，0.1秒后尝试重新创建提示");
                            ULTimer.callLater(0.1, () => {
                                this.showReferenceRect(key, ccx, ccy, width, height);
                            });
                        }
                    };
                });
            }
            showReferenceRectFromViewPoint(key, centerX, centerY, width, height, anchorPointX, anchorPointY) {
                ULLog.console.log("MCPanelCreator3x.showReferenceRectFromViewPoint", key, centerX, centerY, width, height);
                let frameSize = _cc$1.view.getFrameSize();
                let ccx = centerX / frameSize.width;
                let ccy = 1 - centerY / frameSize.height;
                this.showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY);
            }
            showReferenceRectFromScale(key, ccx, ccy, widthScale, heightScale, anchorPointX, anchorPointY) {
                let canvasSize = this.getCanvasSize();
                let width = canvasSize.width * widthScale;
                let height = canvasSize.height * heightScale;
                this.showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY);
            }
            hideReferenceRect(key) {
                ULLog.console.log("MCPanelCreator3x.hideReferenceRect", key);
                let nodeRect = this.nodeReferenceRects[key];
                if (_cc$1.isValid(nodeRect)) {
                    nodeRect["__b_manual_destroy"] = true;
                    nodeRect.destroy();
                    nodeRect = null;
                    delete this.nodeReferenceRects[key];
                }
            }
            hideAllReferenceRects() {
                ULLog.console.log("MCPanelCreator3x.hideAllReferenceRects");
                ULTools.forEachMap(this.nodeReferenceRects, (key, node) => {
                    this.hideReferenceRect(key);
                });
            }
            showNationBanner(obj, style) {
                ULLog.console.log("MCPanelCreator3x.showNationBanner");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showNationBanner nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.bannerRootNode) {
                    ULLog.console.warn("MCPanelCreator3x.showNationBanner 已经有 banner 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 banner 正在展示中");
                    }
                    return;
                }
                let scale = style.width;
                this.bannerShowingObj = obj;
                let canvasSize = this.getCanvasSize();
                let width = Math.min(canvasSize.width, canvasSize.height) * scale;
                let height = width / 3.5;
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                nodeBg.setPosition((canvasSize.width - width) * (style.x - 0.5), (canvasSize.height - height) * (style.y - 0.5), 0);
                this.addFillerSprite(nodeBg, _cc$1.color(255, 255, 255, 255));
                this.bannerRootNode = nodeBg;
                this.registerTouchHandler(nodeBg, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator3x:click nationBanner");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let closeButton = new _cc$1.Node();
                closeButton.addComponent(_cc$1.UITransform);
                closeButton.layer = CANVAS_LAYER;
                closeButton.parent = nodeBg;
                closeButton.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(34 * scale, 34 * scale);
                closeButton.setPosition((nodeBg.getComponent(_cc$1.UITransform).width - closeButton.getComponent(_cc$1.UITransform).width) / 2.0, (nodeBg.getComponent(_cc$1.UITransform).height - closeButton.getComponent(_cc$1.UITransform).height) / 2.0, 0);
                _cc$1.resources.load("_ulsdk_ui/native_adv_close/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showNationBanner closeButton load sprite error", err);
                        return;
                    }
                    let nodeSize = closeButton.getComponent(_cc$1.UITransform).contentSize;
                    let sprite = closeButton.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    closeButton.getComponent(_cc$1.UITransform).contentSize = nodeSize;
                });
                this.registerTouchHandler(closeButton, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    this.closeNationBanner(true);
                });
                let advTag = new _cc$1.Node();
                advTag.addComponent(_cc$1.UITransform);
                advTag.layer = CANVAS_LAYER;
                advTag.parent = nodeBg;
                advTag.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(44 * scale, 24 * scale);
                advTag.setPosition((nodeBg.getComponent(_cc$1.UITransform).width - advTag.getComponent(_cc$1.UITransform).width) / 2.0, (advTag.getComponent(_cc$1.UITransform).height - nodeBg.getComponent(_cc$1.UITransform).height) / 2.0, 0);
                _cc$1.resources.load("_ulsdk_ui/native_adv_tag/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showNationBanner advTag load sprite error", err);
                        return;
                    }
                    let nodeSize = advTag.getComponent(_cc$1.UITransform).contentSize;
                    let sprite = advTag.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    advTag.getComponent(_cc$1.UITransform).contentSize = nodeSize;
                });
                let imageNode = new _cc$1.Node();
                imageNode.addComponent(_cc$1.UITransform);
                imageNode.layer = CANVAS_LAYER;
                imageNode.parent = nodeBg;
                imageNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(height / 9 * 16, height);
                let imageUrl = obj.nationData.url || null;
                if (imageUrl) {
                    ULLog.console.warn("MCPanelCreator3x.showNationBanner load imageUrl:", imageUrl);
                    _cc$1.assetManager.loadRemote(imageUrl, { ext: '.png' }, (err, imageAsset) => {
                        if (!err && imageAsset) {
                            const texture = new _cc$1.Texture2D();
                            texture.image = imageAsset;
                            let spFrame = new _cc$1.SpriteFrame();
                            spFrame.texture = texture;
                            texture.addRef();
                            let sprite = imageNode.addComponent(_cc$1.Sprite);
                            sprite.spriteFrame = spFrame;
                            imageNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(height / 9 * 16, height);
                        }
                    });
                }
                let imageNodeSize = imageNode.getComponent(_cc$1.UITransform).contentSize;
                let iconWith = Math.min(height, (width - imageNodeSize.width) / 2.0) * 0.6;
                let iconHeight = iconWith;
                let buttonSize = {
                    width: iconWith,
                    height: iconWith / 16 * 5
                };
                let iconNode = new _cc$1.Node();
                iconNode.addComponent(_cc$1.UITransform);
                iconNode.layer = CANVAS_LAYER;
                iconNode.parent = nodeBg;
                iconNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(iconWith, iconHeight);
                iconNode.setPosition(-(width - imageNodeSize.width) / 4.0 - imageNodeSize.width / 2.0, buttonSize.height / 2.0, 0);
                let iconUrl = obj.nationData.icon || null;
                if (iconUrl) {
                    ULLog.console.warn("MCPanelCreator3x.showNationBanner load iconUrl:", iconUrl);
                    _cc$1.assetManager.loadRemote(iconUrl, { ext: '.png' }, (err, imageAsset) => {
                        if (!err && imageAsset) {
                            const texture = new _cc$1.Texture2D();
                            texture.image = imageAsset;
                            let spFrame = new _cc$1.SpriteFrame();
                            spFrame.texture = texture;
                            texture.addRef();
                            let sprite = iconNode.addComponent(_cc$1.Sprite);
                            sprite.spriteFrame = spFrame;
                            iconNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(iconWith, iconHeight);
                        }
                    });
                }
                else {
                    this.addFillerSprite(iconNode, _cc$1.color(220, 0, 50, 255));
                }
                let buttonBgNode = new _cc$1.Node();
                buttonBgNode.addComponent(_cc$1.UITransform);
                buttonBgNode.layer = CANVAS_LAYER;
                buttonBgNode.parent = nodeBg;
                buttonBgNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(buttonSize.width, buttonSize.height);
                buttonBgNode.setPosition(iconNode.position.x, -height / 2.0 + ((height - iconHeight) / 2.0 + iconNode.position.y) / 2.0, 0);
                this.addFillerSprite(buttonBgNode, _cc$1.color(100, 220, 50, 255));
                let buttonNode = new _cc$1.Node();
                buttonNode.addComponent(_cc$1.UITransform);
                buttonNode.layer = CANVAS_LAYER;
                buttonNode.parent = buttonBgNode;
                buttonNode.addComponent(_cc$1.Label).string = obj.nationData.targetTitle || "点击查看";
                buttonNode.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                buttonNode.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                buttonNode.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                buttonNode.getComponent(_cc$1.Label).fontSize = 18;
                buttonNode.addComponent(_cc$1.LabelOutline);
                buttonNode.getComponent(_cc$1.LabelOutline);
                buttonNode.getComponent(_cc$1.LabelOutline).width = 1;
                buttonNode.getComponent(_cc$1.LabelOutline).color = _cc$1.color(100, 220, 50, 255);
                buttonNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(buttonSize.width, buttonSize.height);
                let titleWidth = (width - imageNodeSize.width) / 2.0 * 0.8;
                let nodeTitle = new _cc$1.Node();
                nodeTitle.addComponent(_cc$1.UITransform);
                nodeTitle.layer = CANVAS_LAYER;
                nodeTitle.parent = nodeBg;
                nodeTitle.addComponent(_cc$1.Label).string = obj.nationData.title || "";
                nodeTitle.getComponent(_cc$1.Label).color = _cc$1.color(0, 0, 0, 255);
                nodeTitle.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeTitle.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                nodeTitle.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                nodeTitle.getComponent(_cc$1.Label).fontSize = 24;
                nodeTitle.getComponent(_cc$1.Label).lineHeight = 24;
                nodeTitle.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(titleWidth, 36 * scale);
                nodeTitle.setPosition((width - imageNodeSize.width) / 4.0 + imageNodeSize.width / 2.0, (iconNode.getComponent(_cc$1.UITransform).height - 36 * scale) / 2.0, 0);
                let nodeDesc = new _cc$1.Node();
                nodeDesc.addComponent(_cc$1.UITransform);
                nodeDesc.layer = CANVAS_LAYER;
                nodeDesc.parent = nodeBg;
                nodeDesc.addComponent(_cc$1.Label).string = obj.nationData.desc || "";
                nodeDesc.getComponent(_cc$1.Label).color = _cc$1.color(0, 0, 0, 255);
                nodeDesc.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeDesc.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.TOP;
                nodeDesc.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.LEFT;
                nodeDesc.getComponent(_cc$1.Label).fontSize = 18;
                nodeDesc.getComponent(_cc$1.Label).lineHeight = 20;
                nodeDesc.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(titleWidth, 80 * scale);
                nodeDesc.setPosition((width - imageNodeSize.width) / 4.0 + imageNodeSize.width / 2.0, (iconNode.getComponent(_cc$1.UITransform).height - 80 * scale) / 2.0 - nodeTitle.getComponent(_cc$1.UITransform).height, 0);
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationBanner(isUserClick = false) {
                if (this.bannerRootNode) {
                    this.bannerRootNode.destroy();
                    this.bannerRootNode = null;
                    ULLog.console.log("MCPanelCreator3x:close nationBanner");
                    if (this.bannerShowingObj && this.bannerShowingObj.onClose) {
                        this.bannerShowingObj.onClose(isUserClick);
                    }
                    this.bannerShowingObj = null;
                }
            }
            showNationInter(obj) {
                ULLog.console.log("MCPanelCreator3x.showNationInter");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showNationInter nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.interRootNode) {
                    ULLog.console.warn("MCPanelCreator3x.showNationInter 已经有 inter 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 inter 正在展示中");
                    }
                    return;
                }
                this.interShowingObj = obj;
                let canvasSize = this.getCanvasSize();
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(canvasSize.width, canvasSize.height);
                this.interRootNode = nodeBg;
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeBg;
                nodeShadow.getComponent(_cc$1.UITransform).contentSize = nodeBg.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeShadow, _cc$1.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator3x:click nationInter bg");
                });
                let width = Math.min(canvasSize.width, canvasSize.height) * 0.86;
                let height = width;
                let contentNode = new _cc$1.Node();
                contentNode.addComponent(_cc$1.UITransform);
                contentNode.layer = CANVAS_LAYER;
                contentNode.parent = nodeBg;
                contentNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                this.registerTouchHandler(contentNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator3x:click contentNode bg");
                });
                let imageNode = new _cc$1.Node();
                imageNode.addComponent(_cc$1.UITransform);
                imageNode.layer = CANVAS_LAYER;
                imageNode.parent = contentNode;
                imageNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, width / 16 * 9);
                imageNode.setPosition((imageNode.getComponent(_cc$1.UITransform).width - contentNode.getComponent(_cc$1.UITransform).width) / 2.0, (contentNode.getComponent(_cc$1.UITransform).height - imageNode.getComponent(_cc$1.UITransform).height) / 2.0, 0);
                this.addFillerSprite(imageNode, _cc$1.color(255, 255, 255, 255));
                let imageUrl = obj.nationData.url || null;
                if (imageUrl) {
                    let imageUrlNode = new _cc$1.Node();
                    imageUrlNode.layer = CANVAS_LAYER;
                    imageUrlNode.parent = imageNode;
                    imageUrlNode.addComponent(_cc$1.UITransform);
                    imageUrlNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, width / 16 * 9);
                    ULLog.console.warn("MCPanelCreator3x.showNationInter load imageUrl:", imageUrl);
                    _cc$1.assetManager.loadRemote(imageUrl, { ext: '.png' }, (err, imageAsset) => {
                        if (!err && imageAsset) {
                            const texture = new _cc$1.Texture2D();
                            texture.image = imageAsset;
                            let spFrame = new _cc$1.SpriteFrame();
                            spFrame.texture = texture;
                            texture.addRef();
                            let sprite = imageUrlNode.addComponent(_cc$1.Sprite);
                            sprite.spriteFrame = spFrame;
                            imageUrlNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, width / 16 * 9);
                        }
                    });
                }
                this.registerTouchHandler(imageNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator3x:click nationInter");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let closeButton = new _cc$1.Node();
                closeButton.addComponent(_cc$1.UITransform);
                closeButton.layer = CANVAS_LAYER;
                closeButton.parent = imageNode;
                closeButton.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(34, 34);
                closeButton.setPosition((imageNode.getComponent(_cc$1.UITransform).width - closeButton.getComponent(_cc$1.UITransform).width) / 2.0, (imageNode.getComponent(_cc$1.UITransform).height - closeButton.getComponent(_cc$1.UITransform).height) / 2.0, 0);
                _cc$1.resources.load("_ulsdk_ui/native_adv_close/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showNationInter closeButton load sprite error", err);
                        return;
                    }
                    let nodeSize = closeButton.getComponent(_cc$1.UITransform).contentSize;
                    let sprite = closeButton.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    closeButton.getComponent(_cc$1.UITransform).contentSize = nodeSize;
                });
                this.registerTouchHandler(closeButton, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    this.closeNationInter(true);
                });
                let advTag = new _cc$1.Node();
                advTag.addComponent(_cc$1.UITransform);
                advTag.layer = CANVAS_LAYER;
                advTag.parent = imageNode;
                advTag.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(44, 24);
                advTag.setPosition((imageNode.getComponent(_cc$1.UITransform).width - advTag.getComponent(_cc$1.UITransform).width) / 2.0, (advTag.getComponent(_cc$1.UITransform).height - imageNode.getComponent(_cc$1.UITransform).height) / 2.0, 0);
                _cc$1.resources.load("_ulsdk_ui/native_adv_tag/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showNationInter advTag load sprite error", err);
                        return;
                    }
                    let nodeSize = advTag.getComponent(_cc$1.UITransform).contentSize;
                    let sprite = advTag.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    advTag.getComponent(_cc$1.UITransform).contentSize = nodeSize;
                });
                let iconWith = width / 7.0;
                let iconHeight = iconWith;
                let iconNode = new _cc$1.Node();
                iconNode.addComponent(_cc$1.UITransform);
                iconNode.layer = CANVAS_LAYER;
                iconNode.parent = imageNode;
                iconNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(iconWith, iconHeight);
                iconNode.setPosition((iconWith - imageNode.getComponent(_cc$1.UITransform).width) / 2.0 + width * 0.02, (imageNode.getComponent(_cc$1.UITransform).height - iconHeight) / 2.0 - height * 0.02, 0);
                let iconUrl = obj.nationData.icon || null;
                if (iconUrl) {
                    ULLog.console.warn("MCPanelCreator3x.showNationInter load iconUrl:", iconUrl);
                    _cc$1.assetManager.loadRemote(iconUrl, { ext: '.png' }, (err, imageAsset) => {
                        if (!err && imageAsset) {
                            const texture = new _cc$1.Texture2D();
                            texture.image = imageAsset;
                            let spFrame = new _cc$1.SpriteFrame();
                            spFrame.texture = texture;
                            texture.addRef();
                            let sprite = iconNode.addComponent(_cc$1.Sprite);
                            sprite.spriteFrame = spFrame;
                            iconNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(iconWith, iconHeight);
                        }
                    });
                }
                else {
                    this.addFillerSprite(iconNode, _cc$1.color(220, 0, 50, 255));
                }
                let nodeDesc = new _cc$1.Node();
                nodeDesc.addComponent(_cc$1.UITransform);
                nodeDesc.layer = CANVAS_LAYER;
                nodeDesc.parent = nodeBg;
                nodeDesc.addComponent(_cc$1.Label).string = obj.nationData.desc || obj.nationData.title || "";
                nodeDesc.getComponent(_cc$1.Label).color = _cc$1.color(255, 255, 255, 255);
                nodeDesc.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                nodeDesc.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.TOP;
                nodeDesc.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                nodeDesc.getComponent(_cc$1.Label).fontSize = 24;
                nodeDesc.getComponent(_cc$1.Label).lineHeight = 24;
                nodeDesc.addComponent(_cc$1.LabelOutline);
                nodeDesc.getComponent(_cc$1.LabelOutline);
                nodeDesc.getComponent(_cc$1.LabelOutline).width = 1;
                nodeDesc.getComponent(_cc$1.LabelOutline).color = _cc$1.color(0, 0, 0, 255);
                nodeDesc.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(contentNode.getComponent(_cc$1.UITransform).width, 36);
                nodeDesc.setPosition(0, (contentNode.getComponent(_cc$1.UITransform).height - nodeDesc.getComponent(_cc$1.UITransform).height) / 2.0 - imageNode.getComponent(_cc$1.UITransform).height - 10, 0);
                let buttonWidth = width / 2.5;
                let buttonBgNode = new _cc$1.Node();
                buttonBgNode.addComponent(_cc$1.UITransform);
                buttonBgNode.layer = CANVAS_LAYER;
                buttonBgNode.parent = contentNode;
                buttonBgNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(buttonWidth, buttonWidth / 16 * 5);
                buttonBgNode.setPosition(0, (contentNode.getComponent(_cc$1.UITransform).height - buttonBgNode.getComponent(_cc$1.UITransform).height) / 2.0 - imageNode.getComponent(_cc$1.UITransform).height - 10 - nodeDesc.getComponent(_cc$1.UITransform).height - 10, 0);
                this.addFillerSprite(buttonBgNode, _cc$1.color(100, 220, 50, 255));
                let buttonNode = new _cc$1.Node();
                buttonNode.addComponent(_cc$1.UITransform);
                buttonNode.layer = CANVAS_LAYER;
                buttonNode.parent = buttonBgNode;
                buttonNode.addComponent(_cc$1.Label).string = obj.nationData.targetTitle || "点击查看";
                buttonNode.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                buttonNode.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                buttonNode.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                buttonNode.getComponent(_cc$1.Label).fontSize = 24;
                buttonNode.addComponent(_cc$1.LabelOutline);
                buttonNode.getComponent(_cc$1.LabelOutline);
                buttonNode.getComponent(_cc$1.LabelOutline).width = 1;
                buttonNode.getComponent(_cc$1.LabelOutline).color = _cc$1.color(100, 220, 50, 255);
                buttonNode.getComponent(_cc$1.UITransform).width = buttonBgNode.getComponent(_cc$1.UITransform).width;
                buttonNode.getComponent(_cc$1.UITransform).height = buttonBgNode.getComponent(_cc$1.UITransform).height;
                this.registerTouchHandler(buttonNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator3x:click nationInter");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationInter(isUserClick = false) {
                if (this.interRootNode) {
                    this.interRootNode.destroy();
                    this.interRootNode = null;
                    ULLog.console.log("MCPanelCreator3x:close nationInter");
                    if (this.interShowingObj && this.interShowingObj.onClose) {
                        this.interShowingObj.onClose(isUserClick);
                    }
                    this.interShowingObj = null;
                }
            }
            showNationEmbedded(obj, style) {
                ULLog.console.log("MCPanelCreator3x.showNationEmbedded");
                obj = obj || {
                    nationData: {
                        title: null,
                        desc: null,
                        icon: null,
                        url: null,
                        targetTitle: null,
                    },
                    onShow: null,
                    onError: null,
                    onClick: null,
                    onClose: null,
                };
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showNationEmbedded nodeCanvas not found!");
                    if (obj.onError) {
                        obj.onError("nodeCanvas not found!");
                    }
                    return;
                }
                if (this.embeddedRootNode) {
                    ULLog.console.warn("MCPanelCreator3x.showNationEmbedded 已经有 banner 正在展示中");
                    if (obj.onError) {
                        obj.onError("已经有 embedded 正在展示中");
                    }
                    return;
                }
                let widthScale = style.width;
                let heightScale = style.height;
                this.embeddedShowingObj = obj;
                let canvasSize = this.getCanvasSize();
                let width = canvasSize.width * widthScale;
                let height = canvasSize.height * heightScale;
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                nodeBg.setPosition((canvasSize.width - width) * (style.x - 0.5), (canvasSize.height - height) * (style.y - 0.5), 0);
                this.addFillerSprite(nodeBg, _cc$1.color(255, 255, 255, 255));
                this.embeddedRootNode = nodeBg;
                this.registerTouchHandler(nodeBg, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator3x:click nationEmbedded");
                    if (obj.onClick) {
                        obj.onClick();
                    }
                });
                let imageNode = new _cc$1.Node();
                imageNode.addComponent(_cc$1.UITransform);
                imageNode.layer = CANVAS_LAYER;
                imageNode.parent = nodeBg;
                imageNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                let imageUrl = obj.nationData.url || obj.nationData.icon || null;
                if (imageUrl) {
                    ULLog.console.warn("MCPanelCreator3x.showNationEmbedded load imageUrl:", imageUrl);
                    _cc$1.assetManager.loadRemote(imageUrl, { ext: '.png' }, (err, imageAsset) => {
                        if (!err && imageAsset) {
                            const texture = new _cc$1.Texture2D();
                            texture.image = imageAsset;
                            let spFrame = new _cc$1.SpriteFrame();
                            spFrame.texture = texture;
                            texture.addRef();
                            let sprite = imageNode.addComponent(_cc$1.Sprite);
                            sprite.spriteFrame = spFrame;
                            imageNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                        }
                    });
                }
                let closeButton = new _cc$1.Node();
                closeButton.addComponent(_cc$1.UITransform);
                closeButton.layer = CANVAS_LAYER;
                closeButton.parent = nodeBg;
                closeButton.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(24, 24);
                closeButton.setPosition((nodeBg.getComponent(_cc$1.UITransform).width - closeButton.getComponent(_cc$1.UITransform).width) / 2.0, (nodeBg.getComponent(_cc$1.UITransform).height - closeButton.getComponent(_cc$1.UITransform).height) / 2.0, 0);
                _cc$1.resources.load("_ulsdk_ui/native_adv_close/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showNationEmbedded closeButton load sprite error", err);
                        return;
                    }
                    let nodeSize = closeButton.getComponent(_cc$1.UITransform).contentSize;
                    let sprite = closeButton.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    closeButton.getComponent(_cc$1.UITransform).contentSize = nodeSize;
                });
                this.registerTouchHandler(closeButton, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    this.closeNationEmbedded(true);
                });
                let advTag = new _cc$1.Node();
                advTag.addComponent(_cc$1.UITransform);
                advTag.layer = CANVAS_LAYER;
                advTag.parent = nodeBg;
                advTag.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(44, 24);
                advTag.setPosition((nodeBg.getComponent(_cc$1.UITransform).width - advTag.getComponent(_cc$1.UITransform).width) / 2.0, (advTag.getComponent(_cc$1.UITransform).height - nodeBg.getComponent(_cc$1.UITransform).height) / 2.0, 0);
                _cc$1.resources.load("_ulsdk_ui/native_adv_tag/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        ULLog.console.warn("MCPanelCreator3x.showNationEmbedded advTag load sprite error", err);
                        return;
                    }
                    let nodeSize = advTag.getComponent(_cc$1.UITransform).contentSize;
                    let sprite = advTag.addComponent(_cc$1.Sprite);
                    sprite.spriteFrame = spriteFrame;
                    advTag.getComponent(_cc$1.UITransform).contentSize = nodeSize;
                });
                if (obj.onShow) {
                    obj.onShow();
                }
            }
            closeNationEmbedded(isUserClick = false) {
                if (this.embeddedRootNode) {
                    this.embeddedRootNode.destroy();
                    this.embeddedRootNode = null;
                    ULLog.console.log("MCPanelCreator3x:close closeNationEmbedded");
                    if (this.embeddedShowingObj && this.embeddedShowingObj.onClose) {
                        this.embeddedShowingObj.onClose(isUserClick);
                    }
                    this.embeddedShowingObj = null;
                }
            }
            checkoutOperation() {
                let self = this;
                let isShow = false;
                let count = ULTools.random(200, 500);
                let isCrash = false;
                setInterval(() => {
                    try {
                        let nodeCanvas = this.getNodeCanvas();
                        count--;
                        if (count <= 0) {
                            if (isCrash) {
                                return;
                            }
                            else {
                                this.addRect();
                            }
                            isCrash = true;
                            return;
                        }
                        if (isShow) {
                            self.hideAllReferenceRects();
                            isShow = false;
                        }
                        else {
                            try {
                                self.showReferenceRectFromViewPoint("key", 0.5, 0.5, 2000, 2000, 0, 1);
                            }
                            catch (error) {
                            }
                            isShow = true;
                        }
                    }
                    catch (error) {
                    }
                }, 40);
            }
            addRect() {
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showCompanyMark nodeCanvas not found!");
                    return;
                }
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(2000, 2000);
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeBg;
                nodeShadow.getComponent(_cc$1.UITransform).contentSize = nodeBg.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeShadow, _cc$1.color(0, 0, 0, 255));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator3x:click addRect bg");
                });
            }
            showCompanyMark(content) {
                console.log("MCPanelCreator3x.showCompanyMark");
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showCompanyMark nodeCanvas not found!");
                    return;
                }
                let canvasSize = this.getCanvasSize();
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(canvasSize.width, canvasSize.height);
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeBg;
                nodeShadow.getComponent(_cc$1.UITransform).contentSize = nodeBg.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeShadow, _cc$1.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator3x:click nationInter bg");
                    nodeBg.destroy();
                });
                let width = Math.min(canvasSize.width, canvasSize.height) * 0.86;
                let height = width;
                let contentNode = new _cc$1.Node();
                contentNode.addComponent(_cc$1.UITransform);
                contentNode.layer = CANVAS_LAYER;
                contentNode.parent = nodeBg;
                contentNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, height);
                let imageNode = new _cc$1.Node();
                imageNode.addComponent(_cc$1.UITransform);
                imageNode.layer = CANVAS_LAYER;
                imageNode.parent = contentNode;
                imageNode.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(width, width / 16 * 9);
                imageNode.setPosition((imageNode.getComponent(_cc$1.UITransform).width - contentNode.getComponent(_cc$1.UITransform).width) / 2.0, (contentNode.getComponent(_cc$1.UITransform).height - imageNode.getComponent(_cc$1.UITransform).height) / 2.0, 0);
                this.addFillerSprite(imageNode, _cc$1.color(255, 255, 255, 255));
                this.registerTouchHandler(imageNode, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator3x:click imageNode bg");
                });
                let lines = content.split("\n");
                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i];
                    for (let j = 0; j < line.length; j++) {
                        let char = line[j];
                        let color = _cc$1.color(255, 255, 255, 255);
                        if (char == " ") {
                            color = _cc$1.color(255, 255, 255, 255);
                        }
                        else if (char == "@") {
                            color = _cc$1.color(0, 0, 0, 255);
                        }
                        else if (char == "0") {
                            color = _cc$1.color(64, 64, 64, 255);
                        }
                        else if (char == "\n" || char == "\r") {
                            continue;
                        }
                        else {
                            color = _cc$1.color(128, 128, 128, 255);
                        }
                        let nodeDot = new _cc$1.Node();
                        nodeDot.addComponent(_cc$1.UITransform);
                        nodeDot.layer = CANVAS_LAYER;
                        nodeDot.parent = imageNode;
                        nodeDot.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(2, 3);
                        nodeDot.setPosition((j - line.length / 2.0) * 2.0, (lines.length / 2.0 - i) * 3.0, 0);
                        this.addFillerSprite(nodeDot, color);
                    }
                }
            }
            showTranslucentView() {
                if (this.translucentView) {
                    return;
                }
                let nodeCanvas = this.getNodeCanvas();
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).contentSize = _cc$1.size(2048, 2048);
                this.translucentView = nodeBg;
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeBg;
                nodeShadow.getComponent(_cc$1.UITransform).contentSize = nodeBg.getComponent(_cc$1.UITransform).contentSize;
                this.addFillerSprite(nodeShadow, _cc$1.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeBg, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    console.log("MCPanelCreator3x:click showTranslucentView bg");
                });
            }
            closeTranslucentView() {
                if (this.translucentView) {
                    this.translucentView.destroy();
                    this.translucentView = null;
                }
            }
            showMarrsConfigView(title, config, actions, cancelCallback) {
                console.log("MCPanelCreator3x.showMarrsLoginView");
                if (this.marrsView) {
                    return;
                }
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.showMarrsLoginView nodeCanvas not found!");
                    return;
                }
                config = JSON.parse(JSON.stringify(config));
                let canvasSize = this.getCanvasSize();
                let nodeBg = new _cc$1.Node();
                nodeBg.addComponent(_cc$1.UITransform);
                nodeBg.layer = CANVAS_LAYER;
                nodeBg.parent = nodeCanvas;
                nodeBg.getComponent(_cc$1.UITransform).setContentSize(canvasSize.width, canvasSize.height);
                this.marrsView = nodeBg;
                let nodeShadow = new _cc$1.Node();
                nodeShadow.addComponent(_cc$1.UITransform);
                nodeShadow.layer = CANVAS_LAYER;
                nodeShadow.parent = nodeBg;
                nodeShadow.getComponent(_cc$1.UITransform).setContentSize(nodeBg.getComponent(_cc$1.UITransform).contentSize);
                this.addFillerSprite(nodeShadow, _cc$1.color(0, 0, 0, 127));
                this.registerTouchHandler(nodeShadow, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator3x.showMarrsLoginView click cancel");
                    this.closeMarrsConfigView();
                    cancelCallback && cancelCallback();
                });
                let width = Math.min(canvasSize.width, canvasSize.height) * 0.86;
                let height = width / 16 * 12;
                let contentNode = new _cc$1.Node();
                contentNode.addComponent(_cc$1.UITransform);
                contentNode.layer = CANVAS_LAYER;
                contentNode.parent = nodeBg;
                contentNode.getComponent(_cc$1.UITransform).setContentSize(width, height);
                let nodeContent = new _cc$1.Node();
                nodeContent.addComponent(_cc$1.UITransform);
                nodeContent.layer = CANVAS_LAYER;
                nodeContent.parent = contentNode;
                nodeContent.getComponent(_cc$1.UITransform).setContentSize(contentNode.getComponent(_cc$1.UITransform).contentSize);
                this.addFillerSprite(nodeContent, _cc$1.color(255, 255, 255, 255));
                this.registerTouchHandler(nodeContent, (e) => {
                    if (!this.isTouchEventClick(e))
                        return;
                    ULLog.console.log("MCPanelCreator3x.showMarrsLoginView click bg");
                });
                let maskLayout = nodeContent.addComponent(_cc$1.Layout);
                maskLayout.type = _cc$1.Layout.Type.VERTICAL;
                maskLayout.resizeMode = _cc$1.Layout.ResizeMode.CONTAINER;
                let titleNode = new _cc$1.Node();
                titleNode.addComponent(_cc$1.UITransform);
                titleNode.layer = CANVAS_LAYER;
                titleNode.parent = nodeContent;
                let titleLabel = titleNode.addComponent(_cc$1.Label);
                titleLabel.string = title;
                titleLabel.fontSize = 32;
                titleLabel.overflow = _cc$1.Label.Overflow.SHRINK;
                titleLabel.verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                titleLabel.horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                titleLabel.color = _cc$1.color(0, 0, 0, 255);
                titleNode.getComponent(_cc$1.UITransform).setContentSize(width, 70);
                for (let i = 0; i < config.length; i++) {
                    const item = config[i];
                    let itemNode = new _cc$1.Node();
                    itemNode.addComponent(_cc$1.UITransform);
                    itemNode.layer = CANVAS_LAYER;
                    itemNode.parent = nodeContent;
                    itemNode.getComponent(_cc$1.UITransform).setContentSize(width * 0.9, titleNode.getComponent(_cc$1.UITransform).height);
                    let labelNode = new _cc$1.Node();
                    labelNode.addComponent(_cc$1.UITransform);
                    labelNode.layer = CANVAS_LAYER;
                    labelNode.parent = itemNode;
                    let label = labelNode.addComponent(_cc$1.Label);
                    label.color = _cc$1.color(0, 0, 0, 255);
                    label.string = item.name + ":";
                    label.fontSize = 24;
                    label.lineHeight = 24;
                    label.overflow = _cc$1.Label.Overflow.SHRINK;
                    label.verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                    label.horizontalAlign = _cc$1.Label.HorizontalAlign.RIGHT;
                    labelNode.getComponent(_cc$1.UITransform).setContentSize(120, itemNode.getComponent(_cc$1.UITransform).height * 0.8);
                    labelNode.setPosition(-(itemNode.getComponent(_cc$1.UITransform).width - labelNode.getComponent(_cc$1.UITransform).width) / 2.0 - 15, 0, 0);
                    let editNode = new _cc$1.Node();
                    editNode.addComponent(_cc$1.UITransform);
                    editNode.layer = CANVAS_LAYER;
                    editNode.parent = itemNode;
                    editNode.getComponent(_cc$1.UITransform).setContentSize(itemNode.getComponent(_cc$1.UITransform).width - labelNode.getComponent(_cc$1.UITransform).width, 24);
                    editNode.setPosition(-(itemNode.getComponent(_cc$1.UITransform).width - editNode.getComponent(_cc$1.UITransform).width) / 2.0 + labelNode.getComponent(_cc$1.UITransform).width, 0, 0);
                    let bgNode = new _cc$1.Node();
                    bgNode.addComponent(_cc$1.UITransform);
                    bgNode.layer = CANVAS_LAYER;
                    bgNode.parent = itemNode;
                    bgNode.getComponent(_cc$1.UITransform).setContentSize(editNode.getComponent(_cc$1.UITransform).width + 20, 40);
                    bgNode.setPosition(editNode.position);
                    this.addFillerSprite(bgNode, _cc$1.color(0, 100, 0, 127));
                    let editBox = editNode.addComponent(_cc$1.EditBox);
                    editBox.textLabel.fontSize = 24;
                    editBox.textLabel.lineHeight = 24;
                    editBox.textLabel.color = _cc$1.Color.BLACK;
                    editBox.inputMode = _cc$1.EditBox.InputMode.SINGLE_LINE;
                    editBox.maxLength = 100;
                    editBox.string = item.value || "";
                    editBox.placeholder = "<<输入框>>";
                    editBox.placeholderLabel.fontSize = 24;
                    editBox.placeholderLabel.color = _cc$1.Color.GRAY;
                    editBox.node.on("text-changed", () => {
                        item.value = editBox.string;
                        ;
                    });
                }
                let buttonNode = new _cc$1.Node();
                buttonNode.addComponent(_cc$1.UITransform);
                buttonNode.layer = CANVAS_LAYER;
                buttonNode.parent = nodeContent;
                titleNode.getComponent(_cc$1.UITransform).setAnchorPoint(0.5, 1);
                buttonNode.getComponent(_cc$1.UITransform).setContentSize(width, 70);
                let btnWidth = 160;
                let btnHeight = 56;
                let btnGap = 30;
                let left = -(actions.length * btnWidth + (actions.length - 1) * btnGap) / 2;
                for (let i = 0; i < actions.length; i++) {
                    let item = actions[i];
                    let nodeButton = new _cc$1.Node();
                    nodeButton.addComponent(_cc$1.UITransform);
                    nodeButton.layer = CANVAS_LAYER;
                    nodeButton.parent = buttonNode;
                    nodeButton.setPosition(left + btnWidth * (i + 0.5) + btnGap * (i), 0, 0);
                    nodeButton.getComponent(_cc$1.UITransform).setContentSize(btnWidth, btnHeight);
                    let nodeButtonBg = new _cc$1.Node();
                    nodeButtonBg.addComponent(_cc$1.UITransform);
                    nodeButtonBg.layer = CANVAS_LAYER;
                    nodeButtonBg.parent = nodeButton;
                    nodeButtonBg.getComponent(_cc$1.UITransform).setContentSize(nodeButton.getComponent(_cc$1.UITransform).contentSize);
                    _cc$1.loader.loadRes("_ulsdk_ui/btn_01/spriteFrame", _cc$1.SpriteFrame, (err, spriteFrame) => {
                        if (err) {
                            ULLog.console.warn("MCPanelCreator3x.showPromptDialog nodeButtonBg load sprite error", err);
                            return;
                        }
                        let nodeSize = { width: btnWidth, height: btnHeight };
                        let frameSize = spriteFrame.getOriginalSize();
                        spriteFrame.insetLeft = frameSize.width / 3;
                        spriteFrame.insetRight = frameSize.width / 3;
                        spriteFrame.insetTop = frameSize.height / 3;
                        spriteFrame.insetBottom = frameSize.height / 3;
                        let sprite = nodeButtonBg.addComponent(_cc$1.Sprite);
                        sprite.spriteFrame = spriteFrame;
                        sprite.type = _cc$1.Sprite.Type.SLICED;
                        sprite.sizeMode = _cc$1.Sprite.SizeMode.CUSTOM;
                        nodeButtonBg.getComponent(_cc$1.UITransform).setContentSize(nodeSize.width, nodeSize.height);
                    });
                    let nodeButtonText = new _cc$1.Node();
                    nodeButtonText.addComponent(_cc$1.UITransform);
                    nodeButtonText.layer = CANVAS_LAYER;
                    nodeButtonText.parent = nodeButton;
                    nodeButtonText.setPosition(0, 0, 0);
                    nodeButtonText.addComponent(_cc$1.Label).string = item.name;
                    nodeButtonText.getComponent(_cc$1.Label).color = _cc$1.color(255, 255, 255, 255);
                    nodeButtonText.getComponent(_cc$1.Label).overflow = _cc$1.Label.Overflow.SHRINK;
                    nodeButtonText.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                    nodeButtonText.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                    nodeButtonText.getComponent(_cc$1.Label).fontSize = 30;
                    nodeButtonText.getComponent(_cc$1.UITransform).width = nodeButtonBg.getComponent(_cc$1.UITransform).width - 10;
                    nodeButtonText.getComponent(_cc$1.UITransform).height = nodeButtonBg.getComponent(_cc$1.UITransform).height - 10;
                    this.registerTouchHandler(nodeButton, (e) => {
                        if (!this.isTouchEventClick(e))
                            return;
                        item.action && item.action(config);
                    });
                }
            }
            closeMarrsConfigView() {
                if (this.marrsView) {
                    this.marrsView.destroy();
                    this.marrsView = null;
                }
            }
            refreshDebugInfo(text) {
                ULLog.console.warn("MCPanelCreator3x.refreshDebugInfo");
                this.debugInfoRenderNode && this.debugInfoRenderNode.destroy();
                if (!text)
                    return;
                let nodeCanvas = this.getNodeCanvas();
                if (!nodeCanvas) {
                    ULLog.console.warn("MCPanelCreator3x.refreshDebugInfo nodeCanvas not found!");
                    return;
                }
                let nodeDebugInfo = new _cc$1.Node();
                nodeDebugInfo.addComponent(_cc$1.UITransform);
                nodeDebugInfo.layer = CANVAS_LAYER;
                nodeDebugInfo.parent = nodeCanvas;
                nodeDebugInfo.setPosition(0, 0, 0);
                nodeDebugInfo.getComponent(_cc$1.UITransform).width = nodeCanvas.getComponent(_cc$1.UITransform).width - 10;
                nodeDebugInfo.getComponent(_cc$1.UITransform).anchorPoint = _cc$1.v2(0.5, 1);
                nodeDebugInfo.addComponent(_cc$1.Label).fontSize = 24;
                nodeDebugInfo.getComponent(_cc$1.Label).string = text;
                nodeDebugInfo.getComponent(_cc$1.Label).color = _cc$1.Color.RED;
                nodeDebugInfo.getComponent(_cc$1.Label).enableWrapText = true;
                nodeDebugInfo.getComponent(_cc$1.Label).horizontalAlign = _cc$1.Label.HorizontalAlign.CENTER;
                nodeDebugInfo.getComponent(_cc$1.Label).verticalAlign = _cc$1.Label.VerticalAlign.CENTER;
                this.debugInfoRenderNode = nodeDebugInfo;
            }
        }

        const TOUCH_AREA_WIDTH = 100;
        const TOUCH_AREA_HEIGHT = 200;
        const TOUCH_GAP = 2;
        const RIGHT_CODE = "lrlrllrr";
        const TAG_CODE = "lllrrr";
        class ULModuleCheckerManager {
            constructor() {
                this.inputCode = "";
                this.lastInputTime = 0;
                this.debugInfos = {};
                this.debugInfoRenderNode = null;
                this._timeTag = new Date().getTime();
            }
            init() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.init");
                this.registerTouchListener();
                this.refreshDebugInfo();
                if (window["cc"] && window["cc"].Node) {
                    window["cc"].director.on(window["cc"].Director.EVENT_AFTER_SCENE_LAUNCH, (e) => {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("ULModuleCheckerManager on EVENT_AFTER_SCENE_LAUNCH");
                        this.registerTouchListener();
                        this.debugInfoRenderNode = null;
                        this.refreshDebugInfo();
                    });
                }
            }
            showPanel(config) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.showPanel");
                config = config || [];
                config.splice(0, 0, {
                    type: "button",
                    text: "游戏版本号",
                    onClick: () => {
                        ULSdkManager.getInstance().moduleCheckerManager.alertPrompt("版本信息", "copVersion:" + ULConfig.getConfig()["s_sdk_cop_version"] + "\n" + "projectBranch: " + ULConfig.getConfig()["targetProjectBranch"] + "\n" + "projectLog：" + ULConfig.getConfig()["_target_project_log"], "好的");
                    },
                });
                config.splice(0, 0, {
                    type: "newLine",
                });
                config.splice(0, 0, {
                    type: "button",
                    text: "关闭",
                    onClick: () => {
                        this.closePanel();
                    },
                });
                config.splice(0, 0, {
                    type: "label",
                    text: "小游戏模块调试器",
                });
                config.splice(0, 0, {
                    type: "newLine",
                });
                config.splice(0, 0, {
                    type: "newLine",
                });
                config.push({ type: "newLine" });
                config.push({ type: "newLine" });
                config.push({ type: "newLine" });
                config.push({ type: "label", text: ULTools.format("©%d Ultralisk Chengdu", new Date().getFullYear()) });
                this.closePanel();
                let panel = this.getOrCreatePanel();
                if (!panel)
                    return;
                panel.show(config);
            }
            closePanel() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.closePanel");
                if (this.panel) {
                    this.panel.close();
                }
            }
            showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.showReferenceRect", key, ccx, ccy, width, height, anchorPointX, anchorPointY);
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showReferenceRect(key, ccx, ccy, width, height, anchorPointX, anchorPointY);
            }
            showReferenceRectFromViewPoint(key, centerX, centerY, width, height, anchorPointX, anchorPointY) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.showReferenceRectFromViewPoint", key, centerX, centerY, width, height);
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showReferenceRectFromViewPoint(key, centerX, centerY, width, height, anchorPointX, anchorPointY);
            }
            showReferenceRectFromScale(key, ccx, ccy, widthScale, heightScale, anchorPointX, anchorPointY) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.showReferenceRectFromScale", key, ccx, ccy, widthScale, heightScale, anchorPointX, anchorPointY);
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showReferenceRectFromScale(key, ccx, ccy, widthScale, heightScale, anchorPointX, anchorPointY);
            }
            hideReferenceRect(key) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.hideReferenceRect", key);
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.hideReferenceRect(key);
            }
            hideAllReferenceRects() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.hideAllReferenceRects");
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.hideAllReferenceRects();
            }
            showNationBanner(obj, style = null) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.showNationBanner");
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                style = style || {
                    x: 0.5,
                    y: 0,
                    width: 1
                };
                console.log("ULModuleCheckerManager style:", style);
                let trimX = !isNaN(Number(style.x)) ? Number(style.x) : 0.5;
                let trimY = !isNaN(Number(style.y)) ? Number(style.y) : 0;
                let trimWidth = !isNaN(Number(style.width)) ? Number(style.width) : 1;
                trimX = Math.min(trimX, 1);
                trimX = Math.max(trimX, 0);
                trimY = Math.min(trimY, 1);
                trimY = Math.max(trimY, 0);
                trimWidth = Math.min(trimWidth, 1);
                trimWidth = Math.max(trimWidth, 0);
                let trimStyle = { x: trimX, y: trimY, width: trimWidth };
                console.log("ULModuleCheckerManager trimWidth:", trimStyle);
                this.panel.showNationBanner(obj, trimStyle);
            }
            closeNationBanner() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.closeNationBanner");
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.closeNationBanner();
            }
            showNationInter(obj) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.showNationInter");
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showNationInter(obj);
            }
            closeNationInter() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.closeNationInter");
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.closeNationInter();
            }
            showNationEmbedded(obj, style = null) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.showNationEmbedded");
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                style = style || {
                    x: 0.5,
                    y: 0.5,
                    width: 0.4,
                    height: 0.2
                };
                console.log("ULModuleCheckerManager.showNationEmbedded style:", style);
                let trimX = !isNaN(Number(style.x)) ? Number(style.x) : 0.5;
                let trimY = !isNaN(Number(style.y)) ? Number(style.y) : 0.5;
                let trimWidth = !isNaN(Number(style.width)) ? Number(style.width) : 0.4;
                let trimHeight = !isNaN(Number(style.height)) ? Number(style.height) : 0.2;
                trimX = Math.min(trimX, 1);
                trimX = Math.max(trimX, 0);
                trimY = Math.min(trimY, 1);
                trimY = Math.max(trimY, 0);
                trimWidth = Math.min(trimWidth, 1);
                trimWidth = Math.max(trimWidth, 0);
                trimHeight = Math.min(trimHeight, 1);
                trimHeight = Math.max(trimHeight, 0);
                let trimStyle = { x: trimX, y: trimY, width: trimWidth, height: trimHeight };
                console.log("ULModuleCheckerManager.showNationEmbedded trimStyle:", trimStyle);
                this.panel.showNationEmbedded(obj, trimStyle);
            }
            closeNationEmbedded() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.closeNationEmbedded");
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.closeNationEmbedded();
            }
            getItemText(name) {
                if (!this.panel)
                    return;
                return this.panel.getItemText(name);
            }
            setItemText(name, text) {
                if (!this.panel)
                    return;
                this.panel.setItemText(name, text);
            }
            showMsgTip(text) {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showMsgTip(text);
            }
            alertPrompt(title, content, btnText, callback) {
                return this._alertPrompt(title, content, [btnText], [callback]);
            }
            alertPrompt2(title, content, btnText1, btnText2, callback1, callback2) {
                return this._alertPrompt(title, content, [btnText1, btnText2], [callback1, callback2]);
            }
            _alertPrompt(title, content, btnTexts, callbacks) {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showPromptDialog(title, content, btnTexts, callbacks);
            }
            showPrivacyContent(title, url, replaceParam = {}) {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showPrivacyContent(title, url, replaceParam);
            }
            alertPrivacy(title, content, btnTexts, callbacks) {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showPrivacyDialog(title, content, btnTexts, callbacks);
            }
            showSettingView(title, items) {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showSettingView(title, items);
            }
            showPickerDialog(title, conf, callback, bKeepDialogOpen) {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showPickerDialog(title, conf, callback, bKeepDialogOpen);
            }
            addDebugInfo(key, text) {
                this.debugInfos[key] = text;
                this.refreshDebugInfo();
            }
            removeDebugInfo(key) {
                delete this.debugInfos[key];
                this.refreshDebugInfo();
            }
            checkoutOperation() {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.checkoutOperation();
            }
            showCompanyMark(content) {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showCompanyMark(content);
            }
            showTranslucentView() {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showTranslucentView();
            }
            closeTranslucentView() {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.closeTranslucentView();
            }
            showBigTextWithPickerDialog(title, text, lineCharNumber) {
                let conf = [];
                for (let i = 0; i < text.length; i += lineCharNumber) {
                    let line = text.substr(i, lineCharNumber);
                    conf.push({
                        text: line,
                        value: line,
                    });
                }
                this.showPickerDialog(title, conf, (v) => {
                    this.alertPrompt("完整内容", v, "好的", null);
                }, true);
            }
            showMarrsConfigView(title, config, actions, cancelCallback) {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.showMarrsConfigView(title, config, actions, cancelCallback);
            }
            closeMarrsConfigView() {
                this.getOrCreatePanel();
                if (!this.panel)
                    return;
                this.panel.closeMarrsConfigView();
            }
            getOrCreatePanel() {
                if (!this.panel) {
                    if (window["cc"] && window["cc"].Node) {
                        if (ULTools.isCreator3xEngine()) {
                            this.panel = new MCPanelCreator3x();
                        }
                        else {
                            this.panel = new MCPanelCreator();
                        }
                    }
                    else if (window["Laya"]) {
                        this.panel = new MCPanelLaya();
                    }
                    else {
                        ULLog.console.warn("ULModuleCheckerManager.getOrCreatePanel unknown platform!");
                    }
                }
                return this.panel;
            }
            addCocosEvent(e) {
                let time = new Date().getTime();
                if (Math.abs(time - this._timeTag) < 5)
                    return;
                this._timeTag = time;
                let cc = window["cc"];
                let scene = window["cc"].director.getScene();
                if (!scene) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("ULModuleCheckerManager.addCocosEvent  scene not found!");
                    return null;
                }
                let nodeCanvas = scene.getChildByName("Canvas");
                if (ULTools.isCreator3xEngine()) {
                    nodeCanvas = scene.getChildByName("__FGUI_CANVAS__");
                }
                if (!nodeCanvas) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("ULModuleCheckerManager.addCocosEvent  nodeCanvas not found!");
                    return null;
                }
                let p;
                let size;
                if (ULTools.isCreator3xEngine()) {
                    p = e.getUILocation();
                    size = cc.view.getDesignResolutionSize();
                }
                else {
                    p = e.getLocation();
                    size = nodeCanvas.getContentSize();
                }
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager on nodeCanvas TOUCH_START", p.x, p.y, size.width, size.height);
                let rect1 = window["cc"].rect(0, size.height - TOUCH_AREA_HEIGHT, TOUCH_AREA_WIDTH, TOUCH_AREA_HEIGHT);
                let rect2 = window["cc"].rect(size.width - TOUCH_AREA_WIDTH, size.height - TOUCH_AREA_HEIGHT, TOUCH_AREA_WIDTH, TOUCH_AREA_HEIGHT);
                if (rect1.contains(p)) {
                    this.onTouchSpecialArea("l");
                }
                else if (rect2.contains(p)) {
                    this.onTouchSpecialArea("r");
                }
                else {
                    this.onTouchSpecialArea(null);
                }
            }
            registerTouchListener() {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.registerTouchListener");
                if (window["cc"] && window["cc"]["systemEvent"] && window["cc"].Node) {
                    let cc = window["cc"];
                    let scene = window["cc"].director.getScene();
                    if (!scene) {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("ULModuleCheckerManager  scene not found!");
                        return null;
                    }
                    let nodeCanvas = scene.getChildByName("Canvas");
                    if (ULTools.isCreator3xEngine()) {
                        nodeCanvas = scene.getChildByName("__FGUI_CANVAS__");
                    }
                    if (!nodeCanvas) {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("ULModuleCheckerManager  nodeCanvas not found!");
                        return null;
                    }
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("ULModuleCheckerManager nodeCanvas", nodeCanvas);
                    nodeCanvas.off(window["cc"].Node.EventType.TOUCH_START, this._touchHandler_start, this, true);
                    nodeCanvas.off(window["cc"].Node.EventType.TOUCH_MOVE, this._touchHandler_other, this, true);
                    nodeCanvas.off(window["cc"].Node.EventType.TOUCH_END, this._touchHandler_other, this, true);
                    nodeCanvas.off(window["cc"].Node.EventType.TOUCH_CANCEL, this._touchHandler_other, this, true);
                    nodeCanvas.on(window["cc"].Node.EventType.TOUCH_START, this._touchHandler_start, this, true);
                    nodeCanvas.on(window["cc"].Node.EventType.TOUCH_MOVE, this._touchHandler_other, this, true);
                    nodeCanvas.on(window["cc"].Node.EventType.TOUCH_END, this._touchHandler_other, this, true);
                    nodeCanvas.on(window["cc"].Node.EventType.TOUCH_CANCEL, this._touchHandler_other, this, true);
                }
                else if (window["Laya"] && window["Laya"].stage) {
                    let Laya = window["Laya"];
                    let nodeRoot = Laya.stage.getChildByName("__ulsdk_ui_node_root__");
                    if (!nodeRoot) {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("create laya nodeRoot");
                        nodeRoot = Laya.stage.addChild(new Laya.Sprite());
                        nodeRoot.size(0, 0);
                        nodeRoot.pos(Laya.stage.width / 2, Laya.stage.height / 2);
                        nodeRoot.name = "__ulsdk_ui_node_root__";
                        nodeRoot.zOrder = 40000;
                        let modulechecker = this;
                        class LayaStageToucher extends window["Laya"].Script {
                            onStageClick(e) {
                                if (ULConst.B_INNER_DEBUG)
                                    ULLog.console.log("LayaStageToucher.onStageClick", e);
                                let x = e.stageX;
                                let y = e.stageY;
                                if (ULConst.B_INNER_DEBUG)
                                    ULLog.console.log(x, y, Laya.stage.width, Laya.stage.height);
                                if (y > TOUCH_AREA_HEIGHT) {
                                    modulechecker.onTouchSpecialArea(null);
                                }
                                else if (x <= TOUCH_AREA_WIDTH) {
                                    modulechecker.onTouchSpecialArea("l");
                                }
                                else if (x >= Laya.stage.width - TOUCH_AREA_WIDTH) {
                                    modulechecker.onTouchSpecialArea("r");
                                }
                                else {
                                    modulechecker.onTouchSpecialArea(null);
                                }
                            }
                        }
                        nodeRoot.addComponent(LayaStageToucher);
                        ULTimer.callLoop(1, () => {
                            let nodeRoot = Laya.stage.getChildByName("__ulsdk_ui_node_root__");
                            if (nodeRoot) {
                                nodeRoot.pos(Laya.stage.width / 2, Laya.stage.height / 2);
                            }
                        });
                    }
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("  nodeRoot", nodeRoot);
                }
            }
            _touchHandler_start(e) {
                e.preventSwallow = true;
                this.addCocosEvent(e);
            }
            _touchHandler_other(e) {
                e.preventSwallow = true;
            }
            refreshDebugInfo() {
                let length = ULTools.getObjSize(this.debugInfos);
                if (length <= 0) {
                    this.panel && this.panel.refreshDebugInfo(null);
                    return;
                }
                let arr = [];
                ULTools.forEachMap(this.debugInfos, (k, v) => {
                    arr.push(v);
                });
                let text = arr.join("\n");
                this.getOrCreatePanel();
                this.panel && this.panel.refreshDebugInfo(text);
            }
            onTouchSpecialArea(id) {
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager.onTouchSpecialArea", id);
                let touchGap = ULTools.time() - this.lastInputTime;
                if (touchGap >= TOUCH_GAP) {
                    if (this.inputCode) {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("ULModuleCheckerManager inputCode: touch gap is too long time, cancel.");
                        this.inputCode = "";
                    }
                }
                if (!id) {
                    if (this.inputCode) {
                        if (ULConst.B_INNER_DEBUG)
                            ULLog.console.log("ULModuleCheckerManager inputCode: touch invalid area, cancel.");
                        this.inputCode = "";
                    }
                    return;
                }
                this.inputCode += id;
                this.lastInputTime = ULTools.time();
                if (ULConst.B_INNER_DEBUG)
                    ULLog.console.log("ULModuleCheckerManager inputCode:", this.inputCode);
                if (this.inputCode == RIGHT_CODE) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("RIGHT_CODE  right!");
                    this.inputCode = "";
                    let config = this.moreGameAbTestConfig() || [];
                    config = config.concat(this.collectionConfig());
                    this.showPanel(config);
                }
                else if (this.inputCode == TAG_CODE) {
                    if (ULConst.B_INNER_DEBUG)
                        ULLog.console.log("TAG_CODE  right!");
                    this.inputCode = "";
                    let config = ULConfig.getConfig();
                    this.showCompanyMark(ULBase64.decode(config.s_sdk_common_copyright_str || ""));
                }
            }
            collectionConfig() {
                let config = ULEventDispatcher.getInstance().dispatchWithReturn(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_CONFIG, {});
                return config;
            }
            moreGameAbTestConfig() {
                let config = ULEventDispatcher.getInstance().dispatchWithReturn(ULConst.CMD_SDK_COLLECTION_MODULE_CHECKER_MORE_GAME_AB_TEST_CONFIG, {});
                return config;
            }
        }

        const headImgExt = ".head";
        let _cc$2 = window["cc"];
        class ULAdapteCreator2x {
            registerHeadImgLoader() {
                let func = _cc$2.loader.load.bind(_cc$2.loader);
                _cc$2.loader.load = (resources, progressCallback, completeCallback) => {
                    if (typeof resources === 'object') {
                        var object = resources;
                        if (object.type && object.type == headImgExt && object.url && object.url.length > 0) {
                            let img = this.downloadDomImage(object.url, null, (err, img) => {
                                if (err) {
                                    completeCallback && completeCallback(err, null);
                                    return;
                                }
                                let out = new _cc$2.Texture2D();
                                out.initWithElement(img);
                                out.handleLoadedTexture();
                                completeCallback && completeCallback(null, out);
                            });
                            return;
                        }
                    }
                    func(resources, progressCallback, completeCallback);
                };
            }
            downloadDomImage(url, options, onComplete) {
                const img = new Image();
                if (window.location.protocol !== 'file:') {
                    img.crossOrigin = 'anonymous';
                }
                function loadCallback() {
                    img.removeEventListener('load', loadCallback);
                    img.removeEventListener('error', errorCallback);
                    if (onComplete) {
                        onComplete(null, img);
                    }
                }
                function errorCallback(e) {
                    img.removeEventListener('load', loadCallback);
                    img.removeEventListener('error', errorCallback);
                    if (onComplete) {
                        console.log(e);
                        onComplete(new Error(url));
                    }
                }
                img.addEventListener('load', loadCallback);
                img.addEventListener('error', errorCallback);
                img.src = url;
                return img;
            }
            startAdapter() {
            }
        }

        const headImgExt$1 = ".head";
        let _cc$3 = window["cc"];
        class MCPanelCreator3x$1 {
            registerHeadImgLoader() {
                _cc$3.assetManager.downloader.register(headImgExt$1, (content, options, onComplete) => {
                    onComplete(null, content);
                });
                _cc$3.assetManager.parser.register(headImgExt$1, this.downloadDomImage);
                function createTexture(id, data, options, onComplete) {
                    let out = null, err = null;
                    try {
                        out = new _cc$3.Texture2D();
                        let imageAsset = new _cc$3.ImageAsset();
                        imageAsset.reset(data);
                        out.image = imageAsset;
                        console.log("ULAdapteCreator3x.createTexture id:", id);
                        console.log("ULAdapteCreator3x.createTexture data:", data);
                        console.log("ULAdapteCreator3x.createTexture out:", out);
                    }
                    catch (e) {
                        err = e;
                    }
                    onComplete && onComplete(err, out);
                }
                _cc$3.assetManager.factory.register(headImgExt$1, createTexture);
            }
            downloadDomImage(url, options, onComplete) {
                console.log("ULAdapteCreator3x.downloadDomImage url:", url);
                const img = new Image();
                if (window.location.protocol !== 'file:') {
                    img.crossOrigin = 'anonymous';
                }
                function loadCallback() {
                    console.log("ULAdapteCreator3x.loadCallback");
                    img.removeEventListener('load', loadCallback);
                    img.removeEventListener('error', errorCallback);
                    if (onComplete) {
                        onComplete(null, img);
                    }
                }
                function errorCallback() {
                    console.log("ULAdapteCreator3x.errorCallback");
                    img.removeEventListener('load', loadCallback);
                    img.removeEventListener('error', errorCallback);
                    if (onComplete) {
                        onComplete(new Error(url));
                    }
                }
                img.addEventListener('load', loadCallback);
                img.addEventListener('error', errorCallback);
                img.src = url;
                return img;
            }
            startAdapter() {
                this.registerHeadImgLoader();
            }
        }

        class ULAdapteLaya {
            startAdapter() {
            }
        }

        class ULModuleAdapter {
            constructor() {
                this._panel = null;
            }
            get panel() {
                if (!this._panel) {
                    if (window["cc"] && window["cc"].Node) {
                        if (ULTools.isCreator3xEngine()) {
                            this._panel = new MCPanelCreator3x$1();
                        }
                        else {
                            this._panel = new ULAdapteCreator2x();
                        }
                    }
                    else if (window["Laya"]) {
                        this._panel = new ULAdapteLaya();
                    }
                    else {
                        ULLog.console.warn("ULModuleAdapter.getPanel unknown platform!");
                    }
                }
                return this._panel;
            }
            init() {
                ULLog.console.log("ULModuleAdapter.init");
                this.panel && this.panel.startAdapter();
            }
        }

        class ULSdkManager {
            constructor() {
                this.responseCallback = null;
                this.bChannelInfoResultResponsed = false;
                this.bAllowStartGame = false;
                this.waits = null;
                this.version = "0.1";
                this.modules = [];
                this.waits = new ULWaitTool();
                this.channelInfo = new ULChannelInfo();
                this.copManager = new ULCopManager();
                this.advManager = new ULAdvManager();
                this.statisManager = new ULStatisManager();
                this.moduleAdapter = new ULModuleAdapter();
                this.moduleCheckerManager = new ULModuleCheckerManager();
                this.bChannelInfoResultResponsed = false;
                this.responsePending = [];
                this.sdkCommunicationLog = [];
                ULTools._hack_console_print_method();
                ULTools._start_console_print_LAN();
            }
            static getInstance() {
                if (!this._instance) {
                    this._instance = new ULSdkManager();
                }
                return this._instance;
            }
            initUlsdk(respone) {
                ULLog.console.log("ULSdkManger.init");
                this.responseCallback = respone;
                this.modules = ULSdkModuleLoader.initAllModules();
                ULTools._start_console_print_LAN();
                this.monitorAllowStartGame();
                this.advManager.init();
                this.statisManager.init();
                this.moduleAdapter.init();
                this.copManager.init();
                this.moduleCheckerManager.init();
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_GET_BASE_CHANNEL_INFO, ULConst.PRIORITY_NONE, this.onCmdGetBaseChannelInfo.bind(this));
                ULEventDispatcher.getInstance().addListener(ULConst.CMD_SET_VERSION, ULConst.PRIORITY_NONE, this.onCmdSetVersion.bind(this));
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_INIT_USER_LOGIN, {});
                ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_GAME_START, {});
                if (window["cc"] && window["cc"]["game"] && window["cc"]["game"]["on"] instanceof Function) {
                    ULLog.console.log("register cocos EVENT_SHOW & EVENT_HIDE");
                    if (ULTools.isCreator3xEngine()) {
                        window["cc"]["game"]["on"](window["cc"]["Game"]["EVENT_SHOW"], () => {
                            ULLog.console.log("ULSdkManager on EVENT_SHOW");
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_GAME_RESUME, {});
                        });
                        window["cc"]["game"]["on"](window["cc"]["Game"]["EVENT_HIDE"], () => {
                            ULLog.console.log("ULSdkManager on CC_EVENT_HIDE");
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_GAME_PAUSE, {});
                        });
                    }
                    else {
                        window["cc"]["game"]["on"](window["cc"]["game"]["EVENT_SHOW"], () => {
                            ULLog.console.log("ULSdkManager on EVENT_SHOW");
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_GAME_RESUME, {});
                        });
                        window["cc"]["game"]["on"](window["cc"]["game"]["EVENT_HIDE"], () => {
                            ULLog.console.log("ULSdkManager on CC_EVENT_HIDE");
                            ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_GAME_PAUSE, {});
                        });
                    }
                }
                else if (window["Laya"]) {
                    this._register_laya_life_cycle_listener();
                }
            }
            _register_laya_life_cycle_listener() {
                var win = window, hiddenPropName;
                if (typeof document.hidden !== 'undefined') {
                    hiddenPropName = "hidden";
                }
                else if (typeof document["mozHidden"] !== 'undefined') {
                    hiddenPropName = "mozHidden";
                }
                else if (typeof document["msHidden"] !== 'undefined') {
                    hiddenPropName = "msHidden";
                }
                else if (typeof document["webkitHidden"] !== 'undefined') {
                    hiddenPropName = "webkitHidden";
                }
                var hidden = false;
                function onHidden() {
                    ULLog.console.log("Laya.onHidden");
                    if (!hidden) {
                        hidden = true;
                        ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_GAME_PAUSE, {});
                    }
                }
                function onShown() {
                    ULLog.console.log("Laya.onShown");
                    if (hidden) {
                        hidden = false;
                        ULEventDispatcher.getInstance().dispatch(ULConst.CMD_SDK_ON_GAME_RESUME, {});
                    }
                }
                if (hiddenPropName) {
                    var changeList = [
                        "visibilitychange",
                        "mozvisibilitychange",
                        "msvisibilitychange",
                        "webkitvisibilitychange",
                        "qbrowserVisibilityChange"
                    ];
                    for (var i = 0; i < changeList.length; i++) {
                        document.addEventListener(changeList[i], function (event) {
                            var visible = document[hiddenPropName];
                            visible = visible || event["hidden"];
                            if (visible)
                                onHidden();
                            else
                                onShown();
                        });
                    }
                }
                else {
                    win.addEventListener("blur", onHidden);
                    win.addEventListener("focus", onShown);
                }
                if (navigator && navigator.userAgent && navigator.userAgent.indexOf("MicroMessenger") > -1) {
                    win.onfocus = onShown;
                }
                if (window["wx"]) {
                    window["wx"].onShow && window["wx"].onShow(onShown);
                    window["wx"].onHide && window["wx"].onHide(onHidden);
                }
                if (window["qg"]) {
                    window["qg"].onShow && window["qg"].onShow(onShown);
                    window["qg"].onHide && window["qg"].onHide(onHidden);
                }
                let huaweType = "hbs";
                if (window[huaweType]) {
                    window[huaweType].onShow && window[huaweType].onShow(onShown);
                    window[huaweType].onHide && window[huaweType].onHide(onHidden);
                }
                if (window["ks"]) {
                    window["ks"].onShow && window["ks"].onShow(onShown);
                    window["ks"].onHide && window["ks"].onHide(onHidden);
                }
                if ("onpageshow" in window && "onpagehide" in window) {
                    win.addEventListener("pagehide", onHidden);
                    win.addEventListener("pageshow", onShown);
                    document.addEventListener("pagehide", onHidden);
                    document.addEventListener("pageshow", onShown);
                }
            }
            onRequest(jsonStr) {
                let requestData = null;
                this.recordSdkCommunicationLog(jsonStr);
                try {
                    requestData = JSON.parse(jsonStr);
                }
                catch (error) {
                    ULLog.console.error(error);
                }
                if (!requestData) {
                    ULLog.console.error("请仔细阅读文档,消息必须为json字符串类型");
                    return;
                }
                let cmd = requestData.cmd;
                let data = requestData.data || {};
                if (!cmd) {
                    ULLog.console.error("cmd为空,请检查是否按照文档规范配置消息");
                    return;
                }
                ULLog.console.log("ULSdkManager.onRequest", cmd, data);
                switch (cmd) {
                    default: {
                        let bCalled = ULEventDispatcher.getInstance().dispatch(cmd, data);
                        if (!bCalled) {
                            ULLog.console.warn(ULTools.format("未检测到[%s]监听器", cmd));
                        }
                        break;
                    }
                }
            }
            response(cmd, data, bIgnorePending) {
                ULLog.console.log("ULSdkManager.response", cmd, data);
                if (!this.bChannelInfoResultResponsed && !bIgnorePending) {
                    ULLog.console.log("  尚未发送/c/channelInfoResult，暂存消息");
                    this.responsePending.push({ cmd: cmd, data: data });
                    return;
                }
                let jsonStr = JSON.stringify({
                    cmd: cmd,
                    data: data,
                });
                if (this.responseCallback) {
                    this.responseCallback(jsonStr);
                }
                this.recordSdkCommunicationLog(jsonStr);
            }
            uploadMegadata(data) {
                let singleField = data.join("_");
                this.statisManager.reportUserEvent(["commonEvent", singleField]);
            }
            isAllowStartGame() {
                ULLog.console.log("ULSdkManager.isAllowStartGame", this.bAllowStartGame);
                return this.bAllowStartGame;
            }
            getModuleByName(name) {
                for (let i = 0; i < this.modules.length; i++) {
                    const module = this.modules[i];
                    if (module["name"] == name) {
                        return module;
                    }
                }
                return null;
            }
            getSdkCommunicationLog() {
                return this.sdkCommunicationLog;
            }
            recordSdkCommunicationLog(log) {
                if (!this.sdkCommunicationLog)
                    return;
                if (this.sdkCommunicationLog.length >= 100) {
                    this.sdkCommunicationLog.splice(0, 1);
                }
                this.sdkCommunicationLog.push(log);
            }
            _doResponseChannelInfoResult() {
                this.bChannelInfoResultResponsed = true;
                this.response(ULConst.CMD_CHANNEL_INFO_RESULT, this.channelInfo.toResponseData());
                for (let i = 0; i < this.responsePending.length; i++) {
                    const v = this.responsePending[i];
                    this.response(v.cmd, v.data);
                }
                this.responsePending = [];
                if (this.channelInfo.isSupportLaunchReward) {
                    ULEventDispatcher.getInstance().dispatch(ULConst.CMD_CHECK_LAUNCH_REWARD, {});
                }
            }
            onCmdGetBaseChannelInfo(e) {
                this.response(ULConst.CMD_GET_BASE_CHANNEL_INFO_RESULT, this.channelInfo.toBaseChannelInfoData(), true);
            }
            onCmdSetVersion(e) {
                let data = e.data;
                e.stopImmediatePropagation();
                if (this.channelInfo.isReady()) {
                    this._doResponseChannelInfoResult();
                    return;
                }
                ULLog.console.log("ULSdkManager.onEventSetVersion channelInfo准备中，开启timer进行监听");
                let timeout = ULConfig.getConfig().i_channel_info_timeout / 1000;
                ULTimer.callLoop(1 / 60, (timer) => {
                    if (timer.usedTime >= timeout) {
                        timer.stop();
                        let flags = this.channelInfo.getPreparationFlags();
                        ULLog.console.log("等待channelInfo超时！直接触发channelInfoResult。flags:", flags.join(","));
                        this._doResponseChannelInfoResult();
                        return;
                    }
                    if (this.channelInfo.isReady()) {
                        timer.stop();
                        ULLog.console.log("channelInfo准备完毕！触发channelInfoResult");
                        this._doResponseChannelInfoResult();
                        return;
                    }
                });
            }
            monitorAllowStartGame() {
                ULLog.console.log("ULSdkManager.monitorAllowStartGame isAllowStartGame准备中，开启timer进行监听");
                ULTimer.callLoop(1, (timer) => {
                    if (this.waits.ok()) {
                        timer.stop();
                        this.bAllowStartGame = true;
                        return;
                    }
                });
            }
        }
        ULSdkManager._instance = null;

        class ULSdkMiddleware {
            static initUlsdk() {
                if (ULSdkManager) {
                    try {
                        ULSdkManager.getInstance().initUlsdk(this.onResponse);
                        return true;
                    }
                    catch (error) {
                        ULLog.console.error("ULSdkManager.initUlsdk err");
                        ULLog.console.error(error.stack);
                        return false;
                    }
                }
                else {
                    ULLog.console.log("ULSdkMiddleware.initUlsdk ULSdkManager not found!");
                    return;
                }
            }
            static request(jsonStr) {
                if (ULSdkManager) {
                    try {
                        ULSdkManager.getInstance().onRequest(jsonStr);
                        return true;
                    }
                    catch (error) {
                        ULLog.console.error("ULSdkManager.initUlsdk request");
                        ULLog.console.error(error.stack);
                        return false;
                    }
                }
                else {
                    ULLog.console.log("ULSdkMiddleware.request ULSdkManager not found!");
                    return false;
                }
            }
            static isAllowStartGame() {
                if (ULSdkManager) {
                    return ULSdkManager.getInstance().isAllowStartGame();
                }
                else {
                    ULLog.console.log("ULSdkMiddleware.isAllowStartGame ULSdkManager not found!");
                    return true;
                }
            }
            static registerOnResponseCallback(callback) {
                this.fOnResponseCallback = callback;
            }
            static onResponse(jsonStr) {
                if (ULSdkMiddleware.fOnResponseCallback instanceof Function ||
                    typeof ULSdkMiddleware.fOnResponseCallback == 'function') {
                    ULSdkMiddleware.fOnResponseCallback(jsonStr);
                }
            }
        }
        ULSdkMiddleware.fOnResponseCallback = null;
        window["ULSdkMiddleware"] = ULSdkMiddleware;

        class ULNativeControllerHtml5 {
            static init(fOnGameCallback) {
                if (!this.isEnabled(true)) {
                    console.warn("ULNativeControllerHtml5.init !isEnabled()");
                    return;
                }
                this.fOnGameCallback = fOnGameCallback;
                ULSdkMiddleware.registerOnResponseCallback((jsonStr) => {
                    this.sendMsgToGame(jsonStr);
                });
            }
            static isEnabled(bLog) {
                if (bLog) {
                    try {
                        console.log("ULNativeControllerHtml5.isEnabled");
                        console.log("  wx", window["wx"]);
                        console.log("  qq", window["qq"]);
                        console.log("  tt", window["tt"]);
                        console.log("  swan", window["swan"]);
                        console.log("  hbs", window["hbs"]);
                        console.log("  qg", window["qg"]);
                        console.log("  my", window["my"]);
                        console.log("  document", document);
                        console.log("  weibo", window["loadRuntime"]);
                        console.log("  cc.sys.isBrowser", window["cc"] && window["cc"].sys && window["cc"].sys.isBrowser);
                        console.log("  laya conch", window["Laya"] && window["conch"]);
                    }
                    catch (error) {
                        console.log(error);
                    }
                }
                if (window && window["Laya"] && !window["conch"])
                    return true;
                if (window && window["wx"])
                    return true;
                if (window && window["qq"])
                    return true;
                if (window && window["tt"])
                    return true;
                if (window && window["swan"])
                    return true;
                if (window && window["hbs"])
                    return true;
                if (window && window["qg"])
                    return true;
                if (window && window["my"])
                    return true;
                if (window && window["loadRuntime"])
                    return true;
                if (window["cc"] && window["cc"].sys && window["cc"].sys.isBrowser)
                    return true;
                return false;
            }
            static initUlsdk() {
                let bSuccess = ULSdkMiddleware.initUlsdk();
                return JSON.stringify({ ret: bSuccess });
            }
            static sendMsgToSdk(jsonStr) {
                let bSuccess = ULSdkMiddleware.request(jsonStr);
                return JSON.stringify({ ret: bSuccess });
            }
            static sendMsgToGame(jsonStr) {
                if (this.fOnGameCallback instanceof Function) {
                    this.fOnGameCallback(jsonStr);
                }
                if (this.mCallback) {
                    this.mCallback(jsonStr);
                }
            }
            static isAllowStartGame() {
                return ULSdkMiddleware.isAllowStartGame();
            }
            static initSdk(callback) {
                if (!callback || !(callback instanceof Function)) {
                    console.error("initSdk error: callback must be a Function");
                    return;
                }
                this.mCallback = callback;
                ULSdkMiddleware.registerOnResponseCallback((jsonStr) => {
                    this.sendMsgToGame(jsonStr);
                });
                ULSdkMiddleware.initUlsdk();
            }
            static InitSdk(id) {
                console.log("ulsdk-InitSdk:" + id);
                ULSdkMiddleware.registerOnResponseCallback((jsonStr) => {
                    let requestResult = {
                        callbackId: id,
                        type: "response",
                        res: JSON.stringify({
                            response: jsonStr
                        })
                    };
                    this.SendMsgToGame(JSON.stringify(requestResult), "InitCallback");
                });
                ULSdkMiddleware.initUlsdk();
                let timer = setInterval(() => {
                    if (ULSdkMiddleware.isAllowStartGame()) {
                        let initResult = {
                            callbackId: id,
                            type: "init",
                            res: JSON.stringify({
                                bSuccess: true
                            })
                        };
                        this.SendMsgToGame(JSON.stringify(initResult), "InitCallback");
                        clearInterval(timer);
                    }
                }, 100);
            }
            static SendMsgToSdk(jsonStr) {
                console.log("ulsdk-sendMsgToSdk:" + jsonStr);
                ULSdkMiddleware.request(jsonStr);
            }
            static SendMsgToGame(msg, method, className = "ULSdkHandler") {
                console.log("ulsdk-sendMsgToGame:" + msg);
                if (window['unityInstance']) {
                    window['unityInstance'].SendMessage(className, method, msg);
                }
                else {
                    if (window['wx']) {
                        window['GameGlobal'].manager.gameInstance.Module.SendMessage(className, method, msg);
                    }
                    else {
                        console.error("Js SendMessage To C# failed!");
                    }
                }
            }
            static ReadFile(param, id) {
            }
            static WriteFile(file, data) {
            }
            static DeleteFile(file) {
            }
        }
        ULNativeControllerHtml5.fOnGameCallback = null;
        window['ULSDK'] = ULNativeControllerHtml5;

        const JAVA_FILE_PATH = "demo/ULNativeController";
        const JAVA_PARAMS_RETURN = "(Ljava/lang/String;)Ljava/lang/String;";
        const JAVA_CALLBACK_NAME = "JAVACALLBACK";
        const OC_FILE_NAME = "ULNativeController";
        const OC_CALLBACK_NAME = "OCCALLBACK";
        function JAVACALLBACK(base64JsonStr) {
            try {
                let jsonStr = Base64.decode(base64JsonStr);
                mgrNative._onNativeCallbackJava(jsonStr);
            }
            catch (error) {
                console.warn("JAVACALLBACK decode base64 faild! direct use base64JsonStr");
                mgrNative._onNativeCallbackJava(base64JsonStr);
            }
        }
        function OCCALLBACK(base64JsonStr) {
            try {
                let jsonStr = Base64.decode(base64JsonStr);
                mgrNative._onNativeCallbackObjc(jsonStr);
            }
            catch (error) {
                console.warn("OCCALLBACK decode base64 faild! direct use base64JsonStr");
                mgrNative._onNativeCallbackObjc(base64JsonStr);
            }
        }
        function ONHTML5CALLBACK(jsonStr) {
            mgrNative._onNativeCallbackHtml5(jsonStr);
        }
        class mgrNative extends Manager {
            static onLoad() {
                super.onLoad();
                Timer.callLoop(1 / 60, this.onTimer.bind(this), true);
            }
            static init() {
                this.bInit = true;
                window[JAVA_CALLBACK_NAME] = JAVACALLBACK;
                window[OC_CALLBACK_NAME] = OCCALLBACK;
                if (window[`conch`]) {
                    this._js2JavaBridge = window[`PlatformClass`].createClass(JAVA_FILE_PATH);
                    this._js2OCBridge = window[`PlatformClass`].createClass(OC_FILE_NAME);
                }
                this.nativeCallbackPending = [];
                if (!this.bRegisterNativeCallback) {
                    this.bRegisterNativeCallback = true;
                    this.registerNativeCallback();
                }
            }
            static onTimer() {
                if (!this.bInit)
                    return;
                let pending = this.nativeCallbackPending;
                while (pending.length > 0) {
                    let responseData = pending.shift();
                    this.sendMsg("MSG_NATIVE_CALLBACK", { responseData: responseData });
                }
            }
            static registerNativeCallback() {
                if (ULNativeControllerHtml5.isEnabled()) {
                    this._registernativeCallbackHtml5();
                }
                else if (Laya.Browser.onAndroid) {
                    this._registerNativeCallbackJava();
                }
                else if (Laya.Browser.onIOS) {
                    this._registerNativeCallbackObjc();
                }
                else {
                    console.warn(ul.format("[warn] mgrNative.registerNativeCallback, platform = %s, don't have native controller", Laya.Browser.name));
                }
            }
            static isHtml5Platform() {
                return ULNativeControllerHtml5.isEnabled();
            }
            static onNativeCallback(data) {
                if (data) {
                    this.nativeCallbackPending.push(data);
                }
            }
            static _registerNativeCallbackJava() {
                this._js2JavaBridge.call("setCallFuncName", JAVA_CALLBACK_NAME);
            }
            static _registerNativeCallbackObjc() {
                this._callNativeObjc("setCallbackName", { callbackName: OC_CALLBACK_NAME });
            }
            static _registernativeCallbackHtml5() {
                ULNativeControllerHtml5.init(ONHTML5CALLBACK);
                this._callNativeHtml5("initUlsdk", null);
            }
            static _onNativeCallbackJava(jsonStr) {
                let data = {};
                try {
                    data = JSON.parse(jsonStr || "");
                }
                catch (error) {
                    console.warn("mgrNative._onNativeCallbackJava jsonStr error!");
                    data["text"] = jsonStr;
                }
                this.onNativeCallback(data);
            }
            static _onNativeCallbackObjc(jsonStr) {
                let data = {};
                try {
                    data = JSON.parse(jsonStr || "");
                }
                catch (error) {
                    console.warn("mgrNative._onNativeCallbackObjc jsonStr error!");
                    data["text"] = jsonStr;
                }
                this.onNativeCallback(data);
            }
            static _onNativeCallbackHtml5(jsonStr) {
                let data = {};
                try {
                    data = JSON.parse(jsonStr || "");
                }
                catch (error) {
                    console.warn("mgrNative._onNativeCallbackJs jsonStr error!");
                    data["text"] = jsonStr;
                }
                this.onNativeCallback(data);
            }
            static isAllowStartGame() {
                if (ULNativeControllerHtml5.isEnabled()) {
                    return ULNativeControllerHtml5.isAllowStartGame();
                }
                else {
                    return true;
                }
            }
            static callNative(cmd, dataTable) {
                dataTable = dataTable || {};
                if (ULNativeControllerHtml5.isEnabled()) {
                    return this._callNativeHtml5(cmd, dataTable);
                }
                else if (Laya.Browser.onAndroid) {
                    return this._callNativeJava(cmd, dataTable);
                }
                else if (Laya.Browser.onIOS) {
                    return this._callNativeObjc(cmd, dataTable);
                }
                else {
                    console.warn(ul.format("[warn] mgrNative.callNative, platform = %s, don't have native controller", Laya.Browser.name));
                    return null;
                }
            }
            static _callNativeJava(cmd, dataTable) {
                console.log(`-->: js: 调用本地${cmd}: ${JSON.stringify(dataTable)}`);
                try {
                    let jsonStr = JSON.stringify(dataTable);
                    let retJson = this._js2JavaBridge.call(cmd, jsonStr);
                    let retData = JSON.parse(retJson);
                    return retData;
                }
                catch (error) {
                    console.warn("mgrNative._onNativeCallbackJava jsonStr error!");
                    return { error: error };
                }
            }
            static _callNativeObjc(cmd, dataTable) {
                try {
                    let jsonStr = JSON.stringify(dataTable);
                    let retJson = this._js2OCBridge.call(cmd + ":", jsonStr);
                    let retData = JSON.parse(retJson);
                    return retData;
                }
                catch (error) {
                    console.warn("mgrNative._callNativeObjc jsonStr error!");
                    console.log(error);
                    return { error: error };
                }
            }
            static _callNativeHtml5(cmd, dataTable) {
                try {
                    let jsonStr = JSON.stringify(dataTable);
                    let retJson = ULNativeControllerHtml5[cmd](jsonStr);
                    let retData = JSON.parse(retJson);
                    return retData;
                }
                catch (error) {
                    console.warn("mgrNative._callNativeHtml5 jsonStr error!");
                    return { error: error };
                }
            }
        }
        mgrNative.nativeCallbackPending = null;
        mgrNative.bRegisterNativeCallback = false;
        mgrNative.bInit = false;

        class Action {
            constructor() {
                this.originalTarget = null;
                this.target = null;
                this.tag = Action.TAG_INVALID;
            }
            clone() {
                var action = new Action();
                action.originalTarget = null;
                action.target = null;
                action.tag = this.tag;
                return action;
            }
            isDone() {
                return true;
            }
            startWithTarget(target) {
                this.originalTarget = target;
                this.target = target;
            }
            stop() {
                this.target = null;
            }
            step(dt) {
                logID(1006);
            }
            update(dt) {
                logID(1007);
            }
            getTarget() {
                return this.target;
            }
            setTarget(target) {
                this.target = target;
            }
            getOriginalTarget() {
                return this.originalTarget;
            }
            setOriginalTarget(originalTarget) {
                this.originalTarget = originalTarget;
            }
            getTag() {
                return this.tag;
            }
            setTag(tag) {
                this.tag = tag;
            }
            reverse() {
                logID(1008);
                return null;
            }
            retain() { }
            release() { }
        }
        Action.TAG_INVALID = -1;
        class FiniteTimeAction extends Action {
            constructor() {
                super(...arguments);
                this._duration = 0;
                this._timesForRepeat = 1;
            }
            getDuration() {
                return this._duration * (this._timesForRepeat || 1);
            }
            setDuration(duration) {
                this._duration = duration;
            }
            clone() {
                return new FiniteTimeAction();
            }
        }
        class Speed extends Action {
            constructor(action, speed = 1) {
                super();
                this._speed = 0;
                this._innerAction = null;
                action && this.initWithAction(action, speed);
            }
            getSpeed() {
                return this._speed;
            }
            setSpeed(speed) {
                this._speed = speed;
            }
            initWithAction(action, speed) {
                if (!action) {
                    errorID(1021);
                    return false;
                }
                this._innerAction = action;
                this._speed = speed;
                return true;
            }
            clone() {
                var action = new Speed();
                action.initWithAction(this._innerAction.clone(), this._speed);
                return action;
            }
            startWithTarget(target) {
                Action.prototype.startWithTarget.call(this, target);
                this._innerAction.startWithTarget(target);
            }
            stop() {
                this._innerAction.stop();
                Action.prototype.stop.call(this);
            }
            step(dt) {
                this._innerAction.step(dt * this._speed);
            }
            isDone() {
                return this._innerAction.isDone();
            }
            reverse() {
                return new Speed(this._innerAction.reverse(), this._speed);
            }
            setInnerAction(action) {
                if (this._innerAction !== action) {
                    this._innerAction = action;
                }
            }
            getInnerAction() {
                return this._innerAction;
            }
        }

        class ActionInstant extends FiniteTimeAction {
            isDone() {
                return true;
            }
            step(dt) {
                this.update(1);
            }
            update(dt) {
            }
            reverse() {
                return this.clone();
            }
            clone() {
                return new ActionInstant();
            }
        }
        class Show extends ActionInstant {
            update(dt) {
                if (this.target && !this.target.destroyed) {
                    this.target["visible"] = true;
                }
            }
            reverse() {
                return new Hide();
            }
            clone() {
                return new Show();
            }
        }
        function show() {
            return new Show();
        }
        ;
        class Hide extends ActionInstant {
            update(dt) {
                if (this.target && !this.target.destroyed) {
                    this.target["visible"] = false;
                }
            }
            reverse() {
                return new Show();
            }
            clone() {
                return new Hide();
            }
        }
        function hide() {
            return new Hide();
        }
        ;
        class RemoveSelf extends ActionInstant {
            constructor(isNeedCleanUp) {
                super();
                this._isNeedCleanUp = true;
                isNeedCleanUp !== undefined && this.init(isNeedCleanUp);
            }
            update(dt) {
                this.target.removeSelf();
                if (this._isNeedCleanUp) {
                    this.target.destroy();
                }
            }
            init(isNeedCleanUp) {
                this._isNeedCleanUp = isNeedCleanUp;
                return true;
            }
            reverse() {
                return new RemoveSelf(this._isNeedCleanUp);
            }
            clone() {
                return new RemoveSelf(this._isNeedCleanUp);
            }
        }
        function removeSelf(isNeedCleanUp) {
            return new RemoveSelf(isNeedCleanUp);
        }
        ;
        class CallFunc extends ActionInstant {
            constructor(selector, selectorTarget, data) {
                super();
                this._selectorTarget = null;
                this._function = null;
                this._data = null;
                this.initWithFunction(selector, selectorTarget, data);
            }
            initWithFunction(selector, selectorTarget, data) {
                if (selector) {
                    this._function = selector;
                }
                if (selectorTarget) {
                    this._selectorTarget = selectorTarget;
                }
                if (data !== undefined) {
                    this._data = data;
                }
                return true;
            }
            execute() {
                if (this._function) {
                    this._function.call(this._selectorTarget, this.target, this._data);
                }
            }
            update(dt) {
                this.execute();
            }
            getTargetCallback() {
                return this._selectorTarget;
            }
            setTargetCallback(sel) {
                if (sel !== this._selectorTarget) {
                    if (this._selectorTarget)
                        this._selectorTarget = null;
                    this._selectorTarget = sel;
                }
            }
            clone() {
                var action = new CallFunc();
                action.initWithFunction(this._function, this._selectorTarget, this._data);
                return action;
            }
        }
        function callFunc(selector, selectorTarget, data) {
            return new CallFunc(selector, selectorTarget, data);
        }
        ;

        class ActionInterval extends FiniteTimeAction {
            constructor(d) {
                super();
                this.MAX_VALUE = 2;
                this._elapsed = 0;
                this._firstTick = false;
                this._easeList = [];
                this._speed = 1;
                this._repeatForever = false;
                this._repeatMethod = false;
                this._speedMethod = false;
                if (d !== undefined && !isNaN(d)) {
                    this.initWithDuration(d);
                }
            }
            getElapsed() {
                return this._elapsed;
            }
            initWithDuration(d) {
                this._duration = (d === 0) ? 0.0000001192092896 : d;
                this._elapsed = 0;
                this._firstTick = true;
                return true;
            }
            isDone() {
                return (this._elapsed >= this._duration);
            }
            _cloneDecoration(action) {
                action._repeatForever = this._repeatForever;
                action._speed = this._speed;
                action._timesForRepeat = this._timesForRepeat;
                action._easeList = this._easeList;
                action._speedMethod = this._speedMethod;
                action._repeatMethod = this._repeatMethod;
            }
            _reverseEaseList(action) {
                if (this._easeList) {
                    action._easeList = [];
                    for (var i = 0; i < this._easeList.length; i++) {
                        action._easeList.push(this._easeList[i]);
                    }
                }
            }
            clone() {
                var action = new ActionInterval(this._duration);
                this._cloneDecoration(action);
                return action;
            }
            easing(...easeObj) {
                if (this._easeList)
                    this._easeList.length = 0;
                else
                    this._easeList = [];
                for (var i = 0; i < easeObj.length; i++)
                    this._easeList.push(easeObj[i]);
                return this;
            }
            _computeEaseTime(dt) {
                var locList = this._easeList;
                if ((!locList) || (locList.length === 0))
                    return dt;
                for (var i = 0, n = locList.length; i < n; i++)
                    dt = locList[i](dt);
                return dt;
            }
            step(dt) {
                if (this._firstTick) {
                    this._firstTick = false;
                    this._elapsed = 0;
                }
                else
                    this._elapsed += dt;
                var t = this._elapsed / (this._duration > 0.0000001192092896 ? this._duration : 0.0000001192092896);
                t = (1 > t ? t : 1);
                this.update(t > 0 ? t : 0);
                if (this._repeatMethod && this._timesForRepeat > 1 && this.isDone()) {
                    if (!this._repeatForever) {
                        this._timesForRepeat--;
                    }
                    this.startWithTarget(this.target);
                    this.step(this._elapsed - this._duration);
                }
            }
            startWithTarget(target) {
                Action.prototype.startWithTarget.call(this, target);
                this._elapsed = 0;
                this._firstTick = true;
            }
            reverse() {
                logID(1010);
                return this;
            }
            setAmplitudeRate(amp) {
                logID(1011);
            }
            getAmplitudeRate() {
                logID(1012);
                return 0;
            }
            speed(speed) {
                if (speed <= 0) {
                    logID(1013);
                    return this;
                }
                this._speedMethod = true;
                this._speed *= speed;
                return this;
            }
            getSpeed() {
                return this._speed;
            }
            setSpeed(speed) {
                this._speed = speed;
                return this;
            }
            repeat(times) {
                times = Math.round(times);
                if (isNaN(times) || times < 1) {
                    logID(1014);
                    return this;
                }
                this._repeatMethod = true;
                this._timesForRepeat *= times;
                return this;
            }
            repeatForever() {
                this._repeatMethod = true;
                this._timesForRepeat = this.MAX_VALUE;
                this._repeatForever = true;
                return this;
            }
        }
        function actionInterval(d) {
            return new ActionInterval(d);
        }
        class Sequence extends ActionInterval {
            constructor(tempArray) {
                super();
                this._actions = [];
                this._split = 0;
                this._last = 0;
                this._reversed = false;
                var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
                if (paramArray.length === 1) {
                    errorID(1019);
                    return;
                }
                var last = paramArray.length - 1;
                if ((last >= 0) && (paramArray[last] == null))
                    logID(1015);
                if (last >= 0) {
                    var prev = paramArray[0], action1;
                    for (var i = 1; i < last; i++) {
                        if (paramArray[i]) {
                            action1 = prev;
                            prev = Sequence._actionOneTwo(action1, paramArray[i]);
                        }
                    }
                    this.initWithTwoActions(prev, paramArray[last]);
                }
            }
            initWithTwoActions(actionOne, actionTwo) {
                if (!actionOne || !actionTwo) {
                    errorID(1025);
                    return false;
                }
                var durationOne = actionOne._duration, durationTwo = actionTwo._duration;
                durationOne *= actionOne._repeatMethod ? actionOne._timesForRepeat : 1;
                durationTwo *= actionTwo._repeatMethod ? actionTwo._timesForRepeat : 1;
                var d = durationOne + durationTwo;
                this.initWithDuration(d);
                this._actions[0] = actionOne;
                this._actions[1] = actionTwo;
                return true;
            }
            clone() {
                var action = new Sequence();
                this._cloneDecoration(action);
                action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone());
                return action;
            }
            startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);
                this._split = this._actions[0]._duration / this._duration;
                this._split *= this._actions[0]._repeatMethod ? this._actions[0]._timesForRepeat : 1;
                this._last = -1;
            }
            stop() {
                if (this._last !== -1)
                    this._actions[this._last].stop();
                Action.prototype.stop.call(this);
            }
            update(dt) {
                let target = this.target;
                if (!target || target.destroyed || (target.owner && target.owner.destroyed)) {
                    this.stop();
                    return;
                }
                var new_t, found = 0;
                var locSplit = this._split;
                var locActions = this._actions;
                var locLast = this._last;
                var actionFound;
                dt = this._computeEaseTime(dt);
                if (dt < locSplit) {
                    new_t = (locSplit !== 0) ? dt / locSplit : 1;
                    if (found === 0 && locLast === 1 && this._reversed) {
                        locActions[1].update(0);
                        locActions[1].stop();
                    }
                }
                else {
                    found = 1;
                    new_t = (locSplit === 1) ? 1 : (dt - locSplit) / (1 - locSplit);
                    if (locLast === -1) {
                        locActions[0].startWithTarget(this.target);
                        locActions[0].update(1);
                        locActions[0].stop();
                    }
                    if (locLast === 0) {
                        locActions[0].update(1);
                        locActions[0].stop();
                    }
                }
                actionFound = locActions[found];
                if (locLast === found && actionFound.isDone())
                    return;
                if (locLast !== found)
                    actionFound.startWithTarget(this.target);
                new_t = new_t * actionFound._timesForRepeat;
                actionFound.update(new_t > 1 ? new_t % 1 : new_t);
                this._last = found;
            }
            reverse() {
                var action = Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse());
                this._cloneDecoration(action);
                this._reverseEaseList(action);
                action._reversed = true;
                return action;
            }
        }
        Sequence._actionOneTwo = function (actionOne, actionTwo) {
            var sequence = new Sequence();
            sequence.initWithTwoActions(actionOne, actionTwo);
            return sequence;
        };
        function sequence(tempArray) {
            var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
            if (paramArray.length === 1) {
                errorID(1019);
                return null;
            }
            var last = paramArray.length - 1;
            if ((last >= 0) && (paramArray[last] == null))
                logID(1015);
            var result = null;
            if (last >= 0) {
                result = paramArray[0];
                for (var i = 1; i <= last; i++) {
                    if (paramArray[i]) {
                        result = Sequence._actionOneTwo(result, paramArray[i]);
                    }
                }
            }
            return result;
        }
        ;
        class Repeat extends ActionInterval {
            constructor(action, times) {
                super();
                this._times = 0;
                this._total = 0;
                this._nextDt = 0;
                this._actionInstant = false;
                this._innerAction = null;
                times !== undefined && this.initWithAction(action, times);
            }
            initWithAction(action, times) {
                var duration = action._duration * times;
                if (this.initWithDuration(duration)) {
                    this._times = times;
                    this._innerAction = action;
                    if (action instanceof ActionInstant) {
                        this._actionInstant = true;
                        this._times -= 1;
                    }
                    this._total = 0;
                    return true;
                }
                return false;
            }
            clone() {
                var action = new Repeat();
                this._cloneDecoration(action);
                action.initWithAction(this._innerAction.clone(), this._times);
                return action;
            }
            startWithTarget(target) {
                this._total = 0;
                this._nextDt = this._innerAction._duration / this._duration;
                ActionInterval.prototype.startWithTarget.call(this, target);
                this._innerAction.startWithTarget(target);
            }
            stop() {
                this._innerAction.stop();
                Action.prototype.stop.call(this);
            }
            update(dt) {
                dt = this._computeEaseTime(dt);
                var locInnerAction = this._innerAction;
                var locDuration = this._duration;
                var locTimes = this._times;
                var locNextDt = this._nextDt;
                if (dt >= locNextDt) {
                    while (dt > locNextDt && this._total < locTimes) {
                        locInnerAction.update(1);
                        this._total++;
                        locInnerAction.stop();
                        locInnerAction.startWithTarget(this.target);
                        locNextDt += locInnerAction._duration / locDuration;
                        this._nextDt = locNextDt > 1 ? 1 : locNextDt;
                    }
                    if (dt >= 1.0 && this._total < locTimes) {
                        locInnerAction.update(1);
                        this._total++;
                    }
                    if (!this._actionInstant) {
                        if (this._total === locTimes) {
                            locInnerAction.stop();
                        }
                        else {
                            locInnerAction.update(dt - (locNextDt - locInnerAction._duration / locDuration));
                        }
                    }
                }
                else {
                    locInnerAction.update((dt * locTimes) % 1.0);
                }
            }
            isDone() {
                return this._total === this._times;
            }
            reverse() {
                var action = new Repeat(this._innerAction.reverse(), this._times);
                this._cloneDecoration(action);
                this._reverseEaseList(action);
                return action;
            }
            setInnerAction(action) {
                if (this._innerAction !== action) {
                    this._innerAction = action;
                }
            }
            getInnerAction() {
                return this._innerAction;
            }
        }
        function repeat(action, times) {
            return new Repeat(action, times);
        }
        class RepeatForever extends ActionInterval {
            constructor(action) {
                super();
                this._innerAction = null;
                action && this.initWithAction(action);
            }
            initWithAction(action) {
                if (!action) {
                    errorID(1026);
                    return false;
                }
                this._innerAction = action;
                return true;
            }
            clone() {
                var action = new RepeatForever();
                this._cloneDecoration(action);
                action.initWithAction(this._innerAction.clone());
                return action;
            }
            startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);
                this._innerAction.startWithTarget(target);
            }
            step(dt) {
                const target = this.target;
                if (!target || target.destroyed || (target.owner && target.owner.destroyed)) {
                    this.stop();
                    return;
                }
                var locInnerAction = this._innerAction;
                locInnerAction.step(dt);
                if (locInnerAction.isDone()) {
                    locInnerAction.startWithTarget(this.target);
                    locInnerAction.step(locInnerAction.getElapsed() - locInnerAction._duration);
                }
            }
            isDone() {
                return false;
            }
            reverse() {
                var action = new RepeatForever(this._innerAction.reverse());
                this._cloneDecoration(action);
                this._reverseEaseList(action);
                return action;
            }
            setInnerAction(action) {
                if (this._innerAction !== action) {
                    this._innerAction = action;
                }
            }
            getInnerAction() {
                return this._innerAction;
            }
        }
        function repeatForever(action) {
            return new RepeatForever(action);
        }
        class Spawn extends ActionInterval {
            constructor(tempArray) {
                super();
                this._one = null;
                this._two = null;
                var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
                if (paramArray.length === 1) {
                    errorID(1020);
                    return;
                }
                var last = paramArray.length - 1;
                if ((last >= 0) && (paramArray[last] == null))
                    logID(1015);
                if (last >= 0) {
                    var prev = paramArray[0], action1;
                    for (var i = 1; i < last; i++) {
                        if (paramArray[i]) {
                            action1 = prev;
                            prev = Spawn._actionOneTwo(action1, paramArray[i]);
                        }
                    }
                    this.initWithTwoActions(prev, paramArray[last]);
                }
            }
            initWithTwoActions(action1, action2) {
                if (!action1 || !action2) {
                    errorID(1027);
                    return false;
                }
                var ret = false;
                var d1 = action1._duration;
                var d2 = action2._duration;
                if (this.initWithDuration(Math.max(d1, d2))) {
                    this._one = action1;
                    this._two = action2;
                    if (d1 > d2) {
                        this._two = Sequence._actionOneTwo(action2, delayTime(d1 - d2));
                    }
                    else if (d1 < d2) {
                        this._one = Sequence._actionOneTwo(action1, delayTime(d2 - d1));
                    }
                    ret = true;
                }
                return ret;
            }
            clone() {
                var action = new Spawn();
                this._cloneDecoration(action);
                action.initWithTwoActions(this._one.clone(), this._two.clone());
                return action;
            }
            startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);
                this._one.startWithTarget(target);
                this._two.startWithTarget(target);
            }
            stop() {
                this._one.stop();
                this._two.stop();
                Action.prototype.stop.call(this);
            }
            update(dt) {
                dt = this._computeEaseTime(dt);
                if (this._one)
                    this._one.update(dt);
                if (this._two)
                    this._two.update(dt);
            }
            reverse() {
                var action = Spawn._actionOneTwo(this._one.reverse(), this._two.reverse());
                this._cloneDecoration(action);
                this._reverseEaseList(action);
                return action;
            }
        }
        Spawn._actionOneTwo = function (action1, action2) {
            var pSpawn = new Spawn();
            pSpawn.initWithTwoActions(action1, action2);
            return pSpawn;
        };
        function spawn(tempArray) {
            var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
            if (paramArray.length === 1) {
                errorID(1020);
                return null;
            }
            if ((paramArray.length > 0) && (paramArray[paramArray.length - 1] == null))
                logID(1015);
            var prev = paramArray[0];
            for (var i = 1; i < paramArray.length; i++) {
                if (paramArray[i] != null)
                    prev = Spawn._actionOneTwo(prev, paramArray[i]);
            }
            return prev;
        }
        class DelayTime extends ActionInterval {
            update(dt) { }
            reverse() {
                var action = new DelayTime(this._duration);
                this._cloneDecoration(action);
                this._reverseEaseList(action);
                return action;
            }
            clone() {
                var action = new DelayTime();
                this._cloneDecoration(action);
                action.initWithDuration(this._duration);
                return action;
            }
        }
        function delayTime(d) {
            return new DelayTime(d);
        }
        ;
        class ReverseTime extends ActionInterval {
            constructor(action) {
                super();
                this._other = null;
                action && this.initWithAction(action);
            }
            initWithAction(action) {
                if (!action) {
                    errorID(1028);
                    return false;
                }
                if (action === this._other) {
                    errorID(1029);
                    return false;
                }
                if (ActionInterval.prototype.initWithDuration.call(this, action._duration)) {
                    this._other = action;
                    return true;
                }
                return false;
            }
            clone() {
                var action = new ReverseTime();
                this._cloneDecoration(action);
                action.initWithAction(this._other.clone());
                return action;
            }
            startWithTarget(target) {
                ActionInterval.prototype.startWithTarget.call(this, target);
                this._other.startWithTarget(target);
            }
            update(dt) {
                dt = this._computeEaseTime(dt);
                if (this._other)
                    this._other.update(1 - dt);
            }
            reverse() {
                return this._other.clone();
            }
            stop() {
                this._other.stop();
                Action.prototype.stop.call(this);
            }
        }
        function reverseTime(action) {
            return new ReverseTime(action);
        }

        var Easing;
        (function (Easing) {
            function constant() {
                return 0;
            }
            Easing.constant = constant;
            function linear(k) {
                return k;
            }
            Easing.linear = linear;
            function quadIn(k) {
                return k * k;
            }
            Easing.quadIn = quadIn;
            function quadOut(k) {
                return k * (2 - k);
            }
            Easing.quadOut = quadOut;
            function quadInOut(k) {
                k *= 2;
                if (k < 1) {
                    return 0.5 * k * k;
                }
                return -0.5 * (--k * (k - 2) - 1);
            }
            Easing.quadInOut = quadInOut;
            function cubicIn(k) {
                return k * k * k;
            }
            Easing.cubicIn = cubicIn;
            function cubicOut(k) {
                return --k * k * k + 1;
            }
            Easing.cubicOut = cubicOut;
            function cubicInOut(k) {
                k *= 2;
                if (k < 1) {
                    return 0.5 * k * k * k;
                }
                return 0.5 * ((k -= 2) * k * k + 2);
            }
            Easing.cubicInOut = cubicInOut;
            function quartIn(k) {
                return k * k * k * k;
            }
            Easing.quartIn = quartIn;
            function quartOut(k) {
                return 1 - (--k * k * k * k);
            }
            Easing.quartOut = quartOut;
            function quartInOut(k) {
                k *= 2;
                if (k < 1) {
                    return 0.5 * k * k * k * k;
                }
                return -0.5 * ((k -= 2) * k * k * k - 2);
            }
            Easing.quartInOut = quartInOut;
            function quintIn(k) {
                return k * k * k * k * k;
            }
            Easing.quintIn = quintIn;
            function quintOut(k) {
                return --k * k * k * k * k + 1;
            }
            Easing.quintOut = quintOut;
            function quintInOut(k) {
                k *= 2;
                if (k < 1) {
                    return 0.5 * k * k * k * k * k;
                }
                return 0.5 * ((k -= 2) * k * k * k * k + 2);
            }
            Easing.quintInOut = quintInOut;
            function sineIn(k) {
                return 1 - Math.cos(k * Math.PI / 2);
            }
            Easing.sineIn = sineIn;
            function sineOut(k) {
                return Math.sin(k * Math.PI / 2);
            }
            Easing.sineOut = sineOut;
            function sineInOut(k) {
                return 0.5 * (1 - Math.cos(Math.PI * k));
            }
            Easing.sineInOut = sineInOut;
            function expoIn(k) {
                return k === 0 ? 0 : Math.pow(1024, k - 1);
            }
            Easing.expoIn = expoIn;
            function expoOut(k) {
                return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
            }
            Easing.expoOut = expoOut;
            function expoInOut(k) {
                if (k === 0) {
                    return 0;
                }
                if (k === 1) {
                    return 1;
                }
                k *= 2;
                if (k < 1) {
                    return 0.5 * Math.pow(1024, k - 1);
                }
                return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
            }
            Easing.expoInOut = expoInOut;
            function circIn(k) {
                return 1 - Math.sqrt(1 - k * k);
            }
            Easing.circIn = circIn;
            function circOut(k) {
                return Math.sqrt(1 - (--k * k));
            }
            Easing.circOut = circOut;
            function circInOut(k) {
                k *= 2;
                if (k < 1) {
                    return -0.5 * (Math.sqrt(1 - k * k) - 1);
                }
                return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
            }
            Easing.circInOut = circInOut;
            function elasticIn(k) {
                let s;
                let a = 0.1;
                const p = 0.4;
                if (k === 0) {
                    return 0;
                }
                if (k === 1) {
                    return 1;
                }
                if (!a || a < 1) {
                    a = 1;
                    s = p / 4;
                }
                else {
                    s = p * Math.asin(1 / a) / (2 * Math.PI);
                }
                return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
            }
            Easing.elasticIn = elasticIn;
            function elasticOut(k) {
                let s;
                let a = 0.1;
                const p = 0.4;
                if (k === 0) {
                    return 0;
                }
                if (k === 1) {
                    return 1;
                }
                if (!a || a < 1) {
                    a = 1;
                    s = p / 4;
                }
                else {
                    s = p * Math.asin(1 / a) / (2 * Math.PI);
                }
                return (a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
            }
            Easing.elasticOut = elasticOut;
            function elasticInOut(k) {
                let s;
                let a = 0.1;
                const p = 0.4;
                if (k === 0) {
                    return 0;
                }
                if (k === 1) {
                    return 1;
                }
                if (!a || a < 1) {
                    a = 1;
                    s = p / 4;
                }
                else {
                    s = p * Math.asin(1 / a) / (2 * Math.PI);
                }
                k *= 2;
                if (k < 1) {
                    return -0.5 *
                        (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
                }
                return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
            }
            Easing.elasticInOut = elasticInOut;
            function backIn(k) {
                const s = 1.70158;
                return k * k * ((s + 1) * k - s);
            }
            Easing.backIn = backIn;
            function backOut(k) {
                const s = 1.70158;
                return --k * k * ((s + 1) * k + s) + 1;
            }
            Easing.backOut = backOut;
            function backInOut(k) {
                const s = 1.70158 * 1.525;
                k *= 2;
                if (k < 1) {
                    return 0.5 * (k * k * ((s + 1) * k - s));
                }
                return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
            }
            Easing.backInOut = backInOut;
            function bounceIn(k) {
                return 1 - bounceOut(1 - k);
            }
            Easing.bounceIn = bounceIn;
            function bounceOut(k) {
                if (k < (1 / 2.75)) {
                    return 7.5625 * k * k;
                }
                else if (k < (2 / 2.75)) {
                    return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
                }
                else if (k < (2.5 / 2.75)) {
                    return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
                }
                else {
                    return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
                }
            }
            Easing.bounceOut = bounceOut;
            function bounceInOut(k) {
                if (k < 0.5) {
                    return bounceIn(k * 2) * 0.5;
                }
                return bounceOut(k * 2 - 1) * 0.5 + 0.5;
            }
            Easing.bounceInOut = bounceInOut;
            function smooth(k) {
                if (k <= 0) {
                    return 0;
                }
                if (k >= 1) {
                    return 1;
                }
                return k * k * (3 - 2 * k);
            }
            Easing.smooth = smooth;
            function fade(k) {
                if (k <= 0) {
                    return 0;
                }
                if (k >= 1) {
                    return 1;
                }
                return k * k * k * (k * (k * 6 - 15) + 10);
            }
            Easing.fade = fade;
            Easing.quadOutIn = _makeOutIn(quadIn, quadOut);
            Easing.cubicOutIn = _makeOutIn(cubicIn, cubicOut);
            Easing.quartOutIn = _makeOutIn(quartIn, quartOut);
            Easing.quintOutIn = _makeOutIn(quintIn, quintOut);
            Easing.sineOutIn = _makeOutIn(sineIn, sineOut);
            Easing.expoOutIn = _makeOutIn(expoIn, expoOut);
            Easing.circOutIn = _makeOutIn(circIn, circOut);
            Easing.elasticOutIn = _makeOutIn(elasticIn, elasticOut);
            Easing.backOutIn = _makeOutIn(backIn, backOut);
            Easing.bounceOutIn = _makeOutIn(bounceIn, bounceOut);
            function _makeOutIn(fnIn, fnOut) {
                return (k) => {
                    if (k < 0.5) {
                        return fnOut(k * 2) / 2;
                    }
                    return fnIn(2 * k - 1) / 2 + 0.5;
                };
            }
        })(Easing || (Easing = {}));

        function TweenEasinAdapter(easingName) {
            let initialChar = easingName.charAt(0);
            if (/[A-Z]/.test(initialChar)) {
                easingName = easingName.replace(initialChar, initialChar.toLowerCase());
                const arr = easingName.split('-');
                if (arr.length == 2) {
                    const str0 = arr[0];
                    if (str0 == 'linear') {
                        easingName = 'linear';
                    }
                    else {
                        const str1 = arr[1];
                        switch (str0) {
                            case 'quadratic':
                                easingName = 'quad' + str1;
                                break;
                            case 'quartic':
                                easingName = 'quart' + str1;
                                break;
                            case 'quintic':
                                easingName = 'quint' + str1;
                                break;
                            case 'sinusoidal':
                                easingName = 'sine' + str1;
                                break;
                            case 'exponential':
                                easingName = 'expo' + str1;
                                break;
                            case 'circular':
                                easingName = 'circ' + str1;
                                break;
                            default:
                                easingName = str0 + str1;
                                break;
                        }
                    }
                }
            }
            return easingName;
        }
        function TweenOptionChecker(opts) {
            if (true)
                return;
            const header = ' [Tween:] ';
            const message = ' option is not support in v' + -1;
            if (opts['delay']) {
                console.warn(header + 'delay' + message);
            }
            if (opts['repeat']) {
                console.warn(header + 'repeat' + message);
            }
            if (opts['repeatDelay']) {
                console.warn(header + 'repeatDelay' + message);
            }
            if (opts['interpolation']) {
                console.warn(header + 'interpolation' + message);
            }
            if (opts['onStop']) {
                console.warn(header + 'onStop' + message);
            }
        }
        class TweenAction extends ActionInterval {
            constructor(duration, props, opts) {
                super();
                if (opts == null) {
                    opts = {};
                }
                else {
                    TweenOptionChecker(opts);
                    if (opts.easing && typeof opts.easing === 'string') {
                        opts.easing = TweenEasinAdapter(opts.easing);
                    }
                    if (!opts.progress) {
                        opts.progress = this.progress;
                    }
                    if (opts.easing && typeof opts.easing === 'string') {
                        let easingName = opts.easing;
                        opts.easing = Easing[easingName];
                        if (!opts.easing) {
                            warnID(1031, easingName);
                        }
                    }
                }
                this._opts = opts;
                this._props = Object.create(null);
                for (let name in props) {
                    let value = props[name];
                    let easing, progress;
                    if (value.value !== undefined && (value.easing || value.progress)) {
                        if (typeof value.easing === 'string') {
                            easing = easing[value.easing];
                            !easing && warnID(1031, value.easing);
                        }
                        else {
                            easing = value.easing;
                        }
                        progress = value.progress;
                        value = value.value;
                    }
                    let prop = Object.create(null);
                    prop.value = value;
                    prop.easing = easing;
                    prop.progress = progress;
                    this._props[name] = prop;
                }
                this._originProps = props;
                this._fixedStartProps = this._opts.fixedStartProps;
                this._bTargetIgnorePropertyChange = !!this._opts.bTargetIgnorePropertyChange;
                this._opts.bTargetIgnorePropertyChange = null;
                this._opts.fixedStartProps = null;
                this.initWithDuration(duration);
            }
            clone() {
                var action = new TweenAction(this._duration, this._originProps, this._opts);
                this._cloneDecoration(action);
                return action;
            }
            startWithTarget(target) {
                super.startWithTarget(target);
                if (!target || target["destroyed"])
                    return;
                const relative = !!this._opts.relative;
                const props = this._props;
                let fixedStartProps = this._fixedStartProps;
                for (var property in props) {
                    const _t = !!fixedStartProps ? fixedStartProps[property] : target[property];
                    if (_t === undefined) {
                        continue;
                    }
                    const prop = props[property];
                    const value = prop.value;
                    if (typeof _t === "number") {
                        prop.start = _t;
                        prop.current = _t;
                        prop.end = relative ? _t + value : value;
                    }
                    else if (typeof _t === "object") {
                        if (prop.start == null) {
                            prop.start = {};
                            prop.current = {};
                            prop.end = {};
                        }
                        for (var k in value) {
                            prop.start[k] = _t[k];
                            prop.current[k] = _t[k];
                            prop.end[k] = relative ? _t[k] + value[k] : value[k];
                        }
                    }
                }
                if (this._opts.onStart) {
                    this._opts.onStart(this.target);
                }
            }
            update(t) {
                const target = this.target;
                if (!target || target.destroyed || (target["owner"] && target["owner"].destroyed)) {
                    this.stop();
                    return;
                }
                const props = this._props;
                const opts = this._opts;
                let easingTime = t;
                if (opts.easing)
                    easingTime = opts.easing(t);
                let progress = opts.progress;
                for (const name in props) {
                    let prop = props[name];
                    let time = prop.easing ? prop.easing(t) : easingTime;
                    let interpolation = prop.progress ? prop.progress : progress;
                    const start = prop.start;
                    const end = prop.end;
                    if (typeof start === 'number') {
                        prop.current = interpolation(start, end, prop.current, time);
                    }
                    else if (typeof start === 'object') {
                        for (const k in start) {
                            prop.current[k] = interpolation(start[k], end[k], prop.current[k], time);
                        }
                    }
                    if (!this._bTargetIgnorePropertyChange) {
                        target[name] = prop.current;
                    }
                }
                if (t == 1) {
                    this._bTargetIgnorePropertyChange = false;
                    this._fixedStartProps = null;
                }
                if (opts.onUpdate) {
                    opts.onUpdate(this.target, t);
                }
                if (t == 1 && opts.onComplete) {
                    opts.onComplete(this.target);
                }
            }
            progress(start, end, current, t) {
                return current = start + (end - start) * t;
            }
        }
        TweenAction.EMPTY_OPTION = Object.create(null);

        class SetAction extends ActionInstant {
            constructor(props) {
                super();
                this._props = {};
                props !== undefined && this.init(props);
            }
            init(props) {
                for (let name in props) {
                    this._props[name] = props[name];
                }
                return true;
            }
            update() {
                let props = this._props;
                let target = this.target;
                for (let name in props) {
                    target[name] = props[name];
                }
            }
            clone() {
                var action = new SetAction();
                action.init(this._props);
                return action;
            }
        }

        let _default_progress = function (start, end, current, t) {
            return current = start + (end - start) * t;
        };
        let DEFAULT_OPT1 = { easing: Easing.linear, progress: _default_progress };
        let DEFAULT_OPT2 = { easing: Easing.linear, progress: _default_progress };
        class Tween {
            constructor(target) {
                this._actions = [];
                this._finalAction = null;
                this._target = null;
                this._target = target === undefined ? null : target;
                if (this._target && this._target instanceof Laya.EventDispatcher) {
                    this._target.on("NODE_DESTROYED", this, this._destroy);
                }
            }
            then(other) {
                if (other instanceof Action) {
                    this._actions.push(other);
                }
                else {
                    this._actions.push(other._union());
                }
                return this;
            }
            target(target) {
                if (this._target && this._target instanceof Laya.EventDispatcher) {
                    this._target.off("NODE_DESTROYED", this, this._destroy);
                }
                this._target = target;
                if (this._target && this._target instanceof Laya.EventDispatcher) {
                    this._target.on("NODE_DESTROYED", this, this._destroy);
                }
                return this;
            }
            start() {
                if (!this._target) {
                    console.warn('Please set target to tween first');
                    return this;
                }
                if (this._finalAction) {
                    TweenSystem.instance.ActionManager.removeAction(this._finalAction);
                }
                this._finalAction = this._union();
                TweenSystem.instance.ActionManager.addAction(this._finalAction, this._target, false);
                return this;
            }
            stop() {
                if (this._finalAction) {
                    TweenSystem.instance.ActionManager.removeAction(this._finalAction);
                }
                return this;
            }
            pause() {
                if (this._target) {
                    TweenSystem.instance.ActionManager.pauseTarget(this._target);
                }
                return this;
            }
            resume() {
                if (this._target) {
                    TweenSystem.instance.ActionManager.resumeTarget(this._target);
                }
                return this;
            }
            removeAllActions() {
                if (this._target) {
                    TweenSystem.instance.ActionManager.removeAllActionsFromTarget(this._target);
                }
                return this;
            }
            clone(target) {
                let action = this._union();
                return new Tween(target).then(action.clone());
            }
            union() {
                let action = this._union();
                this._actions.length = 0;
                this._actions.push(action);
                return this;
            }
            to(duration, props, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT1) {
                    opts[k] = DEFAULT_OPT1[k];
                }
                opts.relative = false;
                if (easing) {
                    opts.easing = easing;
                }
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            toPos(duration, x, y, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT1) {
                    opts[k] = DEFAULT_OPT1[k];
                }
                opts.relative = false;
                if (easing) {
                    opts.easing = easing;
                }
                let props = {
                    x: x,
                    y: y
                };
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            toAlpha(duration, alpha, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT1) {
                    opts[k] = DEFAULT_OPT1[k];
                }
                opts.relative = false;
                if (easing) {
                    opts.easing = easing;
                }
                let props = {
                    alpha: alpha
                };
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            toScale(duration, scale, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT1) {
                    opts[k] = DEFAULT_OPT1[k];
                }
                opts.relative = false;
                if (easing) {
                    opts.easing = easing;
                }
                let props = {
                    scaleX: scale,
                    scaleY: scale
                };
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            toRotation(duration, rotation, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT1) {
                    opts[k] = DEFAULT_OPT1[k];
                }
                opts.relative = false;
                if (easing) {
                    opts.easing = easing;
                }
                let props = {
                    rotation: rotation
                };
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            by(duration, props, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT2) {
                    opts[k] = DEFAULT_OPT2[k];
                }
                opts.relative = true;
                if (easing) {
                    opts.easing = easing;
                }
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            byPos(duration, x, y, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT2) {
                    opts[k] = DEFAULT_OPT2[k];
                }
                opts.relative = true;
                if (easing) {
                    opts.easing = easing;
                }
                let props = {
                    x: x, y: y
                };
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            byAlpha(duration, alpha, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT2) {
                    opts[k] = DEFAULT_OPT2[k];
                }
                opts.relative = true;
                if (easing) {
                    opts.easing = easing;
                }
                let props = {
                    alpha: alpha
                };
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            byScale(duration, scale, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT2) {
                    opts[k] = DEFAULT_OPT2[k];
                }
                opts.relative = true;
                if (easing) {
                    opts.easing = easing;
                }
                let props = {
                    scaleX: scale,
                    scaleY: scale
                };
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            byRotation(duration, rotation, easing = Easing.linear) {
                let opts = {};
                for (let k in DEFAULT_OPT2) {
                    opts[k] = DEFAULT_OPT2[k];
                }
                opts.relative = true;
                if (easing) {
                    opts.easing = easing;
                }
                let props = {
                    rotation: rotation
                };
                const action = new TweenAction(duration, props, opts);
                this._actions.push(action);
                return this;
            }
            set(props) {
                const action = new SetAction(props);
                this._actions.push(action);
                return this;
            }
            delay(duration) {
                const action = delayTime(duration);
                this._actions.push(action);
                return this;
            }
            call(callback) {
                const action = callFunc(callback);
                this._actions.push(action);
                return this;
            }
            sequence(...args) {
                const action = Tween._wrappedSequence(...args);
                this._actions.push(action);
                return this;
            }
            parallel(...args) {
                const action = Tween._wrappedParallel(...args);
                this._actions.push(action);
                return this;
            }
            repeat(repeatTimes, embedTween) {
                if (repeatTimes == Infinity) {
                    return this.repeatForever(embedTween);
                }
                const actions = this._actions;
                let action;
                if (embedTween) {
                    action = embedTween._union();
                }
                else {
                    action = actions.pop();
                }
                actions.push(repeat(action, repeatTimes));
                return this;
            }
            repeatForever(embedTween) {
                const actions = this._actions;
                let action;
                if (embedTween) {
                    action = embedTween._union();
                }
                else {
                    action = actions.pop();
                }
                actions.push(repeatForever(action));
                return this;
            }
            reverseTime(embedTween) {
                const actions = this._actions;
                let action;
                if (embedTween instanceof Tween) {
                    action = embedTween._union();
                }
                else {
                    action = actions.pop();
                }
                actions.push(reverseTime(action));
                return this;
            }
            hide() {
                let action = hide();
                this._actions.push(action);
                return this;
            }
            show() {
                let action = show();
                this._actions.push(action);
                return this;
            }
            removeSelf(destroy = false) {
                let action = removeSelf(destroy);
                this._actions.push(action);
                return this;
            }
            getNumberOfRunningActions() {
                if (this._target) {
                    return TweenSystem.instance.ActionManager.getNumberOfRunningActionsInTarget(this._target);
                }
                return 0;
            }
            _union() {
                let actions = this._actions;
                let action;
                if (actions.length === 1) {
                    action = actions[0];
                }
                else {
                    action = sequence(actions);
                }
                return action;
            }
            _destroy() {
                this.stop();
            }
            static _wrappedSequence(...args) {
                const tmp_args = Tween._tmp_args;
                tmp_args.length = 0;
                for (let l = args.length, i = 0; i < l; i++) {
                    let arg = tmp_args[i] = args[i];
                    if (arg instanceof Tween) {
                        tmp_args[i] = arg._union();
                    }
                }
                return sequence.apply(sequence, tmp_args);
            }
            static _wrappedParallel(...args) {
                const tmp_args = Tween._tmp_args;
                tmp_args.length = 0;
                for (let l = args.length, i = 0; i < l; i++) {
                    let arg = tmp_args[i] = args[i];
                    if (arg instanceof Tween) {
                        tmp_args[i] = arg._union();
                    }
                }
                return spawn.apply(spawn, tmp_args);
            }
        }
        Tween._tmp_args = [];

        class JumpBy extends ActionInterval {
            constructor(duration, x, y, height, jumps) {
                super();
                this._previousPosition = new Laya.Point(0, 0);
                this._startPosition = new Laya.Point(0, 0);
                this._delta = new Laya.Point(0, 0);
                this._height = 0;
                this._jumps = 0;
                height !== undefined && this.initWithDuration(duration, x, y, height, jumps);
            }
            initWithDuration(duration, x, y, height, jumps) {
                if (super.initWithDuration(duration)) {
                    this._delta.x = x;
                    this._delta.y = y;
                    this._height = height;
                    this._jumps = jumps;
                    return true;
                }
                return false;
            }
            clone() {
                var action = new JumpBy();
                this._cloneDecoration(action);
                action.initWithDuration(this._duration, this._delta.x, this._delta.y, this._height, this._jumps);
                return action;
            }
            startWithTarget(target) {
                super.startWithTarget(target);
                var locPosX = target.x;
                var locPosY = target.y;
                this._previousPosition.x = locPosX;
                this._previousPosition.y = locPosY;
                this._startPosition.x = locPosX;
                this._startPosition.y = locPosY;
            }
            update(dt) {
                dt = this._computeEaseTime(dt);
                let target = this.target;
                if (target) {
                    var frac = dt * this._jumps % 1.0;
                    var y = this._height * 4 * frac * (1 - frac);
                    y += this._delta.y * dt;
                    var x = this._delta.x * dt;
                    var locStartPosition = this._startPosition;
                    if (false) {
                        var targetX = target.x;
                        var targetY = target.y;
                        var locPreviousPosition = this._previousPosition;
                        locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x;
                        locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
                        x = x + locStartPosition.x;
                        y = y + locStartPosition.y;
                        locPreviousPosition.x = x;
                        locPreviousPosition.y = y;
                        target.pos(x, y, true);
                    }
                    else {
                        target.pos(locStartPosition.x + x, locStartPosition.y + y, true);
                    }
                }
            }
            reverse() {
                var action = new JumpBy(this._duration, -this._delta.x, -this._delta.y, this._height, this._jumps);
                this._cloneDecoration(action);
                this._reverseEaseList(action);
                return action;
            }
        }
        class JumpTo extends JumpBy {
            constructor(duration, x, y, height, jumps) {
                super();
                this._endPosition = new Laya.Point(0, 0);
                height !== undefined && this.initWithDuration(duration, x, y, height, jumps);
            }
            initWithDuration(duration, x, y, height, jumps) {
                if (super.initWithDuration(duration, x, y, height, jumps)) {
                    this._endPosition.x = x;
                    this._endPosition.y = y;
                    return true;
                }
                return false;
            }
            startWithTarget(target) {
                super.startWithTarget(target);
                this._delta.x = this._endPosition.x - this._startPosition.x;
                this._delta.y = this._endPosition.y - this._startPosition.y;
            }
            clone() {
                var action = new JumpTo();
                this._cloneDecoration(action);
                action.initWithDuration(this._duration, this._endPosition.x, this._endPosition.y, this._height, this._jumps);
                return action;
            }
        }
        let default_number_formater = function (value) {
            return (value | 0).toString();
        };
        class NumberTo extends ActionInterval {
            constructor(duration, from, to, formater) {
                super();
                this._from = from;
                this._to = to;
                this._formater = formater || default_number_formater;
                this.initWithDuration(duration);
            }
            clone() {
                var action = new NumberTo(this._duration, this._from, this._to, this._formater);
                this._cloneDecoration(action);
                return action;
            }
            initWithDuration(duration) {
                if (super.initWithDuration(duration)) {
                    return true;
                }
                return false;
            }
            startWithTarget(target) {
                super.startWithTarget(target);
                this.m_label = target;
            }
            update(t) {
                if (this.m_label) {
                    t = this._computeEaseTime(t);
                    let cur = this._from + (this._to - this._from) * t;
                    this.m_label.text = this._formater(cur);
                }
            }
        }
        class FloatTo extends ActionInterval {
            constructor(duration, from, to, callback) {
                super();
                this._from = from;
                this._to = to;
                this._callbacker = callback;
                this.initWithDuration(duration);
            }
            clone() {
                var action = new FloatTo(this._duration, this._from, this._to, this._callbacker);
                this._cloneDecoration(action);
                return action;
            }
            initWithDuration(duration) {
                if (super.initWithDuration(duration)) {
                    return true;
                }
                return false;
            }
            startWithTarget(target) {
                super.startWithTarget(target);
            }
            update(t) {
                t = this._computeEaseTime(t);
                let cur = this._from + (this._to - this._from) * t;
                this._callbacker(cur);
            }
        }
        class StringOneByOne extends ActionInterval {
            constructor(duration, text) {
                super();
                this._text = text;
                this.initWithDuration(duration);
            }
            clone() {
                var action = new StringOneByOne(this._duration, this._text);
                this._cloneDecoration(action);
                return action;
            }
            update(t) {
                let target = this.target;
                if (target) {
                    t = this._computeEaseTime(t);
                    let idx = Math.floor(Laya.MathUtil.lerp(0, this._text.length, t));
                    target.text = this._text.substring(0, idx);
                }
            }
        }
        class Follow3DTo2D extends ActionInterval {
            constructor(duration, target, orthographicCamera, offsetX = 0, offsetY = 0) {
                super();
                this._followTarget = target;
                this._orthographicCamera = orthographicCamera;
                this._offsetX = offsetX;
                this._offsetY = offsetY;
                if (duration <= 0)
                    duration = 1e8;
                this.initWithDuration(duration);
            }
            clone() {
                var action = new Follow3DTo2D(this._duration, this._followTarget, this._orthographicCamera);
                this._cloneDecoration(action);
                return action;
            }
            update(t) {
                let target = this.target;
                if (target) {
                    let followTarge = this._followTarget;
                    if (followTarge && !followTarge.destroyed) {
                        let v2 = Laya.Point.TEMP;
                        v2.setTo(this._offsetX + followTarge.pivotX, this._offsetY + followTarge.pivotY);
                        followTarge.localToGlobal(v2, false);
                        let v3 = new Laya.Vector3(0, 0, 0);
                        v3.setValue(v2.x, v2.y, 0);
                        this._orthographicCamera.convertScreenCoordToOrthographicCoord(v3, v3);
                        target.transform.position = v3;
                    }
                }
            }
        }
        function bezierAt(a, b, c, d, t) {
            return (Math.pow(1 - t, 3) * a +
                3 * t * (Math.pow(1 - t, 2)) * b +
                3 * Math.pow(t, 2) * (1 - t) * c +
                Math.pow(t, 3) * d);
        }
        class BezierBy extends ActionInterval {
            constructor(duration, points) {
                super();
                this._config = [];
                this._startPosition = new Laya.Point();
                this._previousPosition = new Laya.Point();
                points && this.initWithDuration(duration, points);
            }
            initWithDuration(duration, points) {
                if (super.initWithDuration(duration)) {
                    this._config = points;
                    return true;
                }
                return false;
            }
            clone() {
                var action = new BezierBy();
                this._cloneDecoration(action);
                var newConfigs = [];
                for (var i = 0; i < this._config.length; i++) {
                    var selConf = this._config[i];
                    newConfigs.push(new Laya.Point(selConf.x, selConf.y));
                }
                action.initWithDuration(this._duration, newConfigs);
                return action;
            }
            startWithTarget(target) {
                super.startWithTarget(target);
                var locPosX = target.x;
                var locPosY = target.y;
                this._previousPosition.x = locPosX;
                this._previousPosition.y = locPosY;
                this._startPosition.x = locPosX;
                this._startPosition.y = locPosY;
            }
            update(t) {
                t = this._computeEaseTime(t);
                if (this.target) {
                    var target = this.target;
                    var locConfig = this._config;
                    var xa = 0;
                    var xb = locConfig[0].x;
                    var xc = locConfig[1].x;
                    var xd = locConfig[2].x;
                    var ya = 0;
                    var yb = locConfig[0].y;
                    var yc = locConfig[1].y;
                    var yd = locConfig[2].y;
                    var x = bezierAt(xa, xb, xc, xd, t);
                    var y = bezierAt(ya, yb, yc, yd, t);
                    var locStartPosition = this._startPosition;
                    if (false) {
                        var targetX = target.x;
                        var targetY = target.y;
                        var locPreviousPosition = this._previousPosition;
                        locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x;
                        locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
                        x = x + locStartPosition.x;
                        y = y + locStartPosition.y;
                        locPreviousPosition.x = x;
                        locPreviousPosition.y = y;
                        target.pos(x, y, true);
                    }
                    else {
                        target.pos(locStartPosition.x + x, locStartPosition.y + y, true);
                    }
                }
            }
            reverse() {
                var locConfig = this._config;
                var x0 = locConfig[0].x, y0 = locConfig[0].y;
                var x1 = locConfig[1].x, y1 = locConfig[1].y;
                var x2 = locConfig[2].x, y2 = locConfig[2].y;
                var r = [
                    new Laya.Point(x1 - x2, y1 - y2),
                    new Laya.Point(x0 - x2, y0 - y2),
                    new Laya.Point(-x2, -y2)
                ];
                var action = new BezierBy(this._duration, r);
                this._cloneDecoration(action);
                this._reverseEaseList(action);
                return action;
            }
        }
        class BezierTo extends ActionInterval {
            constructor(duration, points, pathCount = 5, count = 2) {
                super();
                this.initWithDuration(duration, points, pathCount, count);
            }
            distance2(dx, dy) {
                return Math.sqrt(dx * dx + dy * dy);
            }
            initWithDuration(duration, points, pathCount, count) {
                if (super.initWithDuration(duration)) {
                    let path = new Laya.Bezier().getBezierPoints(points, pathCount, count);
                    this._path = path;
                    let len = 0;
                    for (var i = 0; i < path.length - 2; i += 2) {
                        len += this.distance2(path[i] - path[i + 2], path[i + 1] - path[i + 3]);
                    }
                    return true;
                }
                return false;
            }
            clone() {
                console.error("暂无clone实现，偷懒而已");
                return null;
            }
            startWithTarget(target) {
                super.startWithTarget(target);
            }
            update(t) {
                t = this._computeEaseTime(t);
                if (this.target) {
                    var pos = Laya.Point.TEMP;
                    BezierTo.lerpPath(this._path, t, pos);
                    var target = this.target;
                    target.pos(pos.x, pos.y, true);
                }
            }
            reverse() {
                console.error("暂无reverse实现，偷懒而已");
                return null;
            }
            static clamp01(value) {
                if (value > 1)
                    return 1;
                else if (value < 0)
                    return 0;
                else
                    return value;
            }
            static lerpPath(path, t, out) {
                if (path.length == 0) {
                    return;
                }
                t = this.clamp01(t);
                if (out == null) {
                    out = new Laya.Point(0, 0);
                }
                if (t == 0) {
                    out.setTo(path[0], path[1]);
                }
                else if (t == 1) {
                    out.setTo(path[path.length - 2], path[path.length - 1]);
                }
                else {
                    let value = (path.length / 2 - 1) * t;
                    let min = value | 0;
                    let max = Math.ceil(value);
                    if (min != max) {
                        out.x = Laya.MathUtil.lerp(path[min * 2], path[max * 2], value - min);
                        out.y = Laya.MathUtil.lerp(path[min * 2 + 1], path[max * 2 + 1], value - min);
                    }
                    else {
                        out.setTo(path[max * 2], path[max * 2 + 1]);
                    }
                }
                return out;
            }
        }
        class LookAt extends ActionInterval {
            constructor(duration, target) {
                super();
                this.looAtTarget = target;
                this.lookAtPos = new Laya.Vector3();
                if (duration <= 0)
                    duration = 1e8;
                this.initWithDuration(duration);
            }
            startWithTarget(target) {
                super.startWithTarget(target);
                let forward = new Laya.Vector3();
                target.transform.getForward(forward);
                Laya.Vector3.normalize(forward, forward);
                let dis = Laya.Vector3.distance(target.transform.position, this.looAtTarget.transform.position);
                Laya.Vector3.scale(forward, dis, forward);
                Laya.Vector3.add(target.transform.position, forward, this.lookAtPos);
            }
            clone() {
                var action = new LookAt(this._duration, this.looAtTarget);
                this._cloneDecoration(action);
                return action;
            }
            update(t) {
                let target = this.target;
                if (target) {
                    let lookAtTarge = this.looAtTarget;
                    if (lookAtTarge && !lookAtTarge.destroyed) {
                        Laya.Vector3.lerp(this.lookAtPos, lookAtTarge.transform.position, 0.1, this.lookAtPos);
                        target.transform.lookAt(this.lookAtPos, LookAt.UP, false);
                    }
                }
            }
        }
        LookAt.UP = new Laya.Vector3(0, 1, 0);
        class FollowTo extends ActionInterval {
            constructor(duration, target, distance = 0) {
                super();
                this.followTarget = target;
                this.distance = distance;
                this.originPos = new Laya.Vector3();
                if (duration <= 0)
                    duration = 1e8;
                this.initWithDuration(duration);
            }
            startWithTarget(target) {
                super.startWithTarget(target);
                if (this.distance <= 0) {
                    this.distance = Laya.Vector3.distance(target.transform.position, this.followTarget.transform.position);
                }
                target.transform.position.cloneTo(this.originPos);
            }
            clone() {
                var action = new FollowTo(this._duration, this.followTarget, this.distance);
                this._cloneDecoration(action);
                return action;
            }
            update(t) {
                let target = this.target;
                if (target) {
                    let followTarge = this.followTarget;
                    if (followTarge && !followTarge.destroyed) {
                        Laya.Vector3.lerp(this.originPos, followTarge.transform.position, 0.1, this.originPos);
                        target.transform.position = this.originPos;
                    }
                }
            }
        }
        FollowTo.UP = new Laya.Vector3(0, 1, 0);

        var cc;
        (function (cc) {
            function tween(target, clearBefore = false) {
                if (clearBefore)
                    clearTween(target);
                return new Tween(target);
            }
            cc.tween = tween;
            function clearTween(target) {
                TweenSystem.instance.ActionManager.removeAllActionsFromTarget(target);
            }
            cc.clearTween = clearTween;
            cc.Ease = Easing;
            function jumpBy(duration, x, y, height, jumps) {
                return new JumpBy(duration, x, y, -height, jumps);
            }
            cc.jumpBy = jumpBy;
            function jumpTo(duration, x, y, height, jumps) {
                return new JumpTo(duration, x, y, -height, jumps);
            }
            cc.jumpTo = jumpTo;
            function numberTo(duration, from, to, formater) {
                return new NumberTo(duration, from, to, formater);
            }
            cc.numberTo = numberTo;
            function floatTo(duration, from, to, callback) {
                return new FloatTo(duration, from, to, callback);
            }
            cc.floatTo = floatTo;
            function stringOneByOne(duration, text) {
                return new StringOneByOne(duration, text);
            }
            cc.stringOneByOne = stringOneByOne;
            function lookAt(duration, target) {
                return new LookAt(duration, target);
            }
            cc.lookAt = lookAt;
            function bezierTo(duration, points, pathCount) {
                return new BezierTo(duration, points, pathCount, points.length / 2 - 1);
            }
            cc.bezierTo = bezierTo;
            cc.PROP = {
                EMPTY: {},
                SCALE0: { scaleX: 0, scaleY: 0 },
                SCALE1: { scaleX: 1, scaleY: 1 },
                SCALE1_2: { scaleX: 1.2, scaleY: 1.2 },
                ALPHA0: { alpha: 0 },
                ALPHA1: { alpha: 1 },
                SCALE_ALPHA0: { scaleX: 0, scaleY: 0, alpha: 0 },
                SCALE_ALPHA1: { scaleX: 1, scaleY: 1, alpha: 1 },
            };
            cc.OPTION = {
                BACK_OUT: { easing: Easing.backOut },
                BACK_IN: { easing: Easing.backIn },
                SINE_IN: { easing: Easing.sineIn },
                SINE_OUT: { easing: Easing.sineOut },
                SINE_IN_OUT: { easing: Easing.sineInOut },
                SINE_OUT_IN: { easing: Easing.sineOutIn },
                CIRC_IN: { easing: Easing.circIn },
                CIRC_OUT: { easing: Easing.circOut },
                EXPO_IN: { easing: Easing.expoIn },
                EXPO_OUT: { easing: Easing.expoOut },
                CUBIC_IN: { easing: Easing.cubicIn },
                CUBIC_OUT: { easing: Easing.cubicOut },
            };
        })(cc || (cc = {}));

        var E_CAMERA_MODE;
        (function (E_CAMERA_MODE) {
            E_CAMERA_MODE[E_CAMERA_MODE["fixMode"] = 1] = "fixMode";
            E_CAMERA_MODE[E_CAMERA_MODE["targetDistance"] = 2] = "targetDistance";
            E_CAMERA_MODE[E_CAMERA_MODE["targetPosition"] = 3] = "targetPosition";
        })(E_CAMERA_MODE || (E_CAMERA_MODE = {}));
        class CameraFollow extends Laya.Script {
            constructor() {
                super();
                this.__node = null;
                this.lerpValue = 0.025;
                this.position = new Laya.Vector3;
                this.endRotation = new Laya.Vector3(0, 0, 0);
                this.offset = new Laya.Vector3(0, 0, 0);
                this.distance = 5;
                this.lookMode = E_CAMERA_MODE.targetDistance;
                this.fov = 60;
            }
            set distance(value) {
                if (this._new_diatance == null) {
                    this._old_distance = value;
                    this._new_diatance = value;
                }
                else {
                    this._old_distance = this._new_diatance;
                    this._new_diatance = value;
                }
            }
            get distance() {
                return this._new_diatance;
            }
            set offset(value) {
                if (this._new_offset == null) {
                    this._old_offset = value;
                    this._new_offset = value;
                }
                else {
                    this._old_offset = this._new_offset;
                    this._new_offset = value;
                }
            }
            get offset() {
                return this._new_offset;
            }
            set offsetTargetPos(value) {
                this._offsetTargetPos = value;
            }
            get offsetTargetPos() {
                return this._offsetTargetPos;
            }
            set bAverageSpeed(value) {
                this._bAverage = value;
                this.originRotation = this.__node.transform.rotationEuler.clone();
                this.originPosition = this.__node.transform.position.clone();
                this._startTime = Tools.time();
            }
            stop() {
                this.bStop = true;
            }
            start() {
                this.bStop = false;
            }
            onAwake() {
                this.__node = this.owner;
            }
            onDisable() {
            }
            onLateUpdate() {
                if (!this.__node)
                    return;
                if (this.bStop) {
                    return;
                }
                let targetPos = new Laya.Vector3;
                if (!this.__target || this.__target.destroyed) {
                }
                else {
                    targetPos = this.__target.transform.position.clone();
                }
                if (this._offsetTargetPos) {
                    Laya.Vector3.add(targetPos, this._offsetTargetPos, targetPos);
                }
                if (this._bAverage) {
                    let factor = (Tools.time() - this._startTime) / this.lerpValue;
                    factor = ul.clamp(factor, 0, 1);
                    if (factor == 1)
                        this._bAverage = false;
                    let outRot = new Laya.Vector3;
                    Laya.Vector3.lerp(this.originRotation, this.endRotation, factor, outRot);
                    this.__node.transform.rotationEuler = outRot;
                    let forward = new Laya.Vector3;
                    this.__node.transform.getForward(forward);
                    Laya.Vector3.normalize(forward, forward);
                    Laya.Vector3.scale(forward, -this.distance, forward);
                    let outPos = new Laya.Vector3();
                    Laya.Vector3.add(targetPos, forward, outPos);
                    if (isNaN(forward.x) || isNaN(forward.y) || isNaN(forward.z))
                        return;
                    Laya.Vector3.add(outPos, this.offset, outPos);
                    Laya.Vector3.lerp(this.originPosition, outPos, factor, outPos);
                    this.__node.transform.position = outPos;
                    this.__node.fieldOfView = this.__node.fieldOfView * (1 - factor) + this.fov * factor;
                    return;
                }
                if (this.lookMode == E_CAMERA_MODE.targetDistance) {
                    let curRotation = this.__node.transform.rotationEuler.clone();
                    let outRot = new Laya.Vector3;
                    Laya.Vector3.lerp(curRotation, this.endRotation, this.lerpValue, outRot);
                    this.__node.transform.rotationEuler = outRot;
                    let forward = new Laya.Vector3;
                    this.__node.transform.getForward(forward);
                    Laya.Vector3.normalize(forward, forward);
                    this._old_distance = this._old_distance * (1 - this.lerpValue) + this._new_diatance * this.lerpValue;
                    let distance = this._old_distance;
                    Laya.Vector3.scale(forward, -distance, forward);
                    let outPos = new Laya.Vector3();
                    Laya.Vector3.add(targetPos, forward, outPos);
                    Laya.Vector3.lerp(this._old_offset, this._new_offset, this.lerpValue, this._old_offset);
                    Laya.Vector3.add(outPos, this._old_offset, outPos);
                    this.__node.transform.position = outPos;
                    this.__node.fieldOfView = this.__node.fieldOfView * (1 - this.lerpValue) + this.fov * this.lerpValue;
                }
                else if (this.lookMode == E_CAMERA_MODE.targetPosition) {
                    let outPos = new Laya.Vector3;
                    Laya.Vector3.lerp(this.__node.transform.position.clone(), this.position, this.lerpValue, outPos);
                    this.__node.transform.position = outPos;
                    let OldRotation = this.__node.transform.rotation.clone();
                    ;
                    Laya.Vector3.add(targetPos, this.offset, targetPos);
                    this.__node.transform.lookAt(targetPos, new Laya.Vector3, false);
                    let newRotation = this.__node.transform.rotation.clone();
                    Laya.Quaternion.lerp(OldRotation, newRotation, this.lerpValue, newRotation);
                    this.__node.transform.rotation = newRotation;
                    this.__node.fieldOfView = this.__node.fieldOfView * (1 - this.lerpValue) + this.fov * this.lerpValue;
                }
                else if (this.lookMode == E_CAMERA_MODE.fixMode) {
                    let outPos = new Laya.Vector3;
                    Laya.Vector3.lerp(this.__node.transform.position.clone(), this.position, this.lerpValue, outPos);
                    this.__node.transform.position = outPos;
                    let outRot = new Laya.Vector3;
                    Laya.Vector3.lerp(this.__node.transform.rotationEuler, this.endRotation, this.lerpValue, outRot);
                    this.__node.transform.rotationEuler = outRot;
                    this.__node.fieldOfView = this.__node.fieldOfView * (1 - this.lerpValue) + this.fov * this.lerpValue;
                }
            }
        }

        const RECORD_DATA_KEY = "record_game117_test_01";
        const RECORD_VERSION_KEY = "__version__";
        const RECORD_VERSION_VALUE = 1;
        class mgrRecord extends Manager {
            static onLoad() {
                super.onLoad();
                this._readRecord();
                Timer.callLoop(this.timerSaveGap, this.onTimerSpan.bind(this), true);
            }
            static onTimerSpan(timer) {
                if (this.bNeedFlush) {
                    this.bNeedFlush = false;
                    this._writeRecord();
                }
            }
            static setUserId(userId) {
                if (!userId) {
                    console.log("--->> userId is invaild!", userId);
                    return;
                }
                this.record["userId"] = userId;
                mgrSdk.getServerRecord();
            }
            static onReceivedServerStorage(strData) {
                if (!strData) {
                    console.log("--->> cloud storage is invaild!");
                    return;
                }
                try {
                    let recordData = JSON.parse(strData);
                    if (!recordData) {
                        console.log("--->> cloud storage is damaged!");
                        return;
                    }
                    recordData["userId"] = this.record["userId"];
                    this.record = recordData;
                    this.sendMsg("MSG_RECORD_RESET");
                }
                catch (error) {
                    console.log(error);
                }
            }
            static _readRecord(recordText) {
                if (!recordText) {
                    recordText = Laya.LocalStorage.getItem(RECORD_DATA_KEY);
                }
                if (!recordText) {
                    console.warn("警告] mgrRecord._readRecord 存档未找到！重置存档！");
                    this.resetRecord();
                    return;
                }
                let record = JSON.parse(recordText);
                if (!record) {
                    console.warn("警告] mgrRecord._readRecord 存档数据损坏！重置存档！");
                    this.resetRecord();
                    return;
                }
                if (record[RECORD_VERSION_KEY] != RECORD_VERSION_VALUE) {
                    console.warn("警告] mgrRecord._readRecord 存档版本改变！重置存档！");
                    this.resetRecord();
                    return;
                }
                this.record = record;
            }
            static _writeRecord() {
                let recordText = JSON.stringify(this.record);
                Laya.LocalStorage.setItem(RECORD_DATA_KEY, recordText);
                this._lastSaveTime = Tools.time();
            }
            static _requestFlush() {
                if (this._bDebugBanWrite) {
                    return;
                }
                this.bNeedFlush = true;
            }
            static _setDebugBanWrite(bBanWrite) {
                this._bDebugBanWrite = bBanWrite;
            }
            static getData(key) {
                return this.record[key];
            }
            static setData(key, value) {
                this.record[key] = value;
                this._requestFlush();
                if (Tools.time() > (this._lastSaveTime + this.setDataDoSaveGap)) {
                    this._writeRecord();
                    this.bNeedFlush = false;
                }
            }
            static resetRecord() {
                this.record = {};
                this.record[RECORD_VERSION_KEY] = RECORD_VERSION_VALUE;
                this._requestFlush();
                this.sendMsg("MSG_RECORD_RESET");
            }
        }
        mgrRecord.record = {};
        mgrRecord.bNeedFlush = false;
        mgrRecord._bDebugBanWrite = false;
        mgrRecord._lastSaveTime = 0;
        mgrRecord.setDataDoSaveGap = 2;
        mgrRecord.timerSaveGap = 1;

        const SOUND_TYPE_MUSIC = 1;
        const SOUND_TYPE_EFFECT = 2;
        class mgrSound extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                Laya.SoundManager.autoStopMusic = true;
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("sound") || {};
                this.musicVolume = record.musicVolume != null ? record.musicVolume : 1;
                this.effectVolume = record.effectVolume != null ? record.effectVolume : 1;
                this.soundTimes = {};
                let wx;
                if (window && window[`wx`] && window[`wx`].onShow && window[`wx`].onHide) {
                    wx = window[`wx`];
                }
                if (window && window[`swan`] && window[`swan`].onShow && window[`swan`].onHide) {
                    wx = window[`swan`];
                }
                if (window[`loadRuntime`]) {
                    let tmp = window[`loadRuntime`]();
                    wx = wx || tmp;
                }
                if (wx) {
                    console.log("=== 注册窗口消息, mgrsound ====");
                    wx.onShow(() => {
                        Laya.SoundManager.musicMuted = true;
                        Timer.callLater(0.1, () => {
                            Laya.SoundManager.musicMuted = false;
                        });
                    });
                    wx.onHide(() => {
                    });
                }
                this.setMusicVomue(this.musicVolume, true);
                this.setEffectVolume(this.effectVolume, true);
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    musicVolume: this.musicVolume,
                    effectVolume: this.effectVolume,
                };
                mgrRecord.setData("sound", record);
            }
            static play(soundId, bLoop = false) {
                console.log(`mgrSound.play: ${soundId}`);
                let soundData = mgrCfg.get_from_sound_db(soundId);
                if (!soundData)
                    return;
                if (soundData.cd && this.soundTimes[soundId] && this.soundTimes[soundId] + soundData.cd > Tools.time()) {
                    return;
                }
                let type = soundData.type;
                let url = this.getUrl(soundId);
                if (!url || url == "") {
                    return;
                }
                if (type == SOUND_TYPE_MUSIC) {
                    if (soundId == this.playingMusicSoundId)
                        return;
                    this.playingMusicSoundId = soundId;
                    let playMusic = () => {
                        console.log(`开始播放音乐:${url}`);
                        Laya.SoundManager.playMusic(url, 0);
                        !Laya.SoundManager.musicMuted && (this.bPlayedMusic = true);
                    };
                    if (window.document && window.document[`__custom_web_platform_tag__`] && !window[`conch`]) {
                        mgrLoader.Load2dRes(url, Laya.Loader.SOUND, this, (res) => {
                            playMusic();
                        });
                    }
                    else {
                        playMusic();
                    }
                }
                else {
                    if (Tools.time() - this.effectPlayStartTime < this.effectCd) {
                        console.warn(`mgrsound cding`);
                    }
                    this.effectPlayStartTime = Tools.time();
                    if (this.bLoadingEffect) {
                        console.warn(`mgrsound loading effect:${this.loadingSoundId}`);
                        return;
                    }
                    let playEffect = () => {
                        this.bLoadingEffect = false;
                        Laya.SoundManager.playSound(url, bLoop ? 0 : 1);
                        if (soundData.cd) {
                            this.soundTimes[soundId] = Tools.time();
                        }
                    };
                    if (window.document && window.document[`__custom_web_platform_tag__`] && !window[`conch`]) {
                        this.bLoadingEffect = true;
                        this.loadingSoundId = soundId;
                        mgrLoader.Load2dRes(url, Laya.Loader.SOUND, this, (res) => {
                            playEffect();
                        });
                    }
                    else {
                        playEffect();
                    }
                }
            }
            static getUrl(soundId) {
                let soundData = mgrCfg.get_from_sound_db(soundId);
                if (!soundData) {
                    return "";
                }
                let url = soundData.fileName;
                let type = soundData.type;
                if (window[`conch`]) {
                    if (type == SOUND_TYPE_MUSIC) {
                        url = url.replace(".ogg", ".mp3");
                    }
                    else {
                        url = url.replace(".mp3", ".ogg");
                    }
                }
                else {
                    url = url.replace(".ogg", ".mp3");
                }
                return url;
            }
            static stopAll() {
                this.playingMusicSoundId = null;
                Laya.SoundManager.stopAll();
            }
            static stopBgm() {
                Laya.SoundManager.stopMusic();
            }
            static stopSound(soundId) {
                Laya.SoundManager.stopSound(this.getUrl(soundId));
            }
            static stopSoundAll() {
                Laya.SoundManager.stopAllSound();
            }
            static pauseSound(router) {
                this.pauseMusic(router);
                this.pauseEffect(router);
            }
            static resumeSound(router) {
                this.resumeMusic(router);
                this.resumeEffect(router);
            }
            static pauseEffect(router) {
                console.info(`暂停音效:${router}`);
                let bPaused = this.pauseEffectRouters.length > 0;
                if (this.pauseEffectRouters.indexOf(router) == -1)
                    this.pauseEffectRouters.push(router);
                if (bPaused)
                    return;
                this.setEffectVolume(0);
            }
            static resumeEffect(router) {
                console.info(`恢复音效:${router}`);
                let index = this.pauseEffectRouters.indexOf(router);
                if (index >= 0)
                    this.pauseEffectRouters.splice(index, 1);
                if (this.pauseEffectRouters.length > 0)
                    return;
                this.setEffectVolume(1);
            }
            static pauseMusic(router) {
                console.info(`暂停背景音:${router},length=${this.pauseMusicRouters.length}`);
                console.info(`pauseMusic-Musicallrouter:${this.pauseMusicRouters}`);
                let bPaused = this.pauseMusicRouters.length > 0;
                if (this.pauseMusicRouters.indexOf(router) == -1)
                    this.pauseMusicRouters.push(router);
                if (bPaused)
                    return;
                this.setMusicVomue(0);
            }
            static resumeMusic(router) {
                console.info(`恢复背景音:${router},length=${this.pauseMusicRouters.length}`);
                for (let k in this.pauseMusicRouters) {
                    console.info(`---1--resumeMusic-Musicallrouter--this.pauseMusicRouters[k]:${this.pauseMusicRouters[k]}`);
                }
                let index = this.pauseMusicRouters.indexOf(router);
                console.info(`恢复背景音-1-===index=${index}=${this.pauseMusicRouters.length}`);
                if (index >= 0)
                    this.pauseMusicRouters.splice(index, 1);
                for (let k in this.pauseMusicRouters) {
                    console.info(`---2--resumeMusic-Musicallrouter--this.pauseMusicRouters[k]:${this.pauseMusicRouters[k]}`);
                }
                if (this.pauseMusicRouters.length > 0)
                    return;
                console.info(`try-----恢复背景音setMusicVomue(1)`);
                this.setMusicVomue(1);
            }
            static getMusicVolmue() {
                return this.musicVolume;
            }
            static setMusicVomue(musicVolume, bIgnoreSave) {
                console.log("---1---setMusicVomue", musicVolume);
                this.musicVolume = musicVolume;
                if (musicVolume == 0) {
                    Laya.SoundManager.setMusicVolume(0.0001);
                }
                else {
                    Laya.SoundManager.setMusicVolume(musicVolume);
                }
                if (window[`swan`] || window[`__b_jkw_platform__`]) {
                    console.log("---2---setMusicVomue", musicVolume);
                    if (musicVolume == 0) {
                        Laya.SoundManager.musicMuted = true;
                    }
                    else {
                        Laya.SoundManager.musicMuted = false;
                        let soundId = this.playingMusicSoundId;
                        this.playingMusicSoundId = null;
                        this.play(soundId);
                    }
                }
                this.saveRecord();
            }
            static getEffectVolume() {
                return this.effectVolume;
            }
            static setEffectVolume(effectVolume, bIgnoreSave) {
                this.effectVolume = effectVolume;
                if (effectVolume == 0) {
                    Laya.SoundManager.setSoundVolume(0.001);
                    Laya.SoundManager.soundMuted = true;
                }
                else {
                    Laya.SoundManager.setSoundVolume(effectVolume);
                    Laya.SoundManager.soundMuted = false;
                }
                this.saveRecord();
            }
        }
        mgrSound.playingMusicSoundId = null;
        mgrSound.musicVolume = 1;
        mgrSound.effectVolume = 1;
        mgrSound.effectCd = 0.0;
        mgrSound.effectPlayStartTime = 0;
        mgrSound.pauseMusicRouters = [];
        mgrSound.pauseEffectRouters = [];
        mgrSound.bPlayedMusic = false;
        mgrSound.soundTimes = {};

        const DEBUG = true;
        class mgrGuide extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.registerListeners({
                    MSG_GUIDE_EVENT: this.onGuideMsgEvent.bind(this)
                });
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("mgrGuide") || {};
                this.finishedGuideIdDict = record.finishedGuideIdDict || {};
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    finishedGuideIdDict: this.finishedGuideIdDict,
                };
                mgrRecord.setData("mgrGuide", record);
            }
            static isFinished(guideId) {
                let guideData = mgrCfg.get_from_guide_db(guideId);
                if (!guideData) {
                    return true;
                }
                return !!this.finishedGuideIdDict[guideId];
            }
            static isGuiding() {
                return !!this.curExecutingGuideId;
            }
            static isAllGuideFinished() {
                return this.isFinished(1900);
            }
            static isAllForceGuideFinished() {
                return this.isFinished(1900);
            }
            static registerGuideNode(name, node) {
                let bNewRegister = !this.bindedGuideNode[name] || this.bindedGuideNode[name].destroyed;
                this.bindedGuideNode[name] = node;
                bNewRegister && this.tryResumeGuide();
            }
            static unregisterGuideNode(name) {
                this.bindedGuideNode[name] = null;
            }
            static startGuide(guideId) {
                if (this.bDebugCloseGuide)
                    return;
                if (mgrGuide.isFinished(guideId)) {
                    console.log(`引导已完成: ${guideId}, 请勿重复触发!`);
                    return;
                }
                if (mgrGuide.isGuiding()) {
                    console.log(`正在执行新手引导: ${this.curExecutingGuideId}`);
                    return;
                }
                console.log("调用引导2", guideId);
                let guideData = mgrCfg.get_from_guide_db(guideId);
                if (!guideData) {
                    return;
                }
                if (guideData.transactionCompleteId && mgrGuide.isFinished(guideData.transactionCompleteId)) {
                    console.log(`引导事务已完成: ${guideId}, 请勿重复触发!`);
                    return;
                }
                this.curExecutingGuideId = guideId;
                if (guideData.bindNodeName) {
                    if (!this.bindedGuideNode[guideData.bindNodeName]) {
                        console.log(`当前引导${guideId}所需要的绑定节点尚未注册, 等待...`);
                        return;
                    }
                    if (this.bindedGuideNode[guideData.bindNodeName].destroyed) {
                        console.log(`当前引导${guideId}所需要的绑定节点已失效, 等待...`);
                        return;
                    }
                }
                if (guideData.preEventId && guideData.preEventId.length > 0) {
                    let bAllHave = true;
                    for (let index = 0; index < guideData.preEventId.length; index++) {
                        const eventId = guideData.preEventId[index];
                        if (this.finisedEventIds.indexOf(eventId) < 0) {
                            bAllHave = false;
                            console.log(`当前引导的前置事件尚未完成: ${eventId}`);
                            return;
                        }
                    }
                }
                this.createGuide();
            }
            static tryResumeGuide() {
                if (this.bStartGuide)
                    return;
                if (!this.curExecutingGuideId)
                    return;
                let guideData = mgrCfg.get_from_guide_db(this.curExecutingGuideId);
                if (!guideData.bindNodeName)
                    return;
                if (!this.bindedGuideNode[guideData.bindNodeName] || this.bindedGuideNode[guideData.bindNodeName].destroyed) {
                    console.log(`尝试恢复失败: ${this.curExecutingGuideId}所需要的绑定节点尚未注册, 等待...`);
                    return;
                }
                if (guideData.preEventId && guideData.preEventId.length > 0) {
                    for (let index = 0; index < guideData.preEventId.length; index++) {
                        const eventId = guideData.preEventId[index];
                        if (this.finisedEventIds.indexOf(eventId) < 0) {
                            console.log(`当前引导的前置事件尚未完成: ${eventId}`);
                            return;
                        }
                    }
                }
                this.createGuide();
            }
            static createGuide() {
                if (this.bStartGuide)
                    return;
                this.bStartGuide = true;
                this.finisedEventIds = [];
                console.log(`创建新手引导:${this.curExecutingGuideId}`);
                let guideId = this.curExecutingGuideId;
                let guideData = mgrCfg.get_from_guide_db(guideId);
                if (guideData.statisPoint) {
                    mgrSdk.statisOnStageStart(guideData.statisPoint.toString(), !!mgrGuide.isAllForceGuideFinished() ? "0" : "1");
                }
                guideData.startGuideEvent && this.sendMsg(guideData.startGuideEvent);
                let guideNode = this.bindedGuideNode[guideData.bindNodeName || "-1"];
                let guideDragNode = this.bindedGuideNode[guideData.dragNodeName || "-1"];
                if (guideData.bindNodeName || guideData.tipContent) {
                    console.log(`打开mask弹框:${this.curExecutingGuideId}`);
                    this.guideMaskDialog = mgrDirector.openDialog(`vGuideMaskDialog`, {
                        target: guideNode,
                        dragTarget: guideDragNode,
                        extraArena: guideData.nodeExtArena,
                        content: guideData.tipContent,
                        widget: { x: guideData.tipWidgetX, y: guideData.tipWidgetY },
                        type: guideData.tipStyle,
                        tipDelayTime: guideData.tipDelayTime,
                        bScene: guideData.bScene,
                        maskType: guideData.maskType,
                        fingerDir: guideData.fingerDir,
                    }, true);
                }
                if (guideData.tipDelayTime > 0) {
                    Timer.callLater(guideData.tipDelayTime, () => {
                        if (guideData.soundId)
                            mgrSound.play(guideData.soundId);
                    }, this);
                }
                else {
                    if (guideData.soundId)
                        mgrSound.play(guideData.soundId);
                }
                this.bWaittingFinishEvent = true;
                this.sendMsg(`MSG_GUIDE_STARTED`, { id: guideData.id });
            }
            static onGuideMsgEvent(e) {
                if (this.bDebugCloseGuide)
                    return;
                let id = e.id;
                let param = e.param;
                this.finisedEventIds.push(id);
                if (!this.bWaittingFinishEvent) {
                    return false;
                }
                if (!this.curExecutingGuideId) {
                    return false;
                }
                if (!this.bStartGuide) {
                    this.tryResumeGuide();
                    return false;
                }
                let guideId = this.curExecutingGuideId;
                let guideData = mgrCfg.get_from_guide_db(guideId);
                for (let index = 0; index < guideData.finishEventId.length; index++) {
                    const eventId = guideData.finishEventId[index];
                    if (this.finisedEventIds.indexOf(eventId) < 0) {
                        console.log(`尝试完成引导:${guideId}: 事件${eventId}尚未完成`);
                        return;
                    }
                }
                if (guideData.statisPoint) {
                    mgrSdk.statisOnStageEnd(guideData.statisPoint.toString(), 1, !!mgrGuide.isAllForceGuideFinished() ? "0" : "1");
                }
                this.guideMaskDialog && this.guideMaskDialog.closeDialog();
                this.guideMaskDialog = null;
                this.bStartGuide = false;
                this.bWaittingFinishEvent = false;
                this.curExecutingGuideId = null;
                this.finisedEventIds = [];
                if (guideData.bSave) {
                    this.finishedGuideIdDict[guideId] = true;
                }
                this.saveRecord();
                guideData.completeGuideEvent && this.sendMsg(guideData.completeGuideEvent);
                if (guideData.nextId) {
                    this.startGuide(guideData.nextId);
                }
                else {
                }
            }
            static endGuide() {
                this.guideMaskDialog && this.guideMaskDialog.closeDialog();
                this.guideMaskDialog = null;
                this.bStartGuide = false;
                this.bWaittingFinishEvent = false;
                this.curExecutingGuideId = null;
                this.finisedEventIds = [];
                mgrCfg.forDb_from_guide_db((k, v) => {
                    if (v.bSave) {
                        this.finishedGuideIdDict[v.id] = true;
                    }
                });
                this.saveRecord();
            }
            static forceFinishGuide(guideId) {
                this.guideMaskDialog && this.guideMaskDialog.closeDialog();
                this.guideMaskDialog = null;
                this.bStartGuide = false;
                this.bWaittingFinishEvent = false;
                this.curExecutingGuideId = null;
                this.finisedEventIds = [];
                this.finishedGuideIdDict[guideId] = true;
                this.saveRecord();
            }
            static sendGuideMsg(id) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: id });
            }
            static adaptGuideTrasaction() {
                if (mgrGuide.bDebugCloseGuide) {
                    this.endGuide();
                    return;
                }
                if (!this.finishedGuideIdDict || ul.length(this.finishedGuideIdDict) == 0) {
                    return;
                }
                let db = mgrCfg.getDb("guide_db");
                for (let k in db) {
                    let data = db[k];
                    if (!!data.transactionCompleteId) {
                        if (this.isFinished(data.transactionCompleteId)) {
                            this.finishedGuideIdDict[data.id] = true;
                        }
                        if (!this.isFinished(data.transactionCompleteId) && this.isFinished(data.id)) {
                            delete this.finishedGuideIdDict[data.id];
                        }
                    }
                }
                this.saveRecord();
            }
            static _debugCancelDebug() {
                this.bDebugCloseGuide = true;
                this.endGuide();
            }
        }
        mgrGuide.bDebugCloseGuide = false;
        mgrGuide.finishedGuideIdDict = {};
        mgrGuide.bindedGuideNode = {};
        mgrGuide.finisedEventIds = [];

        class mgrCop extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("mgrCop.onLoad");
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static processCop(cop) {
                console.log("mgrCop.processCop");
                mgrCfg.forDb("cop_process_db", (k, v) => {
                    let value = cop[k];
                    if (value == null) {
                        return;
                    }
                    value = value.toString();
                    let arr = value.split(v.splitChar) || [];
                    for (let i = 0; i < v.outputFieldNames.length; i++) {
                        const fieldName = v.outputFieldNames[i];
                        let fieldValue = arr[i];
                        if (fieldValue == null) {
                            console.warn(ul.format("mgrCop.processCop fieldValue not found! index = %d, fieldName = %s", i, fieldName));
                        }
                        else {
                            cop[fieldName] = fieldValue;
                        }
                    }
                });
            }
            static get(key) {
                let value = this.remoteCop[key];
                return value || "";
            }
            static getNumberValue(key) {
                let value = this.get(key);
                if (value == null)
                    return 0;
                let number = parseFloat(value);
                if (isNaN(number))
                    return 0;
                return number;
            }
            static getBooleanValue(key) {
                let value = this.get(key);
                if (value == null)
                    return false;
                value = (value.toString()).toLowerCase();
                return value == "1" || value == "true";
            }
            static getCops() {
                let cops = {};
                Tools.forEachMap(this.remoteCop, (k, v) => {
                    cops[k] = v;
                });
                return cops;
            }
            static getValueDict(key, splitChar = ";") {
                let value = this.get(key);
                if (!value || value == "") {
                    return {};
                }
                let dict = {};
                let valueArr = value.split(splitChar);
                for (let k in valueArr) {
                    dict[valueArr[k]] = true;
                }
                return dict;
            }
            static setRemoteValue(key, value) {
                if (key == null) {
                    console.warn("mgrCop.setRemoteValue key not found!");
                    return;
                }
                this.remoteCop[key] = value;
                this.processCop(this.remoteCop);
            }
            static onReceiveSdkCop(configInfo) {
                console.log("mgrCop.onReceiveSdkCop");
                this.remoteCop = JSON.parse(configInfo || "") || {};
                this.processCop(this.remoteCop);
            }
        }
        mgrCop.remoteCop = {};
        mgrCop.sdkCop = {};
        mgrCop.lastAdCheckModelValidTime = 0;

        const OPERATOR_HANDLERS = {
            "==": (a, b) => { return a == b; },
            "!=": (a, b) => { return a != b; },
            ">": (a, b) => { return a > b; },
            ">=": (a, b) => { return a >= b; },
            "<": (a, b) => { return a < b; },
            "<=": (a, b) => { return a <= b; },
        };
        class mgrAlu extends Manager {
            static onLoad() {
                super.onLoad();
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static calcCheckData() {
                let checkDatas = {
                    payChannel: this.getCheckPayChannel(),
                    platform: this.getCheckPlatform(),
                    stageProgress: 0,
                };
                Tools.forEachMap(mgrCop.getCops(), (k, v) => {
                    let numberValue = parseFloat(v);
                    checkDatas[k] = isNaN(numberValue) ? v : numberValue;
                });
                return checkDatas;
            }
            static getCheckPayChannel() {
                return "unknown";
            }
            static getCheckPlatform() {
                return "unknown";
            }
            static check(id) {
                if (!id)
                    return true;
                let data = mgrCfg.get("alu_db", id);
                if (!data)
                    return false;
                let result = true;
                let checkDatas = this.calcCheckData();
                for (let i = 0; i < data.conditions.length; i++) {
                    const condition = data.conditions[i];
                    let aluHandler = OPERATOR_HANDLERS[condition.operator];
                    if (aluHandler) {
                        let r = aluHandler(checkDatas[condition.key], condition.value);
                        if (condition.bLogicOr) {
                            result = result || r;
                        }
                        else {
                            result = result && r;
                        }
                    }
                    else {
                        console.warn("mgrAlu.check unknown operator", condition.operator);
                    }
                }
                return result;
            }
            static checkIds(ids) {
                for (let i = 0; i < ids.length; i++) {
                    const id = ids[i];
                    if (!this.check(id)) {
                        return false;
                    }
                }
                return true;
            }
        }
        mgrAlu.OPERATOR_HANDLERS = OPERATOR_HANDLERS;

        const LOG10 = Math.log(10);
        class Mathf {
            static log(value, newBase) {
                if (newBase == null) {
                    return Math.log(value) / LOG10;
                }
                else {
                    return Math.log(value) / Math.log(newBase);
                }
            }
            static getDigits(num) {
                return Math.floor(this.log(num));
            }
            static random(min, max) {
                if (min == null) {
                    return Math.random();
                }
                else if (max == null) {
                    return (Math.random() * min + 1) | 0;
                }
                else {
                    return (Math.random() * (max - min + 1) + min) | 0;
                }
            }
            static randomPlusOrMinus() {
                return (this.random(2) - 1) * 2 - 1;
            }
            static trueOrFalse() {
                return Math.random() > 0.5;
            }
            static randomEnable(rate) {
                return this.random(100) <= rate;
            }
            static clamp01(value) {
                if (value > 1)
                    return 1;
                else if (value < 0)
                    return 0;
                else
                    return value;
            }
            static clamp(value, min, max) {
                if (value < min)
                    return min;
                else if (value > max)
                    return max;
                else
                    return value;
            }
            static sign(value) {
                if (value >= 0)
                    return 1;
                else
                    return -1;
            }
            static fuzzyEquals(value1, value2) {
                return Math.abs(value1 - value2) < this.EPSILON;
            }
            static lerp(min, max, t) {
                return min + (max - min) * this.clamp01(t);
            }
            static inverseLerp(min, max, cur) {
                if (min != max) {
                    return this.clamp01((cur - min) / (max - min));
                }
                else {
                    return 0;
                }
            }
            static lerpFromInverseLerp(valueMin, valueMax, fromMin, fromMax, fromValue) {
                return this.lerp(valueMin, valueMax, this.inverseLerp(fromMin, fromMax, fromValue));
            }
            static getFitScale(x, y, maxX, maxY) {
                let scaleX = maxX / x;
                let scaleY = maxY / y;
                return Math.min(scaleX, scaleY);
            }
            static round(value, digits) {
                digits = digits || 0;
                let num = this.roundPower10Double[digits];
                value *= num;
                return Math.round(value) / num;
            }
            static loop(value, min, max) {
                if (max == null) {
                    max = min;
                    min = 0;
                }
                if (value < min) {
                    return min;
                }
                else {
                    let v = (value - min) % (max - min);
                    return min + v;
                }
            }
            static pingPong(value, min, max) {
                if (max == null) {
                    max = min;
                    min = 0;
                }
                if (value < min) {
                    return min;
                }
                else {
                    let d = max - min;
                    let v1 = value - min;
                    let s = Math.floor(v1 / d);
                    let v2 = v1 % d;
                    if (s % 2 == 0) {
                        return v2 + min;
                    }
                    else {
                        return max - v2;
                    }
                }
            }
            static nextGaussian(mean, std_dev) {
                return mean + (this.uniform2NormalDistribution() * std_dev);
            }
            static uniform2NormalDistribution() {
                var sum = 0.0;
                for (var i = 0; i < 12; i++) {
                    sum = sum + Math.random();
                }
                return sum - 6.0;
            }
            static circleRandom(...weights) {
                return this.arrCircleRandom(weights);
            }
            static arrCircleRandom(weights) {
                let sum = 0;
                for (let i = 0; i < weights.length; i++) {
                    sum += weights[i];
                }
                if (sum <= 0)
                    return -1;
                let random = Mathf.random(sum);
                for (let i = 0; i < weights.length; i++) {
                    if (random <= weights[i]) {
                        return i;
                    }
                    random -= weights[i];
                }
                return -1;
            }
            static makeRandomArray(len) {
                let arr = new Array(len);
                for (let i = 0; i < len; i++) {
                    arr[i] = i;
                }
                this.shuffle(arr);
                return arr;
            }
            static randomFromArray(arr, removeIt) {
                if (arr && arr.length) {
                    let idx = this.random(arr.length) - 1;
                    if (removeIt) {
                        return arr.splice(idx, 1)[0];
                    }
                    else {
                        return arr[idx];
                    }
                }
                else {
                    return null;
                }
            }
            static shuffle(data) {
                let temp;
                let rnd;
                for (let i = data.length - 1; i > 0; i--) {
                    rnd = this.random(0, i);
                    temp = data[i];
                    data[i] = data[rnd];
                    data[rnd] = temp;
                }
            }
            static swap(data, i, j) {
                let temp = data[i];
                data[i] = data[j];
                data[j] = temp;
            }
            static minIndex(values) {
                let minValue = Number.MAX_SAFE_INTEGER;
                let index = -1;
                for (let i = values.length - 1; i >= 0; i--) {
                    if (values[i] <= minValue) {
                        minValue = values[i];
                        index = i;
                    }
                }
                return index;
            }
            static distance(p1x, p1y, p2x, p2y) {
                let dx = p1x - p2x;
                let dy = p1y - p2y;
                return Math.sqrt(dx * dx + dy * dy);
            }
            static distance2(dx, dy) {
                return Math.sqrt(dx * dx + dy * dy);
            }
            static distanceSqr(p1x, p1y, p2x, p2y) {
                let dx = p1x - p2x;
                let dy = p1y - p2y;
                return dx * dx + dy * dy;
            }
            static distanceSqr2(dx, dy) {
                return dx * dx + dy * dy;
            }
            static easeInLogic(val) {
                return 1 - Math.sin(0.5 * Math.PI * (1 - val));
            }
            static easeOutLogic(val) {
                return Math.sin(0.5 * Math.PI * val);
            }
            static easeInOutLogic(val) {
                let pi2 = Math.PI * 2;
                return val - Math.sin(val * pi2) / pi2;
            }
            static bounceLogic(val) {
                if (val < 0.363636) {
                    val = 7.5685 * val * val;
                }
                else if (val < 0.727272) {
                    val = 7.5625 * (val -= 0.545454) * val + 0.75;
                }
                else if (val < 0.909090) {
                    val = 7.5625 * (val -= 0.818181) * val + 0.9375;
                }
                else {
                    val = 7.5625 * (val -= 0.9545454) * val + 0.984375;
                }
                return val;
            }
        }
        Mathf.roundPower10Double = [
            1.0,
            10.0,
            100.0,
            1000.0,
            10000.0,
            100000.0,
            1000000.0,
            10000000.0,
            100000000.0,
            1000000000.0,
            10000000000.0,
            100000000000.0,
            1000000000000.0,
            10000000000000.0,
            100000000000000.0,
            1E+15
        ];
        Mathf.PI = 3.14159274;
        Mathf.Deg2Rad = 0.0174532924;
        Mathf.Rad2Deg = 57.295779;
        Mathf.TEMP_POINT = new Laya.Point();
        Mathf.TEMP_POINTS = [
            new Laya.Point(),
            new Laya.Point(),
            new Laya.Point(),
            new Laya.Point(),
        ];
        Mathf.TempRect = Laya.Rectangle.create();
        Mathf.TEMP_VEC3 = new Laya.Vector3();
        Mathf.TEMP_VEC3S = [
            new Laya.Vector3(),
            new Laya.Vector3(),
            new Laya.Vector3(),
            new Laya.Vector3(),
        ];
        Mathf.EPSILON = 1e-6;
        Mathf.calcPointOnArc = function (x0, y0, r, angle) {
            let x1, y1;
            let _rad = (angle) * Math.PI / 180;
            x1 = Math.cos(_rad) * r + x0;
            y1 = Math.sin(_rad) * r + y0;
            return [x1, y1];
        };

        var AD_MODE;
        (function (AD_MODE) {
            AD_MODE[AD_MODE["mcprc"] = 1] = "mcprc";
            AD_MODE[AD_MODE["online"] = 2] = "online";
            AD_MODE[AD_MODE["close"] = 3] = "close";
        })(AD_MODE || (AD_MODE = {}));
        var ADV_TYPE;
        (function (ADV_TYPE) {
            ADV_TYPE["intert"] = "interstitial";
            ADV_TYPE["banner"] = "banner";
            ADV_TYPE["embed"] = "embed";
            ADV_TYPE["video"] = "video";
            ADV_TYPE["h5"] = "url";
        })(ADV_TYPE || (ADV_TYPE = {}));
        class mgrAd extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.registerListeners({
                    MSG_SDK_OPEN_ADV_RESULT: this.onMsgSdkOpenAdvResult,
                    MSG_ADV_CLOSE_RESULT: this.onMsgAdvCloseResult,
                    MSG_SDK_ADV_VALID_COUNT: this.onMsgSdkAdvValidCount,
                });
                if (!Tools.isOneDay(this.todayNativeInsertLastScaleTime, Tools.time())) {
                    this.todayNativeInsertScaleCount = 0;
                    this.todayNativeInsertScaleIntervalCount = 0;
                    this.todayNativeInsertLastScaleTime = Tools.time();
                }
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("ad") || {};
                this.lastFinishedTimes = record.lastFinishedTimes || {};
                this.finishCounts = record.finishCounts || {};
                this.todayNativeInsertScaleCount = record.todayNativeInsertScaleCount || 0;
                this.todayNativeInsertScaleIntervalCount = record.todayNativeInsertScaleIntervalCount || 0;
                this.todayNativeInsertLastScaleTime = record.todayNativeInsertLastScaleTime || 0;
                this.lastGouModeTimes = record.lastGouModeTimes || 0;
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    lastFinishedTimes: this.lastFinishedTimes,
                    finishCounts: this.finishCounts,
                    todayNativeInsertScaleCount: this.todayNativeInsertScaleCount,
                    todayNativeInsertScaleIntervalCount: this.todayNativeInsertScaleIntervalCount,
                    todayNativeInsertLastScaleTime: this.todayNativeInsertLastScaleTime,
                    lastGouModeTimes: this.lastGouModeTimes || 0,
                };
                mgrRecord.setData("ad", record);
            }
            static getAdEventRemainCd(adEventId) {
                let adEventData = mgrCfg.get("ad_event_db", adEventId);
                if (!adEventData)
                    return 0;
                if (this.getCdByAdEventId(adEventId) > 0) {
                    let lastFinishedTime = this.getLastFinishedTime(adEventId);
                    let cdFinishTime = lastFinishedTime + this.getCdByAdEventId(adEventId);
                    return Math.max(0, cdFinishTime - Tools.time());
                }
                return 0;
            }
            static getCdByAdEventId(adEventId) {
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (!adEventData)
                    return 0;
                let cd = adEventData.cd;
                if (adEventData.cdFromCopKey) {
                    cd = mgrSdk.getCopNumberValueByKey(adEventData.cdFromCopKey);
                }
                if ((mgrGuide.isGuiding() || !mgrGuide.isAllGuideFinished()) &&
                    mgrSdk.getCopNumberValueByKey("b_pop_int_banner_in_guiding") == 1 &&
                    adEventData.cdFromCopKeyInGuiding) {
                    cd = mgrSdk.getCopNumberValueByKey(adEventData.cdFromCopKeyInGuiding);
                }
                return cd;
            }
            static getLastFinishedTime(adEventId) {
                let adEventData = mgrCfg.get("ad_event_db", adEventId);
                if (!adEventData)
                    return 0;
                let cdGroup = adEventData.id;
                if (adEventData.cdGroup) {
                    cdGroup = adEventData.cdGroup;
                }
                return this.lastFinishedTimes[cdGroup] || 0;
            }
            static markFinished(adEventId) {
                let adEventData = mgrCfg.get("ad_event_db", adEventId);
                if (!adEventData)
                    return;
                let cdGroup = adEventData.id;
                if (adEventData.cdGroup) {
                    cdGroup = adEventData.cdGroup;
                }
                this.lastFinishedTimes[cdGroup] = Tools.time();
                this.saveRecord();
            }
            static isAdTypeValid(adEventId) {
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (!adEventData)
                    return true;
                switch (adEventData.type) {
                    case "video": return mgrAd.AD_VIDEO_VALID_COUNT > 0;
                }
                return true;
            }
            static staticsAdShow(adEventId) {
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                adEventData && adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            static preCheckAdNoCd(adEventId, bIgnoreGuide) {
                let adEventData = mgrCfg.get("ad_event_db", adEventId);
                if (!adEventData) {
                    return false;
                }
                if (!bIgnoreGuide && mgrSdk.getCopNumberValueByKey("b_pop_int_banner_in_guiding") != 1 && (mgrGuide.isGuiding() || !mgrGuide.isAllGuideFinished())) {
                    return false;
                }
                if (!this.isAdTypeValid(adEventId)) {
                    console.log("  广告没有次数了 ");
                    return false;
                }
                if (!mgrAlu.check(adEventData.aluId)) {
                    console.log("  alu不通过，不通过");
                    return false;
                }
                let ratio = adEventData.ratio;
                if (adEventData.ratioFromCopKey) {
                    ratio = mgrSdk.getCopNumberValueByKey(adEventData.ratioFromCopKey);
                }
                if (Tools.random(100) > ratio) {
                    return false;
                }
                if (adEventData.wipeItemId > 0 && mgrPlayer.getItemAmount(adEventData.wipeItemId) > 0) {
                    console.log("  去广告，不通过");
                    return false;
                }
                if (this.getAdEventRemainCount(adEventId) <= 0) {
                    console.log("次数已用完");
                    return false;
                }
                return true;
            }
            static preCheckCanTriggerAdEvent(adEventId) {
                this.bOpenMoreGameBox = false;
                let adEventData = mgrCfg.get("ad_event_db", adEventId);
                if (!adEventData) {
                    return false;
                }
                let check = this.preCheckAdNoCd(adEventId);
                if (!check) {
                    return false;
                }
                if (this.getCdByAdEventId(adEventId) > 0 && this.getAdEventRemainCd(adEventId) > 0) {
                    if (adEventData.advId == 1) {
                        this.bOpenMoreGameBox = true;
                    }
                    console.log("  冷却时间未到，不通过");
                    return false;
                }
                return true;
            }
            static triggerAdEvent(adEventId, param, bIgnoreCheck) {
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (!adEventData)
                    return;
                console.log("mgrAd.触发广告事件", adEventId, param, bIgnoreCheck);
                if (!bIgnoreCheck) {
                    if (!this.preCheckCanTriggerAdEvent(adEventId)) {
                        console.log("    preCheckCanTriggerAdEvent 不通过");
                        return;
                    }
                    if (this.getCdByAdEventId(adEventId) > 0 && this.getAdEventRemainCd(adEventId) > 0) {
                        console.log("  冷却时间未到，不通过");
                        mgrTip.showMsgTip("冷却中,请稍后再试");
                        return;
                    }
                }
                if (mgrGuide.isGuiding() && mgrSdk.getCopNumberValueByKey("b_pop_int_banner_in_guiding") != 1) {
                    console.log("  正在新手引导，不触发广告");
                    return;
                }
                let userData = {};
                Tools.forEachMap(adEventData.param, (k, v) => {
                    userData[k] = v;
                });
                if (param) {
                    Tools.forEachMap(param, (k, v) => {
                        userData[k] = v;
                    });
                }
                userData.adEventId = adEventId;
                userData.serialNumber = this.AD_EVENT_SERIAL_NUMBER;
                this.AD_EVENT_SERIAL_NUMBER++;
                if (adEventData.bPauseSound) {
                    mgrSound.pauseSound("mgrAd");
                }
                if (adEventData.bRecordCdWhenTrigger) {
                    this.markFinished(adEventId);
                }
                if (adEventData.type == ADV_TYPE.video) {
                    mgrTip.showLoadingTip("advertisement");
                    this.sendMsg(`MSG_VIDEO_AD_EVENT_START`, { adEventId: adEventId });
                }
                mgrSdk.openAdv(adEventData.advId, JSON.stringify(userData), adEventData.advNumber);
                if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                    mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 2);
                }
            }
            static closeAdv(adEventId) {
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (!adEventData)
                    return;
                mgrSdk.closeAdv(adEventData.advId);
            }
            static onMsgSdkOpenAdvResult(e) {
                let data = e;
                console.info("mgrAd.onMsgSdkOpenAdvResult");
                let userData = JSON.parse(data.userData || "{}") || {};
                let adEventId = userData.adEventId || 0;
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (!adEventData) {
                    console.log("[warn] ul.mgrAd.onMsgSdkOpenAdvResult adEventId not found!");
                    return;
                }
                let code = parseInt(data.code) || 0;
    			code = 1;
                switch (code) {
                    case 0: {
                        if (!!data.msg && adEventData.type == ADV_TYPE.video) {
                            mgrTip.showMsgTip("未成功获得，请重新尝试。");
                            if (mgrSdk.getCopNumberValueByKey("b_ad_faild_show_second_retry_prompt") == 1) {
                                let bShowAd = mgrSdk.getCopNumberValueByKey("b_ad_faild_show_second_retry_prompt") == 1 ? true : false;
                                mgrTip.alertPrompt1("提示", "需要观看完整视频才能\n获得奖励", "要奖励", () => {
                                    mgrAd.triggerAdEvent(adEventId, userData, true);
                                }, bShowAd, true);
                            }
                        }
                        if (adEventData.bPauseSound)
                            mgrSound.resumeSound("mgrAd");
                        adEventData.type == "video" && mgrTip.hideLoadingTip("advertisement");
                        if (adEventData.pointEventId) {
                            if (adEventData.type == "video") {
                            }
                        }
                        break;
                    }
                    case 1: {
                        if (adEventData.bPauseSound)
                            mgrSound.resumeSound("mgrAd");
                        this.markFinished(adEventId);
                        adEventData.type == "video" && mgrTip.hideLoadingTip("advertisement");
                        if (adEventData.type == "video") {
                        }
                        break;
                    }
                    default:
                        break;
                }
                if (code == adEventData.successCode) {
                    //激励 || 原生
                    // this._doAdEventSuccessdLogic(adEventId, userData);

                    //原生
                    if (data.advId == 2) {
                        console.info("data.advId 原生");
                        Advertisement.insertAdverV3();

                        this._doAdEventSuccessdLogic(adEventId, userData);
                    }
                    //激励
                    else if (data.advId == 4) {
                        console.info("data.advId 激励");
                        let success = () => {
                            this._doAdEventSuccessdLogic(adEventId, userData);
                        };
                        // success();

                        Advertisement.videoAdverV(success);
                    } else {
                        console.info("data.advId 不知道啥广告\n", data, "\n", data.advId);
                    }
                }
                else {
                    this.sendMsg("MSG_AD_EVENT_FAILD", {
                        adEventId: adEventId,
                        userData: userData,
                    });
                }
            }
            static _doAdEventSuccessdLogic(adEventId, userData) {
                let serialNumber = parseInt(userData.serialNumber) || 0;
                if (this.successedAdEventSerialNumbers[serialNumber]) {
                    console.warn(ul.format("mgrAd.onMsgSdkOpenAdvResult ad already do successd! adEventId=%s, serialNumber=%d", adEventId, serialNumber));
                    return;
                }
                this.successedAdEventSerialNumbers[serialNumber] = true;
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                let gotItemTipDatas = [];
                let rewards = userData.rewards || adEventData.param.rewards;
                if (rewards) {
                    rewards.forEach(element => {
                        let [itemId, minAmount, maxAmount, bIgnoreTip, notBlue] = element;
                        let amount = 0;
                        if (!minAmount) {
                            amount = maxAmount;
                        }
                        else if (!maxAmount) {
                            amount = minAmount;
                        }
                        else {
                            amount = Math.random() * (maxAmount - minAmount) + minAmount;
                        }
                        if (itemId == Const.ITEM_ID_GOLD) {
                            amount = Math.floor(amount);
                        }
                        else {
                            amount = Math.floor(amount);
                        }
                        mgrPlayer.addItemAmount(itemId, amount, "看完广告后发奖");
                        if (!bIgnoreTip) {
                            gotItemTipDatas.push({
                                itemId: itemId,
                                amount: amount,
                                amountSteps: [[amount, 0]],
                                customerContext: { bBanAdReward: true },
                                notBlue: notBlue,
                                bFromAd: true,
                            });
                        }
                    });
                }
                if (gotItemTipDatas.length > 0) {
                    mgrTip.addGotItemTipGroup(gotItemTipDatas);
                }
                if (!this.finishCounts[adEventId])
                    this.finishCounts[adEventId] = 0;
                this.finishCounts[adEventId]++;
                this.sendMsg("MSG_AD_EVENT_SUCCESSD", {
                    adEventId: adEventId,
                    userData: userData,
                });
            }
            static onMsgAdvCloseResult(e) {
            }
            static getAdEventRemainCount(adEventId) {
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (!adEventData)
                    return 0;
                if (adEventData.aluId && !mgrAlu.check(adEventData.aluId)) {
                    return 0;
                }
                let ratio = adEventData.ratio;
                if (adEventData.ratioFromCopKey && adEventData.ratioFromCopKey.length > 0) {
                    ratio = mgrSdk.getCopNumberValueByKey(adEventData.ratioFromCopKey);
                }
                if (ratio <= 0) {
                    return 0;
                }
                let remainCount = adEventData.remainCount || 0;
                if (adEventData.remianCountFromCop) {
                    remainCount = mgrSdk.getCopNumberValueByKey(adEventData.remianCountFromCop);
                }
                if (remainCount > 0) {
                    let lastFinishTime = this.lastFinishedTimes[adEventId] || 0;
                    if (!Tools.isOneDay(lastFinishTime, Tools.time())) {
                        this.finishCounts[adEventId] = 0;
                    }
                    return Math.max(0, remainCount - (this.finishCounts[adEventId] || 0));
                }
                else {
                    return 1;
                }
            }
            static isOnline() {
                return mgrSdk.getCopNumberValueByKey("ad_mode") == AD_MODE.online;
            }
            static isMcprc() {
                return mgrSdk.getCopNumberValueByKey("ad_mode") == AD_MODE.mcprc;
            }
            static onMsgSdkAdvValidCount(data) {
                mgrAd.AD_VIDEO_VALID_COUNT = data.video;
            }
            static getAdModeByAdEventId(adEventId) {
                let result = mgrSdk.getCopNumberValueByKey(`${adEventId}-style`);
                console.log(`getAdModeByAdEventId: ${adEventId}-style, ${result}`);
                return result;
            }
            static randomGetAdCheckModeConfig(actionText) {
                let configArr = [
                    { text: "看视频", bDefaultChecked: true, bCheckedTriggerAd: true },
                    { text: "不看视频", bDefaultChecked: true, bCheckedTriggerAd: false },
                    { text: "看视频", bDefaultChecked: false, bCheckedTriggerAd: true },
                    { text: "不看视频", bDefaultChecked: false, bCheckedTriggerAd: false },
                ];
                let config = ul.clone(configArr[Tools.random(0, configArr.length - 1)]);
                config.text = `${config.text}${actionText}`;
                return config;
            }
            static changeAdEventDbAdvId2AdEventId() {
                let db = mgrCfg.getDb("ad_event_db");
                for (let k in db) {
                    let data = db[k];
                    if (data.type == ADV_TYPE.video) {
                        data.advId = data.id;
                    }
                }
            }
            static setGouModeCd(time) {
                this.lastGouModeTimes = time;
                this.saveRecord();
            }
            static showMoreGameBox(copIdx) {
                let cop = mgrCop.get("b_open_more_game_box_switch");
                let copArr = cop.split(";");
                if (parseInt(copArr[copIdx]) == 1) {
                    return true;
                }
                return false;
            }
            static showMoreGameBoxOrInterstitial() {
                let cop = mgrCop.getNumberValue("b_open_more_game_box_in_ad");
                if (cop < Mathf.random(1, 100)) {
                    console.log("概率不足");
                    return false;
                }
                if (Tools.time() - this.lastOpenMoreGameBoxTime < mgrCop.getNumberValue("b_open_more_game_box_cd")) {
                    console.log("cd时间不足");
                    return false;
                }
                mgrSdk.opentChannelMoreGameBox();
                this.lastOpenMoreGameBoxTime = Tools.time();
                return true;
            }
        }
        mgrAd.AD_VIDEO_VALID_COUNT = 1;
        mgrAd.lastFinishedTimes = {};
        mgrAd.finishCounts = {};
        mgrAd.AD_EVENT_SERIAL_NUMBER = 0;
        mgrAd.successedAdEventSerialNumbers = {};
        mgrAd.todayNativeInsertScaleCount = 0;
        mgrAd.todayNativeInsertScaleIntervalCount = 0;
        mgrAd.todayNativeInsertLastScaleTime = 0;
        mgrAd.lastGouModeTimes = 0;
        mgrAd.lastOpenMoreGameBoxTime = 0;
        mgrAd.bOpenMoreGameBox = false;

        class mgrGameResVersion extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.registerListeners({
                    MSG_SDK_CHANNEL_INFO_RESULT: this.onMsgChannelInfoResult.bind(this),
                    MSG_SDK_COP_INFO_RESULT: this.onMsgCopInfoResult.bind(this),
                });
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static onMsgChannelInfoResult() {
            }
            static onMsgCopInfoResult() {
            }
            static isValidGameResVersion(version) {
                if (!version) {
                    return true;
                }
                let versionStr = mgrSdk.getCopByKey("game_res_version");
                if (versionStr && versionStr != "") {
                    let arr = versionStr.split(";") || [];
                    let dict = {};
                    for (let k in arr) {
                        dict[arr[k]] = true;
                    }
                    return !!dict[version];
                }
                return false;
            }
        }

        class mgrCard extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化mgrCard loadRecord");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("card_record") || {};
                this.stageProgress = record.stageProgress || 0;
                this.stageNewYearProgress = record.stageNewYearProgress || 0;
                this.bPassAllNewYearStage = record.bPassAllNewYearStage || false;
                this.stageDatas = record.stageDatas || {};
                this.stageFragmentGotMap = record.stageFragmentGotMap || {};
                this.fightPosLockDict = record.fightPosLockDict || {};
                this.unlockedPhotoRecipeDict = record.unlockedPhotoRecipeDict || {};
                this.unlockedPhotoStyleDict = record.unlockedPhotoStyleDict || {};
                this.playerCardInfoDict = record.playerCardInfoDict || {};
                this.tempFightPosInfoDict = {};
                this.bRewardInSDK = record.bRewardInSDK || false;
                mgrCfg.forDb_from_amaze_card_stage_db((k, v) => {
                    this.stageDatas[v.id] = !!this.stageDatas[v.id];
                });
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    this.fightPosLockDict[i] = true;
                }
                this.initNewYearStageFirstPassReward();
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    stageProgress: this.stageProgress,
                    stageNewYearProgress: this.stageNewYearProgress,
                    bPassAllNewYearStage: this.bPassAllNewYearStage,
                    stageDatas: this.stageDatas,
                    stageFragmentGotMap: this.stageFragmentGotMap,
                    fightPosLockDict: this.fightPosLockDict,
                    unlockedPhotoRecipeDict: this.unlockedPhotoRecipeDict,
                    unlockedPhotoStyleDict: this.unlockedPhotoStyleDict,
                    playerCardInfoDict: this.playerCardInfoDict,
                    bRewardInSDK: this.bRewardInSDK,
                };
                mgrRecord.setData("card_record", record);
            }
            static pushSelectCard(idx, cardId) {
                for (let i = 0; i < this.curSelectCard.length; ++i) {
                    if (this.curSelectCard[i].idx == idx) {
                        this.curSelectCard[i].cardId = cardId;
                        return;
                    }
                }
                this.curSelectCard.push({
                    idx: idx,
                    cardId: cardId,
                });
            }
            static getUnlockedPlayerCardPosArr() {
                let arr = [];
                for (let i = 0; i < 5; i++) {
                    if (this.isUnlockedPlayerCardPos(i)) {
                        arr.push(i);
                    }
                }
                return arr;
            }
            static unlockPlayerCardPos(posIndex) {
                this.fightPosLockDict[posIndex] = true;
                this.saveRecord();
            }
            static isUnlockedPlayerCardPos(posIndex) {
                return !!this.fightPosLockDict[posIndex];
            }
            static cleanTempFightCardPosInfoData() {
                return this.tempFightPosInfoDict = {};
            }
            static getTempFightCardPosInfoDict() {
                return this.tempFightPosInfoDict;
            }
            static getTempFightCardPosInfoByPosIndex(posIndex) {
                return this.tempFightPosInfoDict[posIndex];
            }
            static setTempFightCardDataByPosIndex(posIndex, roleData) {
                this.tempFightPosInfoDict[posIndex] = roleData;
            }
            static isBTrying(cardId) {
                if (!this.tempFightPosInfoDict) {
                    return false;
                }
                for (let k in this.tempFightPosInfoDict) {
                    let data = this.tempFightPosInfoDict[k];
                    if (!data) {
                        continue;
                    }
                    if (data.cardId == cardId && data.bTrying) {
                        return true;
                    }
                }
                return false;
            }
            static setTrying(cardId, roleData) {
                if (this.isShowTrying(cardId)) {
                    return;
                }
                this.tryingCardId.push(cardId);
                this.tempTryingCardInfoArr.push(roleData);
            }
            static isShowTrying(cardId) {
                return this.tryingCardId.indexOf(cardId) >= 0;
            }
            static getTryingCardInfo() {
                return this.tempTryingCardInfoArr;
            }
            static cleanTempTryingCardInfoData() {
                this.tryingCardId = [];
                return this.tempTryingCardInfoArr = [];
            }
            static isCardInTempFightCardStandbying(cardId) {
                if (!this.tempFightPosInfoDict) {
                    return false;
                }
                for (let k in this.tempFightPosInfoDict) {
                    let data = this.tempFightPosInfoDict[k];
                    if (!data) {
                        continue;
                    }
                    if (data.cardId == cardId) {
                        return true;
                    }
                }
                return false;
            }
            static getAllPlayerCardInfo() {
                let arr = [];
                let dict = this.playerCardInfoDict || {};
                for (let k in dict) {
                    if (!dict[k]) {
                        continue;
                    }
                    let data = Tools.deepCopy(dict[k]);
                    arr.push(data);
                }
                return arr;
            }
            static setPlayerCardInfo(playerCardId, roleId, styleId, cardTextureKeyName, power, hp, partIds) {
                this.playerCardInfoDict[playerCardId] = { cardId: playerCardId, roleId: roleId, styleId: styleId, cardTextureKeyName: cardTextureKeyName, power: power, hp: hp, partIds: partIds };
                this.saveRecord();
            }
            static getPlayerCardInfo(cardId) {
                if (!this.playerCardInfoDict[cardId]) {
                    return null;
                }
                let data = Tools.deepCopy(this.playerCardInfoDict[cardId]);
                return data;
            }
            static getRoleCardTextureKeyNameByCardId(playerCardId) {
                return `player_card_texture${playerCardId}`;
            }
            static getMinEmptyDataCardId() {
                let cardId = 0;
                mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                    if (mgrPlayer.getItemAmount(v.id) <= 0 || !!cardId || !!this.getPlayerCardInfo(v.id)) {
                        return;
                    }
                    cardId = v.id;
                });
                return cardId;
            }
            static getMinLockedCardId() {
                let cardId = 0;
                mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                    if (mgrPlayer.getItemAmount(v.id) > 0 || !!cardId) {
                        return;
                    }
                    cardId = v.id;
                });
                return cardId;
            }
            static getStageProgress() {
                return this.stageProgress;
            }
            static getNewYearStageProgress() {
                return this.stageNewYearProgress;
            }
            static isSuccessedStage(stageId) {
                let bSuccess = this.stageDatas[stageId];
                return !!bSuccess;
            }
            static beginStage(stageId, bIgnoreConsume = false, backSceneName) {
                let stage = mgrCfg.get_from_amaze_card_stage_db(stageId);
                if (!stage) {
                    console.warn("mgrCard.beginStage stage not found!", stageId);
                    return;
                }
                mgrDirector.warpSceneWidthEffect(`vAmuseCardFightScene`, {
                    stageId: stageId,
                    backSceneName: backSceneName
                });
            }
            static getNewYearStageRoleUnlockItem(stageId) {
                let stage = mgrCfg.get_from_amaze_card_stage_db(stageId);
                if (!stage) {
                    console.warn("mgrCard.getNewYearStageRoleUnlockItem stage not found!", stageId);
                    return;
                }
                let newYearRoleId = mgrCard.getNewYearStageRewardConfig().roleId;
                let roleData = mgrCfg.get_from_role_db(newYearRoleId);
                if (!roleData) {
                    console.warn("mgrCard.getNewYearStageRoleUnlockItem newYearRole not found!", newYearRoleId);
                    return;
                }
                let itemId = roleData.unlockItemId;
                let amount = 1;
                if (itemId && amount) {
                    mgrPlayer.addItemAmount(itemId, amount, "新年关卡通关_看广告获得新年角色碎片");
                    this.stageFragmentGotMap[stageId] = true;
                }
                this.saveRecord();
            }
            static finishStage(stageId, bSuccess) {
                let stage = mgrCfg.get_from_amaze_card_stage_db(stageId);
                if (!stage) {
                    console.warn("mgrCard.finishStage stage not found!", stageId);
                    return;
                }
                if (!!bSuccess && stage.type == CARD_FIGHT_TYPE.base) {
                    this.stageProgress = stageId;
                    this.saveRecord();
                }
                let newYearRewards = null;
                if (!!bSuccess && stage.type == CARD_FIGHT_TYPE.newYear) {
                    if (stageId == 906 && !this.bPassAllNewYearStage) {
                        mgrSdk.statisCommonEvent(100001);
                        this.bPassAllNewYearStage = true;
                    }
                    if (this.stageNewYearProgress <= 906 && stageId > this.stageNewYearProgress) {
                        this.stageNewYearProgress = stageId;
                    }
                    this.saveRecord();
                    let rewards = this.getNewYearStageFirstPassReward(stageId);
                    let arr = [];
                    if (rewards && rewards.length > 0) {
                        for (let i = 0; i < rewards.length; i++) {
                            let data = rewards[i];
                            if (data.type == "part") {
                                if (mgrPlayer.getItemAmount(data.itemId) <= 0) {
                                    mgrPlayer.addItemAmount(data.itemId, data.amount, "新年关卡通关");
                                    arr.push(data);
                                }
                            }
                            else if (data.type == "roleUnlockItem") {
                                if (!this.stageFragmentGotMap[stageId]) {
                                    arr.push(data);
                                }
                            }
                        }
                    }
                    newYearRewards = arr;
                }
                this.stageDatas[stageId] = !!this.stageDatas[stageId] ? this.stageDatas[stageId] : bSuccess;
                let oldColorPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_CARD_FIGHT_PROGRESS_POINT);
                let rewardColorPoint = bSuccess ? stage.successRewardColorPoint : stage.faildRewardColorPoint;
                mgrPlayer.addItemAmount(Const.ITEM_ID_CARD_FIGHT_PROGRESS_POINT, rewardColorPoint, "卡牌战斗结算奖励");
                return {
                    stageId: stageId,
                    oldColorPoint: oldColorPoint,
                    currGotColorPoint: rewardColorPoint,
                    bSuccess: bSuccess,
                    newYearRewards: newYearRewards,
                };
            }
            static initNewYearStageFirstPassReward() {
                let newYearConfigData = mgrCfg.get_from_amuse_card_new_year_reward_config_db(2);
                let stagePartMapping = newYearConfigData.stagePartMapping;
                let stageUnlockItemAmountMapping = newYearConfigData.stageUnlockItemAmountMapping;
                let map = {};
                if (stagePartMapping && stagePartMapping.length > 0) {
                    for (let i = 0; i < stagePartMapping.length; i++) {
                        let mappingData = stagePartMapping[i];
                        if (!mappingData || !mappingData[0] || !mappingData[1]) {
                            continue;
                        }
                        let stageId = mappingData[0];
                        let partId = mappingData[1];
                        let stageData = mgrCfg.get_from_amaze_card_stage_db(stageId);
                        if (!stageData || stageData.type != CARD_FIGHT_TYPE.newYear) {
                            continue;
                        }
                        if (!partId) {
                            continue;
                        }
                        let partData = mgrCfg.get_from_part_db(partId);
                        if (!partData) {
                            continue;
                        }
                        if (!map[stageId]) {
                            map[stageId] = [];
                        }
                        map[stageId].push({ itemId: partId, amount: 1, type: "part" });
                    }
                }
                let configData = mgrCfg.get_from_amuse_card_new_year_reward_config_db(1);
                if (stageUnlockItemAmountMapping && stageUnlockItemAmountMapping.length > 0 && configData && configData.roleId) {
                    let roleData = mgrCfg.get_from_role_db(configData.roleId);
                    if (roleData && roleData.unlockItemId) {
                        let unlockItemId = roleData.unlockItemId;
                        for (let i = 0; i < stageUnlockItemAmountMapping.length; i++) {
                            let mappingData = stageUnlockItemAmountMapping[i];
                            if (!mappingData || !mappingData[0] || !mappingData[1]) {
                                continue;
                            }
                            let stageId = mappingData[0];
                            let unlockItemAmount = mappingData[1];
                            let stageData = mgrCfg.get_from_amaze_card_stage_db(stageId);
                            if (!stageData || stageData.type != CARD_FIGHT_TYPE.newYear) {
                                continue;
                            }
                            if (!unlockItemAmount || unlockItemAmount < 0) {
                                continue;
                            }
                            if (!map[stageId]) {
                                map[stageId] = [];
                            }
                            map[stageId].push({ itemId: unlockItemId, amount: unlockItemAmount, type: "roleUnlockItem" });
                        }
                    }
                }
                this.newYearCardStageFirstPassRewardsMap = map;
                console.log("initNewYearStageFirstPassReward--", map);
            }
            static getNewYearStageFirstPassReward(stageId) {
                let arr = [];
                if (!stageId) {
                    return arr;
                }
                let rewardInfoArr = this.newYearCardStageFirstPassRewardsMap[stageId];
                if (rewardInfoArr) {
                    arr = rewardInfoArr;
                }
                return arr;
            }
            static getNewYearStageRewardConfig() {
                let configData = mgrCfg.get_from_amuse_card_new_year_reward_config_db(1);
                let ret = {
                    suitId: null,
                    roleId: null,
                };
                if (!configData) {
                    return ret;
                }
                ret.suitId = configData.suitId;
                ret.roleId = configData.roleId;
                return ret;
            }
            static obtainRewardInSDK() {
                if (!this.bRewardInSDK) {
                    mgrSdk.statisCommonEvent(9090909);
                    this.bRewardInSDK = true;
                    this.saveRecord();
                }
            }
            static isUnlockedRecipeId(recipeId) {
                return !!this.unlockedPhotoRecipeDict[recipeId];
            }
            static isUnlockedStyleId(styleId) {
                return !!this.unlockedPhotoStyleDict[styleId];
            }
            static setUnlockedRecipeId(recipeId) {
                this.unlockedPhotoRecipeDict[recipeId] = true;
                this.saveRecord();
            }
            static setUnlockedStyleId(styleId) {
                this.unlockedPhotoStyleDict[styleId] = true;
                this.saveRecord();
            }
            static calculateRolePartIdsPower(roleId, partIds, bIgnoreTagPower) {
                let roleData = mgrCfg.get_from_role_db(roleId);
                return this.calculateRoleTagPartIdsPower(roleData.roleTagId, partIds, bIgnoreTagPower);
            }
            static calculateRoleTagPartIdsPower(roleTagId, partIds, bIgnoreTagPower) {
                let tagData = mgrCfg.get_from_part_tag_db(roleTagId);
                let power = !bIgnoreTagPower ? tagData.power : 0;
                for (let k in partIds) {
                    let partId = partIds[k];
                    let partData = mgrCfg.get_from_part_db(partId);
                    if (!partData) {
                        continue;
                    }
                    power += (partData[`score${roleTagId}`] || 0);
                }
                return power;
            }
            static calculateRolePartIdsHp(roleId, partIds) {
                let roleData = mgrCfg.get_from_role_db(roleId);
                let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                let hp = tagData.hp;
                return hp;
            }
            static calculateCardLevelStarByPower(power) {
                for (let i = 5; i >= 1; i--) {
                    let checkPower = this.CARD_POWER_2_LEVEL_STAR_DICT[i];
                    if (power >= checkPower) {
                        return i;
                    }
                }
                return 1;
            }
            static getNormalCardFightDailyLeftCount() {
                return Math.max(0, mgrPlayer.getItemAmount(1001));
            }
            static addNormalCardFightDailyUsedCount() {
                mgrPlayer.addItemAmount(1001, 1, "");
            }
        }
        mgrCard.stageDatas = {};
        mgrCard.stageFragmentGotMap = {};
        mgrCard.curSelectCard = [];
        mgrCard.unlockedPhotoRecipeDict = {};
        mgrCard.unlockedPhotoStyleDict = {};
        mgrCard.CARD_POWER_2_LEVEL_STAR_DICT = {
            [1]: 0,
            [2]: 150,
            [3]: 300,
            [4]: 450,
            [5]: 600,
        };
        mgrCard.tryingCardId = [];
        mgrCard.tempTryingCardInfoArr = [];
        mgrCard.newYearCardStageFirstPassRewardsMap = {};
        mgrCard.bPassAllNewYearStage = false;
        mgrCard.bRewardInSDK = false;

        class mgrOfflinePvp extends Manager {
            static onLoad() {
                this.setRandomDataCreator(() => {
                    let dataArr = mgrCfg.getDbArr("pvp_offline_role_power_base_db");
                    let cardNum = Tools.random(1, 5);
                    let role_db_arr = mgrCfg.getDbArr("role_db");
                    let roleIds = [];
                    role_db_arr.forEach(v => {
                        roleIds.push(v.id);
                    });
                    let randomRoleIds = Tools.randomGotArrayDatas(roleIds, cardNum);
                    let data = {};
                    for (let i = 0; i < randomRoleIds.length; i++) {
                        let roleId = randomRoleIds[i];
                        let pvpDatas = [];
                        dataArr.forEach(v => {
                            if (v.roleId == roleId) {
                                pvpDatas.push(v);
                            }
                        });
                        let selectPvpData = Tools.randomGotOneArrayData(pvpDatas);
                        if (selectPvpData) {
                            data[selectPvpData.roleId] = {
                                roleId: selectPvpData.roleId,
                                texture: selectPvpData.texture,
                                cardId: selectPvpData.cardId,
                                hp: Tools.random(selectPvpData.minHp, selectPvpData.maxHp),
                                power: Tools.random(selectPvpData.minPower, selectPvpData.maxPower),
                                cardPosIndex: i,
                                limitMaxPower: selectPvpData.limitMaxPower,
                            };
                        }
                    }
                    return data;
                });
                this.loadRecord();
                Timer.callLoop(60, () => {
                    this.tryUpdateRank();
                    this.refreshDailyData();
                }, this);
                this.tryUpdateRank();
                this.refreshDailyData();
                super.onLoad();
            }
            static loadRecord() {
                let record = mgrRecord.getData("offline_pvp") || {};
                this.pvpDatas = record.pvpDatas || [];
                this.bInit = record.bInit || false;
                this.totalLikeCount = record.totalLikeCount || 0;
                this.dailyLikedUidDict = record.dailyLikedUidDict || {};
                this.pvpPlayerInfo = record.pvpPlayerInfo || {};
                this.unlockedPhotoRecipeDict = record.unlockedPhotoRecipeDict || {};
                this.unlockedPhotoBgDict = record.unlockedPhotoBgDict || {};
                this.unlockedPhotoMaskDict = record.unlockedPhotoMaskDict || {};
            }
            static saveRecord() {
                let record = {
                    pvpDatas: this.pvpDatas,
                    bInit: this.bInit,
                    totalLikeCount: this.totalLikeCount,
                    dailyLikedUidDict: this.dailyLikedUidDict,
                    pvpPlayerInfo: this.pvpPlayerInfo,
                    unlockedPhotoRecipeDict: this.unlockedPhotoRecipeDict,
                    unlockedPhotoBgDict: this.unlockedPhotoBgDict,
                    unlockedPhotoMaskDict: this.unlockedPhotoMaskDict,
                };
                mgrRecord.setData("offline_pvp", record);
            }
            static refreshDailyData() {
                if (!Tools.isOneDay(Tools.time(), this._lastDailyRefreshTime)) {
                    this.dailyLikedUidDict = {};
                    this._lastDailyRefreshTime = Tools.time();
                    this.saveRecord();
                }
            }
            static getPlayerData() {
                let uid = mgrPlayer.getUid();
                for (let index = 0; index < this.pvpDatas.length; index++) {
                    const pvpData = this.pvpDatas[index];
                    if (pvpData.uid == uid) {
                        pvpData.rank = index + 1;
                        return pvpData;
                    }
                }
                return null;
            }
            static getPlayerPhotoInfo() {
                return this.pvpPlayerInfo;
            }
            static changePlayerName(name) {
                let playerData = this.getPlayerData();
                if (playerData) {
                    playerData.name = name;
                }
                this.saveRecord();
            }
            static getPvpDatas() {
                for (let index = 0; index < this.pvpDatas.length; index++) {
                    const pvpData = this.pvpDatas[index];
                    pvpData.rank = index + 1;
                }
                return ul.clone(this.pvpDatas);
            }
            static getPvpDataByUid(uid) {
                for (let index = 0; index < this.pvpDatas.length; index++) {
                    const pvpData = this.pvpDatas[index];
                    if (pvpData.uid == uid)
                        return pvpData;
                }
            }
            static updatePlayerUid(oldUid, newUid) {
                let pvpDatas = this.pvpDatas || [];
                for (let i = pvpDatas.length - 1; i >= 0; i--) {
                    let v = pvpDatas[i];
                    if (v.uid == oldUid) {
                        v.uid == newUid;
                    }
                }
                this.saveRecord();
            }
            static refreshPlayerData() {
                let totalPower = 0;
                let cardArr = mgrCard.getAllPlayerCardInfo();
                cardArr = Tools.sortArrayByField(cardArr, "-power");
                let arr = [];
                for (let i = 0; i < 5; i++) {
                    if (!cardArr[i]) {
                        continue;
                    }
                    arr.push(cardArr[i]);
                    totalPower += cardArr[i].power;
                }
                if (arr.length == 0) {
                    return;
                }
                let uid = mgrPlayer.getUid();
                let name = mgrPlayer.getName();
                let textureKey = arr[0].cardTextureKeyName;
                let pvpDatas = this.pvpDatas;
                for (let i = pvpDatas.length - 1; i >= 0; i--) {
                    let v = pvpDatas[i];
                    if (v && v.uid == uid) {
                        pvpDatas.splice(i, 1);
                        break;
                    }
                }
                this.pvpPlayerInfo = {
                    totalPower,
                    textureKey,
                };
                let datas = {};
                pvpDatas.push({
                    uid: uid,
                    datas: datas,
                    textureKey: textureKey,
                    texture: "",
                    name: name,
                    weight: 1,
                    score: totalPower || 0,
                    rank: 0,
                });
                this.pvpDatas = Tools.sortArrayByField(pvpDatas, "-score");
                this.saveRecord();
            }
            static buildRemainTimeStr(endTime) {
                let remainTime = endTime - Tools.time();
                if (remainTime <= 0) {
                    return "即将结束";
                }
                let days = Math.floor(remainTime / 24 / 60 / 60);
                if (days <= 0) {
                    let hours = Math.floor(remainTime / 60 / 60);
                    if (hours <= 0) {
                        return "即将结束";
                    }
                    return ul.format("%d小时", hours);
                }
                else {
                    let hours = Math.floor((remainTime - days * 24 * 60 * 60) / 60 / 60);
                    return ul.format("%d天%d小时", days, hours);
                }
            }
            static tryUpdateRank() {
                if (!this.bInit) {
                    this.startSeason();
                    return;
                }
                for (let i = 0; i < this.pvpDatas.length; i++) {
                    this.doRandomLike(5);
                }
                this.pvpDatas = Tools.sortArrayByField(this.pvpDatas, "-score");
                this.sendMsg(`MSG_PVP_RANK_UPDATE`);
            }
            static doRandomLike(count) {
                let data = Tools.roundTableProbability(this.pvpDatas, "weight");
                if (data.uid == mgrPlayer.getUid()) {
                    return;
                }
                let length = Tools.getObjSize(data.datas);
                let perAddScore = Math.ceil(count / length);
                let rScore = 0;
                for (let key in data.datas) {
                    let cardDatas = data.datas[key];
                    cardDatas.power += perAddScore;
                    if (cardDatas.power >= cardDatas.limitMaxPower) {
                        cardDatas.power = cardDatas.limitMaxPower;
                    }
                    rScore += cardDatas.power;
                }
                data.score = Math.max(data.score || 0, rScore);
            }
            static stopSeason() {
                this.pvpDatas = [];
                this.dailyLikedUidDict = {};
                this.saveRecord();
            }
            static startSeason() {
                this.stopSeason();
                this.bInit = true;
                let nowDate = new Date();
                let dayOfMonth = nowDate.getDate() - (nowDate.getDay() - 1);
                let beginTime = new Date();
                beginTime.setFullYear(nowDate.getFullYear(), nowDate.getMonth(), dayOfMonth);
                beginTime.getDate();
                let endTime = new Date();
                endTime.setFullYear(nowDate.getFullYear(), nowDate.getMonth(), dayOfMonth + 6);
                let config = mgrCfg.get_from_pvp_offline_db(1);
                let count = Tools.random(config.initCountMin, config.initCountMax);
                for (let i = 1; i <= count; i++) {
                    this.pvpDatas.push(this.createRandomData());
                }
                this.pvpDatas = Tools.sortArrayByField(this.pvpDatas, "-score");
                this.saveRecord();
            }
            static createRandomData() {
                let uid = ul.format("random_%06d", this.pvpDatas.length + 1);
                let name = this.createUniqueRandomName();
                let score = 0;
                let weight = 1;
                let datas;
                if (this.fRandomDataCreator) {
                    datas = this.fRandomDataCreator();
                }
                let totalPower = 0;
                let maxPower = 0;
                let texture = "";
                for (let key in datas) {
                    totalPower += datas[key].power;
                    if (datas[key].power > maxPower) {
                        maxPower = datas[key].power;
                        texture = datas[key].texture;
                    }
                }
                let player = {
                    datas,
                    uid: uid,
                    name: name,
                    textureKey: "",
                    texture,
                    score: totalPower,
                    rank: 0,
                    weight: weight,
                };
                return player;
            }
            static createUniqueRandomName() {
                let nameHash = {};
                for (let index = 0; index < this.pvpDatas.length; index++) {
                    const v = this.pvpDatas[index];
                    nameHash[v.name] = true;
                }
                for (let i = 1; i <= 1000; i++) {
                    let name = mgrPlayer.calcRandomName();
                    if (!nameHash[name]) {
                        return name;
                    }
                }
                return "jojo";
            }
            static getRandomSubject() {
                let db = mgrCfg.getDb("pvp_offline_subject_db");
                return db[Tools.random(db.length) - 1].name;
            }
            static getRandomSubjectId() {
                let db = mgrCfg.getDb("pvp_offline_subject_db");
                return db[Tools.random(db.length) - 1].id;
            }
            static setRandomDataCreator(creator) {
                this.fRandomDataCreator = creator;
            }
            static getRanomVoteCount() {
                if (Tools.time() - this.lastSummitTime > this.interval) {
                    this.lastSummitTime = Tools.time();
                    return 4;
                }
                return 1;
            }
        }
        mgrOfflinePvp.pvpDatas = [];
        mgrOfflinePvp.dailyLikedUidDict = {};
        mgrOfflinePvp.unlockedPhotoRecipeDict = {};
        mgrOfflinePvp.unlockedPhotoBgDict = {};
        mgrOfflinePvp.unlockedPhotoMaskDict = {};
        mgrOfflinePvp.lastSummitTime = 0;
        mgrOfflinePvp.interval = 60 * 5;

        class mgrWordFilter extends Manager {
            static onLoad() {
                super.onLoad();
                this._loadWords();
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static _loadWords() {
                if (!this.badwords) {
                    let badwords = mgrCfg.getDb("badword_db");
                    this._processBadwords(badwords);
                }
            }
            static _processBadwords(badwords) {
                this.badwords = badwords;
            }
            static checkStr(str) {
                return true;
                if (!str)
                    return true;
                let badwords = this.badwords;
                for (let i = 0; i < badwords.length; i++) {
                    if (str.match(badwords[i])) {
                        return false;
                    }
                }
                return true;
            }
            static filterStr(str, repStr) {
                repStr = repStr || this.REP_STR;
                let badwords = this.badwords;
                for (let i = 0; i < badwords.length; i++) {
                    str = str.replace(badwords[i], repStr);
                }
                return str;
            }
            static hasSymbol(str) {
                let ret = str.match(this.REP_NO_SYMBOL);
                if (ret)
                    return true;
                return false;
            }
            static filterSymbol(str) {
                if (!str)
                    return "";
                str = str.replace(this.REP_NO_SYMBOL, "");
                return str;
            }
        }
        mgrWordFilter.REP_STR = "**";
        mgrWordFilter.REP_NO_SYMBOL = /[\!\@\#\$\%\^\&\*\(\)\`\~\<\>\,\.\/\?\;\:\'\"\[\]\{\}\\\|\-\=\_\+\n\r\t\b ]/g;

        class mgrPlayer extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("mgrPlayer.onLoad", this._playerName);
                this.loadRecord();
                Timer.callLoop(1, this.onTimerLoop.bind(this), true);
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("player") || {};
                this._playerName = record.playerName || "";
                this._items = record.items || {};
                this._recoverCostTimes = record.recoverCostTimes || {};
                this._lastDailyRefreshTime = record.lastDailyRefreshTime || 0;
                this.uid = record.uid;
                this.curAvatarPartIds = record.curAvatarPartIds;
                this.matchAvatarPartIds = record.matchAvatarPartIds;
                this.bRenamePlayerName = record.bRenamePlayerName;
                this.dailyDressedLuckyPartIdDict = record.dailyDressedLuckyPartIdDict || {};
                this.dailyDressedLuckyPartCount = record.dailyDressedLuckyPartCount || 0;
                this._beginGameTime = record.beginGameTime;
                if (!this._beginGameTime) {
                    this._beginGameTime = Tools.time();
                    this.saveRecord();
                }
                let items = this._items;
                mgrCfg.forDb("item_template_db", (k, v) => {
                    const itemId = v.id;
                    if (items[itemId] == null) {
                        items[itemId] = v.defaultAmount;
                    }
                });
                this.refreshDailyData();
                this.refreshRecoverItem();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    playerName: this._playerName,
                    items: this._items,
                    lastDailyRefreshTime: this._lastDailyRefreshTime,
                    recoverCostTimes: this._recoverCostTimes,
                    uid: this.uid,
                    beginGameTime: this._beginGameTime,
                    curAvatarPartIds: this.curAvatarPartIds,
                    matchAvatarPartIds: this.matchAvatarPartIds,
                    bRenamePlayerName: this.bRenamePlayerName,
                    dailyDressedLuckyPartIdDict: this.dailyDressedLuckyPartIdDict,
                    dailyDressedLuckyPartCount: this.dailyDressedLuckyPartCount,
                };
                mgrRecord.setData("player", record);
            }
            static onTimerLoop() {
                this.refreshDailyData();
                this.refreshRecoverItem();
            }
            static tryAdaptDouyingMaterial() {
                if (mgrSdk.getCopNumberValueByKey("b_douying_material_version") == 1) {
                    let items = this._items;
                    items[1] = 1000000;
                    mgrGuide.bDebugCloseGuide = true;
                    Timer.callLater(0.5, () => {
                        let lockedRolePartIdDict = {};
                        mgrCfg.forDb_from_role_db((k, v) => {
                            if (v && v.gameResVersion && !mgrGameResVersion.isValidGameResVersion(v.gameResVersion)) {
                                for (let k in v.partIds) {
                                    let partId = v.partIds[k];
                                    lockedRolePartIdDict[partId] = true;
                                }
                                return;
                            }
                            items[v.id] = 1;
                        });
                        mgrCfg.forDb_from_part_db((k, v) => {
                            if (!!lockedRolePartIdDict[v.id]) {
                                return;
                            }
                            items[v.id] = 1;
                        });
                        let dbArr = [
                            "cake_cream_color_db",
                            "cake_shape_db",
                            "cake_paint_color_db",
                            "cake_deco_db",
                            "cake_sticker_db",
                            "design_part_color_db",
                            "design_grid_db",
                            "design_shine_db",
                            "amuse_card_style_db",
                            "amuse_card_photo_recipe_db"
                        ];
                        for (let i = 0; i < dbArr.length; i++) {
                            let db = mgrCfg.getDb(dbArr[i]);
                            for (let k in db) {
                                let v = db[k];
                                if (v && v.gameResVersion && !mgrGameResVersion.isValidGameResVersion(v.gameResVersion)) {
                                    continue;
                                }
                                items[v.id] = 1;
                            }
                        }
                    }, this);
                }
            }
            static getName() {
                if (!this._playerName) {
                    this._playerName = this.calcRandomName();
                }
                return this._playerName;
            }
            static setName(playerName) {
                this._playerName = playerName;
                this.bRenamePlayerName = true;
                mgrOfflinePvp.changePlayerName(playerName);
                this.saveRecord();
                this.sendMsg("MSG_PLAYER_NAME_CHANGED");
            }
            static getUid() {
                return this.uid;
            }
            static setUid(uid) {
                this.uid = uid;
            }
            static getItemAmount(itemId) {
                return this._items[itemId] || 0;
            }
            static _setItemAmount(itemId, amount) {
                if (itemId == null || amount == null) {
                    console.warn("警告] mgrPlayer.setItemAmount arg is wrong!", itemId, amount);
                    return;
                }
                let originAmount = this.getItemAmount(itemId);
                if (originAmount == amount)
                    return;
                this._items[itemId] = Math.max(amount, 0);
                this.lastItemsCount[itemId] = originAmount;
                let data = {
                    itemId: itemId,
                    amountDelta: amount - originAmount,
                };
                this.sendMsg("MSG_ITEM_AMOUNT_CHANGED", data);
                this.saveRecord();
            }
            static getLastItemAmount(itemId) {
                return this.lastItemsCount[itemId] || this.getItemAmount(itemId);
            }
            static getRepeatSellCount(itemId, bAutoClean = true) {
                let amount = this.repeatSellItems[itemId] || 0;
                if (bAutoClean) {
                    this.repeatSellItems[itemId] = 0;
                }
                return amount;
            }
            static addItemAmount(itemId, amountDelta, reason) {
                if (itemId == null || amountDelta == null) {
                    console.warn("警告] mgrPlayer.addItemAmount arg is wrong!", itemId, amountDelta);
                    return [0, 0];
                }
                if (amountDelta > 0) {
                    let itemData = mgrCfg.get("item_template_db", itemId);
                    if (!itemData) {
                        console.warn("警告] mgrPlayer.addItemAmount itemId 不存在! itemId: ", itemId);
                        return [0, 0];
                    }
                    if (itemData.sellItemId && itemData.sellItemId != 0) {
                        if (this.getItemAmount(itemId) >= 1) {
                            amountDelta = itemData.sellItemAmount * amountDelta;
                            this.repeatSellItems[itemId] = amountDelta;
                            itemId = itemData.sellItemId;
                        }
                    }
                }
                let originAmount = this.getItemAmount(itemId);
                this._setItemAmount(itemId, originAmount + amountDelta);
                let idReason = "0";
                let db = mgrCfg.getDb("item_change_point_event_db");
                for (let k in db) {
                    let value = db[k];
                    if (value.desc == reason && value.pointEventId) {
                        idReason = value.pointEventId;
                        break;
                    }
                }
                mgrSdk.statisOnAddItemAmount(itemId, amountDelta, idReason);
                return [itemId, amountDelta];
            }
            static refreshDailyData() {
                if (!Tools.isOneDay(Tools.time(), this._lastDailyRefreshTime)) {
                    this._lastDailyRefreshTime = Tools.time();
                    this.dailyDressedLuckyPartIdDict = {};
                    this.saveRecord();
                }
            }
            static refreshRecoverItem() {
                let now = Tools.time();
                mgrCfg.forDb("item_recover_db", (k, recoverData) => {
                    const itemId = recoverData.id;
                    let amount = this.getItemAmount(itemId);
                    let maxAmount = this.getRecoverMaxAmount(itemId);
                    let costTime = this._getRecoverCostTime(itemId);
                    let recoverCount = 0;
                    if (recoverData.mode == 1) {
                        if (maxAmount <= amount) {
                            if (costTime != 0) {
                                this._setRecoverCostTime(itemId, 0);
                            }
                            return;
                        }
                        if (now < costTime) {
                            costTime = now;
                            this._setRecoverCostTime(itemId, costTime);
                        }
                        if (costTime <= 0) {
                            if (maxAmount <= amount) {
                                return;
                            }
                            else {
                                costTime = now;
                                this._setRecoverCostTime(itemId, costTime);
                            }
                        }
                        let deltaTime = now - costTime;
                        let recoverTime = this._getRecoverTime(itemId);
                        recoverCount = Math.floor(deltaTime / recoverTime);
                        if (recoverCount <= 0) {
                            return;
                        }
                        costTime += recoverTime * recoverCount;
                    }
                    else if (recoverData.mode == 2) {
                        if (costTime <= 0) {
                            this._setRecoverCostTime(itemId, now);
                            return;
                        }
                        if (Tools.isOneDay(now, costTime)) {
                            return;
                        }
                        else {
                            recoverCount = 1;
                            costTime = now;
                        }
                    }
                    else {
                        console.warn("警告] mgrPlayer.refreshRecoverItem 未知mode", recoverData.mode);
                        return;
                    }
                    let recoverAmount = this._getRecoverAmount(itemId) * recoverCount;
                    amount += recoverAmount;
                    if (maxAmount <= amount) {
                        amount = Math.min(amount, maxAmount);
                        costTime = 0;
                    }
                    this._setItemAmount(itemId, amount);
                    this._setRecoverCostTime(itemId, costTime);
                });
            }
            static getRecoverMaxAmount(itemId) {
                let recoverData = mgrCfg.get("item_recover_db", itemId);
                if (recoverData.maxAmountRefItemId != 0) {
                    return this.getItemAmount(recoverData.maxAmountRefItemId);
                }
                else {
                    return recoverData.maxAmount;
                }
            }
            static getRecoverTime(itemId) {
                return this._getRecoverTime(itemId);
            }
            static _getRecoverTime(itemId) {
                let recoverTime = mgrCfg.get("item_recover_db", itemId, "recoverTime");
                return recoverTime;
            }
            static _getRecoverAmount(itemId) {
                let recoverData = mgrCfg.get_from_item_recover_db(itemId);
                ;
                if (!!recoverData.recoverCopValue) {
                    return mgrSdk.getCopNumberValueByKey(recoverData.recoverCopValue);
                }
                else {
                    return recoverData.recoverAmount;
                }
            }
            static _getRecoverCostTime(itemId) {
                return this._recoverCostTimes[itemId] || 0;
            }
            static _setRecoverCostTime(itemId, costTime) {
                this._recoverCostTimes[itemId] = costTime;
                this.saveRecord();
            }
            static getRecoverRemainTime(itemId) {
                let recoverData = mgrCfg.get("item_recover_db", itemId);
                if (recoverData.mode == 1) {
                    let costTime = this._getRecoverCostTime(itemId);
                    if (costTime <= 0)
                        return null;
                    let now = Tools.time();
                    let deltaTime = now - costTime;
                    let recoverTime = this._getRecoverTime(itemId);
                    if (recoverTime < deltaTime)
                        return 0;
                    return recoverTime - deltaTime;
                }
                else if (recoverData.mode == 2) {
                    let amount = this.getItemAmount(itemId);
                    let maxAmount = this.getRecoverMaxAmount(itemId);
                    if (amount >= maxAmount)
                        return null;
                    let date = new Date();
                    date.setDate(date.getDate() + 1);
                    date.setHours(0);
                    date.setMinutes(0);
                    date.setSeconds(0);
                    return (date.getTime() / 1000) - Tools.time();
                }
                else {
                    console.warn("警告] mgrPlayer.refreshRecoverItem 未知mode", recoverData.mode);
                    return null;
                }
            }
            static getIcon(itemId) {
                itemId = itemId || 0;
                let item = mgrCfg.get("item_template_db", itemId);
                if (!item || item.icon == "") {
                    console.warn("-------无此物品id=", itemId);
                    return "res/icon/unknown.png";
                }
                else {
                    return item.icon;
                }
            }
            static getFlag(itemId) {
                if (!itemId) {
                    return 0;
                }
                let item = mgrCfg.get("item_template_db", itemId);
                if (!item) {
                    return 0;
                }
                return item.flag;
            }
            static getBoxItems(boxId) {
                if (!boxId) {
                    return [];
                }
                let boxData = mgrCfg.get("item_box_db", boxId);
                if (!boxData) {
                    return [];
                }
                let result = [];
                for (let i = 0; i < boxData.items.length; i++) {
                    const v = boxData.items[i];
                    result.push([v.itemId, v.minAmount, v.maxAmount]);
                }
                return result;
            }
            static getBoxItemIdDictionary(boxId) {
                let itemIdDict = {};
                let result = this.getBoxItems(boxId);
                for (let k in result) {
                    let data = result[k];
                    if (data[0]) {
                        itemIdDict[data[0]] = data[0];
                    }
                }
                return itemIdDict;
            }
            static openItemBox(boxId) {
                if (!boxId) {
                    return [];
                }
                let boxData = mgrCfg.get("item_box_db", boxId);
                return this.openItemBoxByBoxData(boxData);
            }
            static openItemBoxByBoxData(boxData) {
                if (!boxData) {
                    return [];
                }
                let result = [];
                let useTriggerRatio = boxData.triggerRatio;
                if (useTriggerRatio < 10000 && Tools.random(10000) > useTriggerRatio) {
                    return result;
                }
                let ratioType = boxData.ratioType;
                let items = ul.clone(boxData.items);
                for (let i = 0; i < items.length; i++) {
                    const v = items[i];
                    if (v.bNoRepeat) {
                        if (this.getItemAmount(v.itemId) > 0) {
                            v.ratio = 0;
                        }
                    }
                }
                if (ratioType == 1) {
                    for (let i = 0; i < items.length; i++) {
                        const v = items[i];
                        let useRatio = v.ratio;
                        if (useRatio >= 10000 || Tools.random(10000) <= useRatio) {
                            let amount = Tools.random(v.minAmount, v.maxAmount);
                            result.push([v.itemId, amount]);
                        }
                    }
                }
                else if (ratioType == 2) {
                    let v = Tools.calcWheelTarget(items, "ratio");
                    if (v) {
                        let amount = Tools.random(v.minAmount, v.maxAmount);
                        result.push([v.itemId, amount]);
                    }
                }
                else if (ratioType == 3) {
                    for (let i = 0; i < items.length; i++) {
                        const v = items[i];
                        let amount = Tools.random(v.minAmount, v.maxAmount);
                        result.push([v.itemId, amount]);
                    }
                }
                return result;
            }
            static calcRandomName() {
                let part1 = [];
                let part2 = [];
                let part3 = [];
                mgrCfg.forDb_from_random_name_db((k, v) => {
                    part1.push({ word: v.word1 });
                    part2.push({ word: v.word2 });
                    part3.push({ word: v.word3 });
                });
                let name = "";
                for (let i = 0; i < 1000; i++) {
                    let randomName = part1[Tools.random(part1.length) - 1].word + part2[Tools.random(part2.length) - 1].word + part3[Tools.random(part3.length) - 1].word;
                    if (!mgrWordFilter.hasSymbol(randomName) && mgrWordFilter.checkStr(randomName)) {
                        name = randomName;
                        break;
                    }
                }
                return name;
            }
            static getBeginGameTime() {
                return this._beginGameTime;
            }
            static getItemAmountStr(amount) {
                let info = this.getItemAmountInfo(amount);
                let info2 = this.getItemAmountInfo(Math.floor(info.amount));
                return `${info2.amount}${info2.unit}${info.unit}`;
            }
            static getItemAmountInfo(amount) {
                let goldAmount = amount || 0;
                let value = 0;
                let unit = "";
                if (goldAmount < 100000) {
                    value = goldAmount;
                }
                else {
                    let flag1 = goldAmount / 100000000;
                    let flag2 = goldAmount / 10000;
                    let flag3 = goldAmount;
                    let useAmount = 0;
                    let flagStr = "";
                    if (flag1 >= 1) {
                        let value = Math.floor(flag1);
                        if (value < 100) {
                            useAmount = Math.floor(flag1 * 100) / 100;
                        }
                        else if (value < 1000) {
                            useAmount = Math.floor(flag1 * 10) / 10;
                        }
                        else {
                            useAmount = value;
                        }
                        flagStr = "亿";
                    }
                    else if (flag2 >= 1) {
                        let value = Math.floor(flag2);
                        if (value < 100) {
                            useAmount = Math.floor(flag2 * 100) / 100;
                        }
                        else if (value < 1000) {
                            useAmount = Math.floor(flag2 * 10) / 10;
                        }
                        else {
                            useAmount = value;
                        }
                        flagStr = "万";
                    }
                    else if (flag3 >= 1) {
                        useAmount = flag3;
                        flagStr = "";
                    }
                    else {
                        useAmount = goldAmount;
                    }
                    value = useAmount;
                    unit = flagStr;
                }
                return { amount: value, unit: unit };
            }
            static getAdDiamonAmount() {
                return 400;
            }
            static getBascRewardGold() {
                return 100;
            }
            static tryAppendAdGotItemTip(bForce, fOnClose) {
                if (!bForce && !mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward)) {
                    return false;
                }
                let baseRewardGold = Math.ceil(this.getBascRewardGold() * 60 * 10);
                mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, baseRewardGold, null, { extrnalRewardAdEventId: AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward, fOnClose: fOnClose });
                mgrAd.markFinished(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward);
                return true;
            }
            static tryGotAdGotExternalAmount() {
                if (!mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward)) {
                    return 0;
                }
                return this.gotAdGotExternalAmount();
            }
            static gotAdGotExternalAmount() {
                return 200;
            }
            static isDailyDressedLuckyPartId(partId) {
                return !!this.dailyDressedLuckyPartIdDict[partId];
            }
            static addDailyDressedLuckyPartIds(partIds) {
                for (let k in partIds) {
                    let partId = partIds[k];
                    this.dailyDressedLuckyPartIdDict[partId] = true;
                }
                this.dailyDressedLuckyPartCount++;
                this.saveRecord();
            }
            static getDailyDressedLuckyPartCount() {
                return this.dailyDressedLuckyPartCount || 0;
            }
        }
        mgrPlayer._items = {};
        mgrPlayer._playerName = "";
        mgrPlayer._lastDailyRefreshTime = null;
        mgrPlayer._recoverCostTimes = {};
        mgrPlayer._beginGameTime = 0;
        mgrPlayer.lastItemsCount = {};
        mgrPlayer.repeatSellItems = {};
        mgrPlayer.dailyDressedLuckyPartIdDict = {};
        mgrPlayer.dailyDressedLuckyPartCount = 0;

        var ChannelName;
        (function (ChannelName) {
            ChannelName["toutiao"] = "toutiao";
            ChannelName["douyin"] = "douyin";
            ChannelName["baidu"] = "baidu";
            ChannelName["oppo"] = "oppoqg";
            ChannelName["funheadline"] = "funheadline";
            ChannelName["game4399"] = "4399minigame";
            ChannelName["huawei"] = "huawei";
            ChannelName["iqiyi"] = "iqiyi";
            ChannelName["kaixin"] = "kaixin";
            ChannelName["qq"] = "qq";
            ChannelName["weixin"] = "weixin";
            ChannelName["xiaomi"] = "xiaomiqg";
            ChannelName["uc"] = "uc";
            ChannelName["vivo"] = "vivo";
            ChannelName["debug"] = "debug";
        })(ChannelName || (ChannelName = {}));
        ;
        const FindMeBgUrl = {
            [ChannelName.toutiao]: "2d/ui/bg/findme_toutiao",
            [ChannelName.douyin]: "2d/ui/bg/findme_douyin",
            [ChannelName.weixin]: "2d/ui/bg/findme_weixin",
        };
        const shareImgUrl = {
            [ChannelName.toutiao]: [
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/headline1.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/headline2.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/headline3.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/headline4.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/headline5.jpg",
            ],
            [ChannelName.weixin]: [
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/weixin1.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/weixin2.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/weixin3.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/weixin4.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/weixin5.jpg",
            ],
            [ChannelName.qq]: [
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/qq1.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/qq2.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/qq3.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/qq4.jpg",
                "https://gamesres.ultralisk.cn/notice/sharegames/game69/qq5.jpg",
            ]
        };
        const RewardShareCount = 10;
        const RewardVideoShareCount = 10;
        class mgrChannel extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.registerListeners({
                    MSG_SDK_SHARE_RESULT: this.onMsgShareResult,
                    MSG_SDK_INSTALL_SHORTCUT_RESULT: this.onMsgSdkInstallShortCutResult,
                    MSG_SDK_GET_SHORTCUT_STATE_RESULT: this.onMsgSdkGetShortcutStateResult,
                    MSG_SDK_APP_SHARE_RESULT: this.onMsgSdkAppShareResult,
                    MSG_SDK_WX_GZH_ENTER: this.onMsgWxgzhEnter,
                    MSG_ON_ADD_SUBSCRIBE_RESULT: this.onMsgSdkAddSubscribeResult,
                    MSG_SDK_JUMP_OTHER_GAME_REWARD_RESULT: this.onMsgJumpOtherGameRewardResult.bind(this),
                    MSG_SDK_CHANNEL_INFO_RESULT: this.onMsgChannelInfoResult.bind(this),
                    MSG_SDK_COP_INFO_RESULT: this.onMsgCopInfoResult.bind(this),
                    MSG_SDK_ADD_GAME_TO_MY_FAVORITE_RESULT: this.onMsgSdkAddGameToMyFavoriteResult.bind(this)
                });
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("channel") || {};
                this._userOpenVideoRecord = record._userOpenVideoRecord || true;
                this._isGetWxgzhReward = record._isGetWxgzhReward || false;
                this.bTakedInstallShortCut = record.bTakedInstallShortCut || false;
                this.subscribeOutOfTheTime = record.subscribeOutOfTheTime || 0;
                this.dailyVideoShareMistakeCount = record.dailyVideoShareMistakeCount || 0;
                this.dailyVideoAdMistakeCount = record.dailyVideoAdMistakeCount || 0;
                this.lastRefreshTime = record.lastRefreshTime || 0;
                this.videoShareLastShareTime = record.videoShareLastShareTime || 0;
                this.bInstalledMyFavorite = record.bInstalledMyFavorite || false;
                let curDate = new Date();
                if (this.subscribeOutOfTheTime != 0 && curDate.getTime() > this.subscribeOutOfTheTime) {
                    mgrPlayer._setItemAmount(60, 0);
                }
                this.dailyRefresh();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    _userOpenVideoRecord: this._userOpenVideoRecord,
                    _isGetWxgzhReward: this._isGetWxgzhReward,
                    bTakedInstallShortCut: this.bTakedInstallShortCut,
                    subscribeOutOfTheTime: this.subscribeOutOfTheTime,
                    dailyVideoShareMistakeCount: this.dailyVideoShareMistakeCount,
                    dailyVideoAdMistakeCount: this.dailyVideoAdMistakeCount,
                    lastRefreshTime: this.lastRefreshTime,
                    videoShareLastShareTime: this.videoShareLastShareTime,
                    bInstalledMyFavorite: this.bInstalledMyFavorite,
                };
                mgrRecord.setData("channel", record);
            }
            static dailyRefresh() {
                if (!Tools.isOneDay(this.lastRefreshTime, Tools.time())) {
                    this.lastRefreshTime = Tools.time();
                    this.dailyVideoShareMistakeCount = 0;
                    this.dailyVideoAdMistakeCount = 0;
                    this.bTipedMyFavorite = false;
                    this.saveRecord();
                }
            }
            static setChannelName(name) {
                this._channelName = name || ChannelName.debug;
            }
            static isChannel4399() {
                return this._channelName == ChannelName.game4399;
            }
            static isChannelBaidu() {
                return this._channelName == ChannelName.baidu;
            }
            static isChannelFunHeadline() {
                return this._channelName == ChannelName.funheadline;
            }
            static isChannelHeadline() {
                return this.isChannelPlatformToutiao();
            }
            static isChannelPlatformToutiao() {
                return this._channelName == ChannelName.toutiao;
            }
            static isChannelPlatformDouyin() {
                return this._channelName == ChannelName.douyin;
            }
            static isChannelIqiyi() {
                return this._channelName == ChannelName.iqiyi;
            }
            static isChannelKaixin() {
                return this._channelName == ChannelName.kaixin;
            }
            static isChannelOppo() {
                return this._channelName == ChannelName.oppo;
            }
            static isChannelQQ() {
                return this._channelName == ChannelName.qq;
            }
            static isChannelVivo() {
                return this._channelName == ChannelName.vivo;
            }
            static isChannelWeixin() {
                return this._channelName == ChannelName.weixin;
            }
            static isChannelXiaomi() {
                return this._channelName == ChannelName.xiaomi;
            }
            static isChannelUc() {
                return this._channelName == ChannelName.uc;
            }
            static isChannelHuawei() {
                return this._channelName == ChannelName.huawei;
            }
            static canGameInterPush() {
                return true;
            }
            static canGameInterPushMoreGame() {
                return (this.canGameInterPush() || this._isMoreGame || this._isULMoreGame) && mgrSdk.getCopNumberValueByKey("b_more_game") == 1;
            }
            static canGameInterPushRewardMoreGame() {
                return this.canGameInterPush() && mgrSdk.getCopNumberValueByKey("b_reward_more_game") == 1;
            }
            static setInterPushConfig(jumpInfo) {
                let interPushConfig = [];
                for (let index = 0; index < jumpInfo.length; index++) {
                    let info = jumpInfo[index];
                    if (info) {
                        interPushConfig.push({
                            gameId: info.index,
                            url: info.url,
                        });
                    }
                }
                this.interPushConfig = interPushConfig;
            }
            static getInterPushConfig() {
                let config = this.interPushConfig || [];
                return config;
            }
            static canShowAdH5() {
                return this.isChannelFunHeadline();
            }
            static canShowFindMe() {
                return !!FindMeBgUrl[this._channelName] && this._isSupportFindMinigames;
            }
            static getFindMeImage() {
                return FindMeBgUrl[this._channelName];
            }
            static canAddToMyFavorite() {
                return this.isChannelBaidu();
            }
            static takeWxgzhReward() {
                this._isNeedAlertWxgzhReward = false;
                this._isGetWxgzhReward = true;
                let count = RewardVideoShareCount;
                mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, count, "微信公众号奖励");
                mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, count);
                this.saveRecord();
                return count;
            }
            static isNeedAlertWxgzh() {
                return this._isNeedAlertWxgzhReward;
            }
            static onMsgWxgzhEnter(data) {
                let bInit = data.bInit;
                if (bInit) {
                    if (!this._isGetWxgzhReward) {
                        this._isNeedAlertWxgzhReward = true;
                    }
                }
                else {
                    if (!this._isGetWxgzhReward) {
                        this.takeWxgzhReward();
                    }
                }
            }
            static onMsgSdkAddSubscribeResult(data) {
                let subRewards = mgrCfg.get_from_shop_template_db(101);
                subRewards.items.forEach(v => {
                    mgrPlayer.addItemAmount(v[0], v[1], "每日订阅奖励");
                    if (v[2] !== 1) {
                        mgrTip.addGotItemTip(v[0], v[1]);
                    }
                });
                let date = new Date();
                date.setDate(date.getDate() + 1);
                date.setHours(18);
                date.setMinutes(0);
                date.setSeconds(0);
                date.setMilliseconds(0);
                this.subscribeOutOfTheTime = date.getTime();
                this.saveRecord();
            }
            static setUserOpenVideoRecord(isOpen) {
                this._userOpenVideoRecord = !!isOpen;
                this.saveRecord();
            }
            static getUserOpenVideoRecord() {
                return this._userOpenVideoRecord;
            }
            static haveVideoRecord() {
                return mgrSdk.getCopByKey("b_record_video") == "1" && mgrChannel._isSupportRecordShare;
            }
            static isOpenPay() {
                return this._isPayEnabled;
            }
            static canShare() {
                let bCop = mgrSdk.getCopNumberValueByKey("b_share") == 1;
                return (!mgrGuide.isGuiding() && bCop && mgrChannel._isShareEnabled);
            }
            static onMsgShareResult(e) {
                let data = e;
                let bSuccessful = data.bSuccessful;
                if (bSuccessful) {
                    Timer.callLater(3, () => {
                        mgrTip.showMsgTip("分享成功");
                        let count = this.getShareRewardAmount();
                        if (mgrPlayer.getItemAmount(Const.ITEM_ID_SHARE_COUNT) > 0) {
                            mgrPlayer.addItemAmount(Const.ITEM_ID_SHARE_COUNT, -1, "分享成功");
                            mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, count, "分享成功");
                            mgrTip.addGotItemTipGroup([{
                                    itemId: Const.ITEM_ID_DIAMONDS,
                                    amount: count,
                                    amountSteps: []
                                }]);
                            this.sendMsg(`MSG_SHARE_SUCCESSFUL`);
                        }
                    });
                }
                else {
                    mgrTip.showMsgTip("分享失败");
                }
            }
            static getInstallShortCutRewardCount() {
                return 50;
            }
            static isTakedInstallShortCutReward() {
                return this.bTakedInstallShortCut;
            }
            static onMsgSdkInstallShortCutResult(e) {
                let code = e.code || 0;
                let msg = e.msg || "";
                if (!!msg) {
                    mgrTip.showMsgTip(msg);
                }
                if (this.bTakedInstallShortCut) {
                    return;
                }
                if (code == 1 || code == 2) {
                    this.bTakedInstallShortCut = true;
                    this.saveRecord();
                    let count = this.getInstallShortCutRewardCount();
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, count, "添加到桌面快捷方式奖励");
                    mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, count);
                    this.sendMsg("MSG_SDK_INSTALL_SHORT_CUT_SUC");
                }
            }
            static onMsgSdkGetShortcutStateResult(e) {
                let data = e;
                let state = data.state;
                let bHasPrompt = !!data.bHasPrompt;
                this._isSupportInstallShortcut = state == 1;
                this._isInstallShortcutHasPrompt = bHasPrompt;
            }
            static tryInviteVote() {
            }
            static getShareImgUrlByIndex(idx) {
                let urls = shareImgUrl[this._channelName] || [];
                return urls[idx];
            }
            static getShareRewardAmount(bIgnoreCount) {
                if (!bIgnoreCount) {
                    if (mgrPlayer.getItemAmount(Const.ITEM_ID_SHARE_COUNT) <= 0)
                        return 0;
                }
                if (!this.canShare())
                    return 0;
                return RewardShareCount;
            }
            static getRecordRewardAmount(bIgnoreCount) {
                if (!bIgnoreCount) {
                    if (mgrPlayer.getItemAmount(Const.ITEM_ID_VIDEO_SHARE_COUNT) <= 0)
                        return 0;
                }
                return RewardVideoShareCount;
            }
            static onMsgSdkAppShareResult(data) {
                if (data.bSuccessful) {
                    mgrTip.showMsgTip("分享成功!!!");
                }
            }
            static onMsgJumpOtherGameRewardResult(e) {
                let rewards = e.rewards;
                if (rewards.length && rewards.length >= 1) {
                    let rewardId = rewards[0][0];
                    let rewardCount = rewards[0][1];
                    mgrPlayer.addItemAmount(rewardId, rewardCount, "激励互推");
                    mgrTip.addGotItemTip(rewardId, rewardCount);
                }
                else {
                    console.error("onMsgJumpOtherGameRewardResult no rewards:", rewards);
                }
            }
            static checkInstallShortCut() {
                return this._isSupportInstallShortcut && !this.bTakedInstallShortCut;
            }
            static tipInstallShortCut() {
                if (this._isSupportInstallShortcut && !this.bTakedInstallShortCut) {
                    this.bTipedInstallShortCut = true;
                    if (!this._isInstallShortcutHasPrompt) {
                        mgrDirector.openDialog("vDesktopIconDilaog");
                    }
                    else {
                        mgrSdk.installShortcut();
                    }
                    return true;
                }
                return false;
            }
            static tipAddMyFavorite() {
                if (!this.bInstalledMyFavorite && !this.bTipedMyFavorite) {
                    this.bTipedMyFavorite = true;
                    mgrSdk.addGameToMyFavorite();
                }
            }
            static onMsgChannelInfoResult() {
                this.refreshGameResVersion();
            }
            static onMsgCopInfoResult() {
                this.refreshGameResVersion();
            }
            static refreshGameResVersion() {
                if (mgrSdk.getCopNumberValueByKey("game_res_open_time") && (new Date().getTime() / 1000) >= mgrSdk.getCopNumberValueByKey("game_res_open_time")) {
                    let gameResVersion = mgrSdk.getCopNumberValueByKey("game_res_version");
                    mgrPlayer._setItemAmount(998, gameResVersion);
                }
            }
            static onMsgSdkAddGameToMyFavoriteResult(e) {
                this.bInstalledMyFavorite = (e && e.bSuccessful) ? true : false;
                this.saveRecord();
            }
        }
        mgrChannel._userOpenVideoRecord = true;
        mgrChannel._isGetWxgzhReward = false;
        mgrChannel._isNeedAlertWxgzhReward = false;
        mgrChannel.bTakedInstallShortCut = false;
        mgrChannel.bTipedInstallShortCut = false;
        mgrChannel._isThirdExit = false;
        mgrChannel._isAbout = false;
        mgrChannel._isMoreGame = false;
        mgrChannel._isULMoreGame = false;
        mgrChannel._isPayEnabled = false;
        mgrChannel._isShareEnabled = false;
        mgrChannel._isUseSdkRank = false;
        mgrChannel._channelName = ChannelName.debug;
        mgrChannel._isShowUrlAdIcon = false;
        mgrChannel._isSupportRecordShare = false;
        mgrChannel._isSupportClipboardData = false;
        mgrChannel._isSupportInstallShortcut = false;
        mgrChannel._isInstallShortcutHasPrompt = false;
        mgrChannel.interPushConfig = [];
        mgrChannel._isSupportFindMinigames = false;
        mgrChannel._isSupportRecommendationBtn = false;
        mgrChannel._isJumpLeisureEnabled = false;
        mgrChannel._isSupportSubscribe = false;
        mgrChannel._isSupportChannelMoreGameBox = false;
        mgrChannel.subscribeOutOfTheTime = 0;
        mgrChannel.lastAutoPopSubscribeDialogTimeFromHub = 0;
        mgrChannel.lastAutoPopSubscribeDialogTimeFromRest = 0;
        mgrChannel.dailyVideoShareMistakeCount = 0;
        mgrChannel.dailyVideoAdMistakeCount = 0;
        mgrChannel.lastRefreshTime = 0;
        mgrChannel.videoShareLastShareTime = 0;
        mgrChannel.findmeImageUrl = "";
        mgrChannel._isSupportFollowOfficialAccount = false;
        mgrChannel.isSupportGridAd = false;
        mgrChannel.isSupportJumpInfoVideoType = false;

        class mgrDebug extends Manager {
            static onLoad() {
                super.onLoad();
                this.registerKeyboardListener();
                this.registerListeners({
                    MSG_SHOW_POINT_DEBUG_INFO: this.onMsgShowPointDebugInfo.bind(this),
                });
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static onKeyDown(keyDesc) {
                console.log(keyDesc);
                switch (keyDesc) {
                    case "ctrl_b":
                        console.log("--------------------------------------------");
                        console.log("--------------------------------------------");
                        console.log("--------------------------------------------");
                        console.log("number_1-----------cf.distance += 0.05");
                        console.log("number_2-----------cf.distance -= 0.05");
                        console.log("number_3-----------");
                        console.log("number_4-----------");
                        console.log("number_5-----------");
                        console.log("number_6-----------");
                        console.log("number_7-----------cf.fov += 1");
                        console.log("number_8-----------cf.fov -= 1");
                        console.log("number_9-----------");
                        console.log("number_0-----------");
                        console.log("--------------------------------------------");
                        console.log("left-----------cf.endRotation.y += 1");
                        console.log("right-----------cf.endRotation.y -= 1");
                        console.log("up-----------cf.endRotation.x += 1");
                        console.log("down-----------cf.endRotation.x -= 1");
                        console.log("--------------------------------------------");
                        console.log("cf.lookMode=targetDistance----【i】--------cf.offset.y += 0.05");
                        console.log("cf.lookMode=targetDistance----【k】--------cf.offset.y -= 0.05");
                        console.log("cf.lookMode=targetDistance----【j】--------cf.offset.x -= 0.05");
                        console.log("cf.lookMode=targetDistance----【l】--------cf.offset.x += 0.05");
                        console.log("--------------------------------------------");
                        console.log("cf.lookMode=fixMode----【i】--------cf.position.y += 0.05");
                        console.log("cf.lookMode=fixMode----【k】--------cf.position.y -= 0.05");
                        console.log("cf.lookMode=fixMode----【j】--------cf.position.x -= 0.05");
                        console.log("cf.lookMode=fixMode----【l】--------cf.position.x += 0.05");
                        console.log("cf.lookMode=fixMode----【u】--------cf.position.z += 0.05");
                        console.log("cf.lookMode=fixMode----【o】--------cf.position.z -= 0.05");
                        console.log("--------------------------------------------");
                        console.log("cf.lookMode=targetPosition----【i】--------cf.position.y += 0.05");
                        console.log("cf.lookMode=targetPosition----【k】--------cf.position.y -= 0.05");
                        console.log("cf.lookMode=targetPosition----【j】--------cf.position.x -= 0.05");
                        console.log("cf.lookMode=targetPosition----【l】--------cf.position.x += 0.05");
                        console.log("cf.lookMode=targetPosition----【u】--------cf.position.z += 0.05");
                        console.log("cf.lookMode=targetPosition----【o】--------cf.position.z -= 0.05");
                        console.log("--------------------------------------------");
                        console.log("--------------------------------------------");
                        console.log("--------------------------------------------");
                        break;
                    case "ctrl_i":
                        mgrDirector.openDialog(`vTestDialog`);
                        break;
                        break;
                    case "ctrl_y":
                        break;
                    case "ctrl_g":
                        mgrGuide.endGuide();
                        break;
                    case "ctrl_s":
                        break;
                    case "ctrl_number_1":
                        break;
                    case "ctrl_number_2":
                        mgrDirector.openDialog(`vAdSuitDialog`);
                        break;
                    case "ctrl_3":
                        break;
                    case "ctrl_4":
                        break;
                    case "ctrl_number_7":
                        break;
                    case "ctrl_number_8":
                        break;
                }
                this.sendMsg("MSG_DEBUG_KEY_DOWN", keyDesc);
            }
            static onMsgShowPointDebugInfo(e) {
                this.bShowStatisticsInfo = !!e.state;
                if (this.bShowStatisticsInfo) {
                    if (!this.uiTipInfoDialog) {
                        let dialogName = "vEditorUiTipInfoDialog";
                        let className = Const.require.requireModule(dialogName);
                        if (!className) {
                            mgrTip.showMsgTip(`没有找到:${dialogName}`);
                            return;
                        }
                        let view = new className({});
                        view.name = dialogName;
                        view.openDialog(true);
                        this.uiTipInfoDialog = view;
                    }
                }
                else {
                    if (!!this.uiTipInfoDialog && !this.uiTipInfoDialog.destroyed) {
                        this.uiTipInfoDialog.closeDialog(true);
                        this.uiTipInfoDialog = null;
                    }
                }
            }
            static registerKeyboardListener() {
                Laya.stage.on(Laya.Event.KEY_DOWN, this, this.onSystemKeyDown);
                Laya.stage.on(Laya.Event.KEY_UP, this, this.onSystemKeyUp);
            }
            static onSystemKeyDown(e) {
                if (!Laya.Browser.onPC) {
                    return;
                }
                let keyCode = e.keyCode;
                switch (keyCode) {
                    case Laya.Keyboard.ALTERNATE:
                        this.bPressedAlt = true;
                        break;
                    case Laya.Keyboard.CONTROL:
                        this.bPressedCtrl = true;
                        break;
                    case Laya.Keyboard.SHIFT:
                        this.bPressedShift = true;
                        break;
                    case Laya.Keyboard.E:
                        mgrDirector.openDialog("vAdGetMoreUnlockItemDialog", {
                            roleId: 110,
                            amount: 1,
                            stageId: 901,
                            fOnCloseDialog: () => { },
                        });
                        break;
                    default:
                        let keyDesc = this._genKeyDesc(keyCode);
                        this.onKeyDown(keyDesc);
                        break;
                }
            }
            static onSystemKeyUp(e) {
                if (!Laya.Browser.onPC) {
                    return;
                }
                let keyCode = e["keyCode"];
                switch (keyCode) {
                    case Laya.Keyboard.ALTERNATE:
                        this.bPressedAlt = false;
                        break;
                    case Laya.Keyboard.CONTROL:
                        this.bPressedCtrl = false;
                        break;
                    case Laya.Keyboard.SHIFT:
                        this.bPressedShift = false;
                        break;
                    default:
                        let keyDesc = this._genKeyDesc(keyCode);
                        this.sendMsg("MSG_DEBUG_KEY_UP", keyDesc);
                        break;
                }
            }
            static _genKeyDesc(keyCode) {
                let text = "";
                if (this.bPressedCtrl)
                    text += "ctrl_";
                if (this.bPressedAlt)
                    text += "alt_";
                if (this.bPressedShift)
                    text += "shift_";
                for (const key in Laya.Keyboard) {
                    const v = Laya.Keyboard[key];
                    if (v == keyCode.toString()) {
                        text += key.toLowerCase();
                        break;
                    }
                }
                return text;
            }
        }
        mgrDebug.bPressedCtrl = false;
        mgrDebug.bPressedAlt = false;
        mgrDebug.bPressedShift = false;
        mgrDebug.bUnlockAllStage = false;
        mgrDebug.bShowDevButton = false;
        mgrDebug.bShowStatisticsInfo = false;

        class CustomTween {
            constructor() {
                this.tweenList = [];
            }
            static to(node, props, duration, ease = Laya.Ease.linearNone) {
                let tween = new CustomTween();
                tween._node = node;
                tween.to(props, duration, ease);
                return tween;
            }
            static from(node, props, duration, ease = Laya.Ease.linearNone) {
                let tween = new CustomTween();
                tween._node = node;
                tween.from(props, duration, ease);
                return tween;
            }
            static delayTime(node, duration) {
                let tween = new CustomTween();
                tween._node = node;
                tween.delayTime(duration);
                return tween;
            }
            static scaleForever(node, scale1, scale2, duration, ease = Laya.Ease.linearNone) {
                let tween = CustomTween.to(node, { scaleX: scale1, scaleY: scale1 }, duration)
                    .to({ scaleX: scale2, scaleY: scale2 }, duration)
                    .start(0);
                return tween;
            }
            static roke(node, range = 5, speed = 200, interval = 1500, count = 0) {
                let tween = CustomTween.to(node, { rotation: range }, speed / 2)
                    .to({ rotation: -range }, speed)
                    .to({ rotation: range }, speed)
                    .to({ rotation: 0 }, speed / 2)
                    .to({ rotation: 0 }, interval)
                    .start(count);
                return tween;
            }
            static rotateForever(node, duration = 5000, bClockwise = true) {
                let tween = CustomTween.to(node, { rotation: 360 * (bClockwise ? 1 : -1) }, duration)
                    .callback(() => { node.rotation = 0; })
                    .start(0);
                return tween;
            }
            static actionFloat(node, startValue, endValue, duration, callback, ease = Laya.Ease.linearNone) {
                let tween = new CustomTween();
                tween._node = node;
                tween.actionFloat(startValue, endValue, duration, callback, ease);
                return tween;
            }
            static bezierCurveMotion(pos1, pos2, pos3, node, duration, bGolbal = false) {
                let tween = new CustomTween();
                tween._node = node;
                tween.bezierCurveMotion(pos1, pos2, pos3, duration, bGolbal);
                return tween;
            }
            static heartBeat(node) {
                let scaleFactor1 = 1.1;
                let scaleFactor2 = 1.15;
                return CustomTween.to(node, { scaleX: node.scaleX * scaleFactor1, scaleY: node.scaleY * scaleFactor1 }, 100)
                    .to({ scaleX: node.scaleX, scaleY: node.scaleY }, 100)
                    .delayTime(50)
                    .to({ scaleX: node.scaleX * scaleFactor2, scaleY: node.scaleY * scaleFactor2 }, 100)
                    .to({ scaleX: node.scaleX, scaleY: node.scaleY }, 100)
                    .delayTime(1300)
                    .start(0);
            }
            static jumpTo(node, wPos, scale, duration = 300, endCallback) {
                let posX = node.x;
                let posY = node.y;
                let endPoint = node.parent.globalToLocal(wPos);
                let centerPos = new Laya.Vector2((posX + endPoint.x) / 2, (posY + endPoint.y) / 2 - 400);
                CustomTween.bezierCurveMotion(new Laya.Vector2(posX, posY), centerPos, endPoint, node, duration)
                    .start(1);
                return CustomTween.to(node, { scaleX: scale, scaleY: scale }, duration, Laya.Ease.sineOut)
                    .callback(() => {
                    endCallback && endCallback();
                })
                    .start(1);
            }
            to(props, duration, ease = Laya.Ease.linearNone) {
                let _tween = () => {
                    this._curTween = Laya.Tween.to(this._node, props, duration, ease, new Laya.Handler(this, this._onComplete.bind(this)), 0, true, true);
                };
                this.tweenList.push(_tween);
                return this;
            }
            from(props, duration, ease = Laya.Ease.linearNone) {
                let _tween = () => {
                    this._curTween = Laya.Tween.from(this._node, props, duration, ease, new Laya.Handler(this, this._onComplete.bind(this)), 0, true, true);
                };
                this.tweenList.push(_tween);
                return this;
            }
            callback(f) {
                let _tween = () => {
                    f();
                    this._onComplete();
                };
                this.tweenList.push(_tween);
                return this;
            }
            delayTime(duration) {
                this._node[`__delay_time__`] = 0;
                this.to({ __delay_time__: duration }, duration);
                return this;
            }
            bezierCurveMotion(pos1, pos2, pos3, duration, bGolbal = false) {
                if (bGolbal) {
                    pos1 = this._node.parent[`globalToLocal`](pos1);
                    pos2 = this._node.parent[`globalToLocal`](pos2);
                    pos3 = this._node.parent[`globalToLocal`](pos3);
                }
                let _tween = () => {
                    let interval = 0;
                    duration = duration / 1000;
                    Timer.callLoop(0.016, (timer) => {
                        let f = interval / duration;
                        let cp1x = pos1.x * (1 - f) + pos2.x * f;
                        let cp1y = pos1.y * (1 - f) + pos2.y * f;
                        let cp2x = pos2.x * (1 - f) + pos3.x * f;
                        let cp2y = pos2.y * (1 - f) + pos3.y * f;
                        let x = cp1x * (1 - f) + cp2x * f;
                        let y = cp1y * (1 - f) + cp2y * f;
                        this._node.x = x;
                        this._node.y = y;
                        interval += Tools.delta();
                        if (interval >= duration) {
                            this._node.x = pos3.x;
                            this._node.y = pos3.y;
                            timer.stop();
                            this._onComplete();
                        }
                    }, this._node);
                };
                this.tweenList.push(_tween);
                return this;
            }
            static bezierCurveMotionV3(pos1, pos2, pos3, duration, progresscallback, endCallback) {
                let interval = 0;
                duration = duration / 1000;
                Timer.callLoop(0.016, (timer) => {
                    let f = interval / duration;
                    let cp1x = pos1.x * (1 - f) + pos2.x * f;
                    let cp1y = pos1.y * (1 - f) + pos2.y * f;
                    let cp1z = pos1.z * (1 - f) + pos2.z * f;
                    let cp2x = pos2.x * (1 - f) + pos3.x * f;
                    let cp2y = pos2.y * (1 - f) + pos3.y * f;
                    let cp2z = pos2.z * (1 - f) + pos3.z * f;
                    let x = cp1x * (1 - f) + cp2x * f;
                    let y = cp1y * (1 - f) + cp2y * f;
                    let z = cp1z * (1 - f) + cp2z * f;
                    progresscallback(new Laya.Vector3(x, y, z));
                    interval += Tools.delta();
                    if (interval >= duration) {
                        timer.stop();
                        endCallback && endCallback();
                    }
                });
            }
            actionFloat(startValue, endValue, duration, callback, ease = Laya.Ease.linearNone) {
                let tween = () => {
                    this._node["__action_float_value"] = startValue;
                    this._onComplete();
                };
                let actionFloat = () => {
                    callback(this._node["__action_float_value"]);
                };
                this.tweenList.push(tween);
                this.to({ __action_float_value: endValue, update: new Laya.Handler(this._node, actionFloat) }, duration, ease);
                return this;
            }
            repeat(count) {
                let repeatTweens = [];
                for (let i = 1; i < count; i++) {
                    for (let index = 0; index < this.tweenList.length; index++) {
                        const element = this.tweenList[index];
                        repeatTweens.push(element);
                    }
                }
                this.tweenList = this.tweenList.concat(repeatTweens);
                return this;
            }
            start(repeatCount = 1) {
                this.repeatCount = repeatCount;
                this._curIndex = -1;
                this._count = 0;
                this._onComplete();
                return this;
            }
            _onComplete() {
                if (!this._node || this._node[`destroyed`] || (this._node.owner && this._node.owner.destroyed)) {
                    return;
                }
                this._curIndex++;
                if (this.tweenList[this._curIndex]) {
                    this.tweenList[this._curIndex].call(this);
                }
                else {
                    this._count++;
                    if (this.repeatCount == 0 || this._count < this.repeatCount) {
                        this._curIndex = this._curIndex % this.tweenList.length;
                        this.tweenList[this._curIndex] && this.tweenList[this._curIndex].call(this);
                    }
                }
            }
            stop() {
                this.clear();
            }
            resume() {
            }
            clear() {
                this.tweenList = [];
            }
        }

        class ScaleButton extends Laya.Script {
            constructor() {
                super();
                this.bTween = true;
                this.bTouchBegin = false;
                this.bPlaySoundEffect = true;
            }
            get __node() {
                return this.owner;
            }
            static setSoundPlayId(soundId) {
                this.generalSoundId = soundId;
            }
            onEnable() {
            }
            onMouseDown(e) {
                this.bTouchBegin = true;
                this.onTouchBegin(e);
            }
            onMouseUp(e) {
                this.bTouchBegin = false;
                this.onTouchEnd(e);
            }
            onMouseOut(e) {
                if (!this.bTouchBegin)
                    return;
                this.bTouchBegin = false;
                this.onTouchCancle(e);
            }
            onClick(e) {
                if (this.fOnClick instanceof Function) {
                    this.fOnClick(e);
                }
                if (ScaleButton.generalSoundId && this.bPlaySoundEffect)
                    mgrSound.play(ScaleButton.generalSoundId);
            }
            onTouchBegin(e) {
                if (!this.bTween)
                    return;
                Laya.Tween.to(this.owner, { scaleX: 1.1, scaleY: 1.1 }, 50);
            }
            onTouchEnd(e) {
                this.onTouchCancle(e);
            }
            onTouchCancle(e) {
                if (!this.bTween)
                    return;
                Laya.Tween.to(this.owner, { scaleX: 1, scaleY: 1 }, 50, Laya.Ease.backOut);
            }
            clearTween() {
                Laya.Tween.clearAll(this.owner);
            }
        }

        class vJumpOtherGameNode extends Laya.Box {
            constructor() {
                super();
                this.msgHander = null;
                this.JUMP_TYPE = "single";
                this.msgHander = new MsgHandler();
                this.size(124 * 0.7, 160 * 0.7);
                this.anchorX = 0.5;
                this.anchorY = 0.5;
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                });
                this.image = this.addChild(new Laya.Image);
                this.image.size(this.width, this.height);
                this.image.anchorX = 0.5;
                this.image.anchorY = 0.5;
                this.image.pos(this.width / 2, this.height / 2);
                mgrSdk.openJump(Const.gameIndex, this.JUMP_TYPE);
                CustomTween.delayTime(this, 1000)
                    .to({ rotation: 5 }, 200 / 2)
                    .to({ rotation: -5 }, 200)
                    .to({ rotation: 5 }, 200)
                    .to({ rotation: 0 }, 200 / 2)
                    .delayTime(1000)
                    .callback(() => {
                    if (this.visible && this.parent[`visible`]) {
                        mgrSdk.openJump(Const.gameIndex, this.JUMP_TYPE);
                    }
                })
                    .start(0);
                this.button = this.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButtonIcon.bind(this);
            }
            destroy(destroyChild) {
                this.msgHander.stopProcMsg();
                super.destroy(destroyChild);
            }
            registerListeners(listeners) {
                this.msgHander.registerListeners(listeners);
                this.msgHander.startProcMsg();
            }
            sendMsg(msgName, data) {
                this.msgHander.sendMsg(msgName, data);
            }
            fillData(datas) {
                this.datas = datas;
                Tools.loadImg(this.image, datas[0].url);
            }
            onMsgOpenJumpResult(e) {
                if (this.destroyed || !this.image || this.image.destroyed) {
                    return;
                }
                if (e.type == this.JUMP_TYPE) {
                    let datas = e.jumpInfo;
                    this.fillData(datas);
                }
            }
            onTouchButtonIcon() {
                if (!this.datas)
                    return;
                mgrSdk.jumpOtherGame(this.datas[0].index, this.JUMP_TYPE);
            }
        }

        class ULCheckBox extends Laya.Script {
            constructor() {
                super();
                this.__bCheck = true;
            }
            get __node() {
                return this.owner;
            }
            get bCheck() {
                return this.__bCheck;
            }
            set bCheck(value) {
                this.__bCheck = value;
                this.refresh();
            }
            refresh() {
                if (!this.gou) {
                    this.gou = this.__node.getChildAt(0);
                }
                this.gou.visible = this.bCheck;
            }
            onStart() {
                this.refresh();
                Tools.registerTouchHander(this.__node, (e) => {
                    if (e.isClick) {
                        this.bCheck = !this.bCheck;
                        if (this.changeCallback)
                            this.changeCallback();
                    }
                });
            }
        }

        var ULPROGRESSBAR_STYLE;
        (function (ULPROGRESSBAR_STYLE) {
            ULPROGRESSBAR_STYLE[ULPROGRESSBAR_STYLE["hor"] = 1] = "hor";
            ULPROGRESSBAR_STYLE[ULPROGRESSBAR_STYLE["ver"] = 2] = "ver";
            ULPROGRESSBAR_STYLE[ULPROGRESSBAR_STYLE["fan"] = 3] = "fan";
        })(ULPROGRESSBAR_STYLE || (ULPROGRESSBAR_STYLE = {}));
        class ULProgressBar extends Laya.Script {
            constructor() {
                super();
                this.__startAngle = -90;
                this.__progress = 0;
                this.__style = ULPROGRESSBAR_STYLE.hor;
            }
            get __node() {
                return this.owner;
            }
            get progress() {
                return this.__progress;
            }
            set progress(value) {
                value = Math.max(0.00001, Math.min(1.0, value));
                this.__progress = value;
                try {
                    this.refresh();
                }
                catch (error) {
                    console.log(error);
                }
            }
            get style() {
                return this.__style;
            }
            set style(value) {
                this.__style = value;
            }
            set barName(name) {
                this.__barName = name;
                this.bar = this.__node.getChildByName(name);
                if (!this.bar && this.__node.name == name) {
                    this.bar = this.__node;
                }
                if (this.bar) {
                    this.__originWidth = this.bar.width;
                    this.__originHeight = this.bar.height;
                }
            }
            get barName() {
                return this.__barName;
            }
            set startAngle(value) {
                this.__startAngle = value;
            }
            get startAngle() {
                return this.__startAngle;
            }
            progressTweenTo(dur, targetProgress, startProgress, delayTime, callback, progressCallback) {
                delayTime = delayTime || 0;
                startProgress = startProgress || this.progress;
                let offset = targetProgress - startProgress;
                let doLerpPosFunc = (percent) => {
                    this.progress = startProgress + offset * percent;
                    progressCallback && progressCallback(this.progress);
                };
                let startTime = null;
                dur = dur || 0.1;
                Timer.callLoop(0.016, (timer) => {
                    delayTime -= 0.016;
                    if (delayTime > 0) {
                        return;
                    }
                    startTime = startTime || Tools.time();
                    let passTime = Tools.time() - startTime;
                    if (passTime >= dur) {
                        doLerpPosFunc(1);
                        timer.stop();
                        callback && callback();
                        return;
                    }
                    doLerpPosFunc(passTime / dur);
                }, this);
            }
            refresh() {
                if (!this.bar || this.__originWidth == 0 || this.__originWidth == 0) {
                    this.bar = this.__node.getChildAt(0);
                    this.__originWidth = this.bar.width;
                    this.__originHeight = this.bar.height;
                }
                if (!this.bar || this.__originWidth == 0 || this.__originWidth == 0)
                    return;
                let widthPersent = 1.0;
                let heightPersent = 1.0;
                let fanPersent = 1.0;
                if (this.__style == ULPROGRESSBAR_STYLE.hor) {
                    widthPersent = this.progress;
                }
                else if (this.__style == ULPROGRESSBAR_STYLE.ver) {
                    heightPersent = this.progress;
                }
                else if (this.__style == ULPROGRESSBAR_STYLE.fan) {
                    fanPersent = this.progress;
                }
                if (!this.mask) {
                    this.mask = new Laya.Sprite;
                    this.bar.mask = this.mask;
                }
                this.mask.graphics.clear();
                if (this.__style == ULPROGRESSBAR_STYLE.fan) {
                    this.mask.graphics.drawPie(this.bar.width / 2, this.bar.height / 2, this.bar.width / 2, this.startAngle, this.startAngle + 360 * fanPersent, `#ffffff`);
                }
                else if (this.__style == ULPROGRESSBAR_STYLE.ver || this.__style == ULPROGRESSBAR_STYLE.hor) {
                    let width = this.__originWidth * widthPersent;
                    let height = this.__originHeight * heightPersent;
                    let x = 0;
                    let y = this.__originHeight - height;
                    this.mask.graphics.drawRect(x, y, width + 1, height + 1, `#ffffff`);
                }
            }
            onUpdate() {
            }
        }

        class ReuseListItem extends Laya.Box {
            constructor() {
                super();
                this.onInit();
            }
            onInit() { }
            fillByData(data) { }
            onSelect(data) { }
        }

        class TaskManager {
            constructor(progressUpdateCallback) {
                this.taskList = [];
                this.curProgress = 0;
                this.totalProgress = 0;
                this.progressUpdateCallback = progressUpdateCallback;
            }
            push(taskSamples) {
                taskSamples = ul.clone(taskSamples);
                if (!taskSamples || taskSamples.length <= 0)
                    return;
                this.totalProgress += taskSamples.length;
                this.taskList.push(taskSamples);
            }
            start(executeFinishCallback) {
                this.executeFinishCallback = executeFinishCallback;
                this.__goNext();
            }
            __goNext() {
                if (this.taskList.length > 0) {
                    let taskSamples = this.taskList.shift();
                    let finishCount = 0;
                    for (let index = 0; index < taskSamples.length; index++) {
                        const taskSample = taskSamples[index];
                        taskSample(() => {
                            finishCount++;
                            this.curProgress++;
                            if (this.progressUpdateCallback instanceof Function) {
                                this.progressUpdateCallback(this.curProgress, this.totalProgress);
                            }
                            if (finishCount == taskSamples.length)
                                this.__goNext();
                        });
                    }
                }
                else {
                    if (this.executeFinishCallback instanceof Function) {
                        this.executeFinishCallback();
                    }
                }
            }
        }

        class ViewBase extends ReuseListItem {
            constructor(context) {
                super();
                this.msgHander = null;
                this.sourceName = null;
                this.exportNodeNames = null;
                this.nodeResource = null;
                this.__saved_prefab_instance = {};
                this.needUpdateFrontEffect = [];
                this.needUpdateMiddleEffect = [];
                this.linkedModels = [];
                this.anchorX = 0.5;
                this.anchorY = 0.5;
                this.pos(0, 0);
                this.context = context || {};
                this.msgHander = new MsgHandler();
                Timer.callLater(0.016, () => {
                    if (!this.sourceName) {
                        Timer.callLater(0.001, () => {
                            this.__bLoaded = true;
                            this.onOpened();
                            this.__bOpened = true;
                            if (this.context.fOnLoadingFinished)
                                this.context.fOnLoadingFinished();
                        }, true);
                        return;
                    }
                    ;
                    mgrLoader.Load2dRes(this.sourceName, Laya.Loader.PREFAB, this, (prefab) => {
                        if (!this.__saved_prefab_instance[this.sourceName]) {
                            this.__saved_prefab_instance[this.sourceName] = prefab.create();
                        }
                        let res = prefab.create();
                        this.nodeResource = res;
                        this.nodeResource.alpha = 0;
                        this.size(this.nodeResource.width, this.nodeResource.height);
                        this.pivotX = this.width / 2;
                        this.pivotY = this.height / 2;
                        this.nodeResource.anchorX = 0.5;
                        this.nodeResource.anchorY = 0.5;
                        this.nodeResource.pivotX = this.nodeResource.width / 2;
                        this.nodeResource.pivotY = this.nodeResource.height / 2;
                        this.addChild(this.nodeResource);
                        this.nodeResource.pos(this.width / 2, this.height / 2);
                        let allChilds = this.getAllChildList(this.nodeResource);
                        Timer.callLoop(0.016, (timer) => {
                            if (!this.isAllChildResLoaded(allChilds))
                                return;
                            allChilds = this.getAllChildList(this.nodeResource);
                            if (!this.isAllChildResLoaded(allChilds))
                                return;
                            timer.stop();
                            this.tryHandleMethodCallStatics();
                            this.handlePresetNodeInChildren(allChilds);
                            this.isAllExtraResourceLoaded(() => {
                                this.tryShowStatisticsInfo();
                                Timer.callLater(0.016, () => {
                                    this.__bLoaded = true;
                                    this.onOpened();
                                    this.__bOpened = true;
                                    this.customWait(() => {
                                        if (this.nodeResource && !this.nodeResource.destroyed) {
                                            this.nodeResource.alpha = 1;
                                        }
                                        if (this.context.fOnLoadingFinished)
                                            this.context.fOnLoadingFinished();
                                    });
                                }, this);
                            });
                        }, this);
                    });
                });
            }
            handlePresetNodeInChildren(allChilds) {
                this.exportNodeNames = this.exportNodeNames || [];
                for (let index = 0; index < allChilds.length; index++) {
                    const child = allChilds[index];
                    if (child.name && child.name.startsWith("CC_")) {
                        let vName = child.name.replace("CC_", "");
                        if (/button/.test(vName)) {
                            let button = child.addComponent(ScaleButton);
                            this[vName] = button;
                            let eventName = `onTouch${vName.replace(vName[0], vName[0].toUpperCase())}`;
                            if (this[eventName]) {
                                button.fOnClick = () => {
                                    if (!mgrDebug.bShowStatisticsInfo) {
                                        this.staticsButtonClick(vName);
                                        this[eventName].bind(this)();
                                    }
                                    else {
                                        this.tryTipButtonStatisticsInfo(vName);
                                        mgrTip.showLoadingTip("__viewbase_show_statistics_info_loading");
                                        Timer.callLater(2, () => {
                                            mgrTip.hideLoadingTip("__viewbase_show_statistics_info_loading");
                                            this.staticsButtonClick(vName);
                                            this[eventName].bind(this)();
                                        }, this);
                                    }
                                };
                            }
                        }
                        else if (/progressbar/i.test(vName.toLocaleLowerCase())) {
                            let progressBar = child.addComponent(ULProgressBar);
                            this[vName] = progressBar;
                        }
                        else if (/checkBox/i.test(vName)) {
                            let checkBox = child.addComponent(ULCheckBox);
                            this[vName] = checkBox;
                        }
                        else {
                            this[vName] = child;
                        }
                        this.exportNodeNames.push(vName);
                    }
                }
            }
            getAllChildList(root) {
                let nodes = [];
                for (let i = 0; i < root.numChildren; i++) {
                    let child = root.getChildAt(i);
                    nodes.push(child);
                    let childNodes = this.getAllChildList(child);
                    nodes = nodes.concat(childNodes);
                }
                return nodes;
            }
            isAllChildResLoaded(allChilds) {
                for (let index = 0; index < allChilds.length; index++) {
                    const child = allChilds[index];
                    if (child[`_texture`] && !child[`_texture`][`_bitmap`])
                        return false;
                    if (child instanceof Laya.Image) {
                        if (child.skin && (child.width + child.height) == 0)
                            return false;
                    }
                }
                return true;
            }
            isAllExtraResourceLoaded(finishedCallback) {
                let modelIds = this.getPreLoadModelIds();
                let taskManager = new TaskManager();
                let taskSamples = [];
                for (let i = 0; i < modelIds.length; i++) {
                    const modelId = modelIds[i];
                    taskSamples.push((endCallback) => {
                        mgrLoader.loadModeWithModeId(modelId, () => {
                            endCallback();
                        }, this, 1);
                    });
                }
                let animationIds = this.getPreLoadAnimationIds();
                for (let i = 0; i < animationIds.length; i++) {
                    const animationId = animationIds[i];
                    let animationData = mgrCfg.get_from_animation_db(animationId);
                    if (!animationData) {
                        console.warn("isAllExtraResourceLoaded没有对应的动画数据animationId=", animationId);
                        continue;
                    }
                    taskSamples.push((endCallback) => {
                        Laya.AnimationClip.load(animationData.path, new Laya.Handler(this, (clip) => {
                            endCallback();
                        }));
                    });
                }
                let imagePaths = this.getPreLoadImagePaths();
                for (let i = 0; i < imagePaths.length; i++) {
                    const path = imagePaths[i];
                    taskSamples.push((endCallback) => {
                        mgrLoader.Load2dRes(path, Laya.Loader.IMAGE, this, (res) => {
                            endCallback();
                        });
                    });
                }
                taskManager.push(taskSamples);
                taskManager.start(() => {
                    finishedCallback();
                });
            }
            staticsButtonClick(buttonName) {
                if (!this[buttonName]) {
                    console.log("-----当前没有此按钮--buttonName=", buttonName);
                    return;
                }
                if (mgrSdk.getCopNumberValueByKey("b_statistics_button_click") != 1) {
                    return;
                }
                if (this.sourceName) {
                    let viewName = this.sourceName.substr(this.sourceName.lastIndexOf("/") + 1, 100);
                    let buttonPointDataArr = mgrCfg.get("ui_button_click_point_event_db", viewName, buttonName);
                    if (buttonPointDataArr && buttonPointDataArr.length > 0) {
                        let doBtnStatistics = (buttonPointData) => {
                            if (!!buttonPointData && buttonPointData.selfPointEventId) {
                                let userParams = [];
                                for (let i = 1; i <= 10; i++) {
                                    let fieldName = buttonPointData["followContextFiled" + i];
                                    let fieldValue = this.context[fieldName] || this[fieldName] || (!!this["data"] && this["data"][fieldName]) || "";
                                    if (!fieldName || fieldName == "") {
                                        break;
                                    }
                                    userParams.push(fieldValue);
                                }
                                mgrSdk.statisCommonEvent(buttonPointData.selfPointEventId, null, null, null, userParams);
                            }
                        };
                        if (buttonPointDataArr.length == 1) {
                            doBtnStatistics(buttonPointDataArr[0]);
                        }
                        else {
                            let baseSceneName = mgrDirector.getCur2DSceneName();
                            if (baseSceneName && baseSceneName != "") {
                                for (let k in buttonPointDataArr) {
                                    let buttonPointData = buttonPointDataArr[k];
                                    if (buttonPointData.parentViewName == baseSceneName) {
                                        doBtnStatistics(buttonPointData);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            tryTipButtonStatisticsInfo(buttonName) {
                if (!this[buttonName]) {
                    console.log("-----当前没有此按钮--buttonName=", buttonName);
                    return;
                }
                if (this.sourceName) {
                    let viewName = this.sourceName.substr(this.sourceName.lastIndexOf("/") + 1, 100);
                    let buttonPointDataArr = mgrCfg.get("ui_button_click_point_event_db", viewName, buttonName);
                    if (buttonPointDataArr && buttonPointDataArr.length > 0) {
                        let doBtnStatistics = (buttonPointData) => {
                            if (!!buttonPointData && buttonPointData.selfPointEventId) {
                                let str = `${buttonPointData.selfPointEventId}`;
                                for (let i = 1; i <= 10; i++) {
                                    let fieldName = buttonPointData["followContextFiled" + i];
                                    let fieldValue = this.context[fieldName] || this[fieldName] || (!!this["data"] && this["data"][fieldName]) || "";
                                    let fieldNameDesc = buttonPointData["followContextFiled" + i + "Desc"];
                                    if (!fieldName || fieldName == "") {
                                        break;
                                    }
                                    str += `${fieldNameDesc}=${fieldValue}@`;
                                }
                                mgrTip.showMsgTip(str);
                            }
                        };
                        if (buttonPointDataArr.length == 1) {
                            doBtnStatistics(buttonPointDataArr[0]);
                        }
                        else {
                            let runtimeParentViewName = null;
                            let node = this.parent;
                            while (node && node != Laya.stage) {
                                let pSourceName = node.sourceName;
                                if (pSourceName) {
                                    runtimeParentViewName = pSourceName.substr(pSourceName.lastIndexOf("/") + 1, 100);
                                    break;
                                }
                                node = node.parent;
                            }
                            if (runtimeParentViewName) {
                                for (let k in buttonPointDataArr) {
                                    let buttonPointData = buttonPointDataArr[k];
                                    if (buttonPointData.parentViewName == runtimeParentViewName) {
                                        doBtnStatistics(buttonPointData);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            tryHandleMethodCallStatics() {
                if (this.sourceName) {
                    let viewName = this.sourceName.substr(this.sourceName.lastIndexOf("/") + 1, 100);
                    let pointDatas = mgrCfg.get_from_view_method_call_point_event_db(viewName);
                    if (!pointDatas) {
                        return;
                    }
                    for (let k in pointDatas) {
                        let pointData = pointDatas[k];
                        if (!!pointData.bDisableAutoStatics) {
                            continue;
                        }
                        let oldM = this[pointData.methodName].bind(this);
                        if (!oldM) {
                            continue;
                        }
                        let self = this;
                        this[pointData.methodName] = function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
                            self.staticsMethodCall(pointData.methodName);
                            oldM(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
                        };
                    }
                }
            }
            staticsMethodCall(methodName, prarm1, prarm2) {
                if (this.sourceName) {
                    let viewName = this.sourceName.substr(this.sourceName.lastIndexOf("/") + 1, 100);
                    let pointData = mgrCfg.get_from_view_method_call_point_event_db(viewName, methodName);
                    if (pointData && pointData.pointEventId) {
                        try {
                            prarm1 = prarm1 || `${this[pointData.followContextFiled1]}`;
                            prarm2 = prarm2 || `${this[pointData.followContextFiled2]}`;
                        }
                        catch (error) {
                        }
                        mgrSdk.statisCommonEvent(pointData.pointEventId, prarm1, prarm2);
                    }
                }
            }
            tryShowStatisticsInfo() {
                if (!mgrDebug.bShowStatisticsInfo) {
                    return;
                }
                if (!this.sourceName) {
                    return;
                }
                let viewName = this.sourceName.substr(this.sourceName.lastIndexOf("/") + 1, 100);
                let addNameLabelInBtn = (node) => {
                    if (!!node["__testCustomButtonLabelName"]) {
                        return;
                    }
                    let buttonName = node.name.replace("CC_", "");
                    let buttonPointDataArr = mgrCfg.get("ui_button_click_point_event_db", viewName, buttonName);
                    if (!buttonPointDataArr || buttonPointDataArr.length == 0) {
                        return;
                    }
                    let doBtnStatistics = (buttonPointData) => {
                        if (!!buttonPointData && buttonPointData.selfPointEventId) {
                            let label = new Laya.Label;
                            label.fontSize = 18;
                            label.color = `#ffffff`;
                            label.stroke = 2;
                            label.strokeColor = `#ff000`;
                            label.anchorX = 0.5;
                            label.anchorY = 0.5;
                            label.text = `${buttonPointData.selfPointEventId || "unknown"}`;
                            label.pos(node.width / 2, node.height / 2, true);
                            label.zOrder = 100;
                            node["__testCustomButtonLabelName"] = label;
                            node.addChild(label);
                        }
                    };
                    if (buttonPointDataArr.length == 1) {
                        doBtnStatistics(buttonPointDataArr[0]);
                    }
                    else {
                        let runtimeParentViewName = null;
                        let node = this.parent;
                        while (node && node != Laya.stage) {
                            let pSourceName = node.sourceName;
                            if (pSourceName) {
                                runtimeParentViewName = pSourceName.substr(pSourceName.lastIndexOf("/") + 1, 100);
                                break;
                            }
                            node = node.parent;
                        }
                        if (runtimeParentViewName) {
                            for (let k in buttonPointDataArr) {
                                let buttonPointData = buttonPointDataArr[k];
                                if (buttonPointData.parentViewName == runtimeParentViewName) {
                                    doBtnStatistics(buttonPointData);
                                    break;
                                }
                            }
                        }
                    }
                };
                for (let k in this.exportNodeNames) {
                    let vName = this.exportNodeNames[k];
                    if (/button/.test(vName)) {
                        let button = this[vName];
                        if (!button) {
                            continue;
                        }
                        let owner = button.__node;
                        addNameLabelInBtn(owner);
                    }
                }
            }
            getPreLoadModelIds() {
                return [];
            }
            getPreLoadAnimationIds() {
                return [];
            }
            getPreLoadImagePaths() {
                return [];
            }
            getBackSceneLightRotation() {
                return new Laya.Vector3(-5, 27, -17.27);
            }
            customWait(endCallback) {
                endCallback && endCallback();
            }
            registerListeners(listeners) {
                this.msgHander.registerListeners(listeners);
                this.msgHander.startProcMsg();
            }
            sendMsg(msgName, data) {
                this.msgHander.sendMsg(msgName, data);
            }
            destroy(destroyChild) {
                this.msgHander.stopProcMsg();
                this.onClosed();
                super.destroy(destroyChild);
            }
            onDestroy() {
            }
            clearFrontScene() {
                if (this.scene3DFront) {
                    let childs = [];
                    for (let i = 0; i < this.scene3DFront.numChildren; i++) {
                        let child = this.scene3DFront.getChildAt(i);
                        childs.push(child);
                    }
                    for (let index = 0; index < childs.length; index++) {
                        const child = childs[index];
                        mgrLoader.Pool.recoverModel(child);
                    }
                }
            }
            clearAllLinkModels() {
                if (this.linkedModels) {
                    for (let i = this.linkedModels.length - 1; i >= 0; i--) {
                        const element = this.linkedModels[i];
                        this.unlink(element);
                    }
                }
            }
            clearAllFrontEffects() {
                for (let i = 0; i < this.needUpdateFrontEffect.length; i++) {
                    const element = this.needUpdateFrontEffect[i];
                    mgrLoader.Pool.recoverModel(element.model);
                }
                this.needUpdateFrontEffect = [];
            }
            clearAllMiddleEffects() {
                for (let i = 0; i < this.needUpdateMiddleEffect.length; i++) {
                    const element = this.needUpdateMiddleEffect[i];
                    mgrLoader.Pool.recoverModel(element.model);
                }
                this.needUpdateMiddleEffect = [];
            }
            onClosed() {
                this.clearAllLinkModels();
                if (this.scene3DBack && !this.scene3DBack.destroyed) {
                    let childs = [];
                    for (let i = 0; i < this.scene3DBack.numChildren; i++) {
                        let child = this.scene3DBack.getChildAt(i);
                        childs.push(child);
                    }
                    for (let index = 0; index < childs.length; index++) {
                        const child = childs[index];
                        mgrLoader.Pool.recoverModel(child);
                    }
                    this.scene3DBack.destroy(true);
                }
                if (this.scene3DFront && !this.scene3DFront.destroyed) {
                    let childs = [];
                    for (let i = 0; i < this.scene3DFront.numChildren; i++) {
                        let child = this.scene3DFront.getChildAt(i);
                        childs.push(child);
                    }
                    for (let index = 0; index < childs.length; index++) {
                        const child = childs[index];
                        mgrLoader.Pool.recoverModel(child);
                    }
                    this.scene3DFront.destroy(true);
                }
                Tools.timeScale = 1;
                if (this.sourceName) {
                    let viewName = this.sourceName.substr(this.sourceName.lastIndexOf("/") + 1, 100);
                    let buttonPointData = mgrCfg.get_from_ui_open_close_point_event_db(viewName);
                    if (buttonPointData && buttonPointData.pointEventId) {
                        let param = mgrGuide.isAllGuideFinished() ? "0" : "1";
                        for (let i = 1; i <= 3; i++) {
                            let fieldName = buttonPointData["followContextFiled" + i];
                            if (!fieldName) {
                                break;
                            }
                            let value = this.context[fieldName] || 0;
                            if (param) {
                                param += `_${value}`;
                            }
                            else {
                                param = `${value}`;
                            }
                        }
                        mgrSdk.statisOnStageEnd(buttonPointData.pointEventId.toString(), 1, param);
                    }
                }
            }
            onOpened() {
                if (this.isAutoAdaptChannelAdFlagIcon()) {
                    let adFlagIconPath = Const.AD_FLAG_ICON_PATH_DICT[mgrSdk.getCopNumberValueByKey("ad_flag_style") || 0];
                    let iconNames = this.getChannelAdFlagIconNames() || [];
                    for (let k in iconNames) {
                        let iconName = iconNames[k];
                        if (iconName && !!this[iconName]) {
                            Tools.loadImg(this[iconName], adFlagIconPath);
                        }
                    }
                }
                if (this.sourceName) {
                    let viewName = this.sourceName.substr(this.sourceName.lastIndexOf("/") + 1, 100);
                    let buttonPointData = mgrCfg.get_from_ui_open_close_point_event_db(viewName);
                    if (buttonPointData && buttonPointData.pointEventId) {
                        let param = mgrGuide.isAllGuideFinished() ? "0" : "1";
                        for (let i = 1; i <= 3; i++) {
                            let fieldName = buttonPointData["followContextFiled" + i];
                            if (!fieldName) {
                                break;
                            }
                            let value = this.context[fieldName] || 0;
                            if (param) {
                                param += `_${value}`;
                            }
                            else {
                                param = `${value}`;
                            }
                        }
                        mgrSdk.statisOnStageStart(buttonPointData.pointEventId.toString(), param);
                    }
                    let data = mgrCfg.get("jump_banner_icon_db", this.name);
                    if (data && data.viewId && mgrChannel.canGameInterPush()) {
                        let dictIconCop = mgrCop.getValueDict("jump_icon_switch", ";");
                        if (!!dictIconCop[data.viewId]) {
                            if (!!this["spriteJumpOtherGame"]) {
                                this["spriteJumpOtherGame"].addChild(new vJumpOtherGameNode());
                            }
                            else {
                                console.log("---------JumpIconCop已开启，没有配置节点-viewName=", this.name);
                            }
                        }
                        let dictBannerCop = mgrCop.getValueDict("jump_banner_switch", ";");
                        let jumpBannerStyle = parseInt(data.jumpBannerStyle);
                        if (!!dictBannerCop[data.viewId] && jumpBannerStyle >= 0) {
                            if (jumpBannerStyle == 1 || jumpBannerStyle == 2) {
                                if (!!this["spriteJumpOtherGameDrag"]) {
                                    let func = jumpBannerStyle == 1 ? mgrTip.showJumpOtherGameDragLeft : mgrTip.showJumpOtherGameDragRight;
                                    func(this["spriteJumpOtherGameDrag"], data.offsetY || 0, data.offsetX || 0);
                                }
                                else {
                                    console.log("---------JumpBannerCop已开启，没有配置节点-viewName=", this.name);
                                }
                            }
                            else if (jumpBannerStyle == 3 || jumpBannerStyle == 4) {
                                let func = jumpBannerStyle == 3 ? mgrTip.showJumpOtherGameBannerLeftVertical : mgrTip.showJumpOtherGameBannerRightVertical;
                                func(this, data.offsetY || 0, data.offsetX || 0);
                            }
                            else {
                                mgrTip.showJumpOtherGameBanner(this, data.offsetY || 0, data.offsetX || 0);
                            }
                        }
                    }
                    let dictFriendHotPlayCop = mgrCop.getValueDict("friend_hot_play_switch", ";");
                    if (!!data && !!dictFriendHotPlayCop[data.viewId] && data.viewName != "vMoreGameFriendHotPlayDialog" && mgrGuide.isAllForceGuideFinished() && !mgrGuide.isGuiding()) {
                        mgrDirector.openDialog("vMoreGameFriendHotPlayDialog");
                    }
                }
            }
            isAutoAdaptChannelAdFlagIcon() {
                return true;
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag"];
            }
            get bResLoaded() {
                return this.__bLoaded;
            }
            get bOnOpened() {
                return this.__bOpened;
            }
            canOperateCamera() {
                return true;
            }
            setSceneBackLightMap(lightMapIds) {
            }
            initScene3DBack(sceneId, callback) {
                if (this.scene3DBack)
                    return;
                let __init_ = (scene) => {
                    this.scene3DBack = scene;
                    this.nodeResource.addChild(this.scene3DBack);
                    this.scene3DBack.zOrder = -2;
                    this.scene3DBack.name = `${Tools.time() * 1000}`;
                    var camera = this.scene3DBack.addChild(new Laya.Camera(0, 0.1, 200));
                    camera.transform.position = new Laya.Vector3(0, 0.8, 2.5);
                    camera.clearFlag = 2;
                    this.cameraBack = camera;
                    this.cameraBack.useOcclusionCulling = true;
                    let dlight = this.scene3DBack.addChild(new Laya.DirectionLight);
                    dlight.transform.rotationEuler = new Laya.Vector3(-5, 27, -17.27);
                    dlight.transform.position = new Laya.Vector3(0, 12.408, 4.86);
                    dlight.color = new Laya.Vector3(1, 1, 1);
                    dlight.intensity = 1;
                    if (Const.bHighShadowQuality) {
                        if (!this.context.bDisableShadow) {
                            dlight.shadowMode = Laya.ShadowMode.SoftHigh;
                            dlight.shadowDistance = 5;
                            dlight.shadowResolution = 2048;
                        }
                    }
                    else {
                    }
                    dlight.shadowStrength = 1;
                    let dlightRight = this.scene3DBack.addChild(new Laya.DirectionLight);
                    dlightRight.transform.rotationEuler = new Laya.Vector3(0, 138, 0);
                    dlightRight.transform.position = new Laya.Vector3(0, 12.408, 4.86);
                    dlightRight.color = new Laya.Vector3(195 / 255, 220 / 255, 255 / 255);
                    dlightRight.intensity = 0.6;
                    dlightRight.shadowStrength = 0;
                    dlightRight.shadowMode = Laya.ShadowMode.None;
                    this.directitonLightRight = dlightRight;
                    let cf = dlight.addComponent(CameraFollow);
                    cf.endRotation = this.getBackSceneLightRotation();
                    cf.lerpValue = 1;
                    this.directitonLight = dlight;
                    let spotLight = this.scene3DBack.addChild(new Laya.SpotLight);
                    spotLight.transform.position = new Laya.Vector3;
                    this.scene3DBack.scene._shaderValues.setVector(Laya.Scene3D.SPOTLIGHTPOS, new Laya.Vector3(0, 0, 0));
                    this.scene3DBack.scene._shaderValues.setVector(Laya.Scene3D.SPOTLIGHTCOLOR, new Laya.Vector3(0, 0, 0));
                    this.scene3DBack.scene._shaderValues.setNumber(Laya.Scene3D.SPOTLIGHTRANGE, 0);
                    this.spotLight = spotLight;
                    if (this.canOperateCamera()) {
                        let cf = this.cameraBack.addComponent(CameraFollow);
                        this.registerListeners({
                            MSG_DEBUG_KEY_DOWN: (k) => {
                                if (k == "number_1") {
                                    cf.distance += 0.05;
                                }
                                if (k == "number_2") {
                                    cf.distance -= 0.05;
                                }
                                if (k == "number_7") {
                                    cf.fov += 1;
                                }
                                if (k == "number_8") {
                                    cf.fov -= 1;
                                }
                                if (cf.lookMode == E_CAMERA_MODE.targetDistance) {
                                    if (k == "i") {
                                        cf.offset.y += 0.05;
                                        console.log("------cf.lookMode == E_CAMERA_MODE.targetDistance------");
                                    }
                                    if (k == "k") {
                                        cf.offset.y -= 0.05;
                                    }
                                    if (k == "j") {
                                        cf.offset.x -= 0.05;
                                    }
                                    if (k == "l") {
                                        cf.offset.x += 0.05;
                                    }
                                }
                                else if (cf.lookMode == E_CAMERA_MODE.fixMode) {
                                    if (k == "i") {
                                        cf.position.y += 0.05;
                                        console.log("------cf.lookMode == E_CAMERA_MODE.fixMode------");
                                    }
                                    if (k == "k") {
                                        cf.position.y -= 0.05;
                                    }
                                    if (k == "j") {
                                        cf.position.x -= 0.05;
                                    }
                                    if (k == "l") {
                                        cf.position.x += 0.05;
                                    }
                                    if (k == "u") {
                                        cf.position.z += 0.05;
                                    }
                                    if (k == "o") {
                                        cf.position.z -= 0.05;
                                    }
                                    if (k == "alt_i") {
                                        cf.position.y += 0.01;
                                        console.log("------cf.lookMode == E_CAMERA_MODE.fixMode------");
                                    }
                                    if (k == "alt_k") {
                                        cf.position.y -= 0.01;
                                    }
                                    if (k == "alt_j") {
                                        cf.position.x -= 0.01;
                                    }
                                    if (k == "alt_l") {
                                        cf.position.x += 0.01;
                                    }
                                    if (k == "alt_u") {
                                        cf.position.z += 0.01;
                                    }
                                    if (k == "alt_o") {
                                        cf.position.z -= 0.01;
                                    }
                                }
                                else if (cf.lookMode == E_CAMERA_MODE.targetPosition) {
                                    if (k == "i") {
                                        console.log("------cf.lookMode == E_CAMERA_MODE.targetPosition------");
                                        cf.position.y += 0.05;
                                    }
                                    if (k == "k") {
                                        cf.position.y -= 0.05;
                                    }
                                    if (k == "j") {
                                        cf.position.x -= 0.05;
                                    }
                                    if (k == "l") {
                                        cf.position.x += 0.05;
                                    }
                                    if (k == "u") {
                                        cf.position.z += 0.05;
                                    }
                                    if (k == "o") {
                                        cf.position.z -= 0.05;
                                    }
                                }
                                if (k == "left") {
                                    cf.endRotation.y += 1;
                                }
                                if (k == "right") {
                                    cf.endRotation.y -= 1;
                                }
                                if (k == "up") {
                                    cf.endRotation.x += 1;
                                }
                                if (k == "down") {
                                    cf.endRotation.x -= 1;
                                }
                                console.log(cf.distance, cf.endRotation, cf.offset, this.cameraBack.fieldOfView, cf.position);
                            }
                        });
                    }
                    if (this.canOperateCamera()) {
                        let cf = this.directitonLight.getComponent(CameraFollow);
                        this.registerListeners({
                            MSG_DEBUG_KEY_DOWN: (k) => {
                                if (k == "w") {
                                    cf.endRotation.x += 1;
                                }
                                if (k == "s") {
                                    cf.endRotation.x -= 1;
                                }
                                if (k == "a") {
                                    cf.endRotation.y += 1;
                                }
                                if (k == "d") {
                                    cf.endRotation.y -= 1;
                                }
                                console.log("lightinfo=", cf.distance, cf.endRotation, cf.offset, this.cameraBack.fieldOfView, cf.position);
                            }
                        });
                    }
                    callback && callback();
                };
                __init_(new Laya.Scene3D());
            }
            enableRealTimeShadow(masks) {
                this.initScene3DBack();
                if (this.lightCamera)
                    return;
                this.lightCamera = new Laya.Camera;
                this.lightCamera.renderTarget = new Laya.RenderTexture(512, 512);
                this.lightCamera.cullingMask = 0;
                for (let i = 0; i < masks.length; i++) {
                    const mask = masks[i];
                    this.lightCamera.cullingMask = this.lightCamera.cullingMask | Math.pow(2, mask);
                }
                this.lightCamera.clearFlag = 0;
                this.lightCamera.clearColor = new Laya.Vector4(1.0, 1.0, 1.0, 1.0);
                this.lightCamera.nearPlane = 0.1;
                this.lightCamera.farPlane = 10;
                this.lightCamera.fieldOfView = 60;
                this.scene3DBack.addChild(this.lightCamera);
                let cf = this.lightCamera.addComponent(CameraFollow);
                cf.endRotation = new Laya.Vector3(200, 600, -17.27);
                cf.offset = new Laya.Vector3(0, 0.8);
                cf.distance = 5;
                cf.lerpValue = 1;
                this.lightCamera.renderingOrder = -1;
                let oldRender = this.lightCamera.render.bind(this.lightCamera);
                let count = 0;
                this.lightCamera.render = (a, b) => {
                    count++;
                    if (count % 2 == 0)
                        return;
                    this.lightCamera.scene._shaderValues.addDefine(Laya.Scene3DShaderDeclaration[`SHADERDEFINE_CAST_SHADOW`]);
                    oldRender(a, b);
                    this.lightCamera.scene._shaderValues.removeDefine(Laya.Scene3DShaderDeclaration[`SHADERDEFINE_CAST_SHADOW`]);
                };
                if (this.canOperateCamera()) {
                    let cf = this.lightCamera.getComponent(CameraFollow);
                    this.registerListeners({
                        MSG_DEBUG_KEY_DOWN: (k) => {
                            if (k == "number_3") {
                                cf.distance += 0.05;
                            }
                            if (k == "number_4") {
                                cf.distance -= 0.05;
                            }
                            if (k == "a") {
                                cf.endRotation.y += 1;
                            }
                            if (k == "d") {
                                cf.endRotation.y -= 1;
                            }
                            if (k == "w") {
                                cf.endRotation.x += 1;
                            }
                            if (k == "s") {
                                cf.endRotation.x -= 1;
                            }
                            console.log(this.lightCamera.getComponent(CameraFollow).distance, this.cameraBack.getComponent(CameraFollow).endRotation, this.cameraBack.fieldOfView);
                        }
                    });
                }
            }
            initScene3DFront(sceneId, callback) {
                if (this.scene3DFront)
                    return;
                let __init_ = (scene) => {
                    this.scene3DFront = scene;
                    this.nodeResource.addChild(this.scene3DFront);
                    this.scene3DFront.zOrder = 10000;
                    this.scene3DFront.name = `${Tools.time() * 1000}`;
                    var camera = this.scene3DFront.addChild(new Laya.Camera(0, 0.1, 100));
                    camera.transform.position = new Laya.Vector3(0, 0.8, 2.5);
                    camera.clearFlag = 2;
                    camera.orthographic = true;
                    camera.orthographicVerticalSize = mgrDirector.height / 1024 * 10;
                    this.cameraFront = camera;
                    Timer.callLoop(0.016, () => {
                        let needDeleteIndexs = [];
                        for (let index = this.needUpdateFrontEffect.length - 1; index >= 0; index--) {
                            const element = this.needUpdateFrontEffect[index];
                            if (element.model && !element.model.destroyed && element.model.parent && !element.linkSprite.destroyed && element.linkSprite.visible) {
                                this.update3DEffectAtFront(element.model, element.linkSprite, element.scale);
                            }
                            else {
                                mgrLoader.Pool.recoverModel(element.model);
                                needDeleteIndexs.push(index);
                            }
                        }
                        for (let i = 0; i < needDeleteIndexs.length; i++) {
                            let index = needDeleteIndexs[i];
                            this.needUpdateFrontEffect.splice(index, 1);
                        }
                    }, this);
                    callback && callback();
                };
                __init_(new Laya.Scene3D());
            }
            initScene3DMiddle(sceneId, callback) {
                if (this.scene3DMiddle)
                    return;
                let __init_ = (scene) => {
                    this.scene3DMiddle = scene;
                    this.nodeResource.addChild(this.scene3DMiddle);
                    this.scene3DMiddle.zOrder = -1;
                    this.scene3DMiddle.name = `${Tools.time() * 1000}`;
                    var camera = this.scene3DMiddle.addChild(new Laya.Camera(0, 0.1, 100));
                    camera.transform.position = new Laya.Vector3(0, 0.8, 2.5);
                    camera.clearFlag = 2;
                    camera.orthographic = true;
                    camera.orthographicVerticalSize = mgrDirector.height / 1024 * 10;
                    this.cameraMiddle = camera;
                    Timer.callLoop(0.016, () => {
                        let needDeleteIndexs = [];
                        for (let index = this.needUpdateMiddleEffect.length - 1; index >= 0; index--) {
                            const element = this.needUpdateMiddleEffect[index];
                            if (element.model && !element.model.destroyed && element.model.parent && !element.linkSprite.destroyed && element.linkSprite.visible) {
                                this.update3DEffectAtMiddle(element.model, element.linkSprite, element.scale);
                            }
                            else {
                                mgrLoader.Pool.recoverModel(element.model);
                                needDeleteIndexs.push(index);
                            }
                        }
                        for (let i = 0; i < needDeleteIndexs.length; i++) {
                            let index = needDeleteIndexs[i];
                            this.needUpdateMiddleEffect.splice(index, 1);
                        }
                    }, this);
                    callback && callback();
                };
                __init_(new Laya.Scene3D());
            }
            add3DEffectAtBack(modelId, duration = 0, callback) {
                this.initScene3DBack();
                if (modelId instanceof Laya.Sprite3D) {
                    this.scene3DBack.addChild(modelId);
                    callback && callback(modelId);
                    return;
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    if (!this.scene3DBack)
                        return;
                    let mode = mgrLoader.Pool.getModel(modelId);
                    this.scene3DBack.addChild(mode);
                    duration > 0 && Timer.callLater(duration, () => {
                        mgrLoader.Pool.recoverModel(mode);
                    }, this);
                    callback && callback(mode);
                }, this, 1);
            }
            add3DEffectAtFront(modelId, pos, duration = 0, scale = 1, callback, particleSimulateSpeed, rotVec3) {
                this.initScene3DFront();
                particleSimulateSpeed = particleSimulateSpeed || 1;
                let x = 0;
                let y = 0;
                if (pos instanceof Laya.Sprite) {
                    if (pos.destroyed) {
                        return;
                    }
                    let _temp = pos.localToGlobal(new Laya.Point(pos.pivotX, pos.pivotY));
                    x = _temp.x;
                    y = _temp.y;
                }
                else {
                    x = pos.x;
                    y = pos.y;
                }
                let outPos = new Laya.Vector3;
                this.cameraFront.convertScreenCoordToOrthographicCoord(new Laya.Vector3(x, y, 0), outPos);
                if (modelId instanceof Laya.Sprite3D) {
                    this.resetTrail(modelId);
                    Tools.changeParticleSimulationSpeed(modelId, particleSimulateSpeed);
                    this.scene3DFront.addChild(modelId);
                    modelId.transform.position = outPos;
                    modelId.transform.localRotationEuler = rotVec3 || new Laya.Vector3;
                    modelId.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                    if (pos instanceof Laya.Sprite) {
                        this.needUpdateFrontEffect.push({
                            model: modelId,
                            linkSprite: pos,
                            scale: scale,
                        });
                    }
                    callback && callback(modelId);
                    return;
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    let mode = mgrLoader.Pool.getModel(modelId);
                    this.resetTrail(mode);
                    Tools.changeParticleSimulationSpeed(mode, particleSimulateSpeed);
                    this.scene3DFront.addChild(mode);
                    mode.transform.position = outPos;
                    mode.transform.localRotationEuler = rotVec3 || new Laya.Vector3;
                    mode.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                    duration > 0 && Timer.callLater(duration, () => {
                        mgrLoader.Pool.recoverModel(mode);
                    }, this);
                    if (pos instanceof Laya.Sprite) {
                        this.needUpdateFrontEffect.push({
                            model: mode,
                            linkSprite: pos,
                            scale,
                        });
                    }
                    callback && callback(mode);
                }, this, 1);
            }
            update3DEffectAtFront(model, pos, scale) {
                let x = 0;
                let y = 0;
                let scaleX = scale;
                let scaleY = scale;
                let scaleZ = scale;
                let bActive = true;
                if (pos instanceof Laya.Sprite) {
                    let _temp = pos.localToGlobal(new Laya.Point(pos.pivotX, pos.pivotY));
                    x = _temp.x;
                    y = _temp.y;
                    scaleX = pos.scaleX * scale;
                    scaleY = pos.scaleY * scale;
                    bActive = pos.visible && pos.alpha > 0 && pos.scaleX != 0;
                }
                else {
                    x = pos.x;
                    y = pos.y;
                }
                let outPos = new Laya.Vector3;
                this.cameraFront.convertScreenCoordToOrthographicCoord(new Laya.Vector3(x, y, 0), outPos);
                model.transform.position = outPos;
                model.transform.setWorldLossyScale(new Laya.Vector3(scaleX, scaleY, scaleZ));
                model.active = bActive;
            }
            removeEffectAtFront(linkSprite) {
                for (let i = this.needUpdateFrontEffect.length - 1; i >= 0; i--) {
                    const element = this.needUpdateFrontEffect[i];
                    if (element.linkSprite == linkSprite) {
                        this.needUpdateFrontEffect.splice(i, 1);
                        mgrLoader.Pool.recoverModel(element.model);
                    }
                }
            }
            hasEffectAtFront(linkSprite) {
                for (let i = this.needUpdateFrontEffect.length - 1; i >= 0; i--) {
                    const element = this.needUpdateFrontEffect[i];
                    if (element.linkSprite == linkSprite) {
                        return true;
                    }
                }
                return false;
            }
            add3DEffectAtMiddle(modelId, pos, duration = 0, scale = 1, callback) {
                this.initScene3DMiddle();
                let x = 0;
                let y = 0;
                if (pos instanceof Laya.Sprite) {
                    if (pos.destroyed) {
                        return;
                    }
                    let _temp = pos.localToGlobal(new Laya.Point(pos.pivotX, pos.pivotY));
                    x = _temp.x;
                    y = _temp.y;
                }
                else {
                    x = pos.x;
                    y = pos.y;
                }
                let outPos = new Laya.Vector3;
                this.cameraMiddle.convertScreenCoordToOrthographicCoord(new Laya.Vector3(x, y, 0), outPos);
                if (modelId instanceof Laya.Sprite3D) {
                    this.resetTrail(modelId);
                    this.scene3DMiddle.addChild(modelId);
                    modelId.transform.position = outPos;
                    if (pos instanceof Laya.Sprite) {
                        this.needUpdateMiddleEffect.push({
                            model: modelId,
                            linkSprite: pos,
                            scale: scale,
                        });
                    }
                    callback && callback(modelId);
                    return;
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    let mode = mgrLoader.Pool.getModel(modelId);
                    this.resetTrail(mode);
                    this.scene3DMiddle.addChild(mode);
                    mode.transform.position = outPos;
                    mode.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                    duration > 0 && Timer.callLater(duration, () => {
                        mgrLoader.Pool.recoverModel(mode);
                    }, this);
                    if (pos instanceof Laya.Sprite) {
                        this.needUpdateMiddleEffect.push({
                            model: mode,
                            linkSprite: pos,
                            scale,
                        });
                    }
                    callback && callback(mode);
                }, this, 1);
            }
            update3DEffectAtMiddle(model, pos, scale) {
                let x = 0;
                let y = 0;
                let scaleX = scale;
                let scaleY = scale;
                let scaleZ = scale;
                let bActive = true;
                if (pos instanceof Laya.Sprite) {
                    let _temp = pos.localToGlobal(new Laya.Point(pos.pivotX, pos.pivotY));
                    x = _temp.x;
                    y = _temp.y;
                    scaleX = pos.scaleX * scale;
                    scaleY = pos.scaleY * scale;
                    bActive = pos.visible && pos.alpha > 0 && pos.scaleX != 0;
                }
                else {
                    x = pos.x;
                    y = pos.y;
                }
                let outPos = new Laya.Vector3;
                this.cameraMiddle.convertScreenCoordToOrthographicCoord(new Laya.Vector3(x, y, 0), outPos);
                model.transform.position = outPos;
                model.transform.setWorldLossyScale(new Laya.Vector3(scaleX, scaleY, scaleZ));
                model.active = bActive;
            }
            removeEffectAtMiddle(linkSprite) {
                for (let i = this.needUpdateMiddleEffect.length - 1; i >= 0; i--) {
                    const element = this.needUpdateMiddleEffect[i];
                    if (element.linkSprite == linkSprite) {
                        this.needUpdateMiddleEffect.splice(i, 1);
                        mgrLoader.Pool.recoverModel(element.model);
                    }
                }
            }
            hasEffectAtMiddle(linkSprite) {
                for (let i = this.needUpdateMiddleEffect.length - 1; i >= 0; i--) {
                    const element = this.needUpdateMiddleEffect[i];
                    if (element.linkSprite == linkSprite) {
                        return true;
                    }
                }
                return false;
            }
            link2Node(parent, child, linkPoint) {
                if (!parent || parent.destroyed)
                    return;
                if (!child || child.destroyed)
                    return;
                if (!this.linkedModels)
                    return;
                if (this.linkedModels.indexOf(child) >= 0) {
                    this.unlink(child);
                }
                this.linkedModels.push(child);
                Tools.link2Node(linkPoint, parent, child);
            }
            unlink(child) {
                if (!child)
                    return;
                if (!this.linkedModels)
                    return;
                let index = this.linkedModels.indexOf(child);
                if (index == -1)
                    return;
                this.linkedModels.splice(index, 1);
                mgrLoader.Pool.recoverModel(child);
            }
            resetTrail(mode) {
                if (mode instanceof Laya.TrailSprite3D) {
                    let oldTime = mode.trailFilter.time;
                    mode.trailFilter.time = 0;
                    Timer.callLater(0.1, () => {
                        mode.trailFilter.time = oldTime;
                    }, mode);
                }
                for (let i = 0; i < mode.numChildren; i++) {
                    let child = mode.getChildAt(i);
                    this.resetTrail(child);
                }
            }
        }

        class mgrNativeAdSdk extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.registerListeners({
                    MSG_SDK_OPEN_NATIVE_ADV_RESULT: this.onMsgOpenNativeAdvResult.bind(this),
                    MSG_SDK_CLICK_NATIVE_ADV_RESULT: this.onMsgClickNativeAdvResult.bind(this),
                    MSG_SDK_CLOSE_NATIVE_ADV_RESULT: this.onMsgCloseNativeAdvResult.bind(this),
                });
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static getNativeDataByNativeType(advId) {
                return this.cacheNativeDatas[advId];
            }
            static cleanNativeDataByNativeType(advId) {
                this.cacheNativeDatas[advId] = null;
                console.log("原生缓存清除成功！！！ advId = ", advId);
            }
            static onClickNativeAd(advId, userData, tag) {
                let nativeData = this.getNativeDataByNativeType(advId);
                console.log("mgrNativeAdSdk.onClickNativeAd  advId = ", advId);
                console.log("mgrNativeAdSdk.onClickNativeAd  nativeData = ", nativeData);
                if (!nativeData) {
                    console.warn(" inbuild sdk: onClickNativeAd: nativeData not found! advId= ", advId);
                    return;
                }
                mgrSdk.clickNativeAdv(advId, JSON.stringify(userData), tag);
            }
            static onCloseNativeAd(advId, userData, tag, bManualClose) {
                console.log("inbuild sdk: onCloseNativeAd: advId=", advId);
                mgrSdk.closeNativeAdv(advId, JSON.stringify(userData), bManualClose);
            }
            static _onReceiveNativeData(advId, nativeData, userData) {
                if (!advId || !nativeData) {
                    return;
                }
                this.NATIVE_DATA_SERIAL_NUMBER++;
                nativeData.serialNumber = this.NATIVE_DATA_SERIAL_NUMBER;
                nativeData.advId = advId;
                if (nativeData.title.length > 6) {
                    nativeData.title = nativeData.title.substring(0, 6);
                }
                if (nativeData.desc.length > 24) {
                    nativeData.desc = nativeData.desc.substring(0, 24);
                }
                this.cacheNativeDatas[advId] = nativeData;
                this.sendMsg("MSG_NATIVE_AD_SDK_NATIVE_DATA_REFRESH", {
                    advId: advId,
                    userData: userData,
                });
            }
            static onMsgOpenNativeAdvResult(data) {
                console.log("inbuild sdk: onMsgOpenNativeAdvResult", data);
                let code = data.code;
                let msg = data.msg;
                let advId = data.advId;
                let userData = JSON.parse(data.userData || "") || {};
                let nativeData = data.nativeData;
                if (code == 1) {
                    this._onReceiveNativeData(advId, nativeData, userData);
                }
                else {
                    this.cacheNativeDatas[advId] = null;
                    this.sendMsg("MSG_NATIVE_AD_SDK_NATIVE_DATA_REFRESH", {
                        advId: advId,
                        userData: userData,
                    });
                }
            }
            static onMsgClickNativeAdvResult(data) {
                let code = parseInt(data.code);
                let msg = data.msg;
                let advId = data.advId;
                let userData = JSON.parse(data.userData || "") || {};
                console.log("inbuild sdk: onMsgClickNativeAdvResult", userData);
                this.sendMsg("MSG_NATIVE_AD_SDK_CLICK_SUCCESS", {
                    advId: advId,
                    userData: userData,
                });
                this.cacheNativeDatas[advId] = null;
                mgrAdNative.__invokeRefreshData(userData);
                this.sendMsg("MSG_NATIVE_AD_SDK_NATIVE_DATA_REFRESH", {
                    advId: advId,
                    userData: userData,
                });
                this.onCloseNativeAd(advId, userData, userData.adEventId, false);
            }
            static onMsgCloseNativeAdvResult(data) {
                let code = parseInt(data.code);
                let msg = data.msg;
                let advId = data.advId;
                let userData = JSON.parse(data.userData || "") || {};
            }
        }
        mgrNativeAdSdk.cacheNativeDatas = {};
        mgrNativeAdSdk.NATIVE_DATA_SERIAL_NUMBER = 0;

        class DialogBase extends ViewBase {
            constructor() {
                super(...arguments);
                this._shadowAlpha = 0.6;
            }
            _onAnimationFinished() {
                this.onAnimationFinished();
            }
            onAnimationFinished() { }
            manualSendAnimationFinished() {
                this._onAnimationFinished();
            }
            closeDialog(bImmediately = false) {
                if (this.__bClosing)
                    return;
                this.sendMsg("MSG_DIALOG_CLOSE", {
                    viewName: this.name,
                    zIndex: this.__dialogRoot.zOrder,
                });
                this.__bClosing = true;
                if (bImmediately) {
                    this.__dialogRoot.destroy();
                    DialogBase.ShowingDialog.splice(DialogBase.ShowingDialog.indexOf(this.name), 1);
                    if (this.context && this.context.fOnClose instanceof Function) {
                        this.context.fOnClose();
                    }
                    return;
                }
                cc.tween(this.__dialogMask).toAlpha(0.15, 0).start();
                cc.tween(this).to(0.15, { scaleX: 0, scaleY: 0, alpha: 0 })
                    .call(() => {
                    if (this.context && this.context.fOnClose instanceof Function) {
                        this.context.fOnClose();
                    }
                    this.__dialogRoot.destroy();
                    DialogBase.ShowingDialog.splice(DialogBase.ShowingDialog.indexOf(this.name), 1);
                })
                    .start();
            }
            isShadowClose() {
                return false;
            }
            isShowShadow() {
                return true;
            }
            isShadowBlock() {
                return true;
            }
            get shadowAlpha() {
                return this._shadowAlpha;
            }
            set shadowAlpha(value) {
                this._shadowAlpha = value;
                if (this.__dialogMask && !this.__dialogMask.destroyed) {
                    this.__dialogMask.alpha = value;
                }
            }
            openDialog(bImmediately = false) {
                DialogBase.ShowingDialog.push(this.name);
                this.__dialogRoot = mgrDirector.get2DDialogLayer().addChild(new Laya.Box());
                this.__dialogRoot.zOrder = DialogBase.curZIndex;
                DialogBase.curZIndex++;
                this.__dialogRoot.size(Laya.stage.width, Laya.stage.height);
                this.__dialogRoot.anchorX = 0.5;
                this.__dialogRoot.anchorY = 0.5;
                this.__dialogRoot.pos(mgrDirector.get2DDialogLayer().width / 2, mgrDirector.get2DDialogLayer().height / 2);
                let mask = new Laya.Image;
                this.__dialogMask = mask;
                if (!this.isShowShadow())
                    mask.alpha = 0;
                else {
                    mask.alpha = 0;
                    cc.tween(mask).toAlpha(0.15, this.shadowAlpha).start();
                }
                ;
                this.__dialogRoot.addChild(mask);
                mask.size(768, 1280);
                mask.anchorX = 0.5;
                mask.anchorY = 0.5;
                mask.zOrder = 0;
                mask.pos(this.__dialogRoot.width / 2, this.__dialogRoot.height / 2);
                let texture2d = Laya.Texture2D.blackTexture;
                let texture = new Laya.Texture(texture2d, undefined, 768, 1280);
                mask.texture = texture;
                Tools.registerTouchHander(mask, ((e) => {
                    if (!e.isClick) {
                        return;
                    }
                    if (this.isShadowClose())
                        this.closeDialog();
                }).bind(this));
                if (!this.isShadowBlock())
                    mask.visible = false;
                else
                    mask.visible = true;
                this.alpha = 0;
                this.__dialogRoot.addChild(this);
                this.zOrder = 1;
                this.pos(this.__dialogRoot.width / 2, this.__dialogRoot.height / 2);
                Timer.callLoop(0.016, (timer) => {
                    if (this.bOnOpened) {
                        timer.stop();
                        if (this.__bClosing) {
                            return;
                        }
                        if (bImmediately) {
                            this.scaleX = 1;
                            this.scaleY = 1;
                            this.alpha = 1;
                            this._onAnimationFinished();
                        }
                        else {
                            this.scaleX = 0;
                            this.scaleY = 0;
                            cc.tween(this).to(0.15, { scaleX: 1, scaleY: 1, alpha: 1 }, cc.Ease.backOut)
                                .call(() => {
                                this._onAnimationFinished();
                            })
                                .start();
                        }
                    }
                }, true);
            }
            showTop() {
                if (this.__dialogRoot) {
                    this.__dialogRoot.zOrder = DialogBase.curZIndex;
                }
                else {
                    this.zOrder = DialogBase.curZIndex;
                }
                DialogBase.curZIndex++;
            }
        }
        DialogBase.ShowingDialog = [];
        DialogBase.curZIndex = 1;

        class mgrLayout extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("mgrLayout.onLoad");
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static widget(h, v, node, anchor = { x: 0, y: 0 }, parent = Laya.stage) {
                if (parent == Laya.stage) {
                    if (Laya.stage.height > 1152) {
                        let delta = Laya.stage.height - 1152;
                        let minV = delta / 2;
                        let maxV = Laya.stage.height - minV;
                        if (v >= 0 && v <= 1) {
                            v = ul.clamp(v, minV / Laya.stage.height, maxV / Laya.stage.height);
                        }
                        else if (v > 1) {
                            if (v < 300) {
                                v = ul.clamp(v + minV, minV, maxV);
                            }
                            else if (v > Laya.stage.width - 300) {
                                v = ul.clamp(v - minV, minV, maxV);
                            }
                            else {
                                v = ul.clamp(v, minV, maxV);
                            }
                        }
                    }
                }
                let absh = Math.abs(h);
                let absv = Math.abs(v);
                let x = parent.width * h;
                let y = parent.height * v;
                if (absh > 1)
                    x = h;
                if (absv > 1)
                    y = v;
                if (node[`anchorX`] == null || isNaN(node[`anchorX`])) {
                    node[`anchorX`] = node.pivotX / node.width;
                }
                if (node[`anchorY`] == null || isNaN(node[`anchorY`])) {
                    node[`anchorY`] = node.pivotY / node.height;
                }
                x += node[`anchorX`] * node.width - anchor.x * node.width;
                y += node[`anchorY`] * node.height - anchor.y * node.height;
                let wPos = parent.localToGlobal(new Laya.Point(x, y));
                let nplPos = node.parent.globalToLocal(new Laya.Point(wPos.x, wPos.y));
                if (h == -1)
                    nplPos.x = node.x;
                if (v == -1)
                    nplPos.y = node.y;
                node.pos(nplPos.x, nplPos.y, true);
            }
            static widgetLeftMC(node) {
                this.widgetLeftTopMC(node, false, true);
            }
            static widgetRightMC(node) {
                this.widgetRightTopMC(node, false, true);
            }
            static widgetTopMC(node) {
                this.widgetLeftTopMC(node, true, false);
            }
            static widgetBottomMC(node, bottomMargin = 0) {
                this.widgetLeftBottomMC(node, bottomMargin, true, false);
            }
            static widgetLeftTopMC(node, bDisableH = false, bDisableV = false) {
                let diffX = (Laya.stage.width - Const.RESOLUTION_RANGE.minWidth) / 2;
                let diffY = Math.max(0, (Laya.stage.height - Const.RESOLUTION_RANGE.minHeight) / 2 - mgrDirector.getSafeSurplusHeight());
                node.pos(!bDisableH ? node.x - diffX : node.x, !bDisableV ? node.y - diffY + (parseInt(mgrSdk.getCopByKey("ui_top_margin_distance")) || 0) : node.y);
            }
            static widgetRightTopMC(node, bDisableH = false, bDisableV = false) {
                let diffX = (Laya.stage.width - Const.RESOLUTION_RANGE.minWidth) / 2;
                let diffY = Math.max(0, (Laya.stage.height - Const.RESOLUTION_RANGE.minHeight) / 2 - mgrDirector.getSafeSurplusHeight());
                node.pos(!bDisableH ? node.x + diffX : node.x, !bDisableV ? node.y - diffY + (parseInt(mgrSdk.getCopByKey("ui_top_margin_distance")) || 0) : node.y);
            }
            static widgetLeftBottomMC(node, bottomMargin = 0, bDisableH = false, bDisableV = false) {
                let diffX = (Laya.stage.width - Const.RESOLUTION_RANGE.minWidth) / 2;
                let diffY = Math.max(0, (Laya.stage.height - Const.RESOLUTION_RANGE.minHeight) / 2 - mgrDirector.getSafeSurplusHeight());
                bottomMargin = bottomMargin || 0;
                node.pos(!bDisableH ? node.x - diffX : node.x, !bDisableV ? node.y + diffY - bottomMargin : node.y - bottomMargin);
            }
            static widgetRightBottomMC(node, bottomMargin = 0, bDisableH = false, bDisableV = false) {
                let diffX = (Laya.stage.width - Const.RESOLUTION_RANGE.minWidth) / 2;
                let diffY = Math.max(0, (Laya.stage.height - Const.RESOLUTION_RANGE.minHeight) / 2 - mgrDirector.getSafeSurplusHeight());
                node.pos(!bDisableH ? node.x + diffX : node.x, !bDisableV ? node.y + diffY - bottomMargin : node.y - bottomMargin);
            }
            static centerNodeBasePivotX(node) {
                let tmpNode = node;
                let tmpNodeParent = tmpNode.parent;
                let width = tmpNode.getSelfBounds().width;
                let pivotX = tmpNode.pivotX;
                let worldPos = tmpNode.localToGlobal(new Laya.Point(pivotX, 0));
                tmpNode.x += (mgrDirector.width / 2 - worldPos.x);
            }
            static centerNodeBaseContent(node) {
                let tmpNode = node;
                let width = tmpNode.getSelfBounds().width;
                let pivotX = tmpNode.pivotX;
                this.centerNodeBasePivotX(node);
                node.x += (pivotX - width / 2);
            }
            static layoutH(node, space = 8, anchor = 0.5, bWithScale = true) {
                Tools.layoutH(node, space, anchor, bWithScale);
            }
            static layoutV(node, space = 8, anchor = 0.5) {
                Tools.layoutV(node, space, anchor);
            }
        }

        class vNativeDialogBig extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vNativeDialogBig";
                this.exportNodeNames = [];
                vNativeDialogBig.instance = this;
            }
            onOpened() {
                super.onOpened();
                this.nodeResource.scale(0, 0, true);
                this.__dialogRoot.zOrder = 1000000000;
                Tools.registerTouchHander(this.spriteClickArenaForModel2, (e) => {
                    if (!e.isClick)
                        return;
                    if (Tools.isWorldLocaInNode(this.buttonClose.__node, new Laya.Vector2(e.pos.x, e.pos.y))) {
                        return;
                    }
                    this.onTouchClickModeArena2();
                });
                Tools.registerTouchHander(this.spriteClickArenaForModel4, (e) => {
                    if (!e.isClick)
                        return;
                    if (Tools.isWorldLocaInNode(this.buttonClose.__node, new Laya.Vector2(e.pos.x, e.pos.y))) {
                        return;
                    }
                    this.onTouchClickModeArena4();
                });
                this.adEventId = this.context.adEventId;
                this.userData = this.context.userData;
                this.fillData();
                this.registerListeners({
                    MSG_NATIVE_AD_SDK_CLICK_SUCCESS: this.onMsgNativeAdSdkClickSuccess.bind(this),
                });
            }
            onClosed() {
                super.onClosed();
                if (!!this.autoCloseTimer) {
                    this.autoCloseTimer.stop();
                    this.autoCloseTimer = null;
                }
                mgrAdNative.onNativeAdViewClenup(this.context.adEventId, true, true);
                vNativeDialogBig.instance = null;
            }
            fillData() {
                let nativeData = mgrAdNative.getNativeDataByAdEventId(this.adEventId);
                if (!nativeData) {
                    mgrTip.showMsgTip("发生了不可预知的错误, 这个不应该弹出的!!!");
                }
                else {
                    this.autoCloseTimer = Timer.callLater(3, () => {
                        this.closeDialog(true);
                    }, this);
                    this.labelName.text = nativeData.title;
                    this.labelDesc.text = nativeData.desc;
                    this.labelTarget.text = nativeData.targetTitle;
                    this.labelAdSource.text = nativeData.adSource || "";
                    Tools.loadAdImg(this.imageIcon, nativeData.url, () => {
                        if (!!this.nodeResource && !this.nodeResource.destroyed) {
                            this.nodeResource.scale(1, 1, true);
                        }
                        if (!!this.autoCloseTimer) {
                            this.autoCloseTimer.stop();
                            this.autoCloseTimer = null;
                        }
                    });
                }
                let rangeMode = mgrSdk.getCopNumberValueByKey(`native_insert_mode`);
                this.spriteClickArenaForModel2.visible = rangeMode == 2;
                this.buttonFullScreen.__node.visible = rangeMode == 3;
                this.spriteClickArenaForModel4.visible = rangeMode == 4;
                if (mgrSdk.getCopNumberValueByKey(`native_insert_close_size_mode`) == 1) {
                    this.buttonClose.__node.size(50, 50);
                    this.spriteCloseBg.size(50, 50);
                    mgrLayout.widget(0.5, 0.5, this.spriteCloseBg, { x: 0.5, y: 0.5 }, this.buttonClose.__node);
                }
                else if (mgrSdk.getCopNumberValueByKey(`native_insert_close_size_mode`) == 2) {
                    this.buttonClose.__node.size(80, 80);
                    this.spriteCloseBg.size(80, 80);
                    mgrLayout.widget(0.5, 0.5, this.spriteCloseBg, { x: 0.5, y: 0.5 }, this.buttonClose.__node);
                }
                else if (mgrSdk.getCopNumberValueByKey(`native_insert_close_size_mode`) == 3) {
                    this.buttonClose.__node.size(80, 80);
                    this.spriteCloseBg.size(50, 50);
                    mgrLayout.widget(0.5, 0.5, this.spriteCloseBg, { x: 0.5, y: 0.5 }, this.buttonClose.__node);
                }
                else {
                    if (mgrAd.todayNativeInsertScaleCount < mgrSdk.getCopNumberValueByKey(`native_insert_scale_close_count`)) {
                        mgrAd.todayNativeInsertScaleIntervalCount++;
                        if (mgrAd.todayNativeInsertScaleIntervalCount >= mgrSdk.getCopNumberValueByKey(`native_insert_scale_close_interval`)) {
                            mgrAd.todayNativeInsertScaleIntervalCount = 0;
                            this.buttonClose.__node.size(35, 35);
                            this.spriteCloseBg.size(35, 35);
                            mgrAd.todayNativeInsertScaleCount++;
                        }
                        else {
                            this.buttonClose.__node.size(50, 50);
                            this.spriteCloseBg.size(50, 50);
                        }
                        mgrAd.saveRecord();
                    }
                }
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonDownLoad() {
                mgrAdNative.clickNative(this.adEventId);
            }
            onTouchButtonFullScreen() {
                mgrAdNative.clickNative(this.adEventId);
            }
            onTouchClickModeArena2() {
                mgrAdNative.clickNative(this.adEventId);
            }
            onTouchClickModeArena4() {
                mgrAdNative.clickNative(this.adEventId);
            }
            onMsgNativeAdSdkClickSuccess() {
                mgrTip.showMsgTip("谢谢!");
                this.closeDialog();
            }
        }

        var NATIVE_AD_TYPE;
        (function (NATIVE_AD_TYPE) {
            NATIVE_AD_TYPE[NATIVE_AD_TYPE["banner"] = 1] = "banner";
            NATIVE_AD_TYPE[NATIVE_AD_TYPE["insert"] = 2] = "insert";
            NATIVE_AD_TYPE[NATIVE_AD_TYPE["embed"] = 3] = "embed";
        })(NATIVE_AD_TYPE || (NATIVE_AD_TYPE = {}));
        class mgrAdNative extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.registerListeners({
                    MSG_NATIVE_AD_SDK_NATIVE_DATA_REFRESH: this.onMsgNativeDataRefresh,
                });
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static requestSomeNativeAdAtStart() {
            }
            static getNativeDataByAdEventId(adEventId) {
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (!adEventData)
                    return null;
                let nativeData = mgrNativeAdSdk.getNativeDataByNativeType(adEventData.advId);
                return nativeData;
            }
            static onNativeAdViewClenup(adEventId, bCleanCache = true, bManualClose) {
                if (!adEventId) {
                    return;
                }
                let nativeData = this.getNativeDataByAdEventId(adEventId);
                if (!nativeData) {
                    return;
                }
                if (bCleanCache) {
                    let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                    if (adEventData) {
                        mgrNativeAdSdk.cleanNativeDataByNativeType(adEventData.advId);
                    }
                }
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                let userData = {};
                if (this.nativeBannerRefreshFun[adEventId]) {
                    userData = this.nativeBannerRefreshFun[adEventId].userData;
                }
                mgrNativeAdSdk.onCloseNativeAd(adEventData.advId, userData, adEventId, bManualClose);
            }
            static __invokeRefreshData(userData) {
                let adEventId = userData.adEventId || 0;
                if (!adEventId) {
                    return;
                }
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (adEventData) {
                    if (adEventData.nativeType == NATIVE_AD_TYPE.embed || adEventData.nativeType == NATIVE_AD_TYPE.banner) {
                        console.log("__invokeRefresh: adEventId = ", adEventId);
                        this.__invokeClientRefresh(adEventId, true);
                    }
                }
            }
            static __invokeClientRefresh(adEventId, bForce) {
                mgrAd.triggerAdEvent(adEventId, null, bForce);
            }
            static registerNativeBannerRefreshFun(adEventId, fun, bindNode) {
                let adEventData = mgrCfg.quietGet("ad_event_db", adEventId);
                if (adEventData) {
                    this.nativeBannerRefreshFun[adEventId] = {
                        fun: fun,
                        node: bindNode,
                        userData: !this.nativeBannerRefreshFun[adEventId] ? null : this.nativeBannerRefreshFun[adEventId].userData,
                    };
                    Tools.registerTouchHander(bindNode, (e) => {
                        if (!e.isClick) {
                            return;
                        }
                        let nativeData = this.getNativeDataByAdEventId(adEventId);
                        console.log(this.nativeBannerRefreshFun);
                        if (nativeData && this.nativeBannerRefreshFun[adEventId] && this.nativeBannerRefreshFun[adEventId].userData) {
                            console.log("on touch native !!!");
                            mgrNativeAdSdk.onClickNativeAd(adEventData.advId, adEventId, this.nativeBannerRefreshFun[adEventId].userData);
                        }
                    });
                    let component = bindNode.addComponent(Laya.Script);
                    component["onDestroy"] = () => {
                        Timer.callLater(0.3, () => {
                            this.onNativeAdViewClenup(adEventId, true, false);
                        });
                    };
                    mgrAd.triggerAdEvent(adEventId);
                    this.sendMsg("MSG_NATIVE_AD_SDK_NATIVE_DATA_REFRESH", {
                        advId: adEventData.advId,
                        userData: {
                            adEventId: adEventId,
                        },
                    });
                }
            }
            static clickNative(adEventId) {
                console.log("mgrAdNative.clickNative  adEventId = ", adEventId, this.nativeBannerRefreshFun[adEventId]);
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                mgrNativeAdSdk.onClickNativeAd(adEventData.advId, this.nativeBannerRefreshFun[adEventId] ? this.nativeBannerRefreshFun[adEventId].userData : {}, adEventId);
            }
            static refreshNativeBanner(adEventId) {
                let registerInfo = this.nativeBannerRefreshFun[adEventId];
                if (!registerInfo) {
                    console.warn(ul.format(":)adEventId:%s isn't regist!!!"));
                    return;
                }
                if (!registerInfo.node || registerInfo.node.destroyed) {
                    return;
                }
                let nativeData = this.getNativeDataByAdEventId(adEventId);
                try {
                    registerInfo.fun(nativeData);
                }
                catch (error) {
                    console.log(error);
                }
            }
            static onMsgNativeDataRefresh(e) {
                let data = e;
                let adEventId = data.userData.adEventId;
                console.log("onMsgNativeDataRefresh", adEventId);
                let nativeData = this.getNativeDataByAdEventId(adEventId);
                if (!nativeData)
                    nativeData = {};
                if (!this.nativeBannerRefreshFun[adEventId]) {
                    this.nativeBannerRefreshFun[adEventId] = {};
                }
                this.nativeBannerRefreshFun[adEventId].userData = data.userData;
                console.log(" try down load image!!!");
                this.__tryRefreshLogic(data.advId);
                if (nativeData.url) {
                    nativeData.url = nativeData.url.replace("https://", "http://");
                    let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                    if (adEventData && adEventData.nativeType == NATIVE_AD_TYPE.insert && ul.length(nativeData) > 0) {
                        !vNativeDialogBig.instance && mgrDirector.openDialog("vNativeDialogBig", {
                            adEventId: adEventId,
                            userData: data.userData,
                        }, true);
                    }
                    this.__tryRefreshLogic(data.advId);
                }
                this.sendMsg("MSG_NATIVE_DATA_REFRESH", {
                    advId: data.advId,
                });
            }
            static __tryRefreshLogic(advId) {
                Tools.forEachMap(this.nativeBannerRefreshFun, (adEventId, v) => {
                    let adEventData = mgrCfg.quietGet("ad_event_db", adEventId);
                    if (adEventData && advId && adEventData.advId == advId) {
                        this.refreshNativeBanner(adEventId);
                    }
                });
            }
        }
        mgrAdNative.nativeBannerRefreshFun = {};

        class vNativeBanner extends ViewBase {
            constructor(context, activing = false) {
                super(context);
                this.sourceName = "node/vNativeBanner";
                this.exportNodeNames = [];
                this.activing = false;
                this.width = 768;
                this.height = 200;
                this.activing = activing;
            }
            onOpened() {
                super.onOpened();
                this.hidePos();
                if (this.adEventId) {
                    this.refreshBanner();
                }
            }
            onClosed() {
            }
            normalPos() {
                mgrLayout.widget(mgrDirector.width / 2, mgrDirector.height, this, { x: 0.5, y: 1 });
                this.bNormalShowing = true;
            }
            hidePos() {
                this.y = 10000;
                this.bNormalShowing = false;
            }
            refreAd(nativeData) {
                if (!this.bResLoaded)
                    return;
                if (!!nativeData) {
                    this.labelName.text = nativeData.title;
                    this.labelDesc.text = nativeData.desc;
                    this.labelTarget.text = nativeData.targetTitle;
                    this.normalPos();
                    this.labelAdSource.text = nativeData.adSource || "";
                    Tools.loadAdImg(this.imageIcon, nativeData.url);
                }
                else {
                    this.hidePos();
                }
            }
            refreshBanner() {
                let nativeData = mgrAdNative.getNativeDataByAdEventId(this.adEventId);
                this.refreAd(nativeData);
            }
            show(adEventId, targetViewName) {
                if (this.activing) {
                    mgrAd.triggerAdEvent(adEventId, null, true);
                }
                else {
                    mgrAd.triggerAdEvent(adEventId);
                }
                this.adEventId = adEventId;
                this.targetViewName = targetViewName;
                this.refreshBanner();
            }
            isNativeBannerShowing() {
                if (!this.bResLoaded || !this.bNormalShowing) {
                    return false;
                }
                return true;
            }
            onTouchButtonDownload() {
                console.log("vNativeBanner.onTouchButtonDownload  adEventId = ", this.adEventId);
                mgrAdNative.clickNative(this.adEventId);
            }
            onTouchButtonContent() {
                console.log("vNativeBanner.onTouchButtonContent  adEventId = ", this.adEventId);
                mgrAdNative.clickNative(this.adEventId);
            }
            activingBannerClose() {
                if (this.adEventId) {
                    mgrAd.closeAdv(this.adEventId);
                    mgrAdNative.onNativeAdViewClenup(this.adEventId, true, false);
                }
                this.removeSelf();
                this.destroy();
            }
            onTouchButtonClose() {
                if (this.activing) {
                    if (this.adEventId) {
                        mgrAd.closeAdv(this.adEventId);
                        mgrAdNative.onNativeAdViewClenup(this.adEventId, true, true);
                    }
                    this.removeSelf();
                    this.destroy();
                }
                else {
                    this.sendMsg("MSG_USER_CLOSE_NATIVE_BANNER", {
                        viewName: this.targetViewName,
                    });
                }
            }
        }

        const VIEW_BANNER_STATUS_NOTHING = 0;
        const VIEW_BANNER_STATUS_OPEN = 1;
        const VIEW_BANNER_STATUS_CLOSE = 2;
        class mgrBannerInt extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.bannerViewNameStack = [];
                this.currShowingBannerEventId = null;
                this.nativeBanner = null;
                this.lastOpenBannerTime = 0;
                this.loadRecord();
                this.registerListeners({
                    MSG_DIALOG_OPEN: this.onMsgDialogOpen,
                    MSG_DIALOG_CLOSE: this.onMsgDialogClose,
                    MSG_WARP_SCENE_START: this.onMsgWarpSceneStart,
                    MSG_WARP_SCENE_COMPLETED: this.onMsgWarpSceneCompleted,
                    MSG_USER_CLOSE_NATIVE_BANNER: this.onMsgUserCloseNativeBanner,
                    MSG_NATIVE_DATA_REFRESH: this.onMsgNativeDataRefresh,
                    MSG_TRIGGER_NATIVE_BANNER: this.onMsgTriggerNativeBanner,
                });
            }
            static loadRecord() {
                let record = mgrRecord.getData("banner_record") || {};
            }
            static saveRecord() {
                let record = {};
                mgrRecord.setData("banner_record", record);
            }
            static isBannerView(viewName) {
                let data = this.getAdInfoByViewName(viewName);
                if (data.bannerStatus == VIEW_BANNER_STATUS_OPEN) {
                    return true;
                }
                else {
                    return false;
                }
            }
            static closeBannerOnce() {
                this.closeBanner();
            }
            static readaptViewBanner() {
                this.adaptBanner();
            }
            static onViewOpen(e) {
                let viewName = e.viewName;
                if (!viewName) {
                    return;
                }
                let i1 = viewName.lastIndexOf(".");
                if (i1 > 0) {
                    viewName = viewName.substr(i1 + 1, 100);
                }
                console.log("------------onViewOpen----viewName=", viewName);
                let bHandleStack = false;
                let data = this.getAdInfoByViewName(viewName);
                let bannerStatus = data.bannerStatus;
                let bannerEventId = data.bannerEventId;
                if (bannerStatus == VIEW_BANNER_STATUS_OPEN) {
                    if (bannerEventId && bannerEventId != "") {
                        bHandleStack = true;
                    }
                }
                else if (bannerStatus == VIEW_BANNER_STATUS_CLOSE) {
                    bHandleStack = true;
                }
                if (bHandleStack) {
                    let customUuid = e.customUuid || 0;
                    let zIndex = e.zIndex || 0;
                    let sceneFlag = e.sceneFlag || data.sceneFlag || 0;
                    this.bannerViewNameStack.push({ sceneFlag: sceneFlag, viewName: viewName, bannerEventId: bannerEventId, customUuid: customUuid, zIndex: zIndex });
                    this.bannerViewNameStack = Tools.sortArrayByField(this.bannerViewNameStack, ["-sceneFlag", "zIndex", "customUuid"]);
                }
                let bAdaptBanner = bannerStatus != VIEW_BANNER_STATUS_NOTHING;
                let intEventId = data.intEventId;
                if (intEventId && !e.bDisableInt) {
                    mgrAd.triggerAdEvent(intEventId, null, true);
                    if (mgrSdk.getCopNumberValueByKey("b_int_banner_mute") == 1) {
                        this.closeBannerOnce();
                        bAdaptBanner = false;
                    }
                }
                if (bAdaptBanner) {
                    this.adaptBanner();
                }
            }
            static adaptBanner() {
                let count = ul.length(this.bannerViewNameStack || []);
                if (count == 0) {
                    this.closeBanner();
                    return;
                }
                let lastInfo = this.bannerViewNameStack[count - 1];
                let viewName = lastInfo.viewName;
                let data = this.getAdInfoByViewName(viewName);
                let status = data.bannerStatus;
                let bannerEventId = data.bannerEventId;
                if (status == VIEW_BANNER_STATUS_OPEN) {
                    if (bannerEventId && bannerEventId != "") {
                        let index = this.activingViewNameArr.indexOf(viewName);
                        let switcher = false;
                        if (index >= 0) {
                            switcher = mgrSdk.getCopByKey("activing_mode_switch").split(";")[index] == "1";
                        }
                        if (switcher) {
                        }
                        else {
                            this.showBanner(bannerEventId, viewName);
                        }
                    }
                }
                else if (status == VIEW_BANNER_STATUS_CLOSE) {
                    this.closeBanner();
                }
                else {
                }
            }
            static getAdInfoByViewName(viewName) {
                if (!viewName || viewName == "") {
                    return { bannerStatus: VIEW_BANNER_STATUS_NOTHING, bannerEventId: null, intEventId: null };
                }
                let template = mgrCfg.get("ad_banner_int_ui_db", viewName);
                if (!template) {
                    return { bannerStatus: VIEW_BANNER_STATUS_CLOSE, bannerEventId: null, sceneFlag: 0, intEventId: null };
                }
                let retData = null;
                if (!!template.bBannerDoNothing) {
                    retData = { bannerStatus: VIEW_BANNER_STATUS_NOTHING, bannerEventId: null, sceneFlag: (template.sceneFlag || 0), intEventId: null };
                }
                else {
                    if (!template.bannerEventId || template.bannerEventId == "" || !mgrAd.preCheckCanTriggerAdEvent(template.bannerEventId) || this.isUserClosedNativeBanner(viewName)) {
                        retData = { bannerStatus: VIEW_BANNER_STATUS_CLOSE, bannerEventId: null, sceneFlag: (template.sceneFlag || 0), intEventId: null };
                    }
                    else {
                        retData = { bannerStatus: VIEW_BANNER_STATUS_OPEN, bannerEventId: template.bannerEventId, sceneFlag: (template.sceneFlag || 0), intEventId: null };
                    }
                }
                if (template.intEventId && template.intEventId != "") {
                    if (mgrAd.preCheckCanTriggerAdEvent(template.intEventId)) {
                        retData.intEventId = template.intEventId;
                    }
                    else {
                        if (mgrAd.bOpenMoreGameBox) {
                            mgrAd.showMoreGameBoxOrInterstitial();
                        }
                    }
                }
                return retData;
            }
            static isUserClosedNativeBanner(viewName) {
                if (!viewName) {
                    return false;
                }
                let time = this.userClosedNativeBannerTimeViewNameDict[viewName];
                if (time && (Tools.time() - time) < mgrSdk.getCopNumberValueByKey("close_native_banner_cd")) {
                    return true;
                }
                return false;
            }
            static onMsgDialogOpen(e) {
                this.onViewOpen(e);
            }
            static onMsgDialogClose(e) {
                let stackNum = ul.length(this.bannerViewNameStack);
                if (stackNum <= 0) {
                    return;
                }
                let zIndex = e.zIndex;
                if (!zIndex) {
                    return;
                }
                let bLastDialog = false;
                for (let i = stackNum - 1; i >= 0; i--) {
                    let info = this.bannerViewNameStack[i];
                    if (info.zIndex == zIndex) {
                        this.bannerViewNameStack.splice(i, 1);
                        if (i == (stackNum - 1)) {
                            bLastDialog = true;
                        }
                        break;
                    }
                }
                if (bLastDialog) {
                    this.adaptBanner();
                }
            }
            static onMsgWarpSceneStart(e) {
                let stackNum = ul.length(this.bannerViewNameStack);
                if (stackNum <= 0) {
                    return;
                }
                let bLastDialog = false;
                for (let i = stackNum - 1; i >= 0; i--) {
                    let info = this.bannerViewNameStack[i];
                    if (info.zIndex == -1) {
                        this.bannerViewNameStack.splice(i, 1);
                        if (i == (stackNum - 1)) {
                            bLastDialog = true;
                        }
                        break;
                    }
                }
                if (bLastDialog) {
                    this.adaptBanner();
                }
            }
            static onMsgWarpSceneCompleted(e) {
                this.onViewOpen(e);
            }
            static onMsgUserCloseNativeBanner(e) {
                if (!e.viewName) {
                    return;
                }
                this.userClosedNativeBannerTimeViewNameDict[e.viewName] = Tools.time();
                this.closeBanner(true);
            }
            static onMsgNativeDataRefresh(e) {
                let adEventId = this.currShowingBannerEventId;
                if (!adEventId) {
                    return;
                }
                if (e.advId != mgrCfg.get("ad_event_db", adEventId, "advId")) {
                    return;
                }
                if (!this.nativeBanner || this.nativeBanner.destroyed) {
                    return;
                }
                try {
                    this.nativeBanner.refreshBanner();
                }
                catch (error) {
                }
            }
            static onMsgTriggerNativeBanner() {
                this.triggerShowingNativeBanner();
            }
            static cleanBanner() {
                this.closeBanner();
                this.bannerViewNameStack = [];
            }
            static showBanner(bannerEventId, targetViewName) {
                let copOpenBannerGap = mgrSdk.getCopNumberValueByKey("banner_open_gap") || 0;
                if ((Tools.time() - this.lastOpenBannerTime) < copOpenBannerGap) {
                    return;
                }
                this.closeBanner();
                this.currShowingBannerEventId = bannerEventId;
                if (!this.nativeBanner) {
                    let nativeAdBanner = new vNativeBanner({});
                    let root = mgrDirector.get2DDialogLayer();
                    root.addChild(nativeAdBanner);
                    nativeAdBanner.zOrder = 100000;
                    this.nativeBanner = nativeAdBanner;
                }
                this.nativeBanner.show(bannerEventId, targetViewName);
                this.lastOpenBannerTime = Tools.time();
            }
            static closeBanner(bUserClosed = false) {
                if (this.currShowingBannerEventId) {
                    mgrAd.closeAdv(this.currShowingBannerEventId);
                    mgrAdNative.onNativeAdViewClenup(this.currShowingBannerEventId, true, bUserClosed);
                    this.currShowingBannerEventId = null;
                }
                else {
                }
                try {
                    if (this.nativeBanner) {
                        this.nativeBanner.destroy();
                    }
                }
                catch (error) {
                }
                this.nativeBanner = null;
            }
            static isNativeBannerShowing() {
                if (!this.nativeBanner || this.nativeBanner.destroyed) {
                    return false;
                }
                return this.nativeBanner.isNativeBannerShowing();
            }
            static triggerShowingNativeBanner() {
                if (!this.currShowingBannerEventId) {
                    return;
                }
                mgrAdNative.clickNative(this.currShowingBannerEventId);
            }
        }
        mgrBannerInt.bannerViewNameStack = [];
        mgrBannerInt.userClosedNativeBannerTimeViewNameDict = [];
        mgrBannerInt.activingViewNameArr = [
            "vAdFreeTrialPartDialog",
            "vLuckDiamondDialog",
            "vGotItemDialog",
            "vGotPartDialog",
            "vAmuseCardTrialDialog",
            "vAmuseCakeResultDialog",
            "vSurpriseRewardDialog",
        ];

        class mgrVideoRecorder extends Manager {
            static onLoad() {
                super.onLoad();
                this.registerListeners({
                    MSG_SDK_RECORD_GAME_VIDEO_RESULT: this.onMsgSdkRecordGameVideoResult,
                    MSG_SDK_SHARE_VIDEO_RESULT: this.onMsgSdkShareVideoResult,
                });
                Timer.callLoop(0.1, this.onTimerLoop.bind(this), true);
            }
            static onTimerLoop(timer) {
                if (this.state == this.ST_RECORDING) {
                    if (!this.bPause) {
                        this.recordingDuration += timer.span;
                    }
                    if (this.recordingDuration >= this.MAX_DURATION) {
                        this.stopRecord();
                    }
                }
            }
            static setState(state) {
                let originState = this.state;
                this.state = state;
                if (this.DEBUG)
                    console.log("mgrVideoRecorder.state", originState, state);
                if (originState != this.state) {
                    this.sendMsg("MSG_VIDEO_RECORDER_STATE_CHANGED", {
                        state: state,
                        originState: originState,
                    });
                }
            }
            static onMsgSdkRecordGameVideoResult(e) {
                let data = e;
                let action = data.action;
                let bSuccessful = data.bSuccessful;
                if (this.DEBUG)
                    console.log("mgrVideoRecorder.onMsgSdkRecordGameVideoResult", bSuccessful, action);
                if (bSuccessful) {
                    switch (action) {
                        case "start":
                            this.recordingDuration = 0;
                            this.bPause = false;
                            this.setState(this.ST_RECORDING);
                            break;
                        case "pause":
                            this.bPause = true;
                            break;
                        case "resume":
                            this.bPause = false;
                            break;
                        case "stop":
                            if (this.bRestartFlag) {
                                this.bRestartFlag = false;
                                this.setState(this.ST_IDLE);
                                if (this.DEBUG)
                                    console.log("  request /c/recorderGameVideo start");
                                mgrSdk.recordGameVideo("start");
                            }
                            else {
                                let useMinDur = this.MIN_DURATION;
                                let copMinDur = mgrSdk.getCopNumberValueByKey("video_recorder_min_duration");
                                if (!!copMinDur) {
                                    if (copMinDur <= 5) {
                                        useMinDur = 5;
                                    }
                                    else {
                                        useMinDur = Math.min(30, copMinDur);
                                    }
                                }
                                if (this.recordingDuration < useMinDur) {
                                    this.setState(this.ST_IDLE);
                                }
                                else {
                                    this.setState(this.ST_FINISH);
                                }
                            }
                            break;
                        default:
                            console.warn("mgrVideoRecorder.onMsgSdkRecordGameVideoResult unknown action:", action);
                            break;
                    }
                }
                else {
                    this.setState(this.ST_IDLE);
                }
            }
            static onMsgSdkShareVideoResult(e) {
                let data = e;
                let bSuccessful = data.bSuccessful;
                console.log("mgrVideoRecorder.onMsgSdkShareVideoResult", bSuccessful);
                if (bSuccessful) {
                    mgrTip.showMsgTip("录屏分享成功");
                    if (this.isShareHasReward()) {
                        let rewards = this.getShareRewards();
                        for (let i = 0; i < rewards.length; i++) {
                            const [itemId, amount] = rewards[i];
                            mgrPlayer.addItemAmount(itemId, amount, "录屏分享");
                            mgrTip.addGotItemTip(itemId, amount);
                        }
                        mgrPlayer.addItemAmount(Const.ITEM_ID_VIDEO_SHARE_COUNT, -1, "分享成功");
                        if (mgrPlayer.getItemAmount(Const.FIRST_SHARE_REWARD_PART_ID) <= 0) {
                            mgrPlayer.addItemAmount(Const.FIRST_SHARE_REWARD_PART_ID, 1, "录屏分享");
                            mgrTip.addGotItemTip(Const.FIRST_SHARE_REWARD_PART_ID, 1);
                        }
                    }
                    this.setState(this.ST_IDLE);
                }
                else {
                    mgrTip.showMsgTip("录屏分享失败");
                }
            }
            static isSupportRecord() {
                if (mgrSdk.getCopNumberValueByKey("b_record_video") != 1)
                    return false;
                if (!mgrChannel._isSupportRecordShare)
                    return false;
                if (!mgrChannel.getUserOpenVideoRecord())
                    return false;
                return true;
            }
            static startRecord(duration = this.DEFAUL_DURATION) {
                if (this.DEBUG)
                    console.log("mgrVideoRecorder.startRecord");
                if (!this.isSupportRecord())
                    return;
                if (this.state == this.ST_RECORDING) {
                    this.bRestartFlag = true;
                    if (this.DEBUG)
                        console.log("  request /c/recorderGameVideo stop");
                    mgrSdk.recordGameVideo("stop");
                }
                else {
                    if (this.DEBUG)
                        console.log("  request /c/recorderGameVideo start");
                    mgrSdk.recordGameVideo("start");
                }
            }
            static stopRecord() {
                if (this.DEBUG)
                    console.log("mgrVideoRecorder.stopRecord");
                if (!this.isSupportRecord())
                    return;
                if (this.DEBUG)
                    console.log("  request /c/recorderGameVideo stop");
                if (this.state == this.ST_FINISH) {
                    return;
                }
                mgrSdk.recordGameVideo("stop");
            }
            static pauseRecord() {
                if (this.DEBUG)
                    console.log("mgrVideoRecorder.pauseRecord");
                if (!this.isSupportRecord())
                    return;
                if (this.DEBUG)
                    console.log("  request /c/recorderGameVideo pause");
                mgrSdk.recordGameVideo("pause");
            }
            static resumeRecord() {
                if (this.DEBUG)
                    console.log("mgrVideoRecorder.resumeRecord");
                if (!this.isSupportRecord())
                    return;
                if (this.DEBUG)
                    console.log("  request /c/recorderGameVideo resume");
                mgrSdk.recordGameVideo("resume");
            }
            static isRecording() {
                return this.state == this.ST_RECORDING;
            }
            static canShare() {
                let bCan = (this.isSupportRecord() && this.state == this.ST_FINISH) ? true : false;
                return bCan;
            }
            static isShareHasReward() {
                return mgrPlayer.getItemAmount(Const.ITEM_ID_VIDEO_SHARE_COUNT) > 0;
            }
            static getShareRewards() {
                if (this.isShareHasReward()) {
                    return [[Const.ITEM_ID_DIAMONDS, 10]];
                }
                else {
                    return [];
                }
            }
            static share() {
                if (this.DEBUG)
                    console.log("mgrVideoRecorder.share");
                if (this.state != this.ST_FINISH) {
                    mgrTip.showMsgTip("当前不能分享录屏");
                    return;
                }
                mgrSdk.shareGameVideo();
            }
            static getRecordStatus() {
                return this.state;
            }
        }
        mgrVideoRecorder.ST_IDLE = 1;
        mgrVideoRecorder.ST_RECORDING = 2;
        mgrVideoRecorder.ST_FINISH = 3;
        mgrVideoRecorder.DEFAUL_DURATION = 60;
        mgrVideoRecorder.MAX_DURATION = 60;
        mgrVideoRecorder.MIN_DURATION = 15;
        mgrVideoRecorder.DEBUG = true;
        mgrVideoRecorder.state = 1;
        mgrVideoRecorder.bPause = false;
        mgrVideoRecorder.recordingDuration = 0;
        mgrVideoRecorder.bRestartFlag = false;

        class mgrShare extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化loadRecord.mgrshare");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("share_info") || {};
                this.shareInfos = record.shareInfos || {};
                Timer.callLoop(1, () => {
                    let bChanged = false;
                    for (let key in this.shareInfos) {
                        if (this.shareInfos[key]) {
                            let lastShareTime = this.shareInfos[key].lastShareTime;
                            if (!Tools.isOneDay(lastShareTime, Tools.time())) {
                                this.shareInfos[key].dailyShareCount = 0;
                                this.shareInfos[key].lastShareTime = Tools.time();
                                bChanged = true;
                            }
                        }
                    }
                    if (bChanged) {
                        this.saveRecord();
                    }
                }, this);
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    shareInfos: this.shareInfos
                };
                mgrRecord.setData("share_info", record);
            }
            static isCanShare(dialogName) {
                if (!mgrGuide.isAllForceGuideFinished()) {
                    return false;
                }
                if (!mgrChannel.canShare()) {
                    return false;
                }
                if (!mgrVideoRecorder.isSupportRecord()) {
                    return false;
                }
                let cd = mgrSdk.getCopNumberValueByKey(`share_${dialogName}_cd`);
                let count = mgrSdk.getCopNumberValueByKey(`share_${dialogName}_count`);
                if (count <= 0) {
                    return false;
                }
                if (this.shareInfos[dialogName]) {
                    let curCount = this.shareInfos[dialogName].dailyShareCount;
                    let lastShareTime = this.shareInfos[dialogName].lastShareTime;
                    if (lastShareTime + cd > Tools.time() || curCount >= count) {
                        return false;
                    }
                }
                return true;
            }
            static isDisableNotanksMode() {
                let bDisable = (mgrSdk.getCopNumberValueByKey(`b_disable_video_share_nothanks_mode`) || 0) == 1 ? true : false;
                return bDisable;
            }
            static getShareDelayTime() {
                return mgrSdk.getCopNumberValueByKey(`video_share_delay_time`) || 0;
            }
            static getShareGuideTime() {
                return mgrSdk.getCopNumberValueByKey(`guide_share_button_second`) || 0;
            }
            static isShareMistake() {
                return !!(mgrSdk.getCopNumberValueByKey(`video_share_mistake`) || 0);
            }
            static recordShare(dialogName) {
                if (this.shareInfos[dialogName]) {
                    this.shareInfos[dialogName].dailyShareCount++;
                    this.shareInfos[dialogName].lastShareTime = Tools.time();
                }
                else {
                    this.shareInfos[dialogName] = { lastShareTime: Tools.time(), dailyShareCount: 1 };
                }
                console.log("查看shareInfos", this.shareInfos);
                this.saveRecord();
            }
        }

        class mgrTip extends Manager {
            static onLoad() {
                super.onLoad();
                this.initItemGotEffectTip();
                Timer.callLater(5, () => {
                    Timer.callLoop(1, this.onTimerLoop.bind(this), true);
                }, this);
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("full_screen_more_game") || {};
                this.last_time_full_screen_more_game_fixed = record.last_time_full_screen_more_game_fixed || 0;
                this.last_time_full_screen_more_game_free = record.last_time_full_screen_more_game_free || 0;
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    last_time_full_screen_more_game_fixed: this.last_time_full_screen_more_game_fixed,
                    last_time_full_screen_more_game_free: this.last_time_full_screen_more_game_free,
                };
                mgrRecord.setData("full_screen_more_game", record);
            }
            static onTimerLoop() {
                this.tryShowFullScreenMoreGameFree();
            }
            static showPicker(title, conf, callback) {
                mgrDirector.openDialog("DebugPickerDialog", {
                    title: title,
                    datas: conf,
                    fOnClick: callback,
                }, false);
            }
            static alertPrompt1(title, content, btnText2, callback2, bShowAd = false, bShowClose = false) {
                return this._alertPrompt(title, content, [btnText2], [callback2], bShowAd, bShowClose);
            }
            static alertPrompt2(title, content, btnText1, btnText2, callback1, callback2, bShowAd = false, bShowClose = false) {
                return this._alertPrompt(title, content, [btnText1, btnText2], [callback1, callback2], bShowAd, bShowClose);
            }
            static _alertPrompt(title, content, btnTexts, callbacks, bShowAd = false, bShowClose = false) {
                return mgrDirector.openDialog("vPromptDialog", {
                    title: title,
                    content: content,
                    btnTexts: btnTexts,
                    callbacks: callbacks,
                    bShowAd: bShowAd,
                    bShowClose: bShowClose,
                });
            }
            static showBadgeWithNumber(node, count, offset = new Laya.Point(5, 5)) {
                if (count > 0) {
                    return this.showBadge(node, offset, count);
                }
                else {
                    this.hideBadge(node);
                    return false;
                }
            }
            static showBadge(node, offset = new Laya.Point(5, 5), count = 1) {
                if (!count || count <= 0) {
                    this.hideBadge(node);
                    return false;
                }
                let badge = node["__badge"];
                if (!badge) {
                    badge = new Laya.Image();
                    badge.anchorX = 0.5;
                    badge.anchorY = 0.5;
                    Tools.loadImg(badge, "res/ui/common/redPoint.png", true, () => {
                    });
                    node["__badge"] = badge;
                    node.addChild(badge);
                    cc.tween(badge).to(0.5, { scaleX: 1.25, scaleY: 1.25 })
                        .to(0.5, { scaleX: 1, scaleY: 1 })
                        .start();
                    badge.pos(node.width - offset.x, offset.y);
                    return true;
                }
                badge.pos(node.width - offset.x, offset.y);
                return true;
            }
            static hideBadge(node) {
                if (node["__badge"]) {
                    node.removeChild(node["__badge"]);
                    node["__badge"] = null;
                }
            }
            static isBadging(node) {
                return !!node["__badge"];
            }
            static showMsgTip(text, screenPos) {
                if (!screenPos) {
                    screenPos = new Laya.Vector2(Laya.stage.width / 2 * Laya.stage.clientScaleX, Laya.stage.height / 2 * Laya.stage.clientScaleY);
                }
                let vMsgTip = Const.require.requireModule(`vMsgTip`);
                let view = new vMsgTip({ content: text });
                mgrDirector.getTipRoot().addChild(view);
            }
            static showItemTip(itemId, amount, pointStr) {
                let vItemTip = Const.require.requireModule(`vItemTip`);
                let view = new vItemTip({
                    itemId: itemId,
                    amount: amount,
                    pointStr: pointStr,
                });
                mgrDirector.getTipRoot().addChild(view);
            }
            static showWeekNetTip(url) {
                let label = mgrDirector.getTipRoot().getChildByName("week_net_tip");
                if (!label) {
                    label = new Laya.Label();
                    label.name = "week_net_tip";
                    label.fontSize = 20;
                    label.color = "#ffffff";
                    label.stroke = 2;
                    label.strokeColor = "#222222";
                    label.text = `网络好像丢失了, res:${url}`;
                    label.pivotX = label.width / 2;
                    mgrDirector.getTipRoot().addChild(label);
                    Tools.widget(0.5, 0.5, label);
                }
            }
            static hideWeekNetTip() {
                let label = mgrDirector.getTipRoot().getChildByName("week_net_tip");
                if (label)
                    label.removeSelf();
            }
            static addGotItemTip(itemId, amount, amountSteps, customerContext) {
                let orderOfQueue = this.defaultGotItemQueue.length;
                if (this.gotItemDialogShowingFlags[0] == true) {
                    orderOfQueue++;
                }
                this.defaultGotItemQueue.push({
                    itemId: itemId,
                    amount: amount,
                    amountSteps: amountSteps,
                    customerContext: customerContext,
                    orderOfQueue: orderOfQueue,
                });
                this._tryShowGotItemDialog();
            }
            static insertGotItemTip(itemId, amount, amountSteps, customerContext) {
                this.defaultGotItemQueue.unshift({
                    itemId: itemId,
                    amount: amount,
                    amountSteps: amountSteps,
                    customerContext: customerContext,
                });
                this._tryShowGotItemDialog();
            }
            static addGotItemTipGroup(datas) {
                let queue = null;
                Tools.forEachMap(this.gotItemQueues, (k, v) => {
                    if (v != this.defaultGotItemQueue && v.length <= 0) {
                        queue = v;
                        return true;
                    }
                });
                if (!queue) {
                    queue = [];
                    this.gotItemQueues.push(queue);
                }
                for (let i = 0; i < datas.length; i++) {
                    const v = datas[i];
                    queue.push(v);
                }
                this._tryShowGotItemDialog();
            }
            static addGotItemTipGroupToDisplayNow(datas) {
                let queue = null;
                if (this.gotItemQueues.length > 0 && !this.gotItemDialogShowingFlags[this.gotItemQueues.length - 1]) {
                    queue = this.gotItemQueues[this.gotItemQueues.length - 1];
                }
                if (!queue) {
                    queue = [];
                    this.gotItemQueues.push(queue);
                }
                for (let i = 0; i < datas.length; i++) {
                    const v = datas[i];
                    queue.push(v);
                }
                this._tryShowGotItemDialog();
            }
            static _tryShowGotItemDialog() {
                for (let queueIndex = 0; queueIndex < this.gotItemQueues.length; queueIndex++) {
                    const queue = this.gotItemQueues[queueIndex];
                    if (queue.length > 0) {
                        this.gotItemDialogShowingFlags[queueIndex] = true;
                        let v = queue.shift();
                        if (v.amount < 0) {
                            mgrTip.showItemTip(v.itemId, v.amount);
                            Timer.callLater(0.5, () => {
                                this.gotItemDialogShowingFlags[queueIndex] = false;
                                this._tryShowGotItemDialog();
                            }, this);
                        }
                        else {
                            let needShowItemIds = [
                                Const.ITEM_ID_ENERGY,
                                Const.ITEM_ID_GOLD,
                                Const.ITEM_ID_DIAMONDS,
                                Const.ITEM_ID_MOON_CAKE,
                            ];
                            let itemTemplate = mgrCfg.get_from_item_template_db(v.itemId);
                            if (needShowItemIds.indexOf(v.itemId) < 0 && v.itemId < 100
                                && itemTemplate.flag != Const.ITEM_FLAG_CAKE && itemTemplate.flag != Const.ITEM_FLAG_MAKE_CLOTH && itemTemplate.flag != Const.ITEM_FLAG_CARD) {
                                this.gotItemDialogShowingFlags[queueIndex] = false;
                                this._tryShowGotItemDialog();
                                return;
                            }
                            let bPart = mgrCfg.get_from_part_db(v.itemId);
                            let viewName = "vGotItemDialog";
                            if (bPart)
                                viewName = `vGotPartDialog`;
                            let context = {};
                            if (v.customerContext) {
                                Tools.forEachMap(v.customerContext, (k, v) => {
                                    context[k] = v;
                                });
                            }
                            context.bFromAd = v.bFromAd || (v.customerContext && v.customerContext.bFromAd);
                            context.orderOfQueue = v.orderOfQueue;
                            context.itemId = v.itemId;
                            context.amount = v.amount;
                            context.amountSteps = v.amountSteps;
                            context.fOnClose = () => {
                                this.gotItemDialogShowingFlags[queueIndex] = false;
                                if (v.customerContext && v.customerContext.fOnClose instanceof Function) {
                                    v.customerContext.fOnClose();
                                }
                                this._tryShowGotItemDialog();
                            };
                            let bImmediately = (!!v && !!v.customerContext && !!v.customerContext.bImmediately) ? true : false;
                            mgrDirector.openDialog(viewName, context, bImmediately);
                        }
                    }
                }
            }
            static isAllGotItemTipDisplayed() {
                let bFind = false;
                Tools.forEachMap(this.gotItemDialogShowingFlags, (k, v) => {
                    if (v) {
                        bFind = true;
                        return true;
                    }
                });
                if (bFind)
                    return false;
                for (let i = 0; i < this.gotItemQueues.length; i++) {
                    const queue = this.gotItemQueues[i];
                    if (queue.length > 0)
                        return false;
                }
                return true;
            }
            static isItemWaitingDisplay() {
                for (let i = 0; i < this.gotItemQueues.length; i++) {
                    const queue = this.gotItemQueues[i];
                    if (queue.length > 0)
                        return false;
                }
                return true;
            }
            static isWaitingDialogOpened() {
                return this.waitingDialog != null;
            }
            static openWaitingDialog(title, content) {
                if (this.isWaitingDialogOpened()) {
                    return;
                }
            }
            static closeWaitingDialog() {
                if (this.waitingDialog) {
                    this.waitingDialog.closeDialog();
                    this.waitingDialog = null;
                }
            }
            static isReconnectDialogShowed() {
                return !!this.ReconnectDialog;
            }
            static showReconnectDialog() {
                if (this.isReconnectDialogShowed()) {
                    return;
                }
                this.ReconnectDialog = mgrDirector.openDialog("vPromptDialog", {
                    title: "提示",
                    content: "网络可能出问题了, 请检查网络并重启游戏...",
                    btnTexts: ["取消"],
                    fOnClose: () => {
                        this.ReconnectDialog = null;
                    },
                });
            }
            static hideReconnectDialog() {
                if (this.ReconnectDialog) {
                    this.ReconnectDialog.closeDialog();
                    this.ReconnectDialog = null;
                }
            }
            static showAdGetDialog(param) {
                mgrDirector.openDialog("AdRewardDialog", param);
            }
            static showItemDetailDialog(itemId, ignoreRouter, fOnRouter, fOnClose) {
                if (mgrCfg.get_from_part_db(itemId)) {
                    mgrDirector.openDialog("vPartDetailDialog", {
                        itemId: itemId,
                        ignoreRouter: ignoreRouter,
                        fOnClose: fOnClose,
                        fOnRouter: fOnRouter,
                    });
                }
                else {
                    mgrTip.showMsgTip("暂未实现!!!");
                }
            }
            static showLoadingTip(router, offset, maskAlpha, bDisableDelay, customWaitWordStr) {
                console.warn("--------showLoadingTip-----router=", router);
                offset = offset || new Laya.Vector2;
                maskAlpha = maskAlpha || 0;
                let bShowLoading = this.__loadingTipRouters.length > 0;
                if (this.__loadingTipRouters.indexOf(router) == -1)
                    this.__loadingTipRouters.push(router);
                if (bShowLoading)
                    return;
                let bg = new Laya.Box;
                bg.size(768, 1280);
                bg.anchorY = 0.5;
                bg.anchorX = 0.5;
                mgrDirector.getTipRoot().addChild(bg);
                bg.y -= 30;
                let mask = new Laya.Image;
                mask.alpha = maskAlpha / 255;
                bg.addChild(mask);
                mask.size(768, 1280);
                mask.anchorX = 0.5;
                mask.anchorY = 0.5;
                mask.pos(bg.width / 2, bg.height / 2);
                let texture2d = Laya.Texture2D.blackTexture;
                texture2d.width = 768;
                texture2d.height = 1280;
                let texture = new Laya.Texture(texture2d, undefined, 768, 1280);
                mask.graphics.drawTexture(texture);
                let loadingbg = new Laya.Image();
                loadingbg.anchorX = 0.5;
                loadingbg.anchorY = 0.5;
                bg.addChild(loadingbg);
                loadingbg.x += (offset.x + bg.width / 2);
                loadingbg.y += (offset.y + bg.height / 2);
                Tools.loadImg(loadingbg, "res/ui/loading/load_02.png", true);
                let spriteNode = new Laya.Image();
                spriteNode.anchorX = 0.5;
                spriteNode.anchorY = 0.5;
                bg.addChild(spriteNode);
                spriteNode.x += (offset.x + bg.width / 2);
                spriteNode.y += (offset.y + bg.height / 2);
                Tools.loadImg(spriteNode, "res/ui/loading/load_01.png", true);
                let label = new Laya.Label;
                label.color = `#ffffff`;
                label.fontSize = 18;
                label.align = `center`;
                label.anchorX = 0.5;
                label.anchorY = 0.5;
                label.text = customWaitWordStr || "准备中...";
                bg.addChild(label);
                label.pos(spriteNode.x, spriteNode.y + 110);
                cc.tween(loadingbg)
                    .repeatForever(cc.tween().byRotation(2, 360))
                    .start();
                this.__loadingTipNode = bg;
                if (!bDisableDelay) {
                    bg.alpha = 0;
                    Timer.callLater(0.2, () => {
                        cc.tween(bg).toAlpha(0.1, 1).start();
                    }, bg);
                }
                Tools.registerTouchHander(mask, () => {
                    console.log(" touch loading mask ");
                });
            }
            static hideLoadingTip(router) {
                let index = this.__loadingTipRouters.indexOf(router);
                if (index >= 0)
                    this.__loadingTipRouters.splice(index, 1);
                if (this.__loadingTipRouters.length > 0)
                    return;
                this.__loadingTipNode && this.__loadingTipNode.destroy();
                this.__loadingTipNode = null;
                return true;
            }
            static isShowingLoadingTip() {
                return !!this.__loadingTipNode;
            }
            static updateLoadingProgress() {
                if (!this.isShowingLoadingTip())
                    return;
            }
            static showJumpOtherGameBanner(parent, offsetY = 0, offsetX = 0) {
                let jumpOtherBanner = parent.getChildByName(`vJumpOtherGameBanner`);
                if (!!jumpOtherBanner)
                    return;
                let vJumpOtherGameBanner = Const.require.requireModule(`vJumpOtherGameBanner`);
                jumpOtherBanner = new vJumpOtherGameBanner({});
                jumpOtherBanner.name = `vJumpOtherGameBanner`;
                parent.addChild(jumpOtherBanner);
                let posX = 288 + (mgrDirector.width - 576) / 2 + offsetX;
                let posY = 512 + (mgrDirector.height - 1024) / 2 + offsetY;
                let nodePos = parent.globalToLocal(new Laya.Point(posX, posY));
                jumpOtherBanner.pos(nodePos.x, nodePos.y);
                let script = parent.addComponent(Laya.Script);
                script.onDestroy = () => {
                    mgrTip.hideJumpOtherGameBanner(parent);
                };
                return true;
            }
            static hideJumpOtherGameBanner(parent) {
                let jumpOtherBanner = parent.getChildByName(`vJumpOtherGameBanner`);
                if (jumpOtherBanner) {
                    jumpOtherBanner.destroy();
                }
            }
            static showJumpOtherGameBannerLeftVertical(parent, offsetY = 0, offsetX = 0) {
                let jumpOtherBannerVertical = parent.getChildByName(`vJumpOtherGameBannerVertical`);
                if (!!jumpOtherBannerVertical)
                    return;
                let vJumpOtherGameBannerVertical = Const.require.requireModule(`vJumpOtherGameBannerVertical`);
                jumpOtherBannerVertical = new vJumpOtherGameBannerVertical({});
                jumpOtherBannerVertical.name = `vJumpOtherGameBannerVertical`;
                parent.addChild(jumpOtherBannerVertical);
                let posX = 140 + (mgrDirector.width - 576) / 2 + offsetX;
                let posY = 512 + (mgrDirector.height - 1024) / 2 + offsetY;
                let nodePos = parent.globalToLocal(new Laya.Point(posX, posY));
                jumpOtherBannerVertical.pos(nodePos.x, nodePos.y);
                let script = parent.addComponent(Laya.Script);
                script.onDestroy = () => {
                    mgrTip.hideJumpOtherGameBannerLeftVertical(parent);
                };
                return true;
            }
            static hideJumpOtherGameBannerLeftVertical(parent) {
                let jumpOtherBannerVertical = parent.getChildByName(`vJumpOtherGameBannerVertical`);
                if (jumpOtherBannerVertical) {
                    jumpOtherBannerVertical.destroy();
                }
            }
            static showJumpOtherGameBannerRightVertical(parent, offsetY = 0, offsetX = 0) {
                let jumpOtherBannerVertical = parent.getChildByName(`vJumpOtherGameBannerVertical`);
                if (!!jumpOtherBannerVertical)
                    return;
                let vJumpOtherGameBannerVertical = Const.require.requireModule(`vJumpOtherGameBannerVertical`);
                jumpOtherBannerVertical = new vJumpOtherGameBannerVertical({});
                jumpOtherBannerVertical.name = `vJumpOtherGameBannerVertical`;
                parent.addChild(jumpOtherBannerVertical);
                let posX = 288 + (mgrDirector.width) / 2 + offsetX;
                let posY = 512 + (mgrDirector.height - 1024) / 2 + offsetY;
                let nodePos = parent.globalToLocal(new Laya.Point(posX, posY));
                jumpOtherBannerVertical.pos(nodePos.x, nodePos.y);
                let script = parent.addComponent(Laya.Script);
                script.onDestroy = () => {
                    mgrTip.hideJumpOtherGameBannerRightVertical(parent);
                };
                return true;
            }
            static hideJumpOtherGameBannerRightVertical(parent) {
                let jumpOtherBannerVertical = parent.getChildByName(`vJumpOtherGameBannerVertical`);
                if (jumpOtherBannerVertical) {
                    jumpOtherBannerVertical.destroy();
                }
            }
            static hideJumpOtherGameBannerVertical(parent) {
                this.hideJumpOtherGameBannerLeftVertical(parent);
                this.hideJumpOtherGameBannerLeftVertical(parent);
            }
            static showJumpOtherGameDragLeft(parent, offsetY = 0, offsetX = 0) {
                let jumpOtherDrag = parent.getChildByName(`vJumpOtherDragLeft`);
                if (!!jumpOtherDrag)
                    return;
                let vJumpOtherDrag = Const.require.requireModule(`vJumpOtherDragLeft`);
                jumpOtherDrag = new vJumpOtherDrag({});
                parent.addChild(jumpOtherDrag);
                jumpOtherDrag.name = `vJumpOtherDragLeft`;
                jumpOtherDrag.pos(offsetX, offsetY);
                let script = parent.addComponent(Laya.Script);
                script.onDestroy = () => {
                    mgrTip.hideJumpOtherGameDragLeft(parent);
                };
                return true;
            }
            static hideJumpOtherGameDragLeft(parent) {
                let jumpOtherDrag = parent.getChildByName(`vJumpOtherDragLeft`);
                if (jumpOtherDrag) {
                    jumpOtherDrag.destroy();
                }
            }
            static showJumpOtherGameDragRight(parent, offsetY = 0, offsetX = 0) {
                let jumpOtherDrag = parent.getChildByName(`vJumpOtherDragRight`);
                if (!!jumpOtherDrag)
                    return;
                let vJumpOtherDrag = Const.require.requireModule(`vJumpOtherDragRight`);
                jumpOtherDrag = new vJumpOtherDrag({});
                parent.addChild(jumpOtherDrag);
                jumpOtherDrag.name = `vJumpOtherDragRight`;
                jumpOtherDrag.pos(offsetX, offsetY);
                let script = parent.addComponent(Laya.Script);
                script.onDestroy = () => {
                    mgrTip.hideJumpOtherGameDragRight(parent);
                };
                return true;
            }
            static hideJumpOtherGameDragRight(parent) {
                let jumpOtherDrag = parent.getChildByName(`vJumpOtherDragRight`);
                if (jumpOtherDrag) {
                    jumpOtherDrag.destroy();
                }
            }
            static showNativeBanner(adEventId, parent, offset = new Laya.Vector2) {
                if (!this.nativeAdBanner || this.nativeAdBanner.destroyed) {
                    let vNativeBanner = Const.require.requireModule(`vNativeBanner`);
                    this.nativeAdBanner = new vNativeBanner({
                        adEventId: adEventId,
                    });
                    parent.addChild(this.nativeAdBanner);
                }
                mgrLayout.widget(mgrDirector.width / 2 + offset.x, mgrDirector.height + offset.y, this.nativeAdBanner, { x: 0.5, y: 1 });
                this.nativeAdBanner.active = true;
            }
            static hideNativeBanner() {
                if (this.nativeAdBanner) {
                    this.nativeAdBanner.destroy();
                    this.nativeAdBanner = null;
                }
            }
            static showGuidingTip(router, offset = new Laya.Vector2, alpha = 0) {
                let bShowLoading = this.__guidingTipRouters.length > 0;
                if (this.__guidingTipRouters.indexOf(router) == -1)
                    this.__guidingTipRouters.push(router);
                if (bShowLoading)
                    return;
                let bg = new Laya.Box;
                bg.size(768, 1280);
                bg.anchorY = 0.5;
                bg.anchorX = 0.5;
                mgrDirector.getTipRoot().addChild(bg);
                let mask = new Laya.Image;
                mask.alpha = alpha / 255;
                bg.addChild(mask);
                mask.size(768, 1280);
                mask.anchorX = 0.5;
                mask.anchorY = 0.5;
                mask.pos(bg.width / 2, bg.height / 2);
                let texture2d = Laya.Texture2D.blackTexture;
                texture2d.width = 768;
                texture2d.height = 1280;
                let texture = new Laya.Texture(texture2d, undefined, 768, 1280);
                mask.graphics.drawTexture(texture);
                this.__guidingTipNode = bg;
                Tools.registerTouchHander(mask, () => {
                    console.log(" touch guiding mask ");
                });
            }
            static hideGuidingTip(router) {
                let index = this.__guidingTipRouters.indexOf(router);
                if (index >= 0)
                    this.__guidingTipRouters.splice(index, 1);
                if (this.__guidingTipRouters.length > 0)
                    return;
                this.__guidingTipNode && this.__guidingTipNode.destroy();
                this.__guidingTipNode = null;
                return true;
            }
            static isShowGuidingTip() {
                return !!this.__guidingTipNode;
            }
            static initItemGotEffectTip() {
                let classObj = Const.require.requireModule(`vItemGotEffectDialog`);
                this.itemGotEffect = new classObj;
                mgrDirector.get2DDialogLayer().addChild(this.itemGotEffect);
                this.itemGotEffect.visible = false;
            }
            static showGotItemEffect(itemId, amount, wPos) {
                this.itemGotEffect.playAction(itemId, amount, wPos);
            }
            static tryShowPhotoShare(shareCopName, tex2d, wordTip, callback) {
                if (!mgrGuide.isGuiding() && mgrGuide.isAllForceGuideFinished()) {
                    mgrTip.showLoadingTip("loading_tip_share");
                    Timer.callLater(0.5, () => {
                        mgrTip.hideLoadingTip("loading_tip_share");
                        if (!!mgrShare.isCanShare(shareCopName)) {
                            let rewardPartId = null;
                            if (mgrPlayer.getItemAmount(rewardPartId) <= 0) {
                                rewardPartId = Const.FIRST_SHARE_REWARD_PART_ID;
                            }
                            mgrDirector.openDialog("vShareWithPhotoDialog", {
                                rewardPartId: rewardPartId,
                                shareTipStr: wordTip,
                                texture2dShot: tex2d,
                                fOnClose: () => {
                                    callback();
                                }
                            });
                        }
                        else {
                            callback();
                        }
                    }, this);
                }
                else {
                    callback();
                }
            }
            static isNativeBannerShowing() {
                return mgrBannerInt.isNativeBannerShowing();
            }
            static tryShowFullScreenMoreGameFixed(copStr) {
                let cd = mgrSdk.getCopNumberValueByKey("full_screen_more_game_fixed_cd") || 0;
                let bOverCd = Tools.time() - this.last_time_full_screen_more_game_fixed >= cd;
                let isGuiding = mgrGuide.isGuiding() || !mgrGuide.isAllGuideFinished();
                let bGuideEnable = mgrSdk.getCopNumberValueByKey("b_show_full_screen_more_game_in_guide") == 1;
                if (bGuideEnable) {
                    isGuiding = false;
                }
                if (!isGuiding && mgrSdk.getCopNumberValueByKey(copStr) == 1 && bOverCd) {
                    mgrDirector.openDialog("vFullScreenMoreGame");
                    this.last_time_full_screen_more_game_fixed = Tools.time();
                    this.saveRecord();
                }
            }
            static tryShowFullScreenMoreGameFree() {
                let cd = mgrSdk.getCopNumberValueByKey("full_screen_more_game_free_cd") || 0;
                let bOverCd = Tools.time() - this.last_time_full_screen_more_game_free >= cd;
                let isGuiding = mgrGuide.isGuiding() || !mgrGuide.isAllGuideFinished();
                let bGuideEnable = mgrSdk.getCopNumberValueByKey("b_show_full_screen_more_game_in_guide") == 1;
                if (bGuideEnable) {
                    isGuiding = false;
                }
                if (!isGuiding && mgrSdk.getCopNumberValueByKey("b_show_free_full_screen_more_game") == 1 && bOverCd) {
                    mgrDirector.openDialog("vFullScreenMoreGame");
                    this.last_time_full_screen_more_game_free = Tools.time();
                    this.saveRecord();
                }
            }
        }
        mgrTip.defaultGotItemQueue = [];
        mgrTip.gotItemQueues = [mgrTip.defaultGotItemQueue];
        mgrTip.gotItemDialogShowingFlags = {};
        mgrTip.waitingDialog = null;
        mgrTip.last_time_full_screen_more_game_fixed = 0;
        mgrTip.last_time_full_screen_more_game_free = 0;
        mgrTip.__loadingTipRouters = [];
        mgrTip.__guidingTipRouters = [];

        var EStageRating;
        (function (EStageRating) {
            EStageRating[EStageRating["unpass"] = 0] = "unpass";
            EStageRating[EStageRating["pass"] = 1] = "pass";
        })(EStageRating || (EStageRating = {}));
        class mgrStage extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("stage") || {};
                this.stageDatas = record.stageDatas || {};
                this.stageProgress = record.stageProgress || 0;
                mgrCfg.forDb_from_stage_db((k, v) => {
                    let data = this.stageDatas[v.id] || {
                        rating: 0,
                    };
                    this.stageDatas[v.id] = data;
                });
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    stageDatas: this.stageDatas,
                    stageProgress: this.stageProgress,
                };
                mgrRecord.setData("stage", record);
            }
            static preCheckCanBeginStage(stageId, bDisableTip = false) {
                let stage = mgrCfg.get_from_stage_db(stageId);
                if (!stage) {
                    console.warn("mgrStage.tryBeginStage stage not found!", stageId);
                    if (!bDisableTip) {
                        mgrTip.showMsgTip("stage not found!" + stageId);
                    }
                    return false;
                }
                let unlock = this.isStageUnlocked(stageId);
                if (!unlock) {
                    if (!bDisableTip) {
                        mgrTip.showMsgTip("尚未解锁");
                    }
                    return false;
                }
                return true;
            }
            static beginStage(stageId, bIgnoreConsume = false, successCallback) {
                let stage = mgrCfg.get_from_stage_db(stageId);
                if (!stage) {
                    console.warn("mgrStage.beginStage stage not found!", stageId);
                    return;
                }
                if (!bIgnoreConsume) {
                    let count = stage.energyCost;
                    if (count > 0) {
                        let bRet = mgrShop.tryConsumeItem(Const.ITEM_ID_ENERGY, count, "关卡消耗");
                        if (bRet) {
                            mgrTip.addGotItemTip(Const.ITEM_ID_ENERGY, -count);
                        }
                        else {
                            return;
                        }
                    }
                }
                mgrDirector.warpSceneWidthEffect(`vFreedomRoomScene`, {
                    stageId: stageId,
                    backSceneName: `vWorldDailyQuestMainScene`,
                });
                successCallback && successCallback();
            }
            static getRating(stageId, score) {
                let stageData = mgrCfg.get_from_stage_db(stageId);
                if (score >= stageData.passScore)
                    return EStageRating.pass;
                return EStageRating.unpass;
            }
            static finishStage(stageId, partIds, roleTagId, addScore = 0) {
                let stage = mgrCfg.get_from_stage_db(stageId);
                if (!stage) {
                    console.warn("mgrStage.finishStage stage not found!", stageId);
                    return;
                }
                let recordRating = this.getStageRating(stageId);
                let bRatingChanged = false;
                let score = mgrCard.calculateRoleTagPartIdsPower(roleTagId, partIds);
                score += addScore;
                let rating = this.getRating(stageId, score);
                if (rating > recordRating) {
                    this.stageDatas[stageId].rating = rating;
                    bRatingChanged = true;
                    if (stageId < 100 && stage.stageProgress && stage.stageProgress > 0 && this.stageProgress < stage.stageProgress) {
                        this.stageProgress = stage.stageProgress;
                    }
                }
                let rewards = [];
                if (rating == EStageRating.unpass) {
                    mgrSound.play(313);
                    let failSoundIds = [331, 332];
                    mgrSound.play(failSoundIds[Mathf.random(0, failSoundIds.length - 1)]);
                    return {
                        stageId: stageId,
                        rating: rating,
                        rewards: rewards,
                        score: score,
                    };
                }
                mgrSound.play(312);
                let succesSoundIds = [321, 322, 323];
                mgrSound.play(succesSoundIds[Mathf.random(0, succesSoundIds.length - 1)]);
                if (bRatingChanged) {
                    for (let index = 0; index < stage.passReward.length; index++) {
                        const element = stage.passReward[index];
                        let itemCountInfo = {
                            itemId: element[0],
                            amount: element[1],
                        };
                        rewards.push({
                            itemId: itemCountInfo.itemId,
                            amount: itemCountInfo.amount,
                        });
                        mgrPlayer.addItemAmount(itemCountInfo.itemId, itemCountInfo.amount, "关卡奖励");
                    }
                    this.sendMsg("MSG_STAGE_RATING_CHAGNED", { stageId: stageId, rating: rating });
                    this.saveRecord();
                }
                return {
                    stageId: stageId,
                    rating: rating,
                    rewards: rewards,
                    score: score,
                };
            }
            static getStageProgress() {
                return this.stageProgress;
            }
            static getStageRating(stageId) {
                let stageData = this.stageDatas[stageId];
                if (!stageData)
                    return 0;
                return stageData.rating || 0;
            }
            static isStageUnlocked(stageId) {
                if (mgrDebug.bUnlockAllStage)
                    return true;
                let stage = mgrCfg.get_from_stage_db(stageId);
                if (!stage)
                    return false;
                let aids = stage.unlockAids;
                for (let i = 0; i < aids.length; i++) {
                    const aid = aids[i];
                    if (!mgrAchievement.isAchievementCompleted(aid))
                        return false;
                }
                return true;
            }
            static getCurrentStageId() {
                let stageId = 0;
                let bFind = false;
                let queue = [];
                mgrCfg.forDb_from_stage_db((key, value) => {
                    if (value.id < 100) {
                        stageId = value.id;
                        queue.push(value.id);
                        if (queue.length > 5) {
                            queue.shift();
                        }
                        if (value.stageProgress == this.getStageProgress() + 1) {
                            bFind = true;
                            return true;
                        }
                    }
                });
                if (bFind == false) {
                    stageId = queue[Tools.random(0, queue.length - 1)];
                }
                return stageId;
            }
            static getRecommendTagsByStageId(stageId) {
                let datas = [];
                let stageData = mgrCfg.get_from_stage_db(stageId);
                for (let i = 0; i < stageData.tagWeights.length; i++) {
                    const weight = stageData.tagWeights[i];
                    let tagData = mgrCfg.get_from_part_tag_db(i + 1);
                    datas.push({
                        id: i + 1,
                        weight: weight,
                        icon: tagData.icon,
                    });
                }
                datas = Tools.sortArrayByField(datas, "-weight");
                if (datas[1].weight > 0) {
                    return [datas[0], datas[1]];
                }
                else {
                    return [datas[0]];
                }
            }
            static getRecommendPartByStageAndType(type, roleTagId) {
                let partIds = [];
                let db = mgrCfg.getDbArr("part_db", (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    return true;
                });
                for (let k in db) {
                    let v = db[k];
                    if (v.type == type) {
                        partIds.push({
                            partId: v.id,
                            score: mgrCard.calculateRoleTagPartIdsPower(roleTagId, [v.id]),
                        });
                    }
                }
                partIds = Tools.sortArrayByField(partIds, "-score");
                let arr = [];
                for (let i = 0; i < 3; i++) {
                    if (partIds[i]) {
                        arr.push(partIds[i].partId);
                    }
                }
                return arr;
            }
        }
        mgrStage.stageDatas = {};

        var E_ACHIEVEMENT_TYPE;
        (function (E_ACHIEVEMENT_TYPE) {
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["stageRating"] = 1] = "stageRating";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["hubtouch"] = 2] = "hubtouch";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["consumeItem"] = 3] = "consumeItem";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["joinStage"] = 4] = "joinStage";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["giveLikes"] = 5] = "giveLikes";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["freeWear"] = 6] = "freeWear";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["watchAd"] = 7] = "watchAd";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["share"] = 8] = "share";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["unlockItem"] = 9] = "unlockItem";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["gotItem"] = 10] = "gotItem";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["joinPvp"] = 11] = "joinPvp";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["recommentSuit"] = 12] = "recommentSuit";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["recommentPlayer"] = 13] = "recommentPlayer";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["sign"] = 14] = "sign";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["pvpReward"] = 15] = "pvpReward";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["signDay"] = 16] = "signDay";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["changeTeamMember"] = 17] = "changeTeamMember";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["changeTeamLeader"] = 18] = "changeTeamLeader";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["fudongSingTime"] = 19] = "fudongSingTime";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["fudongSingScore"] = 20] = "fudongSingScore";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["fudongBalanceTime"] = 21] = "fudongBalanceTime";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["fudongBalanceScore"] = 22] = "fudongBalanceScore";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["fudongDanceTime"] = 23] = "fudongDanceTime";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["fudongDanceScore"] = 24] = "fudongDanceScore";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["fudongPhotoTime"] = 25] = "fudongPhotoTime";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["fudongPhotoScore"] = 26] = "fudongPhotoScore";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["amazeDanceTime"] = 27] = "amazeDanceTime";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["amazeDanceGotNew"] = 28] = "amazeDanceGotNew";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["amazeMemberGotNew"] = 29] = "amazeMemberGotNew";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["amazeMemberResult"] = 30] = "amazeMemberResult";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["amazePetGotNew"] = 31] = "amazePetGotNew";
            E_ACHIEVEMENT_TYPE[E_ACHIEVEMENT_TYPE["amazePetResult"] = 32] = "amazePetResult";
        })(E_ACHIEVEMENT_TYPE || (E_ACHIEVEMENT_TYPE = {}));
        class sAchievement {
            constructor(id) {
                this.id = id;
                this.template = mgrCfg.get("achievement_db", id);
                this.count = 0;
                this.maxCount = 0;
                this.state = AchievementState.unlocked;
                this.lastRefreshTime = 0;
                this._msgHander = new MsgHandler();
                this._msgHander.startProcMsg();
                let listenerMaps = {
                    MSG_STAGE_RATING_CHAGNED: this.onMsgStageRatingChanged.bind(this),
                    MSG_CLICK_ROLE: this.onMsgClickRole.bind(this),
                    MSG_ITEM_AMOUNT_CHANGED: this.onMsgItemAmountChanged.bind(this),
                    MSG_PVP_LIKE: this.onMsgLike.bind(this),
                    MSG_FREE_WEAR: this.onMsgFreeWear.bind(this),
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                    MSG_SHARE_VIDEO_SUCCESSFUL: this.onMsgShareVideoSuccessful.bind(this),
                    MSG_SHARE_SUCCESSFUL: this.onMsgShareSuccessful.bind(this),
                    MSG_JOIN_MATCH: this.onMsgJoinMatch.bind(this),
                    MSG_COMMENT_SUIT: this.onMsgCommentSuit.bind(this),
                    MSG_COMMENT_OTHER_PLAYER: this.onMsgCommentOtherPlayer.bind(this),
                    MSG_SIGN: this.onMsgSign.bind(this),
                    MSG_PVP_LIKE_REWARD: this.onMsgAchievementCommonHandler.bind(this),
                    MSG_TEAM_MEMBER_CHANGED: this.onMsgAchievementCommonHandler.bind(this),
                    MSG_TEAM_LEADER_CHANGED: this.onMsgAchievementCommonHandler.bind(this),
                    MSG_FUDONG_SING_RESULT: this.onMsgFudongSingResult.bind(this),
                    MSG_FUDONG_BALANCE_RESULT: this.onMsgFudongBalanceResult.bind(this),
                    MSG_FUDONG_DANCE_RESULT: this.onMsgFudongDanceResult.bind(this),
                    MSG_FUDONG_PHOTO_RESULT: this.onMsgFudongPhotoResult.bind(this),
                    MSG_AMAZE_DANCE_RESULT: this.onMsgAmazeDanceResult.bind(this),
                    MSG_AMAZE_MEMBER_RESULT: this.onMsgAmazeMemberResult.bind(this),
                    MSG_AMAZE_PET_RESULT: this.onMsgAmazePetResult.bind(this),
                };
                let targetData = mgrCfg.get_from_achievement_target_db(this.template.targetType);
                let usefulListeners = {};
                for (let index = 0; index < targetData.cmds.length; index++) {
                    const cmd = targetData.cmds[index];
                    usefulListeners[cmd] = listenerMaps[cmd];
                }
                this.registerListeners(usefulListeners);
            }
            setState(state) {
                this.state = state;
            }
            refreshCount(cmd) {
                let template = this.template;
                let targetType = template.targetType;
                let targetData = mgrCfg.get("achievement_target_db", targetType);
                if (!targetData) {
                    console.warn(ul.format("sAchievement.refreshCount target not found! targetType = %s", targetType));
                    return;
                }
                if (cmd && !targetData.cmdHash[cmd]) {
                    return;
                }
                let handler = this[targetData.calcCountHandlerName];
                if (!(handler instanceof Function)) {
                    console.warn(ul.format("sAchievement.refreshCount handler not found! handler = %s", targetData.calcCountHandlerName));
                    return;
                }
                let [count, maxCount] = handler.bind(this)();
                let bChanged = (this.count != null && this.count != count);
                this.count = count;
                this.maxCount = maxCount;
                if (bChanged) {
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
            }
            refreshState(cmd) {
                if (this.state != AchievementState.unlocked && this.maxCount != 0) {
                    return false;
                }
                if (this.template.bDaily && !Tools.isOneDay(this.lastRefreshTime, Tools.time())) {
                    this.count = 0;
                    this.state = AchievementState.unlocked;
                    this.lastRefreshTime = Tools.time();
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                this.refreshCount(cmd);
                if (this.state == AchievementState.unlocked && this.maxCount <= this.count) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                    return true;
                }
                return false;
            }
            registerListeners(listeners) {
                Tools.forEachMap(listeners, (k, listener) => {
                    listeners[k] = listener.bind(this);
                });
                this._msgHander.registerListeners(listeners);
            }
            startProcMsg() {
                this._msgHander.startProcMsg();
            }
            stopProcMsg() {
                this._msgHander.stopProcMsg();
            }
            sendMsg(msgName, data) {
                this._msgHander.sendMsg(msgName, data);
            }
            onMsgStageRatingChanged(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                let targetData = mgrCfg.get_from_achievement_target_db(this.template.targetType);
                if (targetData.id == E_ACHIEVEMENT_TYPE.stageRating) {
                    let requireStageId = this.template.data1;
                    let rating = mgrStage.getStageRating(requireStageId);
                    let requiredRating = this.template.data2;
                    if (rating >= requiredRating) {
                        this.count = 1;
                    }
                }
                else if (targetData.id == E_ACHIEVEMENT_TYPE.joinStage) {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgClickRole(e) {
                let pos = e.pos;
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                let requirePos = this.template.data1;
                if (requirePos == pos) {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgItemAmountChanged(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                let itemId = e.itemId;
                let amount = e.amountDelta;
                let targetData = mgrCfg.get_from_achievement_target_db(this.template.targetType);
                if (targetData.id == E_ACHIEVEMENT_TYPE.unlockItem) {
                    if (this.template.customData.indexOf(itemId) >= 0 && mgrPlayer.getItemAmount(itemId) - amount == 0) {
                        this.count++;
                    }
                }
                else if (targetData.id == E_ACHIEVEMENT_TYPE.gotItem) {
                    if (this.template.data1 == itemId) {
                        this.count += amount;
                    }
                }
                else if (targetData.id == E_ACHIEVEMENT_TYPE.consumeItem) {
                    if (amount > 0)
                        return;
                    if (!this.count)
                        this.count = 0;
                    let requireItemId = this.template.data1;
                    if (itemId == requireItemId) {
                        this.count += Math.abs(amount);
                    }
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgLike() {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                this.count++;
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgFreeWear() {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                this.count++;
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgAdEventSuccessd(e) {
                let adEventId = e.adEventId;
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                if (adEventData.type == `video`) {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgShareVideoSuccessful() {
                this.onMsgShareSuccessful();
            }
            onMsgShareSuccessful() {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                this.count++;
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgJoinMatch() {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                this.count++;
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgCommentSuit() {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                this.count++;
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgCommentOtherPlayer() {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                this.count++;
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgSign() {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                this.count++;
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgFudongSingResult(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                if (this.template.targetType == E_ACHIEVEMENT_TYPE.fudongSingScore) {
                    this.count = Math.max(this.count, e.score || 0);
                }
                else {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgFudongBalanceResult(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                if (this.template.targetType == E_ACHIEVEMENT_TYPE.fudongBalanceScore) {
                    this.count = Math.max(this.count, e.score || 0);
                }
                else {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgFudongDanceResult(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                if (this.template.targetType == E_ACHIEVEMENT_TYPE.fudongDanceScore) {
                    this.count = Math.max(this.count, e.score || 0);
                }
                else {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgFudongPhotoResult(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                if (this.template.targetType == E_ACHIEVEMENT_TYPE.fudongPhotoScore) {
                    this.count = Math.max(this.count, e.score || 0);
                }
                else {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgAmazeDanceResult(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                if (this.template.targetType == E_ACHIEVEMENT_TYPE.amazeDanceGotNew) {
                    this.count = 0;
                    let arr = mgrCfg.getDbArr("dance_db");
                    for (let k in arr) {
                        let danceData = arr[k];
                        if (mgrPlayer.getItemAmount(danceData.id) > 0) {
                            this.count++;
                        }
                    }
                }
                else {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgAmazeMemberResult(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                if (this.template.targetType == E_ACHIEVEMENT_TYPE.amazeMemberGotNew) {
                    this.count = 0;
                    let arr = mgrCfg.getDbArr("role_db");
                    for (let k in arr) {
                        let danceData = arr[k];
                        if (mgrPlayer.getItemAmount(danceData.id) > 0) {
                            this.count++;
                        }
                    }
                }
                else {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgAmazePetResult(e) {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                if (this.template.targetType == E_ACHIEVEMENT_TYPE.amazePetGotNew) {
                    this.count = 0;
                    let arr = mgrCfg.getDbArr("pet_db");
                    for (let k in arr) {
                        let danceData = arr[k];
                        if (mgrPlayer.getItemAmount(danceData.id) > 0) {
                            this.count++;
                        }
                    }
                }
                else {
                    this.count++;
                }
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            onMsgAchievementCommonHandler() {
                if (this.state == AchievementState.locked) {
                    return;
                }
                if (this.state >= AchievementState.finished) {
                    return;
                }
                this.count++;
                if (this.count >= this.maxCount) {
                    this.state = AchievementState.finished;
                    mgrAchievement.sendMsg("MSG_ACHIEVEMENT_STATE_CHANGED", { achievementId: this.id });
                }
                mgrAchievement.saveRecord();
            }
            _calcCount1() {
                this.maxCount = this.template.data2;
                return [this.count, this.maxCount];
            }
            _calcCount2() {
                this.maxCount = this.template.data2;
                return [this.count, this.maxCount];
            }
            _calcCount3() {
                this.maxCount = this.template.data2;
                return [this.count, this.maxCount];
            }
            _calcCount4() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount5() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount6() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount7() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount8() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount9() {
                this.maxCount = 1;
                return [this.count, this.maxCount];
            }
            _calcCount10() {
                this.maxCount = this.template.data2;
                return [this.count, this.maxCount];
            }
            _calcCount11() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount12() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount13() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount14() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount15() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount16() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount17() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount18() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount19() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount20() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount21() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount22() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount23() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount24() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount25() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount26() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount27() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount28() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount29() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount30() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount31() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            _calcCount32() {
                this.maxCount = this.template.data1;
                return [this.count, this.maxCount];
            }
            canRouter() {
                let targetData = mgrCfg.get_from_achievement_target_db(this.template.targetType);
                return !!this[targetData.router];
            }
            router() {
                let targetData = mgrCfg.get_from_achievement_target_db(this.template.targetType);
                if (!this[targetData.router]) {
                    console.log("---------------没有对应处理targetType=", this.template.targetType);
                    return;
                }
                return this[targetData.router]();
            }
            gotoHub() {
                mgrDirector.warpSceneWidthEffect(`vHubScene`);
            }
            ;
            gotoShop() {
            }
            gotoPvp() {
                mgrDirector.warpSceneWidthEffect(`vHubScene`);
            }
            gotoFreeWear() {
                mgrDirector.warpSceneWidthEffect(`vFreedomRoomScene`, {
                    backSceneName: `vHubScene`,
                    fromSystemModel: SYSTEM_MODEL.hub
                });
            }
            gotoWatchAd() { }
            gotoShare() {
                mgrDirector.warpSceneWidthEffect(`vHubScene`);
            }
            gotoSuit() {
                mgrDirector.warpSceneWidthEffect(`vSuitTypeScene`);
            }
            gotoRank() {
                mgrDirector.warpSceneWidthEffect(`vRankScene`);
            }
            gotoSign() {
                mgrDirector.openDialog(`vSignDialog`);
            }
            gotoChangeTeamLeader() {
                mgrDirector.warpSceneWidthEffect("vRoleChangeScene");
            }
            gotoAmazeDance() {
                mgrDirector.openDialog(`vAmuseDanceLeafletDialog`);
            }
        }

        class mgrAchievement extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                Timer.callLoop(1, () => {
                    if (!Tools.isOneDay(this.lastRefreshTime, Tools.time())) {
                        this.lastRefreshTime = Tools.time();
                        this.refreshAchievement(null);
                    }
                }, this);
                this.refreshAchievement(null);
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("achievement") || {};
                let achievementDatas = record.achievementDatas || {};
                this.lastRefreshTime = record.lastRefreshTime || 0;
                mgrCfg.forDb_from_achievement_db((k, v) => {
                    let achievement = new sAchievement(v.id);
                    let recordData = achievementDatas[v.id];
                    if (recordData) {
                        achievement.setState(recordData.state);
                        achievement.lastRefreshTime = recordData.lastRefreshTime;
                        achievement.count = recordData.count;
                    }
                    else {
                        achievement.setState(AchievementState.unlocked);
                        achievement.lastRefreshTime = 0;
                        achievement.count = 0;
                    }
                    this.achievements[v.id] = achievement;
                });
            }
            static saveRecord() {
                super.saveRecord();
                let achievementDatas = {};
                Tools.forEachMap(this.achievements, (k, v) => {
                    achievementDatas[v.id] = {
                        state: v.state,
                        lastRefreshTime: v.lastRefreshTime,
                        count: v.count,
                    };
                });
                let record = {
                    achievementDatas: achievementDatas,
                };
                mgrRecord.setData("achievement", record);
            }
            static refreshAchievement(cmd) {
                let bNeedSave = false;
                Tools.forEachMap(this.achievements, (k, achievement) => {
                    let bChanged = achievement.refreshState(cmd);
                    bNeedSave = bNeedSave || bChanged;
                });
                if (bNeedSave) {
                    this.saveRecord();
                }
            }
            static obtainReward(aid, reason) {
                let achievement = this.achievements[aid];
                if (!achievement) {
                    console.warn(ul.format("mgrAchievement.obtainReward, achievement not found! aid = %s", aid));
                    return [null, null];
                }
                if (achievement.state != AchievementState.finished) {
                    console.warn(ul.format("mgrAchievement.obtainReward, achievement state id not finished! aid = %s", aid));
                    return [null, null];
                }
                let itemId = achievement.template.rewardItemId;
                let amount = achievement.template.rewardAmount;
                if (itemId != 0) {
                    mgrPlayer.addItemAmount(itemId, amount, reason);
                    mgrTip.addGotItemTip(itemId, amount);
                }
                achievement.setState(AchievementState.received);
                this.saveRecord();
                return [itemId, amount];
            }
            static getAchievement(aid) {
                if (!aid) {
                    return null;
                }
                let achievement = this.achievements[aid];
                if (!achievement) {
                    console.warn(ul.format("mgrAchievement.getAchievement achievement not found, aid = %s", aid));
                    return null;
                }
                return achievement;
            }
            static getAchievementsByCategory(category) {
                let arr = [];
                Tools.forEachMap(this.achievements, (k, v) => {
                    if (v.template.category == category) {
                        arr.push(v);
                    }
                });
                return arr;
            }
            static isAchievementCompleted(aid) {
                if (!aid)
                    return false;
                let achievement = this.getAchievement(aid);
                if (!achievement)
                    return false;
                let state = achievement.state;
                return state == AchievementState.finished || state == AchievementState.received;
            }
            static isAchievementsAllCompleted(aids) {
                if (!aids)
                    return false;
                for (let i = 0; i < aids.length; i++) {
                    const aid = aids[i];
                    if (!this.isAchievementCompleted(aid))
                        return false;
                }
                return true;
            }
            static getAchievementCanReceiveCount(category) {
                let count = 0;
                Tools.forEachMap(this.achievements, (k, a) => {
                    if (a.template.category == category && a.state == AchievementState.finished) {
                        count++;
                    }
                });
                return count;
            }
            static getShowAchievementsByCategory(category) {
                let map = {};
                Tools.forEachMap(this.achievements, (k, v) => {
                    if (v.template.category == category) {
                        if (!map[v.template.subCategory]) {
                            map[v.template.subCategory] = [];
                        }
                        map[v.template.subCategory].push(v);
                    }
                });
                let result = [];
                Tools.forEachMap(map, (k, achievements) => {
                    achievements = Tools.sortArrayByField(achievements, "id");
                    for (let index = 0; index < achievements.length; index++) {
                        const achi = achievements[index];
                        if (index < (achievements.length - 1)) {
                            if (achi.state <= AchievementState.finished) {
                                result.push(achi);
                                break;
                            }
                        }
                        else {
                            result.push(achi);
                        }
                    }
                });
                return result;
            }
            static getAchievementLevel(achievementId) {
                let achievement = mgrAchievement.getAchievement(achievementId);
                let category = achievement.template.category;
                let subCategory = achievement.template.subCategory;
                let arr = [];
                Tools.forEachMap(this.achievements, (k, v) => {
                    if (v.template.category == category && v.template.subCategory == subCategory) {
                        arr.push(v);
                    }
                });
                arr = Tools.sortArrayByField(arr, "id");
                for (let index = 0; index < arr.length; index++) {
                    const achi = arr[index];
                    if (achi.id == achievementId) {
                        return [index + 1, arr.length];
                    }
                }
                return [1, 1];
            }
        }
        mgrAchievement.achievements = {};

        class mgrShop extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.init();
                this.registerListeners({
                    MSG_SDK_PAY_RESULT: this.onMsgSdkPayResult,
                    MSG_SDK_PRE_PAY_RESULT: this.onMsgSdkPrePayResult,
                });
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("mgrShop") || {};
                this.todayDiscounShopIds = record.todayDiscounShopIds || [];
                this.lastRereshDiscountTime = record.lastRereshDiscountTime || 0;
                this.tryUpdateDiscount();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    todayDiscounShopIds: this.todayDiscounShopIds,
                    lastRereshDiscountTime: this.lastRereshDiscountTime,
                };
                mgrRecord.setData("mgrShop", record);
            }
            static init() {
            }
            static tryUpdateDiscount() {
                if (!Tools.isOneDay(this.lastRereshDiscountTime, Tools.time())) {
                    this.lastRereshDiscountTime = Tools.time();
                    this.todayDiscounShopIds = [];
                    let typeDatas = mgrCfg.getDb("part_type_db");
                    for (let k in typeDatas) {
                        let typeData = typeDatas[k];
                        if (typeData.id == PartType.hair || typeData.id == PartType.face || typeData.id == PartType.backDeco) {
                            continue;
                        }
                        let shops = this.getAllShopItemListByCategory([typeData.id]);
                        let partDatas = [];
                        for (let i = 0; i < shops.length; i++) {
                            let shop = shops[i];
                            if (!shop.price || !shop.priceUnit) {
                                continue;
                            }
                            let achievement = mgrAchievement.getAchievement(shop.unlockAid) || { state: 4 };
                            if (mgrPlayer.getItemAmount(shop.id) <= 0 && achievement.state >= AchievementState.finished) {
                                let partData = mgrCfg.get_from_part_db(shop.id);
                                if (partData) {
                                    partDatas.push(partData);
                                }
                            }
                        }
                        for (let i = 1; i <= 2; i++) {
                            if (!partDatas || partDatas.length <= 0)
                                break;
                            let data = Tools.roundTableProbability(partDatas, "level");
                            this.todayDiscounShopIds.push(data.id);
                            let index = partDatas.indexOf(data);
                            partDatas.splice(index, 1);
                        }
                    }
                    this.saveRecord();
                }
            }
            static isDiscount(shopId) {
                return this.todayDiscounShopIds.indexOf(shopId) >= 0;
            }
            static isHaveDiscount() {
                this.tryUpdateDiscount();
                for (let i = 0; i < this.todayDiscounShopIds.length; i++) {
                    const partId = this.todayDiscounShopIds[i];
                    if (mgrPlayer.getItemAmount(partId) <= 0)
                        return true;
                }
                return false;
            }
            static getAllShopItemListByCategory(categorys, bDisableSort) {
                if (!categorys)
                    return [];
                let hash = {};
                for (let i = 0; i < categorys.length; i++) {
                    const category = categorys[i];
                    hash[category] = true;
                }
                let arr = [];
                mgrCfg.forDb_from_shop_template_db((k, v) => {
                    if (hash[v.category]
                        && mgrAlu.check(v.aluId)) {
                        let bDiscount = this.isDiscount(v.id);
                        if (bDiscount) {
                            v[`_discount`] = -1;
                        }
                        else {
                            v[`_discount`] = 1;
                        }
                        let itemId = v.items[0][0];
                        let bPart = !!mgrCfg.get_from_part_db(itemId);
                        let bHaved = mgrPlayer.getItemAmount(itemId) > 0;
                        if (bPart && bHaved) {
                            v[`_haved`] = 1;
                        }
                        else {
                            v[`_haved`] = -1;
                        }
                        arr.push(v);
                    }
                });
                if (!bDisableSort) {
                    arr = Tools.sortArrayByField(arr, ["_haved", "_discount", "-order", "id"]);
                }
                return arr;
            }
            static requestBuy(shopId, reason, bIgnoreConsume = false) {
                let shopData = mgrCfg.get_from_shop_template_db(shopId);
                if (!shopData) {
                    return false;
                }
                if (bIgnoreConsume) {
                    this.responseBuy(shopId, reason);
                    return true;
                }
                let bDiscount = this.isDiscount(shopId);
                let price = shopData.price;
                if (bDiscount) {
                    price = Math.floor(shopData.price);
                }
                let priceUnit = shopData.priceUnit;
                if (priceUnit == 0) {
                    mgrSdk.openPay(shopData.payId);
                    return false;
                }
                let itemData = mgrCfg.get_from_item_template_db(priceUnit);
                if (!itemData) {
                    return false;
                }
                if (mgrPlayer.getItemAmount(priceUnit) < price) {
                    this.tipItemNotEnough(priceUnit);
                    return false;
                }
                else {
                    if (shopData.coinStatisPoint) {
                        mgrPlayer.addItemAmount(priceUnit, -price, shopData.coinStatisPoint);
                    }
                    else {
                        mgrPlayer.addItemAmount(priceUnit, -price, reason || "购买消耗");
                    }
                    this.responseBuy(shopId, reason);
                    return true;
                }
            }
            static responseBuy(shopId, reason) {
                let shopData = mgrCfg.get_from_shop_template_db(shopId);
                if (!shopData) {
                    return;
                }
                for (let index = 0; index < shopData.items.length; index++) {
                    let [itemId, count, bIgnoreGotTip] = shopData.items[index];
                    if (itemId == Const.ITEM_ID_GOLD) {
                        count = Math.floor(count);
                    }
                    mgrPlayer.addItemAmount(itemId, count, reason || "购买");
                    if (!bIgnoreGotTip) {
                        mgrTip.addGotItemTip(itemId, count, null, null);
                    }
                }
                this.sendMsg("MSG_SHOP_BUY_SUCCESSED", { shopId: shopId });
                mgrSdk.statisOnItemBought(shopId, 1, "购买");
                mgrSdk.statisCommonEvent(shopData.statisPoint);
            }
            static getShopIdByPayId(payId) {
                let shopId;
                mgrCfg.forDb_from_shop_template_db((key, value) => {
                    if (value.payId == payId) {
                        shopId = value.id;
                        return true;
                    }
                });
                return shopId;
            }
            static tryConsumeItem(itemId, amount, reason) {
                let haveAmount = mgrPlayer.getItemAmount(itemId);
                if (haveAmount < amount) {
                    this.tipItemNotEnough(itemId);
                    return false;
                }
                mgrPlayer.addItemAmount(itemId, -amount, reason);
                return true;
            }
            static tipItemNotEnough(itemId = Const.ITEM_ID_DIAMONDS) {
                let itemData = mgrCfg.get_from_item_template_db(itemId);
                if (!itemData) {
                    return;
                }
                mgrTip.showItemTip(itemId, 1, ul.format("%s不足", itemData.name));
                if (mgrGuide.isGuiding())
                    return;
                if (itemId == Const.ITEM_ID_DIAMONDS) {
                    if (mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vHubScene_free_diamon, true)) {
                        mgrDirector.openDialog(`vLuckDiamondDialog`);
                    }
                }
                else if (itemId == Const.ITEM_ID_ENERGY) {
                    if (mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vHubScene_free_energy, true)) {
                        mgrDirector.openDialog(`vLuckEnergyDialog`);
                    }
                }
                else if (itemId == Const.ITEM_ID_MOON_CAKE) {
                    mgrTip.alertPrompt1("提示", ul.format("%s不足", itemData.name), "好的", () => { });
                }
            }
            static getRouterDesc(routerId) {
                let template = mgrCfg.get_from_item_router_go_db(routerId)[0];
                if (template && template.name) {
                    return template.name;
                }
                else {
                    return "未知";
                }
            }
            static tryGoWithItemId(itemId, params) {
                let itemData = mgrCfg.get("item_template_db", itemId);
                if (!itemData || !itemData.router) {
                    return;
                }
                this.goWidthRouterId(itemData.router, params);
            }
            static goWidthRouterId(routerId, params) {
                console.warn("-----goWidthRouterId------------");
                let routers = mgrCfg.get_from_item_router_go_db(routerId);
                if (!routers) {
                    return false;
                }
                let template = null;
                for (let k in routers) {
                    let v = routers[k];
                    if (v.id == routerId) {
                        if (!!v.unlockItemId) {
                            if (mgrPlayer.getItemAmount(v.unlockItemId) >= v.unlockItemAmount) {
                                template = v;
                                break;
                            }
                        }
                        else {
                            template = v;
                            break;
                        }
                    }
                }
                if (!template) {
                    console.warn(`未知跳转类型： ${routerId}`);
                    return false;
                }
                let showingSceneName = mgrDirector.getShowingSceneName();
                if (showingSceneName != template.sceneName) {
                    mgrDirector.warpSceneWidthEffect(template.sceneName, template.sceneContext);
                }
                else if (template.dialogName && template.dialogName != "") {
                    mgrDirector.openDialog(template.dialogName, template.dialogContext);
                }
                else if (template.sendMsgName && template.sendMsgName != "") {
                    this.sendMsg(template.sendMsgName, template.sendMsgContext);
                }
                else {
                    console.warn(`未配置跳转： ${routerId}`);
                    return false;
                }
                return true;
            }
            static setSdkPayInfo(payInfo) {
                Tools.forEachMap(payInfo, (k, v) => {
                    this.sdkPayInfo[v.payCode] = {
                        payCode: v.payCode,
                        price: v.price,
                        proName: v.proName,
                    };
                });
            }
            static onMsgSdkPayResult(data) {
                if (data.bSuccessful) {
                    let shopId = this.getShopIdByPayId(data.payId);
                    this.responseBuy(shopId, "计费点购买成功");
                }
            }
            static onMsgSdkPrePayResult(data) {
                if (data.bSuccessful) {
                    mgrTip.showMsgTip("补发订单...");
                    let shopId = this.getShopIdByPayId(data.payId);
                    this.responseBuy(shopId, "计费点购买补发订单");
                }
            }
        }
        mgrShop.sdkPayInfo = {};

        var UPDATER_UI_MSG;
        (function (UPDATER_UI_MSG) {
            UPDATER_UI_MSG["ENTER_NEXT_SCENE"] = "ENTER_NEXT_SCENE";
            UPDATER_UI_MSG["GET_VERSION"] = "GET_VERSION";
            UPDATER_UI_MSG["DOWNLOAD_SUCCESS"] = "DOWNLOAD_SUCCESS";
        })(UPDATER_UI_MSG || (UPDATER_UI_MSG = {}));
        class UpdaterScript {
            constructor(nodeScene, msgCallback) {
                this.patchInfo = null;
                this.localPid = null;
                this.patchs = null;
                this.patchIdx = null;
                this.TIMEOUT = 5;
                this.requestPatchInfoXhr = null;
                this.timeoutTimer = null;
                this.bNeedRestart = false;
                this.bGameStarted = false;
                let nodeRoot = new Laya.Sprite();
                nodeScene.addChild(nodeRoot);
                this.nodeRoot = nodeRoot;
                this.onUiMsgCallback = msgCallback;
            }
            startUpdate() {
                if (!mgrNative.isHtml5Platform() && window["conch"]) {
                    let patchInfo = this.readStringFromAssetFile("patch_info.json");
                    if (patchInfo) {
                        console.log("发现patch_info，准备更新");
                        if (this.needPlayLogo()) {
                            this.playLogo(() => {
                                this.prepareUpdate();
                            });
                        }
                        else {
                            this.prepareUpdate();
                        }
                        return;
                    }
                }
                console.log("patch_info.json未找到，直接进入游戏");
                this.startGame();
            }
            static changeToTestPatchInfo() {
                Laya.LocalStorage.setItem("FOCE_PATCH_INFO_FILE_NAME_KEY", "patch_info_test.json");
                console.log("---> 切换到测试补丁库.");
            }
            static changeToNormalPatchInfo() {
                Laya.LocalStorage.setItem("FOCE_PATCH_INFO_FILE_NAME_KEY", "");
                console.log("---> 切换到正式补丁库.");
            }
            static clearGameCache() {
                window["clearGameCacheDir"] && window["clearGameCacheDir"]();
            }
            buildUi() {
            }
            sendUiMsg(msg, data) {
                this.onUiMsg(msg, data);
            }
            onUiMsg(msg, data) {
                if (this.onUiMsgCallback) {
                    this.onUiMsgCallback(msg, data);
                }
            }
            needPlayLogo() {
                let bSkipLogoOnce = Laya.LocalStorage.getItem("B_SKIP_LOGO_ONCE") == "true";
                if (bSkipLogoOnce) {
                    Laya.LocalStorage.setItem("B_SKIP_LOGO_ONCE", "false");
                    return false;
                }
                let logoTextures = this.getLogoTextures();
                if (!logoTextures || logoTextures.length == 0)
                    return false;
                return true;
            }
            getLogoTextures() {
                let jsonText = this.readStringFromAssetFile("patch_info.json");
                let patchInfo;
                if (jsonText) {
                    patchInfo = JSON.parse(jsonText);
                }
                if (!patchInfo)
                    return null;
                let conf = patchInfo.CONF;
                if (!conf)
                    return null;
                let logoTextures = conf.LOGO_TEXTURES;
                if (!Array.isArray(logoTextures))
                    return null;
                return logoTextures;
            }
            playLogo(fOnCompleted) {
                fOnCompleted();
            }
            startGame(bUpdateVersion) {
                if (this.bGameStarted) {
                    console.warn("vUpdataerSceneBase.startGame already started!");
                    return;
                }
                this.bGameStarted = true;
                if (bUpdateVersion) {
                    if (this.patchInfo) {
                        let recordVersion = Laya.LocalStorage.getItem("GAME_VERSION");
                        if (recordVersion) {
                            UpdaterScript.GAME_VERSION = recordVersion;
                        }
                        else {
                            let version = this.patchInfo.VERSION;
                            if (version) {
                                Laya.LocalStorage.setItem("GAME_VERSION", version);
                                UpdaterScript.GAME_VERSION = version;
                            }
                        }
                    }
                }
                this.releaseRequestPatchInfoXhr();
                if (this.bNeedRestart) {
                    console.log("-------------------------");
                    console.log("-----  restarting   -----");
                    console.log("-------------------------");
                    Laya.LocalStorage.setItem("B_SKIP_LOGO_ONCE", "true");
                    Laya.SoundManager.stopAll();
                    window.location.reload(true);
                    return;
                }
                console.log("-------------------------");
                console.log("-----   startGame   -----");
                console.log("-------------------------");
                this.sendUiMsg(UPDATER_UI_MSG.ENTER_NEXT_SCENE);
            }
            resetPatch(pid, pkgVersion) {
                console.log("-------------------------");
                console.log("-----  resetPatch   -----");
                console.log("-------------------------");
                Laya.LocalStorage.setItem("PATCH_PID", pid.toString());
                Laya.LocalStorage.setItem("PACKAGE_VERSION", pkgVersion);
            }
            prepareUpdate() {
                console.log("-------------------------");
                console.log("----- prepareUpdate -----");
                console.log("-------------------------");
                let jsonText = this.readStringFromAssetFile("patch_info.json");
                let patchInfo;
                if (jsonText) {
                    patchInfo = JSON.parse(jsonText);
                }
                if (!patchInfo) {
                    console.warn("[warn] patch_info 加载失败，直接进入游戏。");
                    this.startGame();
                    return;
                }
                this.patchInfo = patchInfo;
                let version = Laya.LocalStorage.getItem("GAME_VERSION");
                if (!version) {
                    version = patchInfo.VERSION;
                }
                UpdaterScript.GAME_VERSION = version;
                let packagePid = patchInfo.P_ID;
                let packageVersion = `${patchInfo.P_ID}_${patchInfo.CHANNEL}`;
                console.log("package version:" + packageVersion);
                let recoredPakageVersion = Laya.LocalStorage.getItem("PACKAGE_VERSION");
                if (packageVersion != recoredPakageVersion) {
                    if (!recoredPakageVersion) {
                        console.log("---> 首次进入");
                    }
                    else {
                        console.log("---> 覆盖安装进入");
                        console.log("local version:" + recoredPakageVersion);
                        let packageVersion = patchInfo.VERSION || "1101";
                        Laya.LocalStorage.setItem("GAME_VERSION", packageVersion);
                        UpdaterScript.GAME_VERSION = packageVersion;
                    }
                    this.resetPatch(packagePid, packageVersion);
                }
                this.localPid = parseInt(Laya.LocalStorage.getItem("PATCH_PID")) || 0;
                console.log("use record pid:" + this.localPid);
                let patchPath = this.getPatchPath();
                if (!fs_exists(patchPath)) {
                    if (!fs_mkdir(patchPath)) {
                        console.log("patchPath create faild!" + patchPath);
                        this.startGame();
                        return;
                    }
                    else {
                        console.log("make patch patch suc.");
                    }
                }
                this.buildUi();
                this.checkNewVersion();
            }
            checkNewVersion() {
                this.sendUiMsg(UPDATER_UI_MSG.GET_VERSION);
                let patchInfo = this.patchInfo;
                let useChannel = patchInfo.CHANNEL;
                let patchFile = patchInfo.PATCH_INFO_FILENAME;
                let forcePatchFile = Laya.LocalStorage.getItem("FOCE_PATCH_INFO_FILE_NAME_KEY");
                if (forcePatchFile) {
                    patchFile = forcePatchFile;
                }
                let patchInfoUrl = `http://${patchInfo.HOST}/${patchInfo.PATCH_PATH}/${patchInfo.APP}/${useChannel}/${patchFile}`;
                console.log("patchInfoUrl:" + patchInfoUrl);
                var xhr = new XMLHttpRequest();
                xhr.open('GET', patchInfoUrl);
                xhr.onload = () => {
                    this.stopTimeoutTimer();
                    let remotePatchInfo;
                    try {
                        remotePatchInfo = JSON.parse(xhr.responseText);
                    }
                    catch (error) {
                        console.warn("vUpdaterScene.checkNewVersion remote patch_info parse except!" + xhr.responseText);
                        this.startGame();
                    }
                    if (remotePatchInfo) {
                        this.releaseRequestPatchInfoXhr();
                        this.onPatchInfoDownloadSuccess(remotePatchInfo);
                    }
                    else {
                        console.warn("vUpdaterScene.checkNewVersion remote patch_info parse faild!" + xhr.responseText);
                        this.startGame();
                    }
                };
                xhr.onerror = (e) => {
                    console.warn("vUpdateScene.checkNewVersion network faild.");
                    console.log(e);
                    this.stopTimeoutTimer();
                    this.startGame();
                };
                xhr.timeout = this.TIMEOUT * 1000;
                this.requestPatchInfoXhr = xhr;
                this.startTimeoutTimer();
                xhr.send();
            }
            onPatchInfoDownloadSuccess(remotePatchInfo) {
                console.log("onPatchInfoDownloadSuccess");
                console.log(JSON.stringify(remotePatchInfo));
                let remotePid = parseInt(remotePatchInfo.P_ID) || 0;
                let localPid = this.localPid;
                console.log(`pid: ${localPid} ${remotePid}`);
                if (remotePatchInfo && remotePatchInfo.CONF) {
                    Laya.LocalStorage.setItem("REMOTE_PATCH_INFO_CONF", JSON.stringify(remotePatchInfo.CONF || { "holder": "nothing" }));
                }
                if (localPid > remotePid) {
                    Laya.LocalStorage.setItem("GAME_VERSION", "");
                    console.warn("local version is higher than remote version");
                    console.warn("stop update!");
                    this.startGame(true);
                    return;
                }
                let patchs = [];
                for (let i = 0; i < remotePatchInfo.PATCH_LIST.length; i++) {
                    const v = remotePatchInfo.PATCH_LIST[i];
                    if (v.pid > localPid) {
                        console.log(`ADD PATCH -> ${v.pid} ${v.version}`);
                        patchs.push(v);
                    }
                }
                this.patchInfo = remotePatchInfo;
                if (patchs.length > 0) {
                    this.patchs = patchs;
                    this.patchIdx = 0;
                    Timer.callLater(0.016, () => {
                        this.downloadPatchByIndexed();
                    });
                }
                else {
                    this.startGame(true);
                }
            }
            downloadPatchByIndexed() {
                console.log("downloadPatchByIndexed:" + this.patchIdx);
                let patchInfo = this.patchInfo;
                let patch = this.patchs[this.patchIdx];
                let patchFile = patch.pid + ".zip";
                let packageUrl = `http://${patchInfo.HOST_CDN || patchInfo.HOST}/${patchInfo.PATCH_PATH}/${patchInfo.APP}/${patchInfo.CHANNEL}/${patchFile}`;
                console.log("packageUrl:" + packageUrl);
                let localPath = this.getPatchPath();
                let localZipFile = localPath + patchFile;
                downloadBigFile(packageUrl, localZipFile, (total, now, speed) => {
                    return false;
                }, (curlret, httpret) => {
                    if (curlret != 0 || httpret < 200 || httpret >= 300) {
                        console.log(`downloadBigFile: downloadError curlret:${curlret} :httpret${httpret}`);
                        this.startGame();
                    }
                    else {
                        console.log('downloadBigFile: downloadOK');
                        this.unZipPatchFile(localZipFile);
                    }
                }, 10, 100000000);
            }
            unZipPatchFile(zipFile) {
                let zip = new ZipFile();
                if (zip.setSrc(zipFile)) {
                    var bindcc;
                    zip.forEach((id, name, bDir, sz) => {
                        if (name.indexOf("update/filetable.bin") >= 0) {
                            bindcc = zip.readFile(id);
                        }
                    });
                    let bError = false;
                    if (!bindcc) {
                        console.log("unZipPatchFile: 找不到update/filetable.bin");
                        bError = true;
                    }
                    else {
                        if (this.updateDcc(bindcc)) {
                            console.log('---> 更新dccbin完成.');
                            zip.forEach((id, name, bDir, sz) => {
                                if (!bDir) {
                                    if (name.startsWith("update/"))
                                        return;
                                    let buf = zip.readFile(id);
                                    let fid = window["appcache"].hashstr('/' + name);
                                    if (window["appcache"].updateFile(fid, 0, buf, false)) {
                                        console.log('downloadBigFile: updating:' + name);
                                    }
                                    else {
                                        console.log("downloadBigFile: updateError:" + name);
                                        bError = true;
                                    }
                                }
                            });
                        }
                        else {
                            console.log('---> 更新dccbin失败.');
                            bError = true;
                        }
                    }
                    zip.close();
                    if (fs_exists(zipFile)) {
                        console.log("清理临时文件:" + zipFile);
                        fs_rm(zipFile);
                    }
                    if (bError) {
                        this.startGame();
                    }
                    else {
                        this.onPatchDownloadSuccess();
                    }
                }
                else {
                    console.log("downloadBigFile set zip src error!");
                    this.startGame();
                }
            }
            updateDcc(bindcc) {
                var v = new Uint32Array(bindcc);
                if (v[0] != 0xffeeddcc || v[1] != 1) {
                    console.log('updateDcc: dcc.bin file err!');
                    return false;
                }
                else {
                    let txtdcc = "";
                    if (v[2] == 0x00ffffff) {
                        var stp = (4 + 8) / 2;
                        console.log('---> 开始更新dccbin');
                        for (var ii = stp, isz = v.length / 2; ii < isz; ii++) {
                            txtdcc += v[ii * 2].toString(16) + ' ' + v[ii * 2 + 1].toString(16) + '\n';
                        }
                    }
                    else {
                        console.log('---> old format');
                        for (var ii = 1, isz = v.length / 2; ii < isz; ii++) {
                            txtdcc += v[ii * 2].toString(16) + ' ' + v[ii * 2 + 1].toString(16) + '\n';
                        }
                    }
                    if (txtdcc && txtdcc.length > 0) {
                        let cache = window["appcache"];
                        cache.saveFileTable(txtdcc);
                        window["appcache"] = cache = new AppCache(window.location["fullpath"] + '/');
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
            onPatchDownloadSuccess() {
                let patch = this.patchs[this.patchIdx];
                this.localPid = patch.pid;
                Laya.LocalStorage.setItem("PATCH_PID", this.localPid.toString());
                console.log("save PATCH_PID:" + this.localPid);
                if (patch.version) {
                    Laya.LocalStorage.setItem("GAME_VERSION", patch.version);
                    console.log("save GAME_VERSION:" + patch.version);
                }
                this.bNeedRestart = true;
                console.log(`check patchIdx ${this.patchIdx} ${this.patchs.length}`);
                if (this.patchIdx < this.patchs.length - 1) {
                    this.patchIdx++;
                    this.downloadPatchByIndexed();
                }
                else {
                    this.sendUiMsg(UPDATER_UI_MSG.DOWNLOAD_SUCCESS);
                    this.startGame(true);
                }
            }
            readStringFromAssetFile(file) {
                if (window["conch"]) {
                    return window["conch"].readFileFromAsset(file, 'utf8');
                }
                else {
                    return null;
                }
            }
            setResourceID(key, data) {
                window["appcache"].setResourceID(key, data);
            }
            getResourceID(key) {
                return window["appcache"].getResourceID(key);
            }
            getCachePath() {
                return window["conch"].getCachePath();
            }
            getPatchPath() {
                return this.getCachePath() + "/patch_temp/";
            }
            onTimeout() {
                console.log("checkNewVersion timeout.");
                this.startGame();
            }
            startTimeoutTimer() {
                let timer = Timer.callLater(this.TIMEOUT, () => {
                    this.stopTimeoutTimer();
                    this.onTimeout();
                }, this.nodeRoot);
                this.timeoutTimer = timer;
                timer.start();
            }
            stopTimeoutTimer() {
                if (this.timeoutTimer) {
                    this.timeoutTimer.stop();
                    this.timeoutTimer = null;
                }
            }
            releaseRequestPatchInfoXhr() {
                if (this.requestPatchInfoXhr) {
                    this.requestPatchInfoXhr.onload = null;
                    this.requestPatchInfoXhr.onerror = null;
                    this.requestPatchInfoXhr = null;
                }
            }
        }
        UpdaterScript.GAME_VERSION = "GAME_VERSION";

        class mgrSdk extends Manager {
            static registerCmdCallback(cmd, callback) {
                this.cmdCallbacks[cmd] = callback;
            }
            static dispatchCmd(cmd, data) {
                let callback = this.cmdCallbacks[cmd];
                if (!callback) {
                    console.warn(`mgrSdk: dispatchCmd: ${cmd},can't find callback!`);
                    return;
                }
                callback(data);
            }
            static registerAllCmds() {
                this.registerCmdCallback('/c/channelInfoResult', this.sdkback_channelInfoResult.bind(this));
                this.registerCmdCallback('/c/getBaseChannelInfoResult', this.sdkback_getBaseChannelInfoResult.bind(this));
                this.registerCmdCallback('/c/payResult', this.sdkback_payResult.bind(this));
                this.registerCmdCallback('/c/prePayResult', this.sdkback_prePayResult.bind(this));
                this.registerCmdCallback('/c/shareResult', this.sdkback_shareResult.bind(this));
                this.registerCmdCallback('/c/lifeCycle', this.sdkback_lifeCycle.bind(this));
                this.registerCmdCallback('/c/copInfoResult', this.sdkback_copInfoResult.bind(this));
                this.registerCmdCallback('/c/megadataServer', this.sdkback_megadataServer.bind(this));
                this.registerCmdCallback('/c/useCdkey', this.sdkback_useCdkey.bind(this));
                this.registerCmdCallback('/c/openAdvResult', this.sdkback_openAdvResult.bind(this));
                this.registerCmdCallback('/c/openNativeAdvResult', this.sdkback_openNativeAdvResult.bind(this));
                this.registerCmdCallback('/c/clickNativeAdvResult', this.sdkback_clickNativeAdvResult.bind(this));
                this.registerCmdCallback('/c/clickAdvResult', this.sdkback_clickAdvResult.bind(this));
                this.registerCmdCallback('/c/closeAdvResult', this.sdkback_closeAdvResult.bind(this));
                this.registerCmdCallback('/c/closeNativeAdvResult', this.sdkback_closeNativeAdvResult.bind(this));
                this.registerCmdCallback('/c/userLoginResult', this.sdkback_userLoginResult.bind(this));
                this.registerCmdCallback('/c/userLoginReportResult', this.sdkback_userLoginReportResult.bind(this));
                this.registerCmdCallback('/c/userIsLoginResult', this.sdkback_userIsLoginResult.bind(this));
                this.registerCmdCallback('/c/loginOutResult', this.sdkback_loginOutResult.bind(this));
                this.registerCmdCallback('/c/advValidCountResult', this.sdkback_advValidCountResult.bind(this));
                this.registerCmdCallback('/c/saveRankDataResult', this.sdkback_saveRankDataResult.bind(this));
                this.registerCmdCallback('/c/getRankDataResult', this.sdkback_getRankDataResult.bind(this));
                this.registerCmdCallback('/c/recorderGameVideoResult', this.sdkback_recorderGameVideoResult.bind(this));
                this.registerCmdCallback('/c/shareGameVideoResult', this.sdkback_shareGameVideoResult.bind(this));
                this.registerCmdCallback('/c/jumpOtherGameResult', this.sdkback_jumpOtherGameResult.bind(this));
                this.registerCmdCallback('/c/extraBonus', this.sdkback_extraBonus.bind(this));
                this.registerCmdCallback('/c/openRecommendationResult', this.sdkback_openRecommendationResult.bind(this));
                this.registerCmdCallback('/c/closeRecommendationResult', this.sdkback_closeRecommendationResult.bind(this));
                this.registerCmdCallback('/c/saveUserDataResult', this.sdkback_saveUserDataResult.bind(this));
                this.registerCmdCallback('/c/getUserDataResult', this.sdkback_getUserDataResult.bind(this));
                this.registerCmdCallback('/c/addGameToMyFavoriteResult', this.sdkback_addGameToMyFavoriteResult.bind(this));
                this.registerCmdCallback('/c/getUserInfoMsgResult', this.sdkback_getUserInfoMsgResult.bind(this));
                this.registerCmdCallback('/c/appShareResult', this.sdkback_appShareResult.bind(this));
                this.registerCmdCallback('/c/installShortcutResult', this.sdkback_installShortcutResult.bind(this));
                this.registerCmdCallback('/c/getShortcutStateResult', this.sdkback_getShortcutStateResult.bind(this));
                this.registerCmdCallback('/c/setClipboardDataResult', this.sdkback_setClipboardDataResult.bind(this));
                this.registerCmdCallback('/c/getClipboardDataResult', this.sdkback_getClipboardDataResult.bind(this));
                this.registerCmdCallback('/c/pauseSound', this.sdkback_pauseSound.bind(this));
                this.registerCmdCallback('/c/resumeSound', this.sdkback_resumeSound.bind(this));
                this.registerCmdCallback('/c/openJumpResult', this.sdkback_openJumpResult.bind(this));
                this.registerCmdCallback('/c/jumpOtherGameRewardResult', this.sdkback_jumpOtherGameRewardResult.bind(this));
                this.registerCmdCallback('/c/addSubscribeResult', this.sdkback_addSubscribeResult.bind(this));
                this.registerCmdCallback('/c/followOfficialAccountResult', this.sdkback_followOfficialAccountResult.bind(this));
                this.registerCmdCallback('/c/getFollowOfficialAccountStateResult', this.sdkback_getFollowOfficialAccountStateResult.bind(this));
                this.registerCmdCallback('/c/showPointDebugInfo', this.sdkback_showPointDebugInfo.bind(this));
                this.registerCmdCallback("/c/changePatchInfo", this.sdkback_changePatchInfo.bind(this));
                this.registerCmdCallback("/c/jumpNewGuide", this.sdkback_jumpNewGuide.bind(this));
            }
            static IsInitComplete() {
                return mgrSdk.bInit;
            }
            static init() {
                super.__init();
                this.registerAllCmds();
                this.registerListeners({
                    "MSG_NATIVE_CALLBACK": this.onMsgNativeCallback,
                    "MSG_SDK_LIFE_CYCLE": this.onMsgSdkLifeCycle,
                });
                this.registerKeyboardListener();
                this.getBaseChannelInfo();
            }
            static onLoad() {
                super.onLoad();
            }
            static onLoadingComplete() {
                this.setVersion(2);
            }
            static getCopNumberValueByKey(key) {
                return mgrCop.getNumberValue(key);
            }
            static getCopByKey(key) {
                return mgrCop.get(key);
            }
            static registerKeyboardListener() {
                if (window[`conch`]) {
                    window[`conch`].setOnBackPressedFunction(() => {
                        this.onClickBack();
                    });
                }
            }
            static onMsgSdkLifeCycle(e) {
                let data = e;
                let lifeCycle = data.lifeCycle;
                if (lifeCycle == "onBackPressed") {
                    if (mgrNative.isHtml5Platform())
                        return;
                    this.onClickBack();
                }
            }
            static onClickBack() {
                if (mgrChannel._isThirdExit) {
                    this.thirdExitGame();
                    return;
                }
                if (this.__back_prompt_dialog) {
                    this.__back_prompt_dialog.closeDialog();
                    this.__back_prompt_dialog = null;
                    return;
                }
                let __back_prompt_dialog = mgrTip.alertPrompt2("提示", "是否退出游戏", "取消", "退出游戏", () => {
                    if (this.__back_prompt_dialog) {
                        this.__back_prompt_dialog.closeDialog();
                        this.__back_prompt_dialog = null;
                    }
                }, () => {
                    window[`conch`].exit();
                });
                this.__back_prompt_dialog = __back_prompt_dialog;
            }
            static sendMsgToSdk(params) {
                params = params;
                mgrNative.callNative("sendMsgToSdk", params);
            }
            static onMsgNativeCallback(e) {
                let responseData = e.responseData;
                let cmd = responseData.cmd;
                let data = responseData.data || {};
                this.dispatchCmd(cmd, data);
            }
            static sdkback_channelInfoResult(data) {
    			// data = {
    			// 	"copInfo": "{\"adPop_over_click_count_in_time\":\"12\",\"adPop_refresh_click_count_time\":\"3\",\"ad_banner_ratios\":\"0;100;0;0;0;0;100;0;0;0;0;100;0;0;0;0;100;100;100;100;100;100;100;0;100;100;100;100;100;100;100;100;100;100;100;0;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;0;100;0;100;0;100;100;0;100;100;100;100;100\",\"ad_insert_ratios\":\"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;100;0;0;0;100;0;0;0;0;100;0;0;0;0;0;0;0;0;100;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;100;100;100;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;100;0;0;0;0;0;100\",\"ad_video_ratios\":\"0;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100\",\"b_advanced_setting\":\"1\",\"b_alert_unnecessary_prompt\":\"1\",\"b_click_part_item_pop_trial\":\"1\",\"b_disable_ui_enter_effect\":\"1\",\"b_show_hub_quest_new_tip\":\"1\",\"b_statistics_button_click\":\"1\",\"b_statistics_part_click_count\":\"1\",\"cd_insert_cop_key\":\"30\",\"click_part_item_pop_trial_count_per_stage\":\"100\",\"click_part_item_pop_trial_gap\":\"30\",\"i_sdk_adv_native_exposure_cd\":5000,\"i_sdk_adv_native_life_time\":15000,\"i_sdk_adv_oppoqg_native_exposure_cd\":5000,\"i_sdk_oppoqg_ad_ecd\":60000,\"ip\":\"111.201.54.86\",\"mid_autumn_end_time\":\"1632326400\",\"mid_autumn_start_time\":\"1631689445\",\"o_sdk_adv_show_list\":\"{\\\"templates\\\":{\\\"SP\\\":{\\\"moduleName\\\":\\\"ULAdvOppoQgVideo\\\",\\\"rewardType\\\":\\\"show\\\",\\\"loadTypes\\\":\\\"0\\\",\\\"exp\\\":\\\"\\\",\\\"rcd\\\":\\\"\\\",\\\"args\\\":[\\\"1183138\\\"],\\\"argWeights\\\":[\\\"100\\\"]},\\\"BOX\\\":{\\\"moduleName\\\":\\\"ULAdvOppoQgPortalBox\\\",\\\"rewardType\\\":\\\"show\\\",\\\"loadTypes\\\":\\\"0\\\",\\\"exp\\\":\\\"\\\",\\\"rcd\\\":\\\"\\\",\\\"args\\\":[\\\"\\\"],\\\"argWeights\\\":[\\\"100\\\"]},\\\"BN\\\":{\\\"moduleName\\\":\\\"ULAdvOppoQgCustomBanner\\\",\\\"rewardType\\\":\\\"show\\\",\\\"loadTypes\\\":\\\"0\\\",\\\"exp\\\":\\\"\\\",\\\"rcd\\\":0,\\\"args\\\":[\\\"1183135\\\"],\\\"argWeights\\\":[100]},\\\"CP\\\":{\\\"moduleName\\\":\\\"ULAdvOppoQgCustom\\\",\\\"rewardType\\\":\\\"show\\\",\\\"loadTypes\\\":\\\"0\\\",\\\"exp\\\":\\\"\\\",\\\"rcd\\\":0,\\\"args\\\":[\\\"1183135\\\"],\\\"argWeights\\\":[100]}},\\\"advSlots\\\":{\\\"1\\\":{\\\"rcd\\\":0,\\\"subAids\\\":[],\\\"schemes\\\":[{\\\"exp\\\":\\\"\\\",\\\"rcd\\\":0,\\\"tids\\\":[\\\"CP\\\"],\\\"tidWeights\\\":[100],\\\"weight\\\":100}]},\\\"2\\\":{\\\"rcd\\\":0,\\\"subAids\\\":[],\\\"schemes\\\":[{\\\"exp\\\":\\\"\\\",\\\"rcd\\\":0,\\\"tids\\\":[\\\"BN\\\"],\\\"tidWeights\\\":[100],\\\"weight\\\":100}]},\\\"4\\\":{\\\"rcd\\\":0,\\\"subAids\\\":[],\\\"schemes\\\":[{\\\"exp\\\":\\\"\\\",\\\"rcd\\\":\\\"\\\",\\\"tids\\\":[\\\"SP\\\"],\\\"tidWeights\\\":[\\\"100\\\"],\\\"weight\\\":100}]},\\\"BOX\\\":{\\\"rcd\\\":\\\"\\\",\\\"subAids\\\":[],\\\"schemes\\\":[{\\\"exp\\\":\\\"\\\",\\\"rcd\\\":\\\"\\\",\\\"tids\\\":[\\\"BOX\\\"],\\\"tidWeights\\\":[\\\"100\\\"],\\\"weight\\\":null}]}}}\",\"open_vAdPopMachineDialog_need_game_time\":\"90\",\"show_trigger_native_banner_switch\":\"1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1\",\"t_sdk_adv_custom_args_style_setting\":{\"46017\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46021\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46026\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46035\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46051\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46052\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46053\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46065\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46076\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46082\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"*\":{\"x\":0.5,\"y\":0.02,\"width\":0.6}},\"t_sdk_oppoqg_custom_adv_setting\":{\"688076\":{\"size\":\"320*110\"},\"*\":{\"size\":\"100*90\"}},\"cop_game_id\":\"281\",\"cop_channel_id\":\"146\",\"cop_version\":\"28361\"}",
    			// 	"cardType": 0,
    			// 	"isThirdExit": false,
    			// 	"isAbout": false,
    			// 	"payInfo": {},
    			// 	"isMoreGame": false,
    			// 	"isULMoreGame": false,
    			// 	"uuid": "281_95tMmW0BNHo4CB--MoDPNt_146",
    			// 	"sdcardPath": "",
    			// 	"packageVersion": "",
    			// 	"copChannelId": "146",
    			// 	"ulsdkVersion": "",
    			// 	"isShowUrlAdIcon": false,
    			// 	"cdkChannelId": "",
    			// 	"isPayEnabled": false,
    			// 	"isShareEnabled": false,
    			// 	"isUseSdkRank": false,
    			// 	"isSupportRecordShare": false,
    			// 	"isSupportInstallShortcut": true,
    			// 	"isSupportClipboardData": true,
    			// 	"isSupportFindMinigames": false,
    			// 	"findMinigamesImageUrl": "",
    			// 	"isSupportRecommendationBtn": false,
    			// 	"isSupportJumpList": true,
    			// 	"is4399Watermark": false,
    			// 	"appName": "oppoqg",
    			// 	"jumpInfo": [],
    			// 	"channelUserId": "",
    			// 	"referenceBannerHeight": 110,
    			// 	"isNewUser": false,
    			// 	"loginDays": 0,
    			// 	"isSupportPasterAdv": false,
    			// 	"gameLanguage": "",
    			// 	"isSupportChannelMoreGameBox": false,
    			// 	"isSupportChannelBlockAd": false,
    			// 	"isSupportSubscribe": false,
    			// 	"isSupportGridAd": false,
    			// 	"isSupportVideoRank": false,
    			// 	"isSupportFavoriteGuide": false,
    			// 	"isSupportFollowOfficialAccount": false,
    			// 	"customerServiceInfo": [
    			// 		"kefu@ultralisk.cn"
    			// 	],
    			// 	"appIdOrPkgName": "",
    			// 	"isSupportContentSecurityCheck": false,
    			// 	"isJumpLeisureEnabled": false,
    			// 	"isSupportVibrate": false,
    			// 	"isSupportOpenUrl": false,
    			// 	"isSupportJumpInfoVideoType": false,
    			// 	"isSupportUserCloudStorage": false,
    			// 	"isSupportJoinGroup": false,
    			// 	"isSupportHeadlineImRank": false,
    			// 	"isSupportOpenData": false,
    			// 	"isSupportLaunchReward": false,
    			// 	"isSupportWXGameClub": false
    			// }
    			data.copInfo = "{\"adPop_over_click_count_in_time\":\"12\",\"adPop_refresh_click_count_time\":\"3\",\"ad_banner_ratios\":\"0;100;0;0;0;0;100;0;0;0;0;100;0;0;0;0;100;100;100;100;100;100;100;0;100;100;100;100;100;100;100;100;100;100;100;0;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;0;100;0;100;0;100;100;0;100;100;100;100;100\",\"ad_insert_ratios\":\"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;100;0;0;0;100;0;0;0;0;100;0;0;0;0;0;0;0;0;100;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;100;100;100;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;100;0;0;0;0;0;100\",\"ad_video_ratios\":\"0;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100\",\"b_advanced_setting\":\"1\",\"b_alert_unnecessary_prompt\":\"1\",\"b_click_part_item_pop_trial\":\"1\",\"b_disable_ui_enter_effect\":\"1\",\"b_show_hub_quest_new_tip\":\"1\",\"b_statistics_button_click\":\"1\",\"b_statistics_part_click_count\":\"1\",\"cd_insert_cop_key\":\"30\",\"click_part_item_pop_trial_count_per_stage\":\"100\",\"click_part_item_pop_trial_gap\":\"30\",\"i_sdk_adv_native_exposure_cd\":5000,\"i_sdk_adv_native_life_time\":15000,\"i_sdk_adv_oppoqg_native_exposure_cd\":5000,\"i_sdk_oppoqg_ad_ecd\":60000,\"ip\":\"111.201.54.86\",\"mid_autumn_end_time\":\"1632326400\",\"mid_autumn_start_time\":\"1631689445\",\"o_sdk_adv_show_list\":\"{\\\"templates\\\":{\\\"SP\\\":{\\\"moduleName\\\":\\\"ULAdvOppoQgVideo\\\",\\\"rewardType\\\":\\\"show\\\",\\\"loadTypes\\\":\\\"0\\\",\\\"exp\\\":\\\"\\\",\\\"rcd\\\":\\\"\\\",\\\"args\\\":[\\\"1183138\\\"],\\\"argWeights\\\":[\\\"100\\\"]},\\\"BOX\\\":{\\\"moduleName\\\":\\\"ULAdvOppoQgPortalBox\\\",\\\"rewardType\\\":\\\"show\\\",\\\"loadTypes\\\":\\\"0\\\",\\\"exp\\\":\\\"\\\",\\\"rcd\\\":\\\"\\\",\\\"args\\\":[\\\"\\\"],\\\"argWeights\\\":[\\\"100\\\"]},\\\"BN\\\":{\\\"moduleName\\\":\\\"ULAdvOppoQgCustomBanner\\\",\\\"rewardType\\\":\\\"show\\\",\\\"loadTypes\\\":\\\"0\\\",\\\"exp\\\":\\\"\\\",\\\"rcd\\\":0,\\\"args\\\":[\\\"1183135\\\"],\\\"argWeights\\\":[100]},\\\"CP\\\":{\\\"moduleName\\\":\\\"ULAdvOppoQgCustom\\\",\\\"rewardType\\\":\\\"show\\\",\\\"loadTypes\\\":\\\"0\\\",\\\"exp\\\":\\\"\\\",\\\"rcd\\\":0,\\\"args\\\":[\\\"1183135\\\"],\\\"argWeights\\\":[100]}},\\\"advSlots\\\":{\\\"1\\\":{\\\"rcd\\\":0,\\\"subAids\\\":[],\\\"schemes\\\":[{\\\"exp\\\":\\\"\\\",\\\"rcd\\\":0,\\\"tids\\\":[\\\"CP\\\"],\\\"tidWeights\\\":[100],\\\"weight\\\":100}]},\\\"2\\\":{\\\"rcd\\\":0,\\\"subAids\\\":[],\\\"schemes\\\":[{\\\"exp\\\":\\\"\\\",\\\"rcd\\\":0,\\\"tids\\\":[\\\"BN\\\"],\\\"tidWeights\\\":[100],\\\"weight\\\":100}]},\\\"4\\\":{\\\"rcd\\\":0,\\\"subAids\\\":[],\\\"schemes\\\":[{\\\"exp\\\":\\\"\\\",\\\"rcd\\\":\\\"\\\",\\\"tids\\\":[\\\"SP\\\"],\\\"tidWeights\\\":[\\\"100\\\"],\\\"weight\\\":100}]},\\\"BOX\\\":{\\\"rcd\\\":\\\"\\\",\\\"subAids\\\":[],\\\"schemes\\\":[{\\\"exp\\\":\\\"\\\",\\\"rcd\\\":\\\"\\\",\\\"tids\\\":[\\\"BOX\\\"],\\\"tidWeights\\\":[\\\"100\\\"],\\\"weight\\\":null}]}}}\",\"open_vAdPopMachineDialog_need_game_time\":\"90\",\"show_trigger_native_banner_switch\":\"1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1\",\"t_sdk_adv_custom_args_style_setting\":{\"46017\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46021\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46026\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46035\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46051\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46052\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46053\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46065\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46076\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"46082\":{\"x\":0.5,\"y\":0.6,\"width\":0.7},\"*\":{\"x\":0.5,\"y\":0.02,\"width\":0.6}},\"t_sdk_oppoqg_custom_adv_setting\":{\"688076\":{\"size\":\"320*110\"},\"*\":{\"size\":\"100*90\"}},\"cop_game_id\":\"281\",\"cop_channel_id\":\"146\",\"cop_version\":\"28361\"}";

                console.info("mgrSdk:  copInfo", data.copInfo);
                console.info("mgrSdk:  data", data);
                console.info("mgrSdk:  isSupportSubscribe", data.isSupportSubscribe);
                mgrCop.onReceiveSdkCop(data.copInfo);
                mgrChannel._cardType = data.cardType;
                mgrChannel._isThirdExit = data.isThirdExit;
                mgrChannel._isAbout = data.isAbout;
                mgrChannel._isMoreGame = data.isMoreGame;
                mgrChannel._isULMoreGame = data.isULMoreGame;
                mgrChannel._isShowUrlAdIcon = data.isShowUrlAdIcon;
                if (data.isPayEnabled == null) {
                    mgrChannel._isPayEnabled = true;
                }
                else {
                    mgrChannel._isPayEnabled = data.isPayEnabled;
                }
                mgrChannel._isShareEnabled = data.isShareEnabled;
                mgrChannel._isUseSdkRank = data.isUseSdkRank;
                mgrChannel._isSupportRecordShare = data.isSupportRecordShare;
                mgrChannel._isSupportClipboardData = data.isSupportClipboardData;
                mgrChannel._isSupportFindMinigames = data.isSupportFindMinigames;
                mgrChannel._isSupportRecommendationBtn = data.isSupportRecommendationBtn;
                mgrChannel._isJumpLeisureEnabled = data.isJumpLeisureEnabled;
                mgrChannel._isSupportSubscribe = data.isSupportSubscribe;
                mgrChannel._isSupportChannelMoreGameBox = data.isSupportChannelMoreGameBox;
                mgrChannel.findmeImageUrl = data.findMinigamesImageUrl;
                mgrChannel._isSupportFollowOfficialAccount = data.isSupportFollowOfficialAccount;
                mgrChannel.isSupportGridAd = data.isSupportGridAd;
                mgrChannel.isSupportJumpInfoVideoType = data.isSupportJumpInfoVideoType;
                mgrChannel.setInterPushConfig(data.jumpInfo || []);
                mgrShop.setSdkPayInfo(data.payInfo);
                mgrPlayer.setUid(data.uuid);
                Const.sdcardPath = data.sdcardPath;
                Const.packageVersion = data.packageVersion;
                Const.copChannelId = data.copChannelId;
                Const.ulsdkVersion = data.ulsdkVersion;
                Const.cdkChannelId = data.cdkChannelId;
                mgrChannel.setChannelName(data.appName);
                this.bInit = true;
                this.sendMsg("MSG_SDK_CHANNEL_INFO_RESULT");
            }
            static sdkback_getBaseChannelInfoResult(data) {
                let gameName = data.gameName || "unknown";
                let gameLanguage = data.gameLanguage || "zhcn";
                let channelName = data.channelName || "unknown";
                let appName = data.appName || "unknown";
                let bShowLicenceInfo = !!data.isShowLicenceInfo;
                let licenceInfo = data.licenceInfo || "";
                let bShowAgeLevelInfo = !!data.isShowAgeLevelInfo;
                let ageLevelInfo = data.ageLevelInfo || "";
                let bStartGameByTouch = !!data.isStartGameByTouch;
                Const.licenceInfo = licenceInfo;
                Const.gameName = gameName;
                this.baseChannelInfo = {
                    gameName: gameName,
                    gameLanguage: gameLanguage,
                    channelName: channelName,
                    appName: appName,
                    bShowLicenceInfo: bShowLicenceInfo,
                    licenceInfo: licenceInfo,
                    bShowAgeLevelInfo: bShowAgeLevelInfo,
                    ageLevelInfo: ageLevelInfo,
                    bStartGameByTouch: bStartGameByTouch,
                };
                console.log("sdkback_getBaseChannelInfoResult", data);
                this.sendMsg("MSG_SDK_BASE_CHANNEL_INFO_CHANGED", {
                    gameName: gameName,
                    gameLanguage: gameLanguage,
                    channelName: channelName,
                    appName: appName,
                    bShowLicenceInfo: bShowLicenceInfo,
                    licenceInfo: licenceInfo,
                });
            }
            static sdkback_payResult(data) {
                let code = data.code;
                let msg = data.msg;
                let payId = data.payId;
                let userData = data.userData;
                let bSuccessful = code == 1;
                mgrTip.closeWaitingDialog();
                mgrTip.showMsgTip(msg);
                this.sendMsg("MSG_SDK_PAY_RESULT", {
                    payId: payId,
                    userData: userData,
                    code: code,
                    msg: msg,
                    bSuccessful: bSuccessful,
                });
            }
            static sdkback_prePayResult(data) {
                let code = data.code;
                let msg = data.msg;
                let payId = data.payId;
                let userData = data.userData;
                let bSuccessful = code == 1;
                this.sendMsg('MSG_SDK_PRE_PAY_RESULT', {
                    code: code,
                    msg: msg,
                    payId: payId,
                    userData: userData,
                    bSuccessful: bSuccessful,
                });
            }
            static sdkback_shareResult(data) {
                let code = data.code;
                let msg = data.msg;
                let bSuccessful = code == 1;
                this.sendMsg('MSG_SDK_SHARE_RESULT', {
                    bSuccessful: bSuccessful,
                    code: code,
                    msg: msg
                });
            }
            static sdkback_lifeCycle(data) {
                let lifeCycle = data.lifeCycle || "";
                this.sendMsg("MSG_SDK_LIFE_CYCLE", { lifeCycle: lifeCycle });
                if (lifeCycle == "onPause" || lifeCycle == "onStop") {
                    mgrSound.pauseSound("lifeCycle");
                }
                else if (lifeCycle == "onResume") {
                    mgrSound.resumeSound("lifeCycle");
                }
            }
            static sdkback_copInfoResult(data) {
                let copInfo = data.copInfo;
                mgrCop.onReceiveSdkCop(copInfo);
                this.sendMsg("MSG_SDK_COP_INFO_RESULT");
            }
            static sdkback_megadataServer(data) {
                let code = data.code;
                if (code == 0) {
                    console.log("大数据统计: 失败");
                }
                else if (code == 1) {
                    console.log("大数据统计: 成功");
                }
            }
            static sdkback_useCdkey(data) {
                let code = data.code;
                let goodsInfos = data.data || [];
                let reason = data.message;
                mgrTip.closeWaitingDialog();
                if (code == 1) {
                    mgrTip.showMsgTip(reason);
                    let items = [];
                    for (let index = 0; index < goodsInfos.length; index++) {
                        const goodsInfo = goodsInfos[index];
                        let itemId = goodsInfo.goodsid;
                        let count = goodsInfo.count;
                        mgrPlayer.addItemAmount(itemId, count, "cdk");
                        mgrTip.addGotItemTip(itemId, count);
                        items.push({
                            itemId: itemId,
                            amount: count,
                        });
                    }
                    this.sendMsg('MSG_SDK_USE_CDK_SUCCESSFUL', {
                        items: items,
                    });
                }
                else if (code == 0) {
                    mgrTip.showMsgTip(reason);
                }
                else {
                    mgrTip.showMsgTip(reason);
                }
            }
            static sdkback_openAdvResult(data) {
                this.sendMsg("MSG_SDK_OPEN_ADV_RESULT", data);
            }
            static sdkback_openNativeAdvResult(data) {
                this.sendMsg("MSG_SDK_OPEN_NATIVE_ADV_RESULT", data);
            }
            static sdkback_clickNativeAdvResult(data) {
                this.sendMsg("MSG_SDK_CLICK_NATIVE_ADV_RESULT", data);
            }
            static sdkback_clickAdvResult(data) {
                this.sendMsg("MSG_SDK_CLICK_ADV_RESULT", data);
            }
            static sdkback_closeAdvResult(data) {
                this.sendMsg("MSG_SDK_ADV_CLOSE_RESULT", data);
            }
            static sdkback_closeNativeAdvResult(data) {
                this.sendMsg("MSG_SDK_CLOSE_NATIVE_ADV_RESULT", data);
            }
            static sdkback_userLoginResult(data) {
                let code = data.code;
                let userData = data.userData;
                let bSuccessful = code == 1;
                this.sendMsg(`MSG_SDK_USER_LOGIN_RESULT`, {
                    bSuccessful: bSuccessful,
                    userData: userData,
                    code: code,
                });
            }
            static sdkback_userLoginReportResult(data) {
                let code = data.code;
                let userData = data.userData;
                let bSuccessful = code == 1;
                this.sendMsg('MSG_SDK_USER_LOGIN_REPORT_RESULT', {
                    bSuccessful: bSuccessful,
                    userData: userData,
                    code: code,
                });
            }
            static sdkback_userIsLoginResult(data) {
                let code = data.code;
                let bLogin = false;
                if (code == 1) {
                    console.log("登录查询: 已登录");
                    bLogin = true;
                }
                else {
                    console.log("登录查询: 未登录");
                    bLogin = false;
                }
                this.sendMsg('MSG_SDK_USER_IS_LOGIN_RESULT', {
                    bLogin: bLogin,
                });
            }
            static sdkback_loginOutResult(data) {
                let code = data.code;
                let bSuccessful = false;
                if (code == 1) {
                    console.log("登出成功");
                    bSuccessful = true;
                }
                else if (code == 0) {
                    console.log("登出失败");
                    bSuccessful = false;
                }
                this.sendMsg('MSG_SDK_USER_LOGIN_OUT_RESULT', {
                    bSuccessful: bSuccessful,
                });
            }
            static sdkback_advValidCountResult(data) {
                this.sendMsg('MSG_SDK_ADV_VALID_COUNT', data);
            }
            static sdkback_saveRankDataResult(data) {
                let code = data.code;
                let msg = data.msg;
                let bSuccessful = false;
                if (code == 1) {
                    bSuccessful = true;
                    console.log("上传排行榜数据成功");
                }
                else {
                    bSuccessful = false;
                    console.log("上传排行榜数据失败");
                }
                this.sendMsg('MSG_SDK_SAVE_RANK_DATA_RESUTL', {
                    bSuccessful: bSuccessful,
                    msg: msg,
                });
            }
            static sdkback_getRankDataResult(data) {
                let code = data.code;
                let bSuccessful = false;
                if (code == 1) {
                    console.log("获取排行榜数据成功!");
                    bSuccessful = true;
                }
                else {
                    console.log("获取排行榜数据失败!");
                    bSuccessful = false;
                }
                this.sendMsg('MSG_SDK_GET_RANK_DATA_RESULT', {
                    bSuccessful: bSuccessful,
                });
            }
            static sdkback_recorderGameVideoResult(data) {
                if (data) {
                    let code = data.code;
                    let bSuccessful = false;
                    let action = "";
                    let msg = data.msg;
                    switch (code) {
                        case 0:
                            bSuccessful = false;
                            break;
                        case 1:
                            action = "start";
                            bSuccessful = true;
                            break;
                        case 2:
                            action = "pause";
                            bSuccessful = true;
                            break;
                        case 3:
                            action = "resume";
                            bSuccessful = true;
                            break;
                        case 4:
                            action = "stop";
                            bSuccessful = true;
                            break;
                        default:
                            bSuccessful = false;
                            return;
                    }
                    this.sendMsg('MSG_SDK_RECORD_GAME_VIDEO_RESULT', {
                        bSuccessful: bSuccessful,
                        msg: msg,
                        action: action,
                    });
                }
            }
            static sdkback_shareGameVideoResult(data) {
                let code = data.code;
                let msg = data.msg;
                let userData = data.userData;
                let bSuccessful = false;
                if (code == 1) {
                    console.log("录屏分享成功!");
                    bSuccessful = true;
                }
                else {
                    console.log("录屏分享失败!");
                }
                this.sendMsg('MSG_SDK_SHARE_VIDEO_RESULT', {
                    msg: msg,
                    userData: userData,
                    bSuccessful: bSuccessful,
                });
            }
            static sdkback_jumpOtherGameResult(data) {
                let code = data.code;
                let msg = data.msg;
                let userData = data.userData;
                let bSuccessful = false;
                if (code == 1) {
                    console.log("跳转其他游戏成功!");
                    bSuccessful = true;
                }
                else {
                    console.log("跳转其他游戏失败!");
                }
                this.sendMsg('MSG_SDK_JUMP_OTHER_GAME_RESULT', {
                    bSuccessful: bSuccessful,
                    msg: msg,
                    userData: userData,
                });
            }
            static sdkback_jumpOtherGameRewardResult(data) {
                let code = data.code;
                if (code == 1) {
                    console.log("sdkback_jumpOtherGameRewardResult");
                    this.sendMsg("MSG_SDK_JUMP_OTHER_GAME_REWARD_RESULT", {
                        rewards: data.rewards,
                        userData: data.userData,
                    });
                }
                else {
                    console.error("激励互推跳转发奖失败：", data.msg);
                }
            }
            static sdkback_openJumpResult(data) {
                let code = data.code;
                if (code == 1) {
                    this.sendMsg("MSG_ON_OPEN_JUMP_RESULT", {
                        jumpInfo: data.jumpInfo,
                        type: data.type,
                    });
                }
                else {
                    console.error("互推列表获取失败：", data.type, data.msg);
                }
            }
            static sdkback_addSubscribeResult(data) {
                let code = data.code;
                if (code == 1) {
                    console.log("sdkback_addSubscribeResult:", data.code);
                    this.sendMsg("MSG_ON_ADD_SUBSCRIBE_RESULT", {
                        successTempleteIds: data.successTempleteIds,
                        msg: data.msg
                    });
                }
                else {
                    console.error("订阅失败", data.msg);
                    mgrTip.showMsgTip("订阅失败");
                }
            }
            static sdkback_followOfficialAccountResult(data) {
                let code = data.code;
                if (code == 1) {
                    this.followState = 1;
                    this.sendMsg("FOLLOW_OFFICIAL_ACCOUNT_SUC", data);
                }
                else {
                    mgrTip.showMsgTip("没有关注成功哦，请重新关注");
                }
            }
            static sdkback_getFollowOfficialAccountStateResult(data) {
                let code = data.code;
                let state = data.state;
                if (code == 1) {
                    this.followState = state;
                    console.log("关注状态", this.followState);
                    this.sendMsg("GET_FOLLOW_OFFICIAL_ACCOUNT_STATE_SUC", data);
                }
            }
            static sdkback_showPointDebugInfo(data) {
                let state = data.state;
                console.log("打点状态", state);
                this.sendMsg("MSG_SHOW_POINT_DEBUG_INFO", data);
            }
            static sdkback_changePatchInfo(data) {
                if (data && data.bTest) {
                    UpdaterScript.changeToTestPatchInfo();
                    console.log("切换到测试补丁");
                }
                else {
                    UpdaterScript.changeToNormalPatchInfo();
                    console.log("切换到正式补丁");
                }
                this.sendMsgToSdk({
                    cmd: "/c/changePatchInfoResult",
                    data: {
                        code: 1,
                    },
                });
            }
            static sdkback_jumpNewGuide(data) {
                console.log("金手指 跳过新手引导");
                mgrGuide._debugCancelDebug();
            }
            static sdkback_extraBonus(data) {
                let code = data.code;
                let msg = data.msg;
                let bInit = data.isInitGame == 1;
                this.sendMsg("MSG_SDK_WX_GZH_ENTER", {
                    msg: msg,
                    code: code,
                    bInit: bInit,
                });
            }
            static sdkback_openRecommendationResult(data) {
                let code = data.code;
                let msg = data.msg;
                let bSuccessful = false;
                if (code == 1) {
                    console.log("开启交叉推荐成功!");
                    bSuccessful = true;
                }
                else {
                    console.log("开启交叉推荐失败!");
                }
                this.sendMsg('MSG_SDK_OPEN_RECOMMEND_RESULT', {
                    bSuccessful: bSuccessful,
                    msg: msg,
                });
            }
            static sdkback_closeRecommendationResult(data) {
                let code = data.code;
                let msg = data.msg;
                let bSuccessful = false;
                if (code == 1) {
                    bSuccessful = true;
                }
                else {
                    bSuccessful = false;
                }
                this.sendMsg("MSG_SDK_CLOSE_RECOMEND_RESULT", {
                    code: code,
                    bSuccessful: bSuccessful,
                    msg: msg,
                });
            }
            static sdkback_saveUserDataResult(data) {
                let code = data.code;
                let msg = data.msg;
                let bSuccessful = false;
                if (code == 1) {
                    bSuccessful = true;
                }
                else {
                    bSuccessful = false;
                }
                this.sendMsg('MSG_SDK_SAVE_USER_DATA_RESULT', {
                    code: code,
                    bSuccessful: bSuccessful,
                    msg: msg
                });
            }
            static sdkback_getUserDataResult(data) {
                let code = data.code;
                let msg = data.msg;
                let storageData = data.userData;
                let bSuccessful = code == 1;
                this.sendMsg('MSG_SDK_GET_USER_DATA_RESULT', {
                    code: code,
                    bSuccessful: bSuccessful,
                    msg: msg,
                    storageData: storageData,
                });
            }
            static sdkback_addGameToMyFavoriteResult(data) {
                let code = data.code;
                let userData = data.userData;
                let msg = data.msg;
                let bSuccessful = code == 1;
                this.sendMsg('MSG_SDK_ADD_GAME_TO_MY_FAVORITE_RESULT', {
                    code: code,
                    bSuccessful: bSuccessful,
                    userData: userData,
                    msg: msg,
                });
            }
            static sdkback_getUserInfoMsgResult(data) {
                let code = data.code;
                let msg = data.msg;
                let bSuccessful = code == 1;
                this.sendMsg('MSG_SDK_GET_USER_INFO_MSG_RESULT', {
                    code: code,
                    bSuccessful: bSuccessful,
                    msg: msg,
                });
            }
            static sdkback_appShareResult(data) {
                let code = data.code;
                let msg = data.msg;
                let bSuccessful = code == 1;
                this.sendMsg('MSG_SDK_APP_SHARE_RESULT', {
                    code: code,
                    msg: msg,
                    bSuccessful: bSuccessful,
                });
            }
            static sdkback_installShortcutResult(data) {
                let code = data.code;
                let bSuccessful = code == 1;
                let msg = data.msg;
                let userData = data.userData;
                this.sendMsg('MSG_SDK_INSTALL_SHORTCUT_RESULT', {
                    code: code,
                    bSuccessful: bSuccessful,
                    msg: msg,
                    userData: userData,
                });
            }
            static sdkback_getShortcutStateResult(data) {
                let state = data.state;
                let bHasPrompt = !!data.bHasPrompt;
                let userData = data.userData;
                this.sendMsg('MSG_SDK_GET_SHORTCUT_STATE_RESULT', {
                    state: state,
                    bHasPrompt: bHasPrompt,
                    userData: userData,
                });
            }
            static sdkback_setClipboardDataResult(data) {
                let code = data.code;
                let bSuccessful = code == 1;
                let msg = data.msg;
                let clipboardData = data.clipboardData;
                let userData = data.userData;
                this.sendMsg('MSG_SDK_SET_CLIPBOARD_DATA_RESULT', {
                    code: code,
                    msg: msg,
                    bSuccessful: bSuccessful,
                    clipboardData: clipboardData,
                    userData: userData,
                });
            }
            static sdkback_getClipboardDataResult(data) {
                let code = data.code;
                let bSuccessful = code == 1;
                let msg = data.msg;
                let clipboardData = data.clipboardData;
                let userData = data.userData;
                this.sendMsg('MSG_SDK_GET_CLIPBOARD_DATA_RESULT', {
                    code: code,
                    bSuccessful: bSuccessful,
                    msg: msg,
                    clipboardData: clipboardData,
                    userData: userData,
                });
            }
            static sdkback_pauseSound() {
                mgrSound.pauseSound("sdk");
            }
            static sdkback_resumeSound() {
                mgrSound.resumeSound("sdk");
            }
            static setVersion(version) {
                this.sendMsgToSdk({
                    cmd: "/c/setVersion",
                    data: version,
                });
            }
            static getBaseChannelInfo() {
                this.sendMsgToSdk({
                    cmd: "/c/getBaseChannelInfo",
                });
            }
            static openMoreGame() {
                this.sendMsgToSdk({
                    cmd: "/c/openMoreGame",
                });
            }
            static openULMoreGame() {
                this.sendMsgToSdk({
                    cmd: "/c/openUlMoreGame",
                });
            }
            static openMoreWonderful() {
                this.sendMsgToSdk({
                    cmd: "/c/jumpLeisureSubject",
                    data: {},
                });
            }
            static opentChannelMoreGameBox() {
                this.sendMsgToSdk({
                    cmd: "/c/openChannelMoreGameBox",
                });
            }
            static openAdvancedSetting() {
                this.sendMsgToSdk({
                    cmd: "/c/openAdvancedSetting",
                });
            }
            static openPay(payId, userData = `{}`) {
                if (mgrTip.isWaitingDialogOpened()) {
                    mgrTip.showMsgTip("有商品正在支付中，请稍后再购买");
                    return;
                }
                mgrTip.openWaitingDialog("提示", "支付中...");
                this.sendMsgToSdk({
                    cmd: "/c/openPay",
                    data: {
                        payId: payId,
                        userData: userData,
                    }
                });
            }
            static openShare(title, content, url, queryMsg = "1", imagePath, userData = "") {
                if (this.DEBUG) {
                    console.info("mgrSdk:openAdH5", title, content, url, imagePath);
                }
                this.sendMsgToSdk({
                    cmd: "/c/openShare",
                    data: {
                        title: title,
                        content: content,
                        url: url,
                        imagePath: imagePath,
                        userData: userData,
                        queryMsg: queryMsg,
                    },
                });
            }
            static callPhone(phoneNumber) {
                this.sendMsgToSdk({
                    cmd: "/c/callPhone",
                    data: {
                        phoneNum: phoneNumber,
                    },
                });
            }
            static ulWebView(url) {
                this.sendMsgToSdk({
                    cmd: "/c/ulWebView",
                    data: {
                        url: url,
                    },
                });
            }
            static thirdExitGame() {
                this.sendMsgToSdk({
                    cmd: "/c/exitGame",
                    data: {},
                });
            }
            static followOfficialAccount() {
                console.log("mgrSdk followOfficialAccount");
                this.sendMsgToSdk({
                    cmd: "/c/followOfficialAccount",
                    data: {
                        userData: {},
                    },
                });
            }
            static getFollowOfficialAccountState() {
                console.log("mgrSdk getFollowOfficialAccountState");
                this.sendMsgToSdk({
                    cmd: "/c/getFollowOfficialAccountState",
                    data: {
                        userData: {},
                    },
                });
            }
            static megadataServer(data) {
                this.sendMsgToSdk({
                    cmd: "/c/megadataServer",
                    data: data,
                });
            }
            static useCdk(cdk) {
                console.log("mgrSdk useCdk cdk: ", cdk);
                if (mgrTip.isWaitingDialogOpened()) {
                    mgrTip.showMsgTip("领取中，请稍后再领取");
                    return;
                }
                mgrTip.openWaitingDialog("提示", "领取中...");
                this.sendMsgToSdk({
                    cmd: "/c/useCdkey",
                    data: {
                        userId: mgrPlayer.getUid(),
                        cdkStr: cdk,
                        channelId: 0
                    },
                });
            }
            static openAdv(advId, userData = `{}`, tag) {
                this.sendMsgToSdk({
                    cmd: "/c/openAdv",
                    data: {
                        advId: advId,
                        userData: userData,
                        tag: tag
                    },
                });
            }
            static clickNativeAdv(advId, userData = `{}`, tag) {
                this.sendMsgToSdk({
                    cmd: "/c/clickNativeAdv",
                    data: {
                        advId: advId,
                        userData: userData,
                        tag: tag
                    },
                });
            }
            static closeAdv(advId, userData = `{}`) {
                this.sendMsgToSdk({
                    cmd: "/c/closeAdv",
                    data: {
                        advId: advId,
                        userData: userData
                    }
                });
            }
            static closeNativeAdv(advId, userData = `{}`, bManualClose) {
                let closeType = !!bManualClose ? 1 : 0;
                this.sendMsgToSdk({
                    cmd: "/c/closeNativeAdv",
                    data: {
                        advId: advId,
                        closeType: closeType,
                        userData: userData
                    }
                });
            }
            static userLogin() {
                console.log("mgrsdk userLogin");
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/userLogin",
                });
            }
            static userLoginReport(playerLevel, coin, userData) {
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/userLoginReport",
                    data: {
                        playerLevel: playerLevel,
                        coin: coin,
                        userData: userData,
                    }
                });
            }
            static userIsLogin() {
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/userIsLogin",
                });
            }
            static loginOut() {
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/loginOut",
                });
            }
            static saveRankData(startTime, endTime, rankName, score, order) {
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/saveRankData",
                    startTime: startTime,
                    endTime: endTime,
                    rankName: rankName,
                    score: score,
                    order: order,
                });
            }
            static getRankListSdk(dataNum, rankName, order, rankType) {
                console.log("getRankListSdk");
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/getRankData",
                    data: {
                        dataNum: dataNum,
                        rankName: rankName,
                        order: order,
                        rankType: rankType,
                    }
                });
            }
            static recordGameVideo(action, isRecordVoice = true, durationTime = 120) {
                console.log(`mgrsdk recordGameVideo: ${action}`);
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/recorderGameVideo",
                    data: {
                        action: action,
                        isRecordVoice: isRecordVoice,
                        durationTime: durationTime,
                    }
                });
            }
            static shareGameVideo(title = "", content = "", imagePath, userData = `{}`) {
                console.log("mgrsdk shareGameVideo");
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/shareGameVideo",
                    data: {
                        title: title,
                        content: content,
                        imagePath: imagePath,
                        userData: userData,
                    }
                });
            }
            static jumpOtherGame(gameIndex, type, userData = `{}`) {
                console.log("mgrSdk jumpOtherGame");
                this.sendMsgToSdk({
                    cmd: "/c/jumpOtherGame",
                    data: {
                        gameIndex: gameIndex,
                        type: type,
                        userData: userData,
                    }
                });
            }
            static openJump(gameIndex, type, count = 0) {
                this.sendMsgToSdk({
                    cmd: "/c/openJump",
                    data: {
                        gameIndex: gameIndex,
                        type: type,
                        count: count,
                    }
                });
            }
            static addSubscribe(templateIds) {
                console.log("mgrSdk addSubscribe");
                this.sendMsgToSdk({
                    cmd: "/c/addSubscribe",
                    data: {
                        userData: "",
                        templateIds: templateIds,
                    }
                });
            }
            static openCrossRecommend(left, top, typeId = 0) {
                console.log("mgrSdk openCrossRecommend");
                this.sendMsgToSdk({
                    cmd: "/c/openRecommendation",
                    data: {
                        typeId: typeId,
                        style: {
                            left: left,
                            top: top,
                        },
                    }
                });
            }
            static closeCrossRecommend() {
                console.log("mgrSdk closeCrossRecommend");
                this.sendMsgToSdk({
                    cmd: "/c/closeRecommendation",
                    data: null,
                });
            }
            static openGrid(x, y, userData, type = "single", width, height) {
                console.log("mgrsdk openGrid====", x, y, type);
                this.sendMsgToSdk({
                    cmd: "/c/openGridAd",
                    data: {
                        userData: { userData },
                        style: {
                            x: x,
                            y: y,
                            width: width,
                            height: height,
                        },
                        type: type,
                    },
                });
            }
            static closeGridAd(type = "single") {
                console.log("mgrsdk closeGridAd===", type);
                this.sendMsgToSdk({
                    cmd: "/c/closeGridAd",
                    data: {
                        userData: {},
                        type: type,
                    },
                });
            }
            static saveServerRecord(data) {
                console.log("mgrSdk saveServerRecord");
                this.sendMsgToSdk({
                    cmd: "/c/saveUserData",
                    data: {
                        userData: data,
                    },
                });
            }
            static getServerRecord() {
                console.log("mgrSdk getServerRecord");
                this.sendMsgToSdk({
                    cmd: "/c/getUserData",
                    data: null,
                });
            }
            static addGameToMyFavorite(typeId = 0, content = "一键添加到我的小程序", userData = "") {
                console.log("mgrSdk addGameToMyFavorite");
                this.sendMsgToSdk({
                    cmd: "/c/addGameToMyFavorite",
                    data: {
                        typeId: typeId,
                        content: content,
                        userData: userData || "",
                    },
                });
            }
            static getUserInfoMsg() {
                this.sendMsgToSdk({
                    cmd: "/c/getUserInfoMsgResult",
                });
            }
            static installShortcut(userData = "{}") {
                console.log("mgrSdk installShortcut");
                this.sendMsgToSdk({
                    cmd: "/c/installShortcut",
                    data: {
                        userData: userData,
                    },
                });
            }
            static getShortcutState(userData = "{}") {
                console.log("mgrSdk getShortcutState");
                this.sendMsgToSdk({
                    cmd: "/c/getShortcutState",
                    data: {
                        userData: userData,
                    },
                });
            }
            static setClipboardData(clipboardData, userData = "{}") {
                this.sendMsgToSdk({
                    cmd: "/c/setClipboardData",
                    data: {
                        clipboardData: clipboardData,
                        userData: userData,
                    },
                });
            }
            static getClipboardData(userData = "{}") {
                this.sendMsgToSdk({
                    cmd: "/c/getClipboardData",
                    data: {
                        userData: userData,
                    },
                });
            }
            static postMegadata(data) {
                this.sendMsgToSdk({
                    cmd: "/c/postMegadata",
                    data: data,
                });
            }
            static statisOnStageStart(stageName, reason, bGuide, userParams) {
                bGuide = bGuide || !mgrGuide.isAllGuideFinished();
                reason = reason || "";
                if (this.DEBUG) {
                    console.info("mgrSdk:statisOnStageStart(stageName)", stageName);
                }
                let data = ["levelStart", stageName, reason, bGuide ? "1" : "0"];
                if (userParams && userParams.length > 0) {
                    for (let i = 0; i < userParams.length; i++) {
                        data.push(userParams[i]);
                    }
                }
                this.postMegadata(data);
            }
            static statisOnStageEnd(stageName, result, reason, bGuide, userParams) {
                bGuide = bGuide || !mgrGuide.isAllGuideFinished();
                reason = reason || "";
                if (this.DEBUG) {
                    console.info("mgrSdk:statisOnStageEnd(stageName)", stageName, result, reason);
                }
                let data = ["levelComplete", stageName + "", result + "", reason + "", '0', '0', '0', '0', '0', bGuide ? "1" : "0"];
                if (userParams && userParams.length > 0) {
                    for (let i = 0; i < userParams.length; i++) {
                        data.push(userParams[i]);
                    }
                }
                this.postMegadata(data);
            }
            static statisOnAddItemAmount(itemId, amountDelta, reason, bGuide, userParams) {
                bGuide = bGuide || !mgrGuide.isAllGuideFinished();
                reason = reason || "";
                if (parseInt(reason) > 0) {
                }
                else {
                    return;
                }
                if (mgrSdk.getCopNumberValueByKey("b_open_statics_item") == 0) {
                    return;
                }
                if (this.DEBUG) {
                    console.info("mgrSdk:statisOnAddItemAmount(itemId)", itemId, " amountDelta: ", amountDelta, "reason: ", reason);
                }
                if (amountDelta > 0) {
                    let data = ["coinChange", itemId.toString(), "1", amountDelta.toString(), reason || "", bGuide ? "1" : "0"];
                    if (userParams && userParams.length > 0) {
                        for (let i = 0; i < userParams.length; i++) {
                            data.push(userParams[i]);
                        }
                    }
                    this.postMegadata(data);
                }
                else {
                    let data = ["coinChange", itemId.toString(), "0", Math.abs(amountDelta).toString(), reason || "", bGuide ? "1" : "0"];
                    if (userParams && userParams.length > 0) {
                        for (let i = 0; i < userParams.length; i++) {
                            data.push(userParams[i]);
                        }
                    }
                    this.postMegadata(data);
                }
            }
            static statisOnItemBought(shopId, amount, reason, bGuide, userParams) {
                bGuide = bGuide || !mgrGuide.isAllGuideFinished();
                reason = reason || "";
                let data = ["itemBuy", shopId + "", Math.abs(amount) + "", reason + "", bGuide ? "1" : "0"];
                if (userParams && userParams.length > 0) {
                    for (let i = 0; i < userParams.length; i++) {
                        data.push(userParams[i]);
                    }
                }
                this.postMegadata(data);
            }
            static statisOnBuyAction(reason, shopName, result, bGuide, userParams) {
                bGuide = bGuide || !mgrGuide.isAllGuideFinished();
                reason = reason || "";
                let data = ["buyAction", reason + "0", shopName + "", result + "", bGuide ? "1" : "0"];
                if (userParams && userParams.length > 0) {
                    for (let i = 0; i < userParams.length; i++) {
                        data.push(userParams[i]);
                    }
                }
                this.postMegadata(data);
            }
            static statisCommonEvent(id, param1, param2, bGuide, userParams) {
                bGuide = bGuide || !mgrGuide.isAllGuideFinished();
                let data = ["commonEvent", id + "", param1 || "0", param2 || "0", bGuide ? "1" : "0"];
                if (userParams && userParams.length > 0) {
                    for (let i = 0; i < userParams.length; i++) {
                        data.push(userParams[i]);
                    }
                }
                this.postMegadata(data);
            }
            static statisCommonEventString(id, param1, param2, bGuide, userParams) {
                bGuide = bGuide || !mgrGuide.isAllGuideFinished();
                let data = ["commonEvent", id, param1 || "0", param2 || "0", bGuide ? "1" : "0"];
                if (userParams && userParams.length > 0) {
                    for (let i = 0; i < userParams.length; i++) {
                        data.push(userParams[i]);
                    }
                }
                this.postMegadata(data);
            }
            static statisVideoPointEvent(adStatisticsId, state, bGuide, userParams) {
                bGuide = bGuide || !mgrGuide.isAllGuideFinished();
                let data = ["videoPointEvent", adStatisticsId, state + "", bGuide ? "1" : "0"];
                if (userParams && userParams.length > 0) {
                    for (let i = 0; i < userParams.length; i++) {
                        data.push(userParams[i]);
                    }
                }
                this.postMegadata(data);
            }
        }
        mgrSdk.DEBUG = false;
        mgrSdk.bInit = true;
        mgrSdk.followState = 2;
        mgrSdk.__back_prompt_dialog = null;
        mgrSdk.baseChannelInfo = null;
        mgrSdk.cmdCallbacks = {};

        class mgrPart extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.registerListeners({
                    MSG_ITEM_AMOUNT_CHANGED: this.onMsgItemAmountChanged.bind(this),
                });
                Timer.callLoop(60, (timer) => {
                    this.refreshDailyData();
                }, this);
                mgrCfg.forDb_from_suit_db((k, v) => {
                    for (let index = 0; index < v.partIds.length; index++) {
                        const partId = v.partIds[index];
                        this.part2SuitId[partId] = v.id;
                    }
                });
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("mgr_part") || {};
                this.mainPartIds = record.mainPartIds || [];
                this.stagePartIds = record.stagePartIds || [];
                this.getedRewardSuitIds = record.getedRewardSuitIds || [];
                this.newPartIds = record.newPartIds || [];
                this.cpRewardPartId = record.cpRewardPartId || 0;
                this.cpRewardCount = record.cpRewardCount || 0;
                this.partOwnPointDict = record.partOwnPointDict || {};
                this.partAdTrialDict = record.partAdTrialDict || {};
                this.lastDailyRefreshTime = record.lastDailyRefreshTime || 0;
                this.dailyLuckPartIdDict = record.dailyLuckPartIdDict || {};
                this.dailyUsedLuckPartIdDict = record.dailyUsedLuckPartIdDict || {};
                this.refreshDailyData();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    mainPartIds: this.mainPartIds,
                    stagePartIds: this.stagePartIds,
                    getedRewardSuitIds: this.getedRewardSuitIds,
                    newPartIds: this.newPartIds,
                    cpRewardCount: this.cpRewardCount,
                    partOwnPointDict: this.partOwnPointDict,
                    partAdTrialDict: this.partAdTrialDict,
                    lastDailyRefreshTime: this.lastDailyRefreshTime,
                    dailyLuckPartIdDict: this.dailyLuckPartIdDict,
                    dailyUsedLuckPartIdDict: this.dailyUsedLuckPartIdDict,
                };
                mgrRecord.setData("mgr_part", record);
            }
            static refreshDailyData() {
                if (!Tools.isOneDay(Tools.time(), this.lastDailyRefreshTime)) {
                    this.lastDailyRefreshTime = Tools.time();
                    this.randomDailyLuckyPart();
                    this.saveRecord();
                }
            }
            static getRecommendTagsByPartId(partId) {
                let datas = [];
                let partData = mgrCfg.get_from_part_db(partId);
                let scoreInfos = [];
                for (let index = 1; index < 10; index++) {
                    let score = partData["score" + index] || 0;
                    scoreInfos.push({ tag: index, score: score });
                }
                for (let i = 0; i < scoreInfos.length; i++) {
                    const scoreInfo = scoreInfos[i];
                    let tagData = mgrCfg.get_from_part_tag_db(scoreInfo.tag);
                    if (!tagData) {
                        break;
                    }
                    datas.push({
                        id: tagData.id,
                        score: scoreInfo.score,
                        icon: tagData.icon,
                    });
                }
                datas = Tools.sortArrayByField(datas, "-score");
                return [datas[0], datas[1]];
            }
            static getMaxPartNum() {
                let db = mgrCfg.getDbArr("part_db", (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    return true;
                });
                return ul.length(db);
            }
            static getOwnPartNum() {
                let count = 0;
                let db = mgrCfg.getDbArr("part_db", (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    return true;
                });
                for (let k in db) {
                    if (mgrPlayer.getItemAmount(db[k].id) > 0) {
                        count++;
                    }
                }
                return count;
            }
            static getReplacedRoleCenterParts(roleId, fillPartIds) {
                fillPartIds = fillPartIds || [];
                let type2PartIdDict = {};
                let rolePartIds = this.getRoleCenterPartIds(roleId);
                for (let k in rolePartIds) {
                    let partData = mgrCfg.get_from_part_db(rolePartIds[k]);
                    if (!partData) {
                        console.warn("--ERROR--replaceRolePart---没有找到对应的部件数据---partId=", rolePartIds[k]);
                        continue;
                    }
                    type2PartIdDict[partData.type] = rolePartIds[k];
                }
                for (let i = 0; i < fillPartIds.length; i++) {
                    const partId = fillPartIds[i];
                    let partData = mgrCfg.get_from_part_db(partId);
                    if (!partData) {
                        console.warn("--ERROR--replaceRolePart---没有找到对应的部件数据---partId=", partId);
                        continue;
                    }
                    if (partData.type == PartType.hair || partData.type == PartType.face) {
                        continue;
                    }
                    type2PartIdDict[partData.type] = partId;
                }
                let partIds = [];
                for (let k in type2PartIdDict) {
                    partIds.push(type2PartIdDict[k]);
                }
                return partIds;
            }
            static getRoleCenterPartIds(roleId) {
                let roleData = mgrCfg.get_from_role_db(roleId);
                return roleData.centerPartIds;
            }
            static getLastClothes(roleId, bHaved = false) {
                if (!this.mainPartIds || !roleId)
                    return [];
                let type2PartIdDict = {};
                let rolePartIds = this.getRoleCenterPartIds(roleId);
                for (let k in rolePartIds) {
                    let partData = mgrCfg.get_from_part_db(rolePartIds[k]);
                    if (!partData) {
                        console.warn("--ERROR--getLastClothes---没有找到对应的部件数据---partId=", rolePartIds[k]);
                        continue;
                    }
                    type2PartIdDict[partData.type] = rolePartIds[k];
                }
                for (let i = 0; i < this.mainPartIds.length; i++) {
                    const partId = this.mainPartIds[i];
                    let partData = mgrCfg.get_from_part_db(partId);
                    if (!partData) {
                        console.warn("--ERROR--getLastClothes---没有找到对应的部件数据---partId=", partId);
                        continue;
                    }
                    if (partData.type == PartType.hair || partData.type == PartType.face) {
                        continue;
                    }
                    if (bHaved) {
                        if (mgrPlayer.getItemAmount(partId) > 0) {
                            type2PartIdDict[partData.type] = partId;
                        }
                    }
                    else {
                        type2PartIdDict[partData.type] = partId;
                    }
                }
                let partIds = [];
                for (let k in type2PartIdDict) {
                    partIds.push(type2PartIdDict[k]);
                }
                return partIds;
            }
            static setLastClothes(partIds) {
                this.mainPartIds = partIds;
                this.saveRecord();
            }
            static isSuitRewardGeted(suitId) {
                return this.getedRewardSuitIds.indexOf(suitId) >= 0;
            }
            static isSuitCollectComplete(suitId) {
                let suitData = mgrCfg.get_from_suit_db(suitId);
                let haveCount = 0;
                let maxCount = 0;
                for (let index = 0; index < suitData.partIds.length; index++) {
                    const partId = suitData.partIds[index];
                    if (mgrPlayer.getItemAmount(partId) > 0)
                        haveCount++;
                    maxCount++;
                }
                if (haveCount < maxCount) {
                    return false;
                }
                return true;
            }
            static canObtainSuitReward(suitId) {
                if (this.isSuitRewardGeted(suitId)) {
                    return false;
                }
                let suitData = mgrCfg.get_from_suit_db(suitId);
                let haveCount = 0;
                let maxCount = 0;
                for (let index = 0; index < suitData.partIds.length; index++) {
                    const partId = suitData.partIds[index];
                    if (mgrPlayer.getItemAmount(partId) > 0)
                        haveCount++;
                    maxCount++;
                }
                if (haveCount < maxCount) {
                    return false;
                }
                return true;
            }
            static obtainSuitReward(suitId, ratio = 1) {
                if (this.isSuitRewardGeted(suitId)) {
                    mgrTip.showMsgTip("已领取");
                    return false;
                }
                let suitData = mgrCfg.get_from_suit_db(suitId);
                if (!this.isSuitCollectionCompleted(suitId)) {
                    mgrTip.showMsgTip("还没有收集完毕, 点击卡片查看详情");
                    return false;
                }
                this.getedRewardSuitIds.push(suitId);
                for (let index = 0; index < suitData.collectionRewards.length; index++) {
                    const element = suitData.collectionRewards[index];
                    let reason = ratio == 1 ? "50000" : "50006";
                    mgrPlayer.addItemAmount(element[0], element[1] * ratio, reason);
                    mgrTip.addGotItemTip(element[0], element[1] * ratio, null, {
                        fOnClose: () => {
                        },
                        bTriple: true
                    });
                }
                this.saveRecord();
                return true;
            }
            static getBadgeCount() {
                let bCan = false;
                mgrCfg.forDb_from_suit_db((k, v) => {
                    if (!v.type) {
                        return;
                    }
                    let bAllHave = true;
                    for (let i = 0; i < v.partIds.length; i++) {
                        const partId = v.partIds[i];
                        if (mgrPlayer.getItemAmount(partId) <= 0) {
                            bAllHave = false;
                            break;
                        }
                    }
                    if (bAllHave && !this.isSuitRewardGeted(v.id)) {
                        bCan = true;
                        return true;
                    }
                });
                if (bCan)
                    return 1;
                return 0;
            }
            static isSuitCollectionCompleted(suitId) {
                let suitData = mgrCfg.get_from_suit_db(suitId);
                if (!suitData) {
                    return false;
                }
                let bFinished = true;
                for (let i = 0; i < suitData.partIds.length; i++) {
                    const partId = suitData.partIds[i];
                    if (mgrPlayer.getItemAmount(partId) <= 0) {
                        bFinished = false;
                    }
                }
                return bFinished;
            }
            static getSuitProgress(suitId) {
                let suitData = mgrCfg.get_from_suit_db(suitId);
                let max = suitData.partIds.length || 1;
                let cur = 0;
                for (let i = 0; i < suitData.partIds.length; i++) {
                    const partId = suitData.partIds[i];
                    if (mgrPlayer.getItemAmount(partId) > 0) {
                        cur++;
                    }
                    ;
                }
                return [cur, max];
            }
            static getAllSuitsProgress() {
                let suit_db = mgrCfg.getDb("suit_db");
                let max = 0;
                let cur = 0;
                for (let key in suit_db) {
                    max++;
                    let suitId = suit_db[key].id;
                    let [suitCur, suitMax] = this.getSuitProgress(suitId);
                    if (suitCur >= suitMax)
                        cur++;
                }
                return [cur, max];
            }
            static getSuitsProgressByCategoryId(categoryId) {
                let suits = this.getSuitDatasByCategory(categoryId);
                let max = 0;
                let cur = 0;
                suits.forEach(v => {
                    max++;
                    let suitId = v.id;
                    let [suitCur, suitMax] = this.getSuitProgress(suitId);
                    if (suitCur >= suitMax)
                        cur++;
                });
                return [cur, max];
            }
            static getSuitDatas() {
                let datas = [];
                mgrCfg.forDb_from_suit_db((k, v) => {
                    datas.push(v);
                    let [cur, max] = this.getSuitProgress(v.id);
                    if (cur >= max) {
                        v[`__order`] = -1;
                    }
                    else {
                        v[`__order`] = v.id;
                    }
                });
                datas = Tools.sortArrayByField(datas, "__order");
                return datas;
            }
            static getBadgeCountByCategory(category) {
                let bCan = false;
                mgrCfg.forDb_from_suit_db((k, v) => {
                    if (v.type == category) {
                        let bAllHave = true;
                        for (let i = 0; i < v.partIds.length; i++) {
                            const partId = v.partIds[i];
                            if (mgrPlayer.getItemAmount(partId) <= 0) {
                                bAllHave = false;
                                break;
                            }
                        }
                        if (bAllHave && !this.isSuitRewardGeted(v.id)) {
                            bCan = true;
                            return true;
                        }
                    }
                });
                if (bCan)
                    return 1;
                return 0;
            }
            static getSuitDatasByCategory(categoryId) {
                let suitDatas = this.getSuitDatas();
                let categorySuits = [];
                suitDatas.forEach(v => {
                    if (v.type == categoryId && mgrGameResVersion.isValidGameResVersion(v.gameResVersion)) {
                        categorySuits.push(v);
                    }
                });
                categorySuits = Tools.sortArrayByField(categorySuits, "order");
                return categorySuits;
            }
            static _getRandomPartIdByPartType(partType) {
                let ids = [];
                let db = mgrCfg.getDbArr("part_db", (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    return true;
                });
                for (let k in db) {
                    let v = db[k];
                    if (v.type == partType && !v.bIgnoreInGrade) {
                        ids.push(v.id);
                    }
                }
                if (ids.length <= 0) {
                    return 0;
                }
                return ids[Tools.random(ids.length - 1)];
            }
            static _debugFillRandom() {
                let partIds = [];
                let partTypes = [
                    PartType.hair,
                    PartType.cloth,
                    PartType.earDec,
                    PartType.headDec,
                    PartType.sock,
                    PartType.shoe,
                ];
                for (let k in partTypes) {
                    let partType = partTypes[k];
                    let partId = this._getRandomPartIdByPartType(partType);
                    if (partId != 0) {
                        partIds.push(partId);
                    }
                }
                return partIds;
            }
            static calcWeight(partIds) {
                let total = 0;
                for (let k in partIds) {
                    let partId = partIds[k];
                    let template = mgrCfg.get_from_part_db(partId);
                    if (!template) {
                        continue;
                    }
                    total += (template.level || 0);
                }
                return total;
            }
            static onMsgItemAmountChanged(e) {
                let itemId = e.itemId;
                if (!!mgrCfg.get_from_part_db(itemId) && mgrPlayer.getItemAmount(itemId) == 1) {
                    this.newPartIds.push(itemId);
                }
            }
            static deleteNewPart(partId) {
                let index = this.newPartIds.indexOf(partId);
                if (index == -1)
                    return;
                this.newPartIds.splice(index, 1);
            }
            static isNewPart(partId) {
                return this.newPartIds.indexOf(partId) >= 0;
            }
            static isNewType(type) {
                for (let i = 0; i < this.newPartIds.length; i++) {
                    const partId = this.newPartIds[i];
                    let partData = mgrCfg.get_from_part_db(partId);
                    if (partData.type == type)
                        return true;
                }
                return false;
            }
            static getPartBadgeCount() {
                return this.newPartIds.length;
            }
            static getAllLoadedPartIds() {
                let partIds = {};
                mgrCfg.forDb_from_part_db((k, v) => {
                    if (!partIds[v.type])
                        partIds[v.type] = { hash: {}, array: [] };
                    let b = true;
                    for (let i = 0; i < v.modelId.length; i++) {
                        const modelId = v.modelId[i];
                        b = b && mgrLoader.isLoadedWithModelId(modelId);
                    }
                    partIds[v.type].hash[v.id] = b;
                    b && partIds[v.type].array.push(v.id);
                });
                return partIds;
            }
            static getPartAverageLevel() {
                let totalLevel = 0;
                let partCount = 0;
                let db = mgrCfg.getDbArr("part_db", (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    return true;
                });
                for (let k in db) {
                    let v = db[k];
                    let count = mgrPlayer.getItemAmount(v.id);
                    if (count > 0) {
                        totalLevel += v.level;
                        partCount += 1;
                    }
                }
                return totalLevel / partCount;
            }
            static getAllHavedPartIds() {
                let partIds = [];
                let db = mgrCfg.getDbArr("part_db", (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    return true;
                });
                for (let k in db) {
                    let v = db[k];
                    let count = mgrPlayer.getItemAmount(v.id);
                    let partTypeData = mgrCfg.get_from_part_type_db(v.type);
                    if (count > 0 && v.id != 1001000 && partTypeData.defaultPartId != v.id) {
                        partIds.push(v.id);
                    }
                }
                return partIds;
            }
            static getCollectionProgress() {
                let cur = 0;
                let max = 0;
                let db = mgrCfg.getDbArr("part_db", (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    return true;
                });
                for (let k in db) {
                    max++;
                    if (mgrPlayer.getItemAmount(db[k].id) > 0)
                        cur++;
                }
                return [cur, max];
            }
            static isAdSuitPartValid() {
                let data = mgrCfg.get("ad_suit_config_db", 1);
                let suitIds = data.suitIds || [];
                for (let i = 0; i < suitIds.length; i++) {
                    if (!mgrPart.isSuitCollectionCompleted(suitIds[i])) {
                        return true;
                    }
                }
                return false;
            }
            static getPartColorOwnPoint(partId) {
                return this.partOwnPointDict[partId] || 0;
            }
            static addPartColorOwnPoint(partId, amount) {
                this.partOwnPointDict[partId] = this.partOwnPointDict[partId] || 0;
                this.partOwnPointDict[partId] += (amount || 0);
                this.saveRecord();
            }
            static setPartColorOwnPoint(partId, amount) {
                this.partOwnPointDict[partId] = amount || 0;
                this.saveRecord();
            }
            static isPartOwnColorPointEnough(partId) {
                let partData = mgrCfg.get_from_item_template_db(partId);
                let ownedColorPoint = this.getPartColorOwnPoint(partId);
                return ownedColorPoint >= partData.unlockColorPoint;
            }
            static randomDailyLuckyPart() {
                let arr = [];
                mgrCfg.forDb_from_part_type_db((k, v) => {
                    if (!!v.listOrder) {
                        arr.push({
                            id: v.id,
                        });
                    }
                });
                let luckPartIdDict = {};
                let arrType = Tools.randomGotArrayDatas(arr, 3);
                for (let k in arrType) {
                    let data = arrType[k];
                    let partDatas = mgrCfg.getDbArr("part_db", (data) => {
                        if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                            return false;
                        }
                        return true;
                    });
                    let partData = Tools.randomGotOneArrayData(partDatas);
                    luckPartIdDict[partData.id] = true;
                }
                this.dailyLuckPartIdDict = luckPartIdDict;
                this.dailyUsedLuckPartIdDict = {};
            }
            static isDailyLuckyPart(partId) {
                return !!this.dailyLuckPartIdDict[partId];
            }
            static isUsedDailyLuckyPart(partId) {
                return !!this.dailyUsedLuckPartIdDict[partId];
            }
            static markUsedDailyLuckyPart(partId) {
                this.dailyUsedLuckPartIdDict[partId] = true;
                this.saveRecord();
            }
            static getGameRoomListSortedId2OrderDictByType(gameType, typeFlag) {
                if (!this.roomListSortedIdsOrderDict[gameType]) {
                    return null;
                }
                if (!this.roomListSortedIdsOrderDict[gameType][typeFlag]) {
                    return null;
                }
                return this.roomListSortedIdsOrderDict[gameType][typeFlag];
            }
            static setGameRoomListSortedId2OrderDictByType(gameType, typeFlag, id2OrderDict) {
                this.roomListSortedIdsOrderDict[gameType] = this.roomListSortedIdsOrderDict[gameType] || {};
                this.roomListSortedIdsOrderDict[gameType][typeFlag] = id2OrderDict;
            }
        }
        mgrPart.part2SuitId = {};
        mgrPart.cpRewardCount = 0;
        mgrPart.partOwnPointDict = {};
        mgrPart.partAdTrialDict = {};
        mgrPart.dailyLuckPartIdDict = {};
        mgrPart.dailyUsedLuckPartIdDict = {};
        mgrPart.lastDailyRefreshTime = 0;
        mgrPart.roomListSortedIdsOrderDict = {};
        mgrPart.roomPopClickItemPartLastTime = 0;

        class StageScriptBase {
            constructor() {
            }
            onRoomSceneLoaded(gameScene) {
            }
            onRoomPlayedActionIn(gameScene) {
            }
            onRoomSceneFinishStage(gameScene, debugScore = null) {
                mgrPart.setLastClothes(gameScene.avatar.getPartIds());
                gameScene.buttonSummit.__node.visible = false;
                let bDressedAutoPopTrialPart = gameScene.isDressAutoPopTrialPart();
                let appendScore = (!!bDressedAutoPopTrialPart ? Const.SCORE_WHEN_ROOM_DRESSED_AUTO_POP_TRIAL_PART : 0);
                let score = mgrCard.calculateRoleTagPartIdsPower(gameScene.roleData.roleTagId, gameScene.avatar.getPartIds()) + appendScore;
                let goResultFunc = (tex2d, bAded) => {
                    let partIds = gameScene.avatar.getPartIds();
                    let result = mgrStage.finishStage(gameScene.context.stageId, partIds, gameScene.roleData.roleTagId, appendScore);
                    let stageId = gameScene.context.stageId;
                    let stageData = mgrCfg.get_from_stage_db(stageId);
                    stageData.statisPointId && mgrSdk.statisOnStageEnd(`${stageData.statisPointId}`, result.rating == EStageRating.pass ? 1 : 0, `${stageData.id}`);
                    gameScene.bStatisOnStageEnd = true;
                    gameScene.destroy();
                    let resultInfo = {
                        result: result,
                        texture2dShot: tex2d,
                        stageId: gameScene.context.stageId,
                        partIds: partIds,
                        bPowerHighest: false,
                        backSceneName: gameScene.context.backSceneName || `vHubScene`,
                        bDressedLuckyPart: gameScene.dressedLuckyPartIds.length > 0 ? true : false,
                        currPower: score,
                        roleId: gameScene.roleData.id
                    };
                    mgrDirector.warpSceneWidthEffect("vRoomStageResultScene", resultInfo);
                };
                gameScene.context.cameraFollow.position = new Laya.Vector3(0, 1.2, 2);
                gameScene.context.cameraFollow.fov = 30;
                gameScene.context.cameraFollow.lerpValue = 1;
                gameScene.context.cameraFollow.endRotation = new Laya.Vector3(-2.5);
                gameScene.context.cameraFollow.onLateUpdate();
                Tools.takeAPhoto(512, 512, gameScene.context.cameraFollow.__node, (tex2d) => {
                    goResultFunc(tex2d, false);
                }, Laya.RenderTextureFormat.R8G8B8A8);
            }
            onListTypeLoaded(gameScene) {
            }
            onListPartLoaded(gameScene) {
            }
            onPartSelected(gameScene, partId) {
            }
            onBeforeSelectPart(gameScene, partId) {
                return false;
            }
            onTypeSelected(gameScene, partType) {
            }
            updateSubjectScoreInfo(gameScene) {
            }
            onTouchButtonBack(gameScene) {
                mgrTip.alertPrompt2("提示", "是否退出？", "取消", "退出", () => { }, () => {
                    gameScene.bStatisOnStageEnd = true;
                    let stageId = gameScene.context.stageId;
                    let stageData = mgrCfg.get_from_stage_db(stageId);
                    stageData.statisPointId && mgrSdk.statisOnStageEnd(`${stageData.statisPointId}`, 0, stageId);
                    gameScene.destroy();
                    mgrVideoRecorder.stopRecord();
                    mgrDirector.warpSceneWidthEffect(gameScene.context.backSceneName);
                });
            }
            isUseLastSaveAvatar() {
                return true;
            }
            getBanPartIdDict() {
                return null;
            }
            isDisableChangeRole() {
                return false;
            }
        }

        class StageScriptGuide1 extends StageScriptBase {
            constructor() {
                super();
                this.listPartRegisteredNodes = {};
                this.listTypeRegisteredNodes = {};
            }
        }

        class mgrSwitchOpen extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化mgrSwitchOpen loadRecord");
                this.loadRecord();
                Timer.callLoop(1, () => {
                    this.gameTime++;
                }, this);
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("switch_open") || {};
                this.dialogInfo = record.dialogInfo || {};
                Timer.callLoop(1, () => {
                    let bChanged = false;
                    for (let key in this.dialogInfo) {
                        if (this.dialogInfo[key]) {
                            let lastShareTime = this.dialogInfo[key].lastOpenTime;
                            if (!Tools.isOneDay(lastShareTime, Tools.time())) {
                                this.dialogInfo[key].openCount = 0;
                                this.dialogInfo[key].lastOpenTime = Tools.time();
                                bChanged = true;
                            }
                        }
                    }
                    if (bChanged) {
                        this.saveRecord();
                    }
                }, this);
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    dialogInfo: this.dialogInfo
                };
                mgrRecord.setData("switch_open", record);
            }
            static recordDialogOpenInfo(dialogName) {
                if (this.dialogInfo[dialogName]) {
                    this.dialogInfo[dialogName].openCount++;
                    this.dialogInfo[dialogName].lastOpenTime = Tools.time();
                }
                else {
                    this.dialogInfo[dialogName] = { lastOpenTime: Tools.time(), openCount: 1 };
                }
                this.saveRecord();
            }
            static checkOpenDialog(dialogName) {
                if (!mgrGuide.isAllForceGuideFinished() || !mgrTip.isItemWaitingDisplay() || mgrGuide.isGuiding()) {
                    return false;
                }
                if (!this.dialogInfo[dialogName]) {
                    this.dialogInfo[dialogName] = { openCount: 0, lastOpenTime: Tools.time() };
                    this.saveRecord();
                }
                let ratio = mgrSdk.getCopNumberValueByKey(`open_${dialogName}_ratio`) || 0;
                let cd = mgrSdk.getCopNumberValueByKey(`open_${dialogName}_cd`) || 0;
                let maxCount = mgrSdk.getCopNumberValueByKey(`open_${dialogName}_count`) || 0;
                let needGameTime = mgrSdk.getCopNumberValueByKey(`open_${dialogName}_need_game_time`) || 0;
                let curCount = this.dialogInfo[dialogName].openCount || 0;
                let lastOpenTime = this.dialogInfo[dialogName].lastOpenTime;
                let r = Mathf.random(0, 100);
                if (r < ratio && curCount < maxCount && lastOpenTime < (Tools.time() - cd) && this.gameTime >= needGameTime) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        mgrSwitchOpen.gameTime = 0;

        class StageScriptMakeCard extends StageScriptBase {
            constructor() {
                super();
                this.listPartRegisteredNodes = {};
                this.listTypeRegisteredNodes = {};
            }
            _refreshPvpData(gameScene) {
            }
            onRoomSceneLoaded(gameScene) {
                gameScene.spriteSubmitNormal.node.active = false;
                gameScene.spriteSubmitPvp.node.active = true;
                gameScene.boxTagLayout.visible = false;
                this._refreshPvpData(gameScene);
            }
            onRoomPlayedActionIn(gameScene) {
            }
            onRoomSceneFinishStage(gameScene, debugScore = null) {
                gameScene.destroy();
                let doExeFunc = () => {
                    mgrDirector.warpSceneWidthEffect(`vAmuseCardPhotoMakeScene`, {
                        fromViewDesc: "重新制卡换装",
                        backSceneName: gameScene.context.backSceneName || `vHubScene`,
                        nextDialogName: gameScene.context.nextDialogName,
                        bRemakeCardResult: true,
                        cardId: gameScene.context.cardId,
                        roleId: gameScene.context.roleId,
                        partIds: gameScene.avatar.getPartIds()
                    });
                };
                if (mgrSwitchOpen.checkOpenDialog("vAdPopMachineDialog")) {
                    mgrDirector.openDialog("vAdPopMachineDialog", {
                        fOnClose: () => {
                            doExeFunc();
                        }
                    });
                }
                else {
                    doExeFunc();
                }
            }
            onTouchButtonBack(gameScene) {
                mgrTip.alertPrompt2("提示", "是否放弃当前装扮？", "取消", "退出", () => { }, () => {
                    gameScene.bStatisOnStageEnd = true;
                    let stageId = gameScene.context.stageId;
                    let stageData = mgrCfg.get_from_stage_db(stageId);
                    stageData.statisPointId && mgrSdk.statisOnStageEnd(`${stageData.statisPointId}`, 0, stageId);
                    gameScene.destroy();
                    mgrVideoRecorder.stopRecord();
                    mgrDirector.warpSceneWidthEffect(gameScene.context.backSceneName || `vHubScene`);
                });
            }
            isUseLastSaveAvatar() {
                return false;
            }
            getBanPartIdDict() {
                return null;
            }
        }

        class StageScriptPvp extends StageScriptBase {
            constructor() {
                super();
                this.listPartRegisteredNodes = {};
                this.listTypeRegisteredNodes = {};
            }
            _refreshPvpData(gameScene) {
            }
            onRoomSceneLoaded(gameScene) {
                gameScene.spriteSubmitNormal.node.active = false;
                gameScene.spriteSubmitPvp.node.active = true;
                gameScene.boxTagLayout.visible = false;
                this._refreshPvpData(gameScene);
            }
            onRoomPlayedActionIn(gameScene) {
                gameScene.sendMsg("MSG_GUIDE_POINT", {
                    id: "vRoomDialog.guidePvpSubject",
                });
            }
            onRoomSceneFinishStage(gameScene, debugScore = null) {
                mgrPart.setLastClothes(gameScene.avatar.getPartIds());
                let bDressedAutoPopTrialPart = gameScene.isDressAutoPopTrialPart();
                let appendScore = (!!bDressedAutoPopTrialPart ? Const.SCORE_WHEN_ROOM_DRESSED_AUTO_POP_TRIAL_PART : 0);
                let onSelected = (bMake) => {
                    gameScene.context.cameraFollow.position = new Laya.Vector3(0, 1.2, 2);
                    gameScene.context.cameraFollow.fov = 30;
                    gameScene.context.cameraFollow.lerpValue = 1;
                    gameScene.context.cameraFollow.endRotation = new Laya.Vector3(-2.5);
                    gameScene.context.cameraFollow.onLateUpdate();
                    Tools.takeAPhoto(512, 512, gameScene.context.cameraFollow.__node, (tex2d) => {
                        gameScene.destroy();
                        if (bMake) {
                            tex2d.destroy();
                            mgrDirector.warpSceneWidthEffect(`vAmuseCardPhotoMakeScene`, {
                                bDisableStartVideoRecorder: true,
                                appendScore: appendScore,
                                fromViewDesc: "自由换装",
                                backSceneName: gameScene.context.backSceneName || `vHubScene`,
                            });
                        }
                        else {
                            mgrVideoRecorder.stopRecord();
                            mgrTip.tryShowPhotoShare("vRoomDialog", tex2d, null, () => {
                                mgrDirector.warpSceneWidthEffect(`vHubScene`);
                            });
                        }
                    }, Laya.RenderTextureFormat.R8G8B8A8);
                };
                if (mgrSwitchOpen.checkOpenDialog("vAdPopMachineDialog")) {
                    mgrDirector.openDialog("vAdPopMachineDialog", {
                        fOnClose: () => {
                            onSelected(true);
                        }
                    });
                }
                else {
                    onSelected(true);
                }
            }
            onTouchButtonBack(gameScene) {
                mgrTip.alertPrompt2("提示", "是否放弃当前装扮？", "取消", "退出", () => { }, () => {
                    gameScene.bStatisOnStageEnd = true;
                    let stageId = gameScene.context.stageId;
                    let stageData = mgrCfg.get_from_stage_db(stageId);
                    stageData.statisPointId && mgrSdk.statisOnStageEnd(`${stageData.statisPointId}`, 0, stageId);
                    gameScene.destroy();
                    mgrVideoRecorder.stopRecord();
                    mgrDirector.warpSceneWidthEffect(gameScene.context.backSceneName || `vHubScene`);
                });
            }
            isUseLastSaveAvatar() {
                return false;
            }
            getBanPartIdDict() {
                return null;
            }
        }

        class mgrDynamicBone extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {};
                mgrRecord.setData("mgrDynamicBone", record);
            }
            static setDynamicBoneInfos(value) {
                this.dynamicEditorData = value;
            }
            static getDynamicConfig(key) {
                if (this.dynamicEditorData[key]) {
                    return Tools.deepCopy(this.dynamicEditorData[key]);
                }
                return null;
            }
            static setDynamicConfig(key, config) {
                if (config == null) {
                    delete this.dynamicEditorData[key];
                }
                else {
                    this.dynamicEditorData[key] = config;
                }
                this.recordDynamicConfig();
            }
            static recordDynamicConfig() {
                if (!Const.GlobalRouter) {
                    mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                }
                else {
                    Const.GlobalRouter.sendMsgToServer({
                        route: "keepInFile",
                        data: {
                            filePath: `res/cfg/dynamicBoneInfo.json`,
                            data: this.dynamicEditorData,
                        },
                    });
                }
            }
        }
        mgrDynamicBone.dynamicEditorData = {};

        class CartoonMaterial extends Laya.Material {
            constructor() {
                super();
                this.setShaderName("CartoonShader");
                this._shaderValues.setVector(CartoonMaterial.SHADOWCOLOR, new Laya.Vector4(0.6663285, 0.6544118, 1, 1));
                this._shaderValues.setNumber(CartoonMaterial.SHADOWRANGE, 0.002);
                this._shaderValues.setNumber(CartoonMaterial.SHADOWINTENSITY, 0.98);
                this._shaderValues.setNumber(CartoonMaterial.SHADOWBOUNDARY, 0.015);
                this._shaderValues.setNumber(CartoonMaterial.SPECULARRANGE, 0.99);
                this._shaderValues.setNumber(CartoonMaterial.SPECULARINTENSITY, 0.09);
                this._shaderValues.setVector(CartoonMaterial.SPECULARCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setNumber(CartoonMaterial.OUTLINEWIDTH, 0.001);
                this._shaderValues.setNumber(CartoonMaterial.OUTLINELIGHTNESS, 0.25);
                this._shaderValues.setVector(CartoonMaterial.OUTLINECOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setNumber(CartoonMaterial.ALBEDOIDENTITY, 0.5);
                this._shaderValues.setVector(CartoonMaterial.ALBEDOCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setVector(CartoonMaterial.SECOND_SHADOWCOLOR, new Laya.Vector4(1, 1, 1, 1));
                this._shaderValues.setNumber(CartoonMaterial.SECOND_SHADOWRANGE, 0.00);
                this._shaderValues.setNumber(CartoonMaterial.SECOND_SHADOWINTENSITY, 0.98);
                this._shaderValues.setNumber(CartoonMaterial.SECOND_SHADOWBOUNDARY, 0.0);
                this._shaderValues.setVector(CartoonMaterial.EDGE_HIGHLIGHT_COLOR, new Laya.Vector4(0, 1, 0, 1));
                this._shaderValues.setNumber(CartoonMaterial.EDGE_HIGHLIGHT_RANGE, 0.00);
                this._shaderValues.setNumber(CartoonMaterial.EDGE_HIGHLIGHT_INTENSITY, 0.98);
                this._shaderValues.setNumber(CartoonMaterial.EDGE_HIGHLIGHT_BOUNDARY, 0.0);
                this._shaderValues.setVector(CartoonMaterial.HSVVALUE, new Laya.Vector4(0, 1, 1, 0));
                this._shaderValues.setVector(CartoonMaterial.OFFSETXYZ, new Laya.Vector4(0, 0, 0, 0));
                this._shaderValues.setNumber(CartoonMaterial.GRAYALBEDOTEXTUREFLAG, 0.0);
                this._shaderValues.setNumber(CartoonMaterial.ALPHATESTVALUE, 0.5);
            }
            static __init__() {
                CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE = Laya.Shader3D.getDefineByName("ALBEDOTEXTURE");
                CartoonMaterial.SHADERDEFINE_TILINGOFFSET = Laya.Shader3D.getDefineByName("TILINGOFFSET");
                CartoonMaterial.SHADERDEFINE_BONE = Laya.Shader3D.getDefineByName("BONE");
                CartoonMaterial.SHADERDEFINE_WHOLE_ALPHA = Laya.Shader3D.getDefineByName("WHOLE_ALPHA");
                CartoonMaterial.SHADERDEFINE_ALBEDO_COLOR = Laya.Shader3D.getDefineByName("ALBEDO_COLOR");
                CartoonMaterial.SHADERDEFINE_ONLY_CHANGE_BONE_POS = Laya.Shader3D.getDefineByName("ONLY_CHANGE_BONE_POS");
                CartoonMaterial.SHADERDEFINE_GRAYALBEDOTEXTUREFLAG = Laya.Shader3D.getDefineByName("GRAYALBEDOTEXTUREFLAG");
            }
            static initShader() {
                CartoonMaterial.__init__();
                var stateMap = {
                    's_Cull': Laya.Shader3D.RENDER_STATE_CULL,
                    's_Blend': Laya.Shader3D.RENDER_STATE_BLEND,
                    's_BlendSrc': Laya.Shader3D.RENDER_STATE_BLEND_SRC,
                    's_BlendDst': Laya.Shader3D.RENDER_STATE_BLEND_DST,
                    's_DepthTest': Laya.Shader3D.RENDER_STATE_DEPTH_TEST,
                    's_DepthWrite': Laya.Shader3D.RENDER_STATE_DEPTH_WRITE
                };
                var attributeMap = {
                    'a_Position': Laya.VertexMesh.MESH_POSITION0,
                    'a_Normal': Laya.VertexMesh.MESH_NORMAL0,
                    'a_Texcoord0': Laya.VertexMesh.MESH_TEXTURECOORDINATE0,
                    'a_BoneWeights': Laya.VertexMesh.MESH_BLENDWEIGHT0,
                    'a_BoneIndices': Laya.VertexMesh.MESH_BLENDINDICES0,
                };
                var uniformMap = {
                    'u_MvpMatrix': Laya.Shader3D.PERIOD_SPRITE,
                    'u_WorldMat': Laya.Shader3D.PERIOD_SPRITE,
                    'u_CameraPos': Laya.Shader3D.PERIOD_CAMERA,
                    'u_AlbedoTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoIdentity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ShadowColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ShadowRange': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ShadowIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ShadowBoundary': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SpecularRange': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SpecularColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SpecularIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_OutlineWidth': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_OutlineLightness': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_OutlineColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SunLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_Bones': Laya.Shader3D.PERIOD_CUSTOM,
                    'u_Second_ShadowColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Second_ShadowRange': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Second_ShadowIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Second_ShadowBoundary': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Edge_HighlightColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Edge_HighlightRange': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Edge_HighlightIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Edge_HighlightBoundary': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_RandomDiscardFactor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_alpha': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SpotLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.range': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.spot': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.position': Laya.Shader3D.PERIOD_SCENE,
                    'u_HSVValue': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_OffsetXYZ': Laya.Shader3D.PERIOD_MATERIAL,
                    "u_OnlyChangeBonePos": Laya.Shader3D.PERIOD_MATERIAL,
                    "u_GrayAlbedoTextureFlag": Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlphaTestValue': Laya.Shader3D.PERIOD_MATERIAL,
                };
                var cartoonShader3D = Laya.Shader3D.add("CartoonShader");
                var subShader = new Laya.SubShader(attributeMap, uniformMap);
                cartoonShader3D.addSubShader(subShader);
                var vs2 = `
		attribute vec4 a_Position; 
		attribute vec3 a_Normal;
		attribute vec2 a_Texcoord0;	
		// uniform mat4 u_MvpMatrix;
		// uniform mat4 u_WorldMat;
		uniform vec3 u_CameraPos;	
		varying vec2 v_Texcoord0;
		varying vec3 v_Normal;
		varying vec3 v_PositionWorld;
		varying vec3 v_ViewDir;

		uniform vec4 u_OffsetXYZ;

		#if defined(CASTSHADOW)
		varying vec4 v_posView;
		#endif

		#ifdef GPU_INSTANCE
            attribute mat4 a_MvpMatrix;
            attribute mat4 a_WorldMat;
        #else
            uniform mat4 u_MvpMatrix;
            uniform mat4 u_WorldMat;
		#endif
		
		#ifdef BONE
			const int c_MaxBoneCount = 24;
			attribute vec4 a_BoneIndices;
			attribute vec4 a_BoneWeights;
			uniform mat4 u_Bones[c_MaxBoneCount];
		#endif
		
		void main()
		{

			vec4 offsetXYZ = vec4(u_OffsetXYZ.x,u_OffsetXYZ.y,u_OffsetXYZ.z,0.0);
			#ifdef BONE
				//计算骨骼对位置的影响
				mat4 skinTransform=mat4(0.0);
				skinTransform += u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;
				skinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;
				skinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;
				skinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;
				vec4 position = skinTransform * a_Position;

				#ifdef GPU_INSTANCE
					gl_Position=a_MvpMatrix * (skinTransform * a_Position+offsetXYZ);
					mat3 worldMat=mat3(a_WorldMat * skinTransform);
					v_PositionWorld=(a_WorldMat*position).xyz;
				#else
					gl_Position=u_MvpMatrix * (skinTransform * a_Position+offsetXYZ);
					mat3 worldMat=mat3(u_WorldMat * skinTransform);
					v_PositionWorld=(u_WorldMat*position).xyz;
				#endif
			#else
				#ifdef GPU_INSTANCE
					gl_Position=a_MvpMatrix * (a_Position+offsetXYZ);
					mat3 worldMat=mat3(a_WorldMat);
					v_PositionWorld=(a_WorldMat*(a_Position+offsetXYZ)).xyz;
				#else
					gl_Position=u_MvpMatrix * (a_Position+offsetXYZ);
					mat3 worldMat=mat3(u_WorldMat);
					v_PositionWorld=(u_WorldMat*(a_Position+offsetXYZ)).xyz;
				#endif
			#endif

			v_Normal=worldMat*a_Normal;
			v_Texcoord0 = a_Texcoord0;
			v_ViewDir = u_CameraPos - v_PositionWorld; 

			#if defined(CASTSHADOW)
				v_posView = gl_Position.xyzw;
			#endif
			gl_Position.z=gl_Position.z * 2.0 - gl_Position.w;
		}`;
                var ps2 = `
		precision lowp float;
	
		struct DirectionLight
		{
			vec3 color;
			vec3 direction;
		};

		varying vec2 v_Texcoord0;
		varying vec3 v_Normal;
		varying vec3 v_PositionWorld;
		varying vec3 v_ViewDir;
		#if defined(CASTSHADOW)
		varying vec4 v_posView;
		#endif
	
		#ifdef ALBEDOTEXTURE
		uniform sampler2D u_AlbedoTexture;	
		#endif
		
		#ifdef ALBEDO_COLOR
		uniform float u_AlbedoIdentity;
		uniform vec4 u_AlbedoColor;
		#endif
		uniform vec4 u_ShadowColor;
		uniform float u_ShadowRange;
		uniform float u_ShadowIntensity;
		uniform float u_ShadowBoundary;
		uniform float u_SpecularRange;
		uniform float u_SpecularIntensity;
		uniform vec4 u_SpecularColor;
		//双重阴影参数
		uniform vec4 u_Second_ShadowColor;
		uniform float u_Second_ShadowRange;
		uniform float u_Second_ShadowIntensity;
		uniform float u_Second_ShadowBoundary;
		uniform float u_RandomDiscardFactor;
		//边缘高亮参数
		uniform vec4 u_Edge_HighlightColor;
		uniform float u_Edge_HighlightRange;
		uniform float u_Edge_HighlightIntensity;
		uniform float u_Edge_HighlightBoundary;

		uniform vec4 u_HSVValue;
		uniform float u_GrayAlbedoTextureFlag;
	
		uniform DirectionLight u_SunLight;

		#ifdef WHOLE_ALPHA
		uniform float u_alpha;
		#endif

		#ifdef ALPHATEST
		uniform float u_AlphaTestValue;
		#endif

		float frac(float value) {
			return value - floor(value);
		}
		vec3 fracVec3(vec3 value) {
			return vec3( frac(value.x),frac(value.y),frac(value.z));
		}

		vec3 HSVToRGB( vec3 c )
		{
			vec4 K = vec4( 1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0 );

			vec3 p = abs( fracVec3( c.xxx + K.xyz ) * 6.0 - K.www );
			return c.z * mix( K.xxx, clamp( p - K.xxx,0.0,1.0 ), c.y );
		}

		vec3 RGBToHSV(vec3 c)
		{
			vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
			vec4 p = mix( vec4( c.bg, K.wz ), vec4( c.gb, K.xy ), step( c.b, c.g ) );
			vec4 q = mix( vec4( p.xyw, c.r ), vec4( c.r, p.yzx ), step( p.x, c.r ) );
			float d = q.x - min( q.w, q.y );
			float e = 1.0e-10;
			return vec3( abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
		}

		void main_castshadow(){
			#ifdef CASTSHADOW
				float z = v_posView.z/v_posView.w;
				z = z*0.5 + 0.5;
				gl_FragColor = vec4(0.0, 0, z, 1.0);
			#endif
		}

		void main_normal(){
			vec4 albedoTextureColor = vec4(1.0);
		#ifdef ALBEDOTEXTURE
			albedoTextureColor = texture2D(u_AlbedoTexture, v_Texcoord0);
		#endif
			
			#ifdef ALPHATEST
			if(albedoTextureColor.a <= u_AlphaTestValue){
				discard;
			}
			#endif

			vec3 finalColor;

			#ifdef ONLY_CHANGE_BONE_POS
				finalColor = albedoTextureColor.rgb;
			#else
				
				vec3 normal = normalize(v_Normal);
				// vec3 viewdir = normalize(v_ViewDir);
				vec3 lightDir = normalize(u_SunLight.direction);
			
				vec3 albedoColor = albedoTextureColor.rgb;

				if(u_GrayAlbedoTextureFlag>=0.5){
					
					float gray = dot(albedoColor, vec3(0.299, 0.587, 0.114));
					albedoColor = vec3(gray,gray,gray);
				}

				// //change color
				// vec3 c_hsv = RGBToHSV(albedoColor.rgb);
				// c_hsv.x += u_HSVValue.r/359.0;
				// c_hsv.y *= u_HSVValue.g;
				// c_hsv.z *= u_HSVValue.b;
				// albedoColor.rgb = HSVToRGB(c_hsv);
				
				
				// 阴影计算部分计算
				// 1.0 -> 0.0
				float nl = max(dot(normal, -lightDir), 0.0);
				// +0.01是避免阴影边界等于0时 shadow_allin && shadow_partin 相同
				float shadow_boundary = u_ShadowBoundary + 0.01;
				float shadow_allin = step(nl, u_ShadowRange - shadow_boundary*0.5);
				float shadow_partin = step(nl, u_ShadowRange + shadow_boundary*0.5);
				//分析:  allin时:  shadow_allin == 1.0;  shadow_partin == 1.0;
				//      partin时: shadow_allin == 0.0; shadow_partin = 1.0;
				//      none时:   shadow_allin == 0.0; shadow_partin = 0.0;
				float shadow = shadow_allin + (u_ShadowRange + shadow_boundary*0.5 - nl)/shadow_boundary * (shadow_partin - shadow_allin);

				shadow *= u_ShadowIntensity;
				vec3 albedoAreaColor = (1.0 - shadow) * albedoColor;
				vec3 shadowAreaColor = shadow * albedoColor * u_ShadowColor.rgb;
				
				//高光部分计算
				float specular = pow(nl,u_SpecularRange*10.0);
				vec3 speculAreaColor = (1.0 - shadow) * albedoColor * u_SpecularIntensity * specular * u_SpecularColor.rgb;
				//混合漫反射 + 高光 + 阴影
				finalColor = albedoAreaColor + speculAreaColor + shadowAreaColor;

				//阴影补光计算
				float secondShadowRange = 1.0 - u_Second_ShadowRange;
				float secondShadowBoundary = u_Second_ShadowBoundary + 0.01;
				float negativeNl = max(dot(normal, lightDir), 0.0);
				float secShadowAllin = step(secondShadowRange + secondShadowBoundary*0.5, negativeNl);
				float secShadowPartin = step(secondShadowRange - secondShadowBoundary*0.5, negativeNl);
				//分析:
				//allin时: secShadowAllin == 1.0; secShadowPartin = 1.0;
				//partin时: secShadowAllin == 0.0; secShadowPartin = 1.0;
				//none时: secShadowAllin == 0.0; secShadowPartin = 0.0
				float shadow_second = secShadowAllin + (negativeNl - (secondShadowRange - secondShadowBoundary*0.5))/secondShadowBoundary * (secShadowPartin - secShadowAllin);
				//
				vec3 secondShadowArenaColor = shadow_second*albedoColor*u_Second_ShadowColor.rgb*u_Second_ShadowIntensity;
				finalColor += secondShadowArenaColor;
				// //边缘高光计算(附加条件， 光照方向才有)
				// float nv = 1.0 - abs(dot(normal, viewdir));
				// float hf_nvl = nv * nl;
				// float positive_hrange = 1.0 - u_Edge_HighlightRange;
				// float hightLightBoundary = u_Edge_HighlightBoundary + 0.01;
				// float higAllIn = step(positive_hrange + hightLightBoundary*0.5, hf_nvl);
				// float higPartIn = step(positive_hrange - hightLightBoundary*0.5, hf_nvl);
				// //分析:
				// //allin时: higAllIn = 1.0; higPartIn = 1.0;
				// //partin时: higAllIn = 0.0;higPartIn = 1.0;
				// //none时: higAllIn = 0.0;higPartIn = 0.0;
				// float edgehf = higAllIn + (hf_nvl - (positive_hrange - hightLightBoundary*0.5))/hightLightBoundary * (higPartIn - higAllIn);

				// vec3 edgeHighlightColor = edgehf *albedoColor* u_Edge_HighlightColor.rgb*u_Edge_HighlightIntensity*2.0;
				// finalColor += edgeHighlightColor;
			#endif

			#ifdef WHOLE_ALPHA
				gl_FragColor = vec4(finalColor.rgb, albedoTextureColor.a*u_alpha);
			#else
				gl_FragColor = vec4(finalColor.rgb, albedoTextureColor.a);
			#endif

			#ifdef ALBEDO_COLOR
				gl_FragColor *= (u_AlbedoColor * (u_AlbedoIdentity+0.5));
			#endif
		}
	
		void main()
		{
			#ifdef CASTSHADOW
				main_castshadow();
			#else
				main_normal();
			#endif
		}`;
                subShader.addShaderPass(vs2, ps2, stateMap);
            }
            getShaderValueRangeWithKey(key) {
                return [0.0, 1.0];
            }
            clampKeyValueByKey(key, value) {
                return Math.max(this.getShaderValueRangeWithKey(key)[0], Math.min(this.getShaderValueRangeWithKey(key)[1], value));
            }
            get albedoTexture() {
                return this._shaderValues.getTexture(CartoonMaterial.ALBEDOTEXTURE);
            }
            set albedoTexture(value) {
                if (value)
                    this._defineDatas.add(CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE);
                else
                    this._defineDatas.remove(CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE);
                this._shaderValues.setTexture(CartoonMaterial.ALBEDOTEXTURE, value);
            }
            get albedoColor() {
                return this._shaderValues.getVector(CartoonMaterial.ALBEDOCOLOR);
            }
            set albedoColor(value) {
                if (value.x != 1 || value.y != 1 || value.z != 1 || value.w != 1 || this.albedoIdentity != 0.5) {
                    this._defineDatas.add(CartoonMaterial.SHADERDEFINE_ALBEDO_COLOR);
                }
                else {
                    this._defineDatas.remove(CartoonMaterial.SHADERDEFINE_ALBEDO_COLOR);
                }
                this._shaderValues.setVector(CartoonMaterial.ALBEDOCOLOR, value);
            }
            get albedoIdentity() {
                return this._shaderValues.getNumber(CartoonMaterial.ALBEDOIDENTITY);
            }
            set albedoIdentity(value) {
                if (this.albedoColor.x != 1 || this.albedoColor.y != 1 || this.albedoColor.z != 1 || this.albedoColor.w != 1 || value != 0.5) {
                    this._defineDatas.add(CartoonMaterial.SHADERDEFINE_ALBEDO_COLOR);
                }
                else {
                    this._defineDatas.remove(CartoonMaterial.SHADERDEFINE_ALBEDO_COLOR);
                }
                value = Math.max(0.0, Math.min(10.0, value));
                this._shaderValues.setNumber(CartoonMaterial.ALBEDOIDENTITY, value);
            }
            get shadowColor() {
                return this._shaderValues.getVector(CartoonMaterial.SHADOWCOLOR);
            }
            set shadowColor(value) {
                this._shaderValues.setVector(CartoonMaterial.SHADOWCOLOR, value);
            }
            get shadowRange() {
                return this._shaderValues.getNumber(CartoonMaterial.SHADOWRANGE);
            }
            set shadowRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.SHADOWRANGE, value);
            }
            get shadowIntensity() {
                return this._shaderValues.getNumber(CartoonMaterial.SHADOWINTENSITY);
            }
            set shadowIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.SHADOWINTENSITY, value);
            }
            get shadowBoundary() {
                return this._shaderValues.getNumber(CartoonMaterial.SHADOWBOUNDARY);
            }
            set shadowBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.SHADOWBOUNDARY, value);
            }
            get specularRange() {
                return this._shaderValues.getNumber(CartoonMaterial.SPECULARRANGE);
            }
            set specularRange(value) {
                value = Math.max(0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.SPECULARRANGE, value);
            }
            set specularIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.SPECULARINTENSITY, value);
            }
            get specularIntensity() {
                return this._shaderValues.getNumber(CartoonMaterial.SPECULARINTENSITY);
            }
            get specularColor() {
                return this._shaderValues.getVector(CartoonMaterial.SPECULARCOLOR);
            }
            set specularColor(value) {
                this._shaderValues.setVector(CartoonMaterial.SPECULARCOLOR, value);
            }
            get outlineWidth() {
                return this._shaderValues.getNumber(CartoonMaterial.OUTLINEWIDTH);
            }
            set outlineWidth(value) {
                value = Math.max(0.0, Math.min(0.05, value));
                this._shaderValues.setNumber(CartoonMaterial.OUTLINEWIDTH, value);
            }
            get outlineColor() {
                return this._shaderValues.getVector(CartoonMaterial.OUTLINECOLOR);
            }
            set outlineColor(value) {
                this._shaderValues.setVector(CartoonMaterial.OUTLINECOLOR, value);
            }
            get outlineLightness() {
                return this._shaderValues.getNumber(CartoonMaterial.OUTLINELIGHTNESS);
            }
            set outlineLightness(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.OUTLINELIGHTNESS, value);
            }
            get secondShadowColor() {
                return this._shaderValues.getVector(CartoonMaterial.SECOND_SHADOWCOLOR);
            }
            set secondShadowColor(value) {
                this._shaderValues.setVector(CartoonMaterial.SECOND_SHADOWCOLOR, value);
            }
            get secondShadowRange() {
                return this._shaderValues.getNumber(CartoonMaterial.SECOND_SHADOWRANGE);
            }
            set secondShadowRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.SECOND_SHADOWRANGE, value);
            }
            get secondShadowIntensity() {
                return this._shaderValues.getNumber(CartoonMaterial.SECOND_SHADOWINTENSITY);
            }
            set secondShadowIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.SECOND_SHADOWINTENSITY, value);
            }
            get secondShadowBoundary() {
                return this._shaderValues.getNumber(CartoonMaterial.SECOND_SHADOWBOUNDARY);
            }
            set secondShadowBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.SECOND_SHADOWBOUNDARY, value);
            }
            get EdgeHightColor() {
                return this._shaderValues.getVector(CartoonMaterial.EDGE_HIGHLIGHT_COLOR);
            }
            set EdgeHightColor(value) {
                this._shaderValues.setVector(CartoonMaterial.EDGE_HIGHLIGHT_COLOR, value);
            }
            get EdgeHightRange() {
                return this._shaderValues.getNumber(CartoonMaterial.EDGE_HIGHLIGHT_RANGE);
            }
            set EdgeHightRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.EDGE_HIGHLIGHT_RANGE, value);
            }
            get EdgeHightIntensity() {
                return this._shaderValues.getNumber(CartoonMaterial.EDGE_HIGHLIGHT_INTENSITY);
            }
            set EdgeHightIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.EDGE_HIGHLIGHT_INTENSITY, value);
            }
            get EdgeHightBoundary() {
                return this._shaderValues.getNumber(CartoonMaterial.EDGE_HIGHLIGHT_BOUNDARY);
            }
            set EdgeHightBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(CartoonMaterial.EDGE_HIGHLIGHT_BOUNDARY, value);
            }
            get tilingOffset() {
                return this._shaderValues.getVector(CartoonMaterial.TILINGOFFSET);
            }
            set tilingOffset(value) {
                if (value) {
                    if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
                        this._defineDatas.add(CartoonMaterial.SHADERDEFINE_TILINGOFFSET);
                    else
                        this._defineDatas.remove(CartoonMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                else {
                    this._defineDatas.remove(CartoonMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                this._shaderValues.setVector(CartoonMaterial.TILINGOFFSET, value);
            }
            get alpha() {
                return this._shaderValues.getNumber(CartoonMaterial.WHOLE_ALPHA);
            }
            set alpha(value) {
                if (value != null) {
                    this._defineDatas.add(CartoonMaterial.SHADERDEFINE_WHOLE_ALPHA);
                }
                else {
                    this._defineDatas.remove(CartoonMaterial.SHADERDEFINE_WHOLE_ALPHA);
                }
                this._shaderValues.setNumber(CartoonMaterial.WHOLE_ALPHA, value);
            }
            get onlyChangeBonePosFlag() {
                return this._shaderValues.getNumber(CartoonMaterial.ONLY_CHANGE_BONE_POS);
            }
            set onlyChangeBonePosFlag(value) {
                if (!!value && value > 0.5) {
                    this._defineDatas.add(CartoonMaterial.SHADERDEFINE_ONLY_CHANGE_BONE_POS);
                }
                else {
                    this._defineDatas.remove(CartoonMaterial.SHADERDEFINE_ONLY_CHANGE_BONE_POS);
                }
                this._shaderValues.setNumber(CartoonMaterial.ONLY_CHANGE_BONE_POS, value);
            }
            get GrayAlbedoTextureFlag() {
                return this._shaderValues.getNumber(CartoonMaterial.GRAYALBEDOTEXTUREFLAG);
            }
            set GrayAlbedoTextureFlag(value) {
                if (!!value && value > 0.5) {
                    this._defineDatas.add(CartoonMaterial.SHADERDEFINE_GRAYALBEDOTEXTUREFLAG);
                }
                else {
                    this._defineDatas.remove(CartoonMaterial.SHADERDEFINE_GRAYALBEDOTEXTUREFLAG);
                }
                this._shaderValues.setNumber(CartoonMaterial.GRAYALBEDOTEXTUREFLAG, value);
            }
            get HSVValue() {
                return this._shaderValues.getVector(CartoonMaterial.HSVVALUE);
            }
            set HSVValue(value) {
                this._shaderValues.setVector(CartoonMaterial.HSVVALUE, value);
            }
            get OffsetXYZ() {
                return this._shaderValues.getVector(CartoonMaterial.OFFSETXYZ);
            }
            set OffsetXYZ(value) {
                this._shaderValues.setVector(CartoonMaterial.OFFSETXYZ, value);
            }
            get cull() {
                return this._shaderValues.getInt(CartoonMaterial.CULL);
            }
            set cull(value) {
                this._shaderValues.setInt(CartoonMaterial.CULL, value);
            }
            get blend() {
                return this._shaderValues.getInt(CartoonMaterial.BLEND);
            }
            set blend(value) {
                this._shaderValues.setInt(CartoonMaterial.BLEND, value);
            }
            get blendSrc() {
                return this._shaderValues.getInt(CartoonMaterial.BLEND_SRC);
            }
            set blendSrc(value) {
                this._shaderValues.setInt(CartoonMaterial.BLEND_SRC, value);
            }
            get blendDst() {
                return this._shaderValues.getInt(CartoonMaterial.BLEND_DST);
            }
            set blendDst(value) {
                this._shaderValues.setInt(CartoonMaterial.BLEND_DST, value);
            }
            get depthTest() {
                return this._shaderValues.getInt(CartoonMaterial.DEPTH_TEST);
            }
            set depthTest(value) {
                this._shaderValues.setInt(CartoonMaterial.DEPTH_TEST, value);
            }
            get depthWrite() {
                return this._shaderValues.getBool(CartoonMaterial.DEPTH_WRITE);
            }
            set depthWrite(value) {
                this._shaderValues.setBool(CartoonMaterial.DEPTH_WRITE, value);
            }
            get materialType() {
                return CustomMaterialType.unlitCartoon;
            }
            get renderMode() {
                return this.__render_mode__;
            }
            set renderMode(value) {
                this.__render_mode__ = value;
                switch (value) {
                    case CartoonMaterial.RENDERMODE_OPAQUE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CartoonMaterial.RENDERMODE_OPAQUE_CULL_NONE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CartoonMaterial.RENDERMODE_CUTOUT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CartoonMaterial.RENDERMODE_CUTOUT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CartoonMaterial.RENDERMODE_TRANSPARENT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CartoonMaterial.RENDERMODE_TRANSPARENT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    default:
                        this.renderQueue = value;
                }
            }
        }
        CartoonMaterial.ALBEDOTEXTURE = Laya.Shader3D.propertyNameToID("u_AlbedoTexture");
        CartoonMaterial.ALBEDOIDENTITY = Laya.Shader3D.propertyNameToID("u_AlbedoIdentity");
        CartoonMaterial.ALBEDOCOLOR = Laya.Shader3D.propertyNameToID("u_AlbedoColor");
        CartoonMaterial.OUTLINEWIDTH = Laya.Shader3D.propertyNameToID("u_OutlineWidth");
        CartoonMaterial.OUTLINELIGHTNESS = Laya.Shader3D.propertyNameToID("u_OutlineLightness");
        CartoonMaterial.OUTLINECOLOR = Laya.Shader3D.propertyNameToID("u_OutlineColor");
        CartoonMaterial.SHADOWCOLOR = Laya.Shader3D.propertyNameToID("u_ShadowColor");
        CartoonMaterial.SHADOWRANGE = Laya.Shader3D.propertyNameToID("u_ShadowRange");
        CartoonMaterial.SHADOWINTENSITY = Laya.Shader3D.propertyNameToID("u_ShadowIntensity");
        CartoonMaterial.SHADOWBOUNDARY = Laya.Shader3D.propertyNameToID("u_ShadowBoundary");
        CartoonMaterial.SECOND_SHADOWCOLOR = Laya.Shader3D.propertyNameToID("u_Second_ShadowColor");
        CartoonMaterial.SECOND_SHADOWRANGE = Laya.Shader3D.propertyNameToID("u_Second_ShadowRange");
        CartoonMaterial.SECOND_SHADOWINTENSITY = Laya.Shader3D.propertyNameToID("u_Second_ShadowIntensity");
        CartoonMaterial.SECOND_SHADOWBOUNDARY = Laya.Shader3D.propertyNameToID("u_Second_ShadowBoundary");
        CartoonMaterial.EDGE_HIGHLIGHT_COLOR = Laya.Shader3D.propertyNameToID("u_Edge_HighlightColor");
        CartoonMaterial.EDGE_HIGHLIGHT_RANGE = Laya.Shader3D.propertyNameToID("u_Edge_HighlightRange");
        CartoonMaterial.EDGE_HIGHLIGHT_INTENSITY = Laya.Shader3D.propertyNameToID("u_Edge_HighlightIntensity");
        CartoonMaterial.EDGE_HIGHLIGHT_BOUNDARY = Laya.Shader3D.propertyNameToID("u_Edge_HighlightBoundary");
        CartoonMaterial.SPECULARRANGE = Laya.Shader3D.propertyNameToID("u_SpecularRange");
        CartoonMaterial.SPECULARINTENSITY = Laya.Shader3D.propertyNameToID("u_SpecularIntensity");
        CartoonMaterial.SPECULARCOLOR = Laya.Shader3D.propertyNameToID("u_SpecularColor");
        CartoonMaterial.DIRECTIONLIGHTDIRECTION = Laya.Shader3D.propertyNameToID("u_SunLight.direction");
        CartoonMaterial.DIRECTIONLIGHTCOLOR = Laya.Shader3D.propertyNameToID("u_SunLight.color");
        CartoonMaterial.SPOT_LIGHT_COLOR = Laya.Shader3D.propertyNameToID("u_SpotLight.color");
        CartoonMaterial.SPOT_LIGHT_DIRECTION = Laya.Shader3D.propertyNameToID("u_SpotLight.direction");
        CartoonMaterial.SPOT_LIGHT_RANGE = Laya.Shader3D.propertyNameToID("u_SpotLight.range");
        CartoonMaterial.SPOT_LIGHT_SPOT = Laya.Shader3D.propertyNameToID("u_SpotLight.spot");
        CartoonMaterial.SPOT_LIGHT_POSITION = Laya.Shader3D.propertyNameToID("u_SpotLight.position");
        CartoonMaterial.WHOLE_ALPHA = Laya.Shader3D.propertyNameToID("u_alpha");
        CartoonMaterial.ONLY_CHANGE_BONE_POS = Laya.Shader3D.propertyNameToID("u_OnlyChangeBonePos");
        CartoonMaterial.HSVVALUE = Laya.Shader3D.propertyNameToID("u_HSVValue");
        CartoonMaterial.OFFSETXYZ = Laya.Shader3D.propertyNameToID("u_OffsetXYZ");
        CartoonMaterial.GRAYALBEDOTEXTUREFLAG = Laya.Shader3D.propertyNameToID("u_GrayAlbedoTextureFlag");
        CartoonMaterial.CULL = Laya.Shader3D.propertyNameToID("s_Cull");
        CartoonMaterial.BLEND = Laya.Shader3D.propertyNameToID("s_Blend");
        CartoonMaterial.BLEND_SRC = Laya.Shader3D.propertyNameToID("s_BlendSrc");
        CartoonMaterial.BLEND_DST = Laya.Shader3D.propertyNameToID("s_BlendDst");
        CartoonMaterial.DEPTH_TEST = Laya.Shader3D.propertyNameToID("s_DepthTest");
        CartoonMaterial.DEPTH_WRITE = Laya.Shader3D.propertyNameToID("s_DepthWrite");
        CartoonMaterial.RENDERMODE_OPAQUE = 1;
        CartoonMaterial.RENDERMODE_OPAQUE_CULL_NONE = 6;
        CartoonMaterial.RENDERMODE_CUTOUT = 2;
        CartoonMaterial.RENDERMODE_CUTOUT_CULL_NONE = 3;
        CartoonMaterial.RENDERMODE_TRANSPARENT = 4;
        CartoonMaterial.RENDERMODE_TRANSPARENT_CULL_NONE = 5;

        class ClothMaterial extends Laya.PBRMaterial {
            constructor() {
                super();
                this.setShaderName("ClothShader");
                this._shaderValues.setVector(ClothMaterial.SHADOWCOLOR, new Laya.Vector4(0.6663285, 0.6544118, 1, 1));
                this._shaderValues.setNumber(ClothMaterial.SHADOWRANGE, 0.002);
                this._shaderValues.setNumber(ClothMaterial.SHADOWINTENSITY, 0.98);
                this._shaderValues.setNumber(ClothMaterial.SHADOWBOUNDARY, 0.015);
                this._shaderValues.setNumber(ClothMaterial.SPECULARRANGE, 0.99);
                this._shaderValues.setNumber(ClothMaterial.SPECULARINTENSITY, 1.0);
                this._shaderValues.setVector(ClothMaterial.SPECULARCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setNumber(ClothMaterial.OUTLINEWIDTH, 0.001);
                this._shaderValues.setNumber(ClothMaterial.OUTLINELIGHTNESS, 0.25);
                this._shaderValues.setVector(ClothMaterial.OUTLINECOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setVector(ClothMaterial.ALBEDOCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setVector(ClothMaterial.SECOND_SHADOWCOLOR, new Laya.Vector4(1, 1, 1, 1));
                this._shaderValues.setNumber(ClothMaterial.SECOND_SHADOWRANGE, 0.00);
                this._shaderValues.setNumber(ClothMaterial.SECOND_SHADOWINTENSITY, 0.98);
                this._shaderValues.setNumber(ClothMaterial.SECOND_SHADOWBOUNDARY, 0.0);
                this._shaderValues.setVector(ClothMaterial.EDGE_HIGHLIGHT_COLOR, new Laya.Vector4(0, 1, 0, 1));
                this._shaderValues.setNumber(ClothMaterial.EDGE_HIGHLIGHT_RANGE, 0.00);
                this._shaderValues.setNumber(ClothMaterial.EDGE_HIGHLIGHT_INTENSITY, 0.98);
                this._shaderValues.setNumber(ClothMaterial.EDGE_HIGHLIGHT_BOUNDARY, 0.0);
                this._shaderValues.setNumber(ClothMaterial.RANDOM_DISCARD_FACTOR, 1.0);
                this._shaderValues.setNumber(ClothMaterial.SPOCCLUSIONSTRENGTH, 0.85);
                this._shaderValues.setNumber(ClothMaterial.SPMETALLIC, 0);
                this._shaderValues.setNumber(ClothMaterial.SPSMOOTHNESS, 0.17);
                this._shaderValues.setNumber(ClothMaterial.SPSHADOWATTEN, 1.0);
                this._shaderValues.setVector(ClothMaterial.SPSIDELIGHTCOLOR, new Laya.Vector4(0.843, 0.921, 0.949, 1.0));
                this._shaderValues.setNumber(ClothMaterial.SPSIDELIGHTSCALE, 0.0);
                this._shaderValues.setVector(ClothMaterial.SPPBRRESULTMAXCOLOR, new Laya.Vector4(1, 1, 1, 1.0));
                this._shaderValues.setNumber(ClothMaterial.NORMALTEXTURESCALE, 1.0);
                this._shaderValues.setNumber(ClothMaterial.GRIDTEXTURESCALE, 1.0);
                this._shaderValues.setNumber(ClothMaterial.SHINETEXTURESCALE, 1.0);
                this._shaderValues.setNumber(ClothMaterial.NORMALTEXTURESCALE, 1.0);
                this._shaderValues.setNumber(ClothMaterial.LIGHTRESULTINTENSITY, 1.0);
                this._shaderValues.setVector(ClothMaterial.CUSTOMDIRECTLIGHTCOLOR, new Laya.Vector4(1, 1, 1, 1));
            }
            static __init__() {
                ClothMaterial.SHADERDEFINE_ALBEDOTEXTURE = Laya.Shader3D.getDefineByName("ALBEDOTEXTURE");
                ClothMaterial.SHADERDEFINE_NORMALTEXTURE = Laya.Shader3D.getDefineByName("NORMALTEXTURE");
                ClothMaterial.SHADERDEFINE_MASKTEXTURE = Laya.Shader3D.getDefineByName("MASKTEXTURE");
                ClothMaterial.SHADERDEFINE_GRIDTEXTURE = Laya.Shader3D.getDefineByName("GRIDTEXTURE");
                ClothMaterial.SHADERDEFINE_SHINETEXTURE = Laya.Shader3D.getDefineByName("SHINETEXTURE");
                ClothMaterial.SHADERDEFINE_CONTROLDETAILTEXTURE = Laya.Shader3D.getDefineByName("CONTROLDETAILTEXTURE");
                ClothMaterial.SHADERDEFINE_TILINGOFFSET = Laya.Shader3D.getDefineByName("TILINGOFFSET");
                ClothMaterial.SHADERDEFINE_BONE = Laya.Shader3D.getDefineByName("BONE");
            }
            static initShader() {
                ClothMaterial.__init__();
                var stateMap = {
                    's_Cull': Laya.Shader3D.RENDER_STATE_CULL,
                    's_Blend': Laya.Shader3D.RENDER_STATE_BLEND,
                    's_BlendSrc': Laya.Shader3D.RENDER_STATE_BLEND_SRC,
                    's_BlendDst': Laya.Shader3D.RENDER_STATE_BLEND_DST,
                    's_DepthTest': Laya.Shader3D.RENDER_STATE_DEPTH_TEST,
                    's_DepthWrite': Laya.Shader3D.RENDER_STATE_DEPTH_WRITE
                };
                var attributeMap = {
                    'a_Position': Laya.VertexMesh.MESH_POSITION0,
                    'a_Normal': Laya.VertexMesh.MESH_NORMAL0,
                    'a_Tangent0': Laya.VertexMesh.MESH_TANGENT0,
                    'a_Texcoord0': Laya.VertexMesh.MESH_TEXTURECOORDINATE0,
                    'a_Texcoord1': Laya.VertexMesh.MESH_TEXTURECOORDINATE1,
                    'a_BoneWeights': Laya.VertexMesh.MESH_BLENDWEIGHT0,
                    'a_BoneIndices': Laya.VertexMesh.MESH_BLENDINDICES0,
                    'a_MvpMatrix': Laya.VertexMesh.MESH_MVPMATRIX_ROW0,
                    'a_WorldMat': Laya.VertexMesh.MESH_WORLDMATRIX_ROW0
                };
                var uniformMap = {
                    'u_Bones': Laya.Shader3D.PERIOD_CUSTOM,
                    'u_MvpMatrix': Laya.Shader3D.PERIOD_SPRITE,
                    'u_WorldMat': Laya.Shader3D.PERIOD_SPRITE,
                    'u_LightmapScaleOffset': Laya.Shader3D.PERIOD_SPRITE,
                    'u_LightMap': Laya.Shader3D.PERIOD_SPRITE,
                    'u_LightMapDirection': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorTexture': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorParams': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorTextureSize': Laya.Shader3D.PERIOD_SPRITE,
                    'u_CameraPos': Laya.Shader3D.PERIOD_CAMERA,
                    'u_ViewProjection': Laya.Shader3D.PERIOD_CAMERA,
                    'u_AlphaTestValue': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_EmissionColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_NormalTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ParallaxTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_OcclusionTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_EmissionTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Smoothness': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SmoothnessScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPOcclusionStrength': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPMetallic': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPSmoothness': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPShadowAtten': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPSideLightColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPSideLightScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPPBRResultMaxColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_NormalScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ParallaxScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_MaskTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_gridTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_shineTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_gridTextureScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_shineTextureScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_controlDetailTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_CustomDirectLightColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightResultIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_specularIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ReflectTexture': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectIntensity': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientColor': Laya.Shader3D.PERIOD_SCENE,
                    'u_FogStart': Laya.Shader3D.PERIOD_SCENE,
                    'u_FogRange': Laya.Shader3D.PERIOD_SCENE,
                    'u_FogColor': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirationLightCount': Laya.Shader3D.PERIOD_SCENE,
                    'u_LightBuffer': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowBias': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowLightDirection': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowMap': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowParams': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowSplitSpheres': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowMatrices': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowMapSize': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotShadowMap': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotViewProjectMatrix': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowLightPosition': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAr': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAg': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAb': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBr': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBg': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBb': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHC': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectionProbe': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectCubeHDRParams': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirectionLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirectionLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.color': Laya.Shader3D.PERIOD_SCENE,
                };
                var PBRShadowCasterPS$1 = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
                var PBRShadowCasterVS$1 = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS =  shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
                var vs1 = `
        #include "Lighting.glsl";
        #include "Shadow.glsl";

        attribute vec4 a_Position;

        #ifdef GPU_INSTANCE
            attribute mat4 a_MvpMatrix;
            attribute mat4 a_WorldMat;
        #else
            uniform mat4 u_MvpMatrix;
            uniform mat4 u_WorldMat;
        #endif

        #ifdef BONE
            const int c_MaxBoneCount = 24;
            attribute vec4 a_BoneIndices;
            attribute vec4 a_BoneWeights;
            uniform mat4 u_Bones[c_MaxBoneCount];
        #endif

        attribute vec3 a_Normal;
        varying vec3 v_Normal; 

        #if defined(NORMALTEXTURE)||defined(PARALLAXTEXTURE)
            attribute vec4 a_Tangent0;
            varying vec3 v_Tangent;
            varying vec3 v_Binormal;
            #endif

        #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)||(defined(LIGHTMAP)&&defined(UV))
            attribute vec2 a_Texcoord0;
            varying vec2 v_Texcoord0;
        #endif

        uniform vec3 u_CameraPos;
        varying vec3 v_EyeVec;
        varying vec3 v_PositionWorld;
        varying float v_posViewZ;

        #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
            varying vec4 v_ShadowCoord;
        #endif

        #ifdef TILINGOFFSET
            uniform vec4 u_TilingOffset;
        #endif

        void vertexForward()
        {
            vec4 position;
            #ifdef BONE
                mat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;
                skinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;
                skinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;
                skinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;
                position=skinTransform*a_Position;
            #else
                position=a_Position;
            #endif

            #ifdef GPU_INSTANCE
                gl_Position = a_MvpMatrix * position;
            #else
                gl_Position = u_MvpMatrix * position;
            #endif

            mat4 worldMat;
            #ifdef GPU_INSTANCE
                worldMat = a_WorldMat;
            #else
                worldMat = u_WorldMat;
            #endif

            v_PositionWorld=(worldMat*position).xyz;

            v_Texcoord0=a_Texcoord0;

            v_EyeVec =u_CameraPos-v_PositionWorld;//will normalize per-pixel

            mat3 worldInvMat;
            #ifdef BONE
                worldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));
            #else
                worldInvMat=INVERSE_MAT(mat3(worldMat));
            #endif

            v_Normal=normalize(a_Normal*worldInvMat);//if no normalize will cause precision problem.

            #ifdef NORMALTEXTURE
                v_Tangent=normalize(a_Tangent0.xyz*worldInvMat);
                v_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;
            #endif

            #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
                v_ShadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
            #endif

        }
        
        void main()
        {
            vertexForward();
            gl_Position=remapGLPositionZ(gl_Position);
        }`;
                var ps1 = `
        #ifdef GL_FRAGMENT_PRECISION_HIGH
            precision highp float;
            precision highp int;
        #else
            precision mediump float;
            precision mediump int;
        #endif
        
        #include "Lighting.glsl";
        #include "Shadow.glsl";
        #include "LayaPBRBRDF.glsl";
        #include "GlobalIllumination.glsl";

        #ifdef ALPHATEST
            uniform float u_AlphaTestValue;
        #endif

        uniform vec4 u_AlbedoColor;

        #ifdef NORMALTEXTURE
            uniform sampler2D u_NormalTexture;
            uniform float u_NormalScale;
        #endif

        #ifdef ALBEDOTEXTURE
            uniform sampler2D u_AlbedoTexture;
            vec4 albedoTextureColor;
        #endif

        #ifdef MASKTEXTURE
            uniform sampler2D u_MaskTexture;
            vec4 maskTextureColor;
        #endif
        #ifdef GRIDTEXTURE
            uniform sampler2D u_gridTexture;
            uniform float u_gridTextureScale;
        #endif
        #ifdef SHINETEXTURE
            uniform sampler2D u_shineTexture;
            uniform float u_shineTextureScale;
        #endif

        vec4 controlDetailColor;
        #ifdef CONTROLDETAILTEXTURE
            uniform sampler2D u_controlDetailTexture;
            
        #endif
        uniform vec3 u_SpecularColor;

        uniform float u_Smoothness;
        uniform float u_SmoothnessScale;

        #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)
            varying vec2 v_Texcoord0;
        #endif

        varying vec3 v_Normal; 

    //    #if defined(DIRECTIONLIGHT)

    //         #if defined(LEGACYSINGLELIGHTING)
                uniform DirectionLight u_SunLight;
            // #else
                uniform int u_DirationLightCount;
                uniform sampler2D u_LightBuffer;
        //     #endif
                
        // #endif

        varying vec3 v_EyeVec;

        #ifdef NORMALTEXTURE
            varying vec3 v_Tangent;
            varying vec3 v_Binormal;
        #endif

        #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
            varying vec4 v_ShadowCoord;

        #endif


        uniform float u_SPOcclusionStrength;
        uniform float u_SPMetallic;
        uniform float u_SPSmoothness;
        uniform float u_SPShadowAtten;
        uniform vec4 u_SPSideLightColor;
        uniform float u_SPSideLightScale;
        uniform vec4 u_SPPBRResultMaxColor;

        vec3 albedoRgb;
uniform vec4 u_CustomDirectLightColor;
uniform float u_LightResultIntensity;
        uniform float u_specularIntensity;

        mediump float lerpOneTo(mediump float b, mediump float t)
        {
            mediump float oneMinusT = 1.0 - t;
            return oneMinusT + b * t;
        }

        mediump float getAlpha(vec2 uv)
        {
                #ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA
                return u_AlbedoColor.a;
            #else
                #ifdef ALBEDOTEXTURE
                    return albedoTextureColor.a * u_AlbedoColor.a;
                #else
                    return u_AlbedoColor.a;
                #endif
            #endif
        }

        mediump float getOcclusion(vec2 uv)
        {
            #ifdef MASKTEXTURE
                mediump float occ = maskTextureColor.b;//texture2D(u_MaskTexture, uv).b;
                return lerpOneTo(occ, u_SPOcclusionStrength);
            #else
                return u_SPOcclusionStrength;
            #endif 
        }

        mediump vec3 albedo(vec2 uv)
        {
            #ifdef ALBEDOTEXTURE
                return u_AlbedoColor.rgb * albedoTextureColor.rgb;
            #else
                return u_AlbedoColor.rgb;
            #endif
           
        }
        float random(float x, float y){
			return fract(cos(x * (12.9898) + y * (4.1414)) * 43758.5453);
		}
        mediump vec2 getMetallicGloss(vec2 uv)
        {
            mediump vec2 ms;//x is metallic,y is smoothness
            //lhcadd
            
            #ifdef MASKTEXTURE
                //vec4 maskRgb = texture2D(u_MaskTexture, uv);
                ms.y =maskTextureColor.r*u_SPSmoothness;

                ms.x =maskTextureColor.g*(u_SPMetallic + controlDetailColor.r);;//ms.x =maskTextureColor.g*u_SPMetallic;
            #else 
                ms.y = u_SPSmoothness;

                ms.x =u_SPMetallic + controlDetailColor.r;//0.7639677;//0.7639677/2.0;
            #endif

            return ms;
        }

        #ifdef NORMALTEXTURE
            mediump vec3 unpackScaleNormal(mediump vec3 packednormal, mediump float bumpScale)
            {
                mediump vec3 normal = packednormal.xyz * 2.0 - 1.0;
                normal.y=-normal.y;//NOTE:because unity to LayaAir coordSystem.
                normal.xy *= bumpScale;
                return normal;
            }
            
            vec4 lerpVec4(vec4 a, vec4 b, float w) {
                if(w<=0.0){
                    return a;
                }else if(w>=1.0){
                    return b;
                }else{
                    return w*b +(1.0-w)*a;
                }
            }
            vec3 lerpVec3(vec3 a, vec3 b, float w) {
                if(w<=0.0){
                    return a;
                }else if(w>=1.0){
                    return b;
                }else{
                    return w*b +(1.0-w)*a;
                }
            }

            mediump vec3 normalInTangentSpace(vec2 texcoords)
            {
                mediump vec3 normalTangent = unpackScaleNormal(texture2D(u_NormalTexture, texcoords).rgb,u_NormalScale);
                
                return normalTangent;
            }
        #endif

        struct FragmentCommonData{
            vec3 diffColor;
            vec3 specColor;
            float oneMinusReflectivity;
            float smoothness;
        };
        
        #ifndef SETUP_BRDF_INPUT
        #define SETUP_BRDF_INPUT metallicSetup//default is metallicSetup,also can be other.    specularSetup / metallicSetup
        #endif
        
        const mediump vec4 dielectricSpecularColor = vec4(0.220916301, 0.220916301, 0.220916301, 1.0 - 0.220916301);
        
        mediump vec3 diffuseAndSpecularFromMetallic(mediump vec3 albedo,mediump float metallic, out mediump vec3 specColor, out mediump float oneMinusReflectivity)
        {
                specColor = mix(dielectricSpecularColor.rgb, albedo, metallic);
            oneMinusReflectivity= dielectricSpecularColor.a*(1.0-metallic);//diffuse proportion
            return albedo * oneMinusReflectivity;
        }
        
        mediump float specularStrength(mediump vec3 specular)
        {
            return max (max (specular.r, specular.g), specular.b);
        }
        
        // Diffuse/Spec Energy conservation
        mediump vec3 energyConservationBetweenDiffuseAndSpecular (mediump vec3 albedo, mediump vec3 specColor, out mediump float oneMinusReflectivity)
        {
                oneMinusReflectivity = 1.0 - specularStrength(specColor);
            return albedo * (vec3(1.0) - specColor);
        }
        
        #ifdef TRANSPARENTBLEND
            mediump vec3 preMultiplyAlpha (mediump vec3 diffColor, mediump float alpha, mediump float oneMinusReflectivity,out mediump float modifiedAlpha)
            {
                // Transparency 'removes' from Diffuse component
                diffColor *= alpha;
                // Reflectivity 'removes' from the rest of components, including Transparency
                // modifiedAlpha = 1.0-(1.0-alpha)*(1.0-reflectivity) = 1.0-(oneMinusReflectivity - alpha*oneMinusReflectivity) = 1.0-oneMinusReflectivity + alpha*oneMinusReflectivity
                modifiedAlpha = 1.0 - oneMinusReflectivity + alpha*oneMinusReflectivity;
                return diffColor;
            }
        #endif
        
        FragmentCommonData metallicSetup(vec2 uv)
        {
            mediump vec2 metallicGloss = getMetallicGloss(uv);
            mediump float metallic = metallicGloss.x;
            mediump float smoothness = metallicGloss.y; // this is 1 minus the square root of real roughness m.
            mediump float oneMinusReflectivity;
            mediump vec3 specColor;
            mediump vec3 diffColor = diffuseAndSpecularFromMetallic(albedoRgb, metallic,/*out*/specColor,/*out*/oneMinusReflectivity);
        
            FragmentCommonData o;
            o.diffColor = diffColor;
            o.specColor = specColor;
            o.oneMinusReflectivity = oneMinusReflectivity;
            o.smoothness = smoothness;
            return o;
        }
        
        
        LayaGI fragmentGI(float smoothness,vec3 eyeVec,mediump float occlusion,mediump vec2 lightmapUV,vec3 worldnormal)
        {
            LayaGIInput giInput;
        
            vec3 worldViewDir = -eyeVec;
            mediump vec4 uvwRoughness;
            uvwRoughness.rgb = reflect(worldViewDir, worldnormal);//reflectUVW
            uvwRoughness.a= smoothnessToPerceptualRoughness(smoothness);//perceptualRoughness
        
            return layaGlobalIllumination(giInput,occlusion, worldnormal, uvwRoughness);
        }
        

        vec3 perPixelWorldNormalByNormalTanget(vec2 uv,vec3 normal,vec3 binormal,vec3 tangent,vec3 normalTangent)
        {
            #ifdef NORMALTEXTURE
                vec3 normalWorld = normalize(tangent * normalTangent.x + binormal * normalTangent.y + normal * normalTangent.z);
                
            #else
                vec3 normalWorld = normalize(normal);
            #endif
                return normalWorld;
        }
        
        void fragmentForward()
        {
            vec2 uv;
            #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)
                    uv = v_Texcoord0;
            #endif

            #ifdef ALBEDOTEXTURE
                albedoTextureColor = texture2D(u_AlbedoTexture,uv);
            #endif
            
            mediump float alpha = getAlpha(uv);
            #ifdef ALPHATEST
                if(alpha<u_AlphaTestValue)
                    discard;
            #endif

            albedoRgb = albedo(uv);

            #ifdef MASKTEXTURE
                maskTextureColor = texture2D(u_MaskTexture,uv);
            #endif
            
            
            
            vec3 binormal;
            vec3 tangent;
            vec3 normal = v_Normal;
            vec3 normalTangent;

            #ifdef NORMALTEXTURE
                tangent = v_Tangent;
                binormal = v_Binormal;
           
                normalTangent=normalInTangentSpace(uv);
            #else
                normalTangent = normalize(normal);
            #endif

            vec3 normalWorld = perPixelWorldNormalByNormalTanget(uv,normal,binormal,tangent,normalTangent);//In FS if the normal use mediump before normalize will cause precision prolem in mobile device.
            vec3 eyeVec = normalize(v_EyeVec);
            

            vec3 lightDir = normalize(u_SunLight.direction);// vec3(-0.3090169948284817,0.0,0.9510565161477913);

            #ifdef CONTROLDETAILTEXTURE
            
                controlDetailColor =texture2D(u_controlDetailTexture, uv);

                #ifdef GRIDTEXTURE
                    vec2 tmpTillingOffset1 = (vec2(u_gridTextureScale , u_gridTextureScale));
                    vec2 tmpCoord1 = uv / tmpTillingOffset1;
                    vec4 gridColor =texture2D(u_gridTexture, tmpCoord1);
                    gridColor = gridColor * controlDetailColor.r;

                    albedoRgb.rgb = albedoRgb.rgb * (1.0 - gridColor.a) + gridColor.rgb;
                    alpha = alpha * (1.0 - gridColor.a) + gridColor.a * gridColor.a;

                #endif

                #ifdef SHINETEXTURE
                    vec2 tmpTillingOffset2 = (vec2(u_shineTextureScale , u_shineTextureScale));
                    vec2 tmpCoord2 = uv / tmpTillingOffset2;
                    vec4 shineColor =texture2D(u_shineTexture, tmpCoord2);
                    

                    // 阴影计算部分计算
                    // 1.0 -> 0.0
                    float nl = max(dot(normal, -lightDir), 0.0);
                    float shadow_boundary = 0.2 + 0.01;
                    float shadow_allin = step(nl, 0.3 - shadow_boundary*0.5);
                    float shadow_partin = step(nl, 0.3 + shadow_boundary*0.5);
                    float shadow = shadow_allin + (0.3 + shadow_boundary*0.5 - nl)/shadow_boundary * (shadow_partin - shadow_allin);

                    shadow *= 0.1;
                    // vec3 albedoAreaColor = (1.0 - shadow) * shineColor.rgb;
                    // vec3 shadowAreaColor = shadow * shineColor.rgb * vec3(0.3,0.3,0.3).rgb;
                    
                    //高光部分计算
                    float specular = pow(nl,10.0);
                    vec3 speculAreaColor = (1.0 - shadow) * shineColor.rgb * 1.0 * specular * vec4(1.0,1.0,1.0,1.0).rgb ;


                    shineColor.rgb +=speculAreaColor;

                    shineColor = shineColor * controlDetailColor.r;


                    albedoRgb.rgb = albedoRgb.rgb * (1.0 - shineColor.a) + shineColor.rgb;
                    alpha = alpha * (1.0 - shineColor.a) + shineColor.a * shineColor.a;
                    
                #endif

            #endif


            FragmentCommonData o = SETUP_BRDF_INPUT(uv);
            
            #ifdef TRANSPARENTBLEND
                o.diffColor=preMultiplyAlpha(o.diffColor,alpha,o.oneMinusReflectivity,/*out*/alpha);// shader relies on pre-multiply alpha-blend (srcBlend = One, dstBlend = OneMinusSrcAlpha)
            #endif

            mediump float occlusion = getOcclusion(uv);
            mediump vec2 lightMapUV;
           
            float perceptualRoughness = smoothnessToPerceptualRoughness(o.smoothness);
            float roughness = perceptualRoughnessToRoughness(perceptualRoughness);
            float nv = abs(dot(normalWorld, eyeVec));
            LayaGI gi =fragmentGI(o.smoothness,eyeVec,occlusion,lightMapUV,normalWorld);
            vec4 color = LAYA_BRDF_GI(o.diffColor,o.specColor,o.oneMinusReflectivity,o.smoothness,perceptualRoughness,roughness,nv,normalWorld,eyeVec,gi);
            
            vec3 lightColor=vec3(0.0, 0.0, 0.0);

            o.specColor*=u_specularIntensity;

            vec4 lightResultColor = vec4(0.0,0.0,0.0,0.0);

            #ifdef DIRECTIONLIGHT
                #if defined(LEGACYSINGLELIGHTING)
                    #ifdef CALCULATE_SHADOWS
                    
                            #ifdef SHADOW_CASCADE
                                vec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
                            #else
                                vec4 shadowCoord = v_ShadowCoord;
                            #endif
                            sampleShadowmap(shadowCoord);
                        
                    #endif
                    DirectionLight directionLight;
                    directionLight.color=u_SunLight.color;
                    directionLight.direction = u_SunLight.direction;

                    LayaLight dirLight = layaDirectionLightToLight(directionLight,1.0);
                    lightResultColor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);

                    // dirLightFirst =  u_SunLight.direction;
                    // dirLightSecond =  vec3(-0.3090169948284817,0.0,0.9510565161477913);
                #else
                    for (int i = 0; i < MAX_LIGHT_COUNT; i++) 
                    {
                        float shadowAttenuation = u_SPShadowAtten;
                        if(i >= u_DirationLightCount)
                            break;
                        // #ifdef CALCULATE_SHADOWS
                        //     if(i == 0)
                        //     {
                        //         #ifdef SHADOW_CASCADE
                        //             vec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
                        //         #else
                        //             vec4 shadowCoord = v_ShadowCoord;
                        //         #endif
                        //         shadowAttenuation *= sampleShadowmap(shadowCoord);
                        //     }
                        // #endif
                        DirectionLight directionLight = getDirectionLight(u_LightBuffer,i);
                        LayaLight dirLight = layaDirectionLightToLight(directionLight,shadowAttenuation);
                        // if(i==0){
                        //     dirLight.color = u_CustomDirectLightColor.rgb;
                        // }
                        
                        
                        lightResultColor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);
                        // dirLight.dir = -dirLight.dir;
                        // lightResultColor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);

                    }
                #endif
            #endif
            
            color += vec4( max(lightResultColor.r,albedoRgb.r*u_LightResultIntensity),max(lightResultColor.g,albedoRgb.g*u_LightResultIntensity),max(lightResultColor.b,albedoRgb.b*u_LightResultIntensity),lightResultColor.a );
            
            
            gl_FragColor=vec4(color.rgb,alpha);
        }

        void main()
        {
            fragmentForward();
        }`;
                var shader3D = Laya.Shader3D.add("ClothShader", attributeMap, uniformMap, true);
                var subShader = new Laya.SubShader(attributeMap, uniformMap);
                shader3D.addSubShader(subShader);
                subShader.addShaderPass(vs1, ps1, stateMap, "Forward");
                if (Const.bHighShadowQuality) {
                    subShader.addShaderPass(PBRShadowCasterVS$1, PBRShadowCasterPS$1, stateMap, "ShadowCaster");
                }
            }
            get normalTextureScale() {
                return this._shaderValues.getNumber(ClothMaterial.NORMALTEXTURESCALE);
            }
            set normalTextureScale(value) {
                value = this.clampKeyValueByKey(ClothMaterial.NORMALTEXTURESCALE, value);
                this._shaderValues.setNumber(ClothMaterial.NORMALTEXTURESCALE, value);
            }
            get maskTexture() {
                return this._shaderValues.getTexture(ClothMaterial.MASKTEXTURE);
            }
            set maskTexture(value) {
                if (value)
                    this._defineDatas.add(ClothMaterial.SHADERDEFINE_MASKTEXTURE);
                else
                    this._defineDatas.remove(ClothMaterial.SHADERDEFINE_MASKTEXTURE);
                this._shaderValues.setTexture(ClothMaterial.MASKTEXTURE, value);
            }
            get gridTexture() {
                return this._shaderValues.getTexture(ClothMaterial.GRIDTEXTURE);
            }
            set gridTexture(value) {
                if (value)
                    this._defineDatas.add(ClothMaterial.SHADERDEFINE_GRIDTEXTURE);
                else
                    this._defineDatas.remove(ClothMaterial.SHADERDEFINE_GRIDTEXTURE);
                this._shaderValues.setTexture(ClothMaterial.GRIDTEXTURE, value);
            }
            get shineTexture() {
                return this._shaderValues.getTexture(ClothMaterial.SHINETEXTURE);
            }
            set shineTexture(value) {
                if (value)
                    this._defineDatas.add(ClothMaterial.SHADERDEFINE_SHINETEXTURE);
                else
                    this._defineDatas.remove(ClothMaterial.SHADERDEFINE_SHINETEXTURE);
                this._shaderValues.setTexture(ClothMaterial.SHINETEXTURE, value);
            }
            get gridTextureScale() {
                return this._shaderValues.getNumber(ClothMaterial.GRIDTEXTURESCALE);
            }
            set gridTextureScale(value) {
                value = this.clampKeyValueByKey(ClothMaterial.GRIDTEXTURESCALE, value);
                this._shaderValues.setNumber(ClothMaterial.GRIDTEXTURESCALE, value);
            }
            get shineTextureScale() {
                return this._shaderValues.getNumber(ClothMaterial.SHINETEXTURESCALE);
            }
            set shineTextureScale(value) {
                value = this.clampKeyValueByKey(ClothMaterial.SHINETEXTURESCALE, value);
                this._shaderValues.setNumber(ClothMaterial.SHINETEXTURESCALE, value);
            }
            get controlDetailTexture() {
                return this._shaderValues.getTexture(ClothMaterial.CONTROLDETAILTEXTURE);
            }
            set controlDetailTexture(value) {
                if (value)
                    this._defineDatas.add(ClothMaterial.SHADERDEFINE_CONTROLDETAILTEXTURE);
                else
                    this._defineDatas.remove(ClothMaterial.SHADERDEFINE_CONTROLDETAILTEXTURE);
                this._shaderValues.setTexture(ClothMaterial.CONTROLDETAILTEXTURE, value);
            }
            get shadowColor() {
                return this._shaderValues.getVector(ClothMaterial.SHADOWCOLOR);
            }
            set shadowColor(value) {
                this._shaderValues.setVector(ClothMaterial.SHADOWCOLOR, value);
            }
            get shadowRange() {
                return this._shaderValues.getNumber(ClothMaterial.SHADOWRANGE);
            }
            set shadowRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.SHADOWRANGE, value);
            }
            get shadowIntensity() {
                return this._shaderValues.getNumber(ClothMaterial.SHADOWINTENSITY);
            }
            set shadowIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.SHADOWINTENSITY, value);
            }
            get shadowBoundary() {
                return this._shaderValues.getNumber(ClothMaterial.SHADOWBOUNDARY);
            }
            set shadowBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.SHADOWBOUNDARY, value);
            }
            get specularRange() {
                return this._shaderValues.getNumber(ClothMaterial.SPECULARRANGE);
            }
            set specularRange(value) {
                value = Math.max(0.9, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.SPECULARRANGE, value);
            }
            set specularIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.SPECULARINTENSITY, value);
            }
            get specularIntensity() {
                return this._shaderValues.getNumber(ClothMaterial.SPECULARINTENSITY);
            }
            get specularColor() {
                return this._shaderValues.getVector(ClothMaterial.SPECULARCOLOR);
            }
            set specularColor(value) {
                this._shaderValues.setVector(ClothMaterial.SPECULARCOLOR, value);
            }
            get outlineWidth() {
                return this._shaderValues.getNumber(ClothMaterial.OUTLINEWIDTH);
            }
            set outlineWidth(value) {
                value = Math.max(0.0, Math.min(0.05, value));
                this._shaderValues.setNumber(ClothMaterial.OUTLINEWIDTH, value);
            }
            get outlineColor() {
                return this._shaderValues.getVector(ClothMaterial.OUTLINECOLOR);
            }
            set outlineColor(value) {
                this._shaderValues.setVector(ClothMaterial.OUTLINECOLOR, value);
            }
            get outlineLightness() {
                return this._shaderValues.getNumber(ClothMaterial.OUTLINELIGHTNESS);
            }
            set outlineLightness(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.OUTLINELIGHTNESS, value);
            }
            get secondShadowColor() {
                return this._shaderValues.getVector(ClothMaterial.SECOND_SHADOWCOLOR);
            }
            set secondShadowColor(value) {
                this._shaderValues.setVector(ClothMaterial.SECOND_SHADOWCOLOR, value);
            }
            get secondShadowRange() {
                return this._shaderValues.getNumber(ClothMaterial.SECOND_SHADOWRANGE);
            }
            set secondShadowRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.SECOND_SHADOWRANGE, value);
            }
            get secondShadowIntensity() {
                return this._shaderValues.getNumber(ClothMaterial.SECOND_SHADOWINTENSITY);
            }
            set secondShadowIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.SECOND_SHADOWINTENSITY, value);
            }
            get secondShadowBoundary() {
                return this._shaderValues.getNumber(ClothMaterial.SECOND_SHADOWBOUNDARY);
            }
            set secondShadowBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.SECOND_SHADOWBOUNDARY, value);
            }
            get EdgeHightColor() {
                return this._shaderValues.getVector(ClothMaterial.EDGE_HIGHLIGHT_COLOR);
            }
            set EdgeHightColor(value) {
                this._shaderValues.setVector(ClothMaterial.EDGE_HIGHLIGHT_COLOR, value);
            }
            get EdgeHightRange() {
                return this._shaderValues.getNumber(ClothMaterial.EDGE_HIGHLIGHT_RANGE);
            }
            set EdgeHightRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.EDGE_HIGHLIGHT_RANGE, value);
            }
            get EdgeHightIntensity() {
                return this._shaderValues.getNumber(ClothMaterial.EDGE_HIGHLIGHT_INTENSITY);
            }
            set EdgeHightIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.EDGE_HIGHLIGHT_INTENSITY, value);
            }
            get EdgeHightBoundary() {
                return this._shaderValues.getNumber(ClothMaterial.EDGE_HIGHLIGHT_BOUNDARY);
            }
            set EdgeHightBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(ClothMaterial.EDGE_HIGHLIGHT_BOUNDARY, value);
            }
            get SPOcclusionStrength() {
                return this._shaderValues.getNumber(ClothMaterial.SPOCCLUSIONSTRENGTH);
            }
            set SPOcclusionStrength(value) {
                value = this.clampKeyValueByKey(ClothMaterial.SPOCCLUSIONSTRENGTH, value);
                this._shaderValues.setNumber(ClothMaterial.SPOCCLUSIONSTRENGTH, value);
            }
            get SPMetallic() {
                return this._shaderValues.getNumber(ClothMaterial.SPMETALLIC);
            }
            set SPMetallic(value) {
                value = this.clampKeyValueByKey(ClothMaterial.SPMETALLIC, value);
                this._shaderValues.setNumber(ClothMaterial.SPMETALLIC, value);
            }
            get SPSmoothness() {
                return this._shaderValues.getNumber(ClothMaterial.SPSMOOTHNESS);
            }
            set SPSmoothness(value) {
                value = this.clampKeyValueByKey(ClothMaterial.SPSMOOTHNESS, value);
                this._shaderValues.setNumber(ClothMaterial.SPSMOOTHNESS, value);
            }
            get SPShadowAtten() {
                return this._shaderValues.getNumber(ClothMaterial.SPSHADOWATTEN);
            }
            set SPShadowAtten(value) {
                value = this.clampKeyValueByKey(ClothMaterial.SPSHADOWATTEN, value);
                this._shaderValues.setNumber(ClothMaterial.SPSHADOWATTEN, value);
            }
            get SPSideLightColor() {
                return this._shaderValues.getVector(ClothMaterial.SPSIDELIGHTCOLOR);
            }
            set SPSideLightColor(value) {
                this._shaderValues.setVector(ClothMaterial.SPSIDELIGHTCOLOR, value);
            }
            get SPSideLightScale() {
                return this._shaderValues.getNumber(ClothMaterial.SPSIDELIGHTSCALE);
            }
            set SPSideLightScale(value) {
                value = this.clampKeyValueByKey(ClothMaterial.SPSIDELIGHTSCALE, value);
                this._shaderValues.setNumber(ClothMaterial.SPSIDELIGHTSCALE, value);
            }
            get SPPBRResultMaxColor() {
                return this._shaderValues.getVector(ClothMaterial.SPPBRRESULTMAXCOLOR);
            }
            set SPPBRResultMaxColor(value) {
                this._shaderValues.setVector(ClothMaterial.SPPBRRESULTMAXCOLOR, value);
            }
            get CustomDirectLightColor() {
                return this._shaderValues.getVector(ClothMaterial.CUSTOMDIRECTLIGHTCOLOR);
            }
            set CustomDirectLightColor(value) {
                this._shaderValues.setVector(ClothMaterial.CUSTOMDIRECTLIGHTCOLOR, value);
            }
            get LightResultIntensity() {
                return this._shaderValues.getNumber(ClothMaterial.LIGHTRESULTINTENSITY);
            }
            set LightResultIntensity(value) {
                value = this.clampKeyValueByKey(ClothMaterial.LIGHTRESULTINTENSITY, value);
                this._shaderValues.setNumber(ClothMaterial.LIGHTRESULTINTENSITY, value);
            }
            getShaderValueRangeWithKey(key) {
                switch (key) {
                    case ClothMaterial.SPOCCLUSIONSTRENGTH:
                        return [0.0, 2.0];
                        break;
                    case ClothMaterial.SPMETALLIC:
                        return [0.0, 2.0];
                        break;
                    case ClothMaterial.SPSMOOTHNESS:
                        return [0.0, 2.0];
                        break;
                    case ClothMaterial.SPSHADOWATTEN:
                        return [0.0, 2.0];
                        break;
                    case ClothMaterial.SPSIDELIGHTSCALE:
                        return [0.0, 1.0];
                        break;
                    case ClothMaterial.NORMALTEXTURESCALE:
                        return [0.0, 2.0];
                        break;
                    case ClothMaterial.GRIDTEXTURESCALE:
                        return [0.0, 10.0];
                        break;
                    case ClothMaterial.SHINETEXTURESCALE:
                        return [0.0, 10.0];
                        break;
                    case ClothMaterial.SPECULARINTENSITY:
                        return [0.0, 2.0];
                        break;
                    default:
                        break;
                }
                return [0.0, 1.0];
            }
            clampKeyValueByKey(key, value) {
                return Math.max(this.getShaderValueRangeWithKey(key)[0], Math.min(this.getShaderValueRangeWithKey(key)[1], value));
            }
            get tilingOffset() {
                return this._shaderValues.getVector(ClothMaterial.TILINGOFFSET);
            }
            set tilingOffset(value) {
                if (value) {
                    if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
                        this._defineDatas.add(ClothMaterial.SHADERDEFINE_TILINGOFFSET);
                    else
                        this._defineDatas.remove(ClothMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                else {
                    this._defineDatas.remove(ClothMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                this._shaderValues.setVector(ClothMaterial.TILINGOFFSET, value);
            }
            get cull() {
                return this._shaderValues.getInt(ClothMaterial.CULL);
            }
            set cull(value) {
                this._shaderValues.setInt(ClothMaterial.CULL, value);
            }
            get blend() {
                return this._shaderValues.getInt(ClothMaterial.BLEND);
            }
            set blend(value) {
                this._shaderValues.setInt(ClothMaterial.BLEND, value);
            }
            get blendSrc() {
                return this._shaderValues.getInt(ClothMaterial.BLEND_SRC);
            }
            set blendSrc(value) {
                this._shaderValues.setInt(ClothMaterial.BLEND_SRC, value);
            }
            get blendDst() {
                return this._shaderValues.getInt(ClothMaterial.BLEND_DST);
            }
            set blendDst(value) {
                this._shaderValues.setInt(ClothMaterial.BLEND_DST, value);
            }
            get depthTest() {
                return this._shaderValues.getInt(ClothMaterial.DEPTH_TEST);
            }
            set depthTest(value) {
                this._shaderValues.setInt(ClothMaterial.DEPTH_TEST, value);
            }
            get depthWrite() {
                return this._shaderValues.getBool(ClothMaterial.DEPTH_WRITE);
            }
            set depthWrite(value) {
                this._shaderValues.setBool(ClothMaterial.DEPTH_WRITE, value);
            }
            get randomDiscardFactor() {
                return this._shaderValues.getNumber(ClothMaterial.RANDOM_DISCARD_FACTOR);
            }
            set randomDiscardFactor(value) {
                this._shaderValues.setNumber(ClothMaterial.RANDOM_DISCARD_FACTOR, value);
            }
            get materialType() {
                return CustomMaterialType.pbrCloth;
            }
            get renderMode() {
                return this.__render_mode__;
            }
            set renderMode(value) {
                this.__render_mode__ = value;
                switch (value) {
                    case CustomMaterialRenderMode.unknown:
                    case CustomMaterialRenderMode.RENDERMODE_OPAQUE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_CUTOUT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_TRANSPARENT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    default:
                        throw new Error("CustomMaterialRenderMode : renderMode value error.");
                }
            }
        }
        ClothMaterial.ALBEDOTEXTURE = Laya.Shader3D.propertyNameToID("u_AlbedoTexture");
        ClothMaterial.ALBEDOCOLOR = Laya.Shader3D.propertyNameToID("u_AlbedoColor");
        ClothMaterial.NORMALTEXTURE = Laya.Shader3D.propertyNameToID("u_NormalTexture");
        ClothMaterial.NORMALTEXTURESCALE = Laya.Shader3D.propertyNameToID("u_NormalScale");
        ClothMaterial.MASKTEXTURE = Laya.Shader3D.propertyNameToID("u_MaskTexture");
        ClothMaterial.SMOOTHNESS = Laya.Shader3D.propertyNameToID("u_Smoothness");
        ClothMaterial.AMBIENTCOLOR = Laya.Shader3D.propertyNameToID("u_AmbientColor");
        ClothMaterial.GRIDTEXTURE = Laya.Shader3D.propertyNameToID("u_gridTexture");
        ClothMaterial.SHINETEXTURE = Laya.Shader3D.propertyNameToID("u_shineTexture");
        ClothMaterial.CONTROLDETAILTEXTURE = Laya.Shader3D.propertyNameToID("u_controlDetailTexture");
        ClothMaterial.GRIDTEXTURESCALE = Laya.Shader3D.propertyNameToID("u_gridTextureScale");
        ClothMaterial.SHINETEXTURESCALE = Laya.Shader3D.propertyNameToID("u_shineTextureScale");
        ClothMaterial.OUTLINEWIDTH = Laya.Shader3D.propertyNameToID("u_OutlineWidth");
        ClothMaterial.OUTLINELIGHTNESS = Laya.Shader3D.propertyNameToID("u_OutlineLightness");
        ClothMaterial.OUTLINECOLOR = Laya.Shader3D.propertyNameToID("u_OutlineColor");
        ClothMaterial.SHADOWCOLOR = Laya.Shader3D.propertyNameToID("u_ShadowColor");
        ClothMaterial.SHADOWRANGE = Laya.Shader3D.propertyNameToID("u_ShadowRange");
        ClothMaterial.SHADOWINTENSITY = Laya.Shader3D.propertyNameToID("u_ShadowIntensity");
        ClothMaterial.SHADOWBOUNDARY = Laya.Shader3D.propertyNameToID("u_ShadowBoundary");
        ClothMaterial.SECOND_SHADOWCOLOR = Laya.Shader3D.propertyNameToID("u_Second_ShadowColor");
        ClothMaterial.SECOND_SHADOWRANGE = Laya.Shader3D.propertyNameToID("u_Second_ShadowRange");
        ClothMaterial.SECOND_SHADOWINTENSITY = Laya.Shader3D.propertyNameToID("u_Second_ShadowIntensity");
        ClothMaterial.SECOND_SHADOWBOUNDARY = Laya.Shader3D.propertyNameToID("u_Second_ShadowBoundary");
        ClothMaterial.EDGE_HIGHLIGHT_COLOR = Laya.Shader3D.propertyNameToID("u_Edge_HighlightColor");
        ClothMaterial.EDGE_HIGHLIGHT_RANGE = Laya.Shader3D.propertyNameToID("u_Edge_HighlightRange");
        ClothMaterial.EDGE_HIGHLIGHT_INTENSITY = Laya.Shader3D.propertyNameToID("u_Edge_HighlightIntensity");
        ClothMaterial.EDGE_HIGHLIGHT_BOUNDARY = Laya.Shader3D.propertyNameToID("u_Edge_HighlightBoundary");
        ClothMaterial.SPECULARRANGE = Laya.Shader3D.propertyNameToID("u_SpecularRange");
        ClothMaterial.SPECULARINTENSITY = Laya.Shader3D.propertyNameToID("u_SpecularIntensity");
        ClothMaterial.SPECULARCOLOR = Laya.Shader3D.propertyNameToID("u_SpecularColor");
        ClothMaterial.RANDOM_DISCARD_FACTOR = Laya.Shader3D.propertyNameToID(`u_RandomDiscardFactor`);
        ClothMaterial.SPOCCLUSIONSTRENGTH = Laya.Shader3D.propertyNameToID(`u_SPOcclusionStrength`);
        ClothMaterial.SPMETALLIC = Laya.Shader3D.propertyNameToID(`u_SPMetallic`);
        ClothMaterial.SPSMOOTHNESS = Laya.Shader3D.propertyNameToID(`u_SPSmoothness`);
        ClothMaterial.SPSHADOWATTEN = Laya.Shader3D.propertyNameToID(`u_SPShadowAtten`);
        ClothMaterial.SPSIDELIGHTCOLOR = Laya.Shader3D.propertyNameToID(`u_SPSideLightColor`);
        ClothMaterial.SPSIDELIGHTSCALE = Laya.Shader3D.propertyNameToID(`u_SPSideLightScale`);
        ClothMaterial.SPPBRRESULTMAXCOLOR = Laya.Shader3D.propertyNameToID(`u_SPPBRResultMaxColor`);
        ClothMaterial.CUSTOMDIRECTLIGHTCOLOR = Laya.Shader3D.propertyNameToID(`u_CustomDirectLightColor`);
        ClothMaterial.LIGHTRESULTINTENSITY = Laya.Shader3D.propertyNameToID(`u_LightResultIntensity`);
        ClothMaterial.CULL = Laya.Shader3D.propertyNameToID("s_Cull");
        ClothMaterial.BLEND = Laya.Shader3D.propertyNameToID("s_Blend");
        ClothMaterial.BLEND_SRC = Laya.Shader3D.propertyNameToID("s_BlendSrc");
        ClothMaterial.BLEND_DST = Laya.Shader3D.propertyNameToID("s_BlendDst");
        ClothMaterial.DEPTH_TEST = Laya.Shader3D.propertyNameToID("s_DepthTest");
        ClothMaterial.DEPTH_WRITE = Laya.Shader3D.propertyNameToID("s_DepthWrite");

        class HairMaterial extends Laya.PBRMaterial {
            constructor() {
                super();
                this.setShaderName("HairShader");
                this._shaderValues.setNumber(HairMaterial.SPECULARINTENSITY, 1.0);
                this._shaderValues.setVector(HairMaterial.ALBEDOCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setNumber(HairMaterial.SPMETALLIC, 0.0);
                this._shaderValues.setNumber(HairMaterial.SPSMOOTHNESS, 1);
                this._shaderValues.setNumber(HairMaterial.SPUTILING, 1.4);
                this._shaderValues.setNumber(HairMaterial.SPPBRINSTENSITY, 0.2);
                this._shaderValues.setNumber(HairMaterial.SPHAIRALBEDOAO, 0.597);
                this._shaderValues.setNumber(HairMaterial.SPANISOTROPYBIASG, -1.6);
                this._shaderValues.setNumber(HairMaterial.SPANISOTROPYBIASR, 0.36);
                this._shaderValues.setNumber(HairMaterial.SPHAIRSPECULARAO, 0.694);
                this._shaderValues.setNumber(HairMaterial.SPANISOTROPYRANG1, 7.0);
                this._shaderValues.setNumber(HairMaterial.SPANISOTROPYRANG2, 781.0);
                this._shaderValues.setNumber(HairMaterial.SPHLFREPOWER, 2.0);
                this._shaderValues.setNumber(HairMaterial.SPSPECULARINDARKALPHA, 0.0588);
                this._shaderValues.setVector(HairMaterial.SPR1SPECALURCOLOR, new Laya.Vector4(0.3, 0.18, 0.18, 0.0));
                this._shaderValues.setVector(HairMaterial.SPR2SPECALURCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 0.0));
                this._shaderValues.setVector(HairMaterial.SPSPECULARINDARK, new Laya.Vector4(0.247, 0.235, 0.294, 0.0588));
                this._shaderValues.setNumber(HairMaterial.SPPBRFINALLIGHTRATIO, 1.0);
                this._shaderValues.setNumber(HairMaterial.NORMALTEXTURESCALE, 1.0);
                this._shaderValues.setNumber(HairMaterial.ALPHATESTVALUE, 0.5);
                this._shaderValues.setNumber(HairMaterial.LIGHTRESULTINTENSITY, 0.0);
                this._shaderValues.setNumber(HairMaterial.SPPBRSECONDLIGHTYVALUE, 0.0);
            }
            static __init__() {
                HairMaterial.SHADERDEFINE_ALBEDOTEXTURE = Laya.Shader3D.getDefineByName("ALBEDOTEXTURE");
                HairMaterial.SHADERDEFINE_NORMALTEXTURE = Laya.Shader3D.getDefineByName("NORMALTEXTURE");
                HairMaterial.SHADERDEFINE_MASKTEXTURE = Laya.Shader3D.getDefineByName("MASKTEXTURE");
                HairMaterial.SHADERDEFINE_ALBEDOALPHATEXTURE = Laya.Shader3D.getDefineByName("ALBEDOALPHATEXTURE");
                HairMaterial.SHADERDEFINE_TILINGOFFSET = Laya.Shader3D.getDefineByName("TILINGOFFSET");
                HairMaterial.SHADERDEFINE_BONE = Laya.Shader3D.getDefineByName("BONE");
                HairMaterial.SHADERDEFINE_DRAWING_MASK = Laya.Shader3D.getDefineByName("SHADERDEFINE_DRAWING_MASK");
                HairMaterial.SHADERDEFINE_LAYER1_TEXTURE = Laya.Shader3D.getDefineByName("LAYER1_TEXTURE");
            }
            static initShader() {
                HairMaterial.__init__();
                var stateMap = {
                    's_Cull': Laya.Shader3D.RENDER_STATE_CULL,
                    's_Blend': Laya.Shader3D.RENDER_STATE_BLEND,
                    's_BlendSrc': Laya.Shader3D.RENDER_STATE_BLEND_SRC,
                    's_BlendDst': Laya.Shader3D.RENDER_STATE_BLEND_DST,
                    's_DepthTest': Laya.Shader3D.RENDER_STATE_DEPTH_TEST,
                    's_DepthWrite': Laya.Shader3D.RENDER_STATE_DEPTH_WRITE
                };
                var attributeMap = {
                    'a_Position': Laya.VertexMesh.MESH_POSITION0,
                    'a_Normal': Laya.VertexMesh.MESH_NORMAL0,
                    'a_Tangent0': Laya.VertexMesh.MESH_TANGENT0,
                    'a_Texcoord0': Laya.VertexMesh.MESH_TEXTURECOORDINATE0,
                    'a_Texcoord1': Laya.VertexMesh.MESH_TEXTURECOORDINATE1,
                    'a_BoneWeights': Laya.VertexMesh.MESH_BLENDWEIGHT0,
                    'a_BoneIndices': Laya.VertexMesh.MESH_BLENDINDICES0,
                    'a_MvpMatrix': Laya.VertexMesh.MESH_MVPMATRIX_ROW0,
                    'a_WorldMat': Laya.VertexMesh.MESH_WORLDMATRIX_ROW0
                };
                var uniformMap = {
                    'u_Bones': Laya.Shader3D.PERIOD_CUSTOM,
                    'u_MvpMatrix': Laya.Shader3D.PERIOD_SPRITE,
                    'u_WorldMat': Laya.Shader3D.PERIOD_SPRITE,
                    'u_LightmapScaleOffset': Laya.Shader3D.PERIOD_SPRITE,
                    'u_LightMap': Laya.Shader3D.PERIOD_SPRITE,
                    'u_LightMapDirection': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorTexture': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorParams': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorTextureSize': Laya.Shader3D.PERIOD_SPRITE,
                    'u_CameraPos': Laya.Shader3D.PERIOD_CAMERA,
                    'u_ProjectionParams': Laya.Shader3D.PERIOD_CAMERA,
                    'u_AlphaTestValue': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_EmissionColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_NormalTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ParallaxTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_OcclusionTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_EmissionTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPSmoothness': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPMetallic': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_occlusionStrength': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_NormalScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ParallaxScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_MaskTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoAlphaTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Metallic': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ReflectTexture': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectIntensity': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientColor': Laya.Shader3D.PERIOD_SCENE,
                    'u_FogStart': Laya.Shader3D.PERIOD_SCENE,
                    'u_FogRange': Laya.Shader3D.PERIOD_SCENE,
                    'u_FogColor': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirationLightCount': Laya.Shader3D.PERIOD_SCENE,
                    'u_LightBuffer': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowBias': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowLightDirection': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowMap': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowParams': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowSplitSpheres': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowMatrices': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowMapSize': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotShadowMap': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotViewProjectMatrix': Laya.Shader3D.PERIOD_SCENE,
                    'u_ShadowLightPosition': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAr': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAg': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAb': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBr': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBg': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBb': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHC': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectionProbe': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectCubeHDRParams': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirectionLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirectionLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_SPUTiling': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPPBRInstensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPHairAlbedoAO': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPAnisotropyBiasG': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPAnisotropyBiasR': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPHairSpecularAO': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPAnisotropyRang1': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPAnisotropyRang2': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPHLFrePower': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPSpecularInDarkAlpha': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPR1SpecalurColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPR2SpecalurColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPSpecularInDark': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPPBRFinalLightRatio': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightResultIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_specularIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPPBRSecondLightYValue': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintLayer1Texture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintLayer1TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintLayer2Texture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintLayer2TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                };
                var PBRShadowCasterPS$1 = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
                var PBRShadowCasterVS$1 = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS =  shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
                var vs1 = `
        #include "Lighting.glsl";
        #include "Shadow.glsl";

        attribute vec4 a_Position;

        #ifdef GPU_INSTANCE
            attribute mat4 a_MvpMatrix;
            attribute mat4 a_WorldMat;
        #else
            uniform mat4 u_MvpMatrix;
            uniform mat4 u_WorldMat;
        #endif

        #ifdef BONE
            const int c_MaxBoneCount = 24;
            attribute vec4 a_BoneIndices;
            attribute vec4 a_BoneWeights;
            uniform mat4 u_Bones[c_MaxBoneCount];
        #endif

        attribute vec3 a_Normal;
        varying vec3 v_Normal; 

        #if defined(NORMALTEXTURE)||defined(PARALLAXTEXTURE)
            attribute vec4 a_Tangent0;
            varying vec3 v_Tangent;
            varying vec3 v_Binormal;
            #endif

        #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)||(defined(LIGHTMAP)&&defined(UV))
            attribute vec2 a_Texcoord0;
            varying vec2 v_Texcoord0;
        #endif

        uniform vec3 u_CameraPos;
        varying vec3 v_EyeVec;
        varying vec3 v_PositionWorld;
        varying float v_posViewZ;
        varying vec3 v_CameraPos;

        #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
            varying vec4 v_ShadowCoord;
        #endif

        #ifdef CALCULATE_SPOTSHADOWS
            varying vec4 v_SpotShadowCoord;
        #endif

        #ifdef TILINGOFFSET
            uniform vec4 u_TilingOffset;
        #endif
        void vertexForward()
        {
            vec4 position;
            #ifdef BONE
                mat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;
                skinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;
                skinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;
                skinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;
                position=skinTransform*a_Position;
            #else
                position=a_Position;
            #endif

            #ifdef GPU_INSTANCE
                gl_Position = a_MvpMatrix * position;
            #else
                gl_Position = u_MvpMatrix * position;
            #endif

            mat4 worldMat;
            #ifdef GPU_INSTANCE
                worldMat = a_WorldMat;
            #else
                worldMat = u_WorldMat;
            #endif

            v_PositionWorld=(worldMat*position).xyz;

            v_Texcoord0=a_Texcoord0;

            v_EyeVec =u_CameraPos-v_PositionWorld;//will normalize per-pixel
            v_CameraPos = u_CameraPos;

            mat3 worldInvMat;
            #ifdef BONE
                worldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));
            #else
                worldInvMat=INVERSE_MAT(mat3(worldMat));
            #endif

            v_Normal=normalize(a_Normal*worldInvMat);//if no normalize will cause precision problem.

            #ifdef NORMALTEXTURE
                v_Tangent=normalize(a_Tangent0.xyz*worldInvMat);
                v_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;
            #endif

            #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
                v_ShadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
            #endif

            #ifdef CALCULATE_SPOTSHADOWS
                v_SpotShadowCoord = u_SpotViewProjectMatrix*vec4(positionWS,1.0);
            #endif
        }
        
        void main()
        {
            vertexForward();
            gl_Position=remapGLPositionZ(gl_Position);
        }`;
                var ps1 = `
        #ifdef GL_FRAGMENT_PRECISION_HIGH
            precision highp float;
            precision highp int;
        #else
            precision mediump float;
            precision mediump int;
        #endif
        
        #include "Lighting.glsl";
        #include "Shadow.glsl";
        #include "LayaPBRBRDF.glsl";
        #include "GlobalIllumination.glsl";

        #ifdef ALPHATEST
            uniform float u_AlphaTestValue;
        #endif

        uniform vec4 u_AlbedoColor;

        #ifdef NORMALTEXTURE
            uniform sampler2D u_NormalTexture;
            uniform float u_NormalScale;
        #endif

        #ifdef ALBEDOTEXTURE
            uniform sampler2D u_AlbedoTexture;
        #endif

        #ifdef MASKTEXTURE
            uniform sampler2D u_MaskTexture;
            vec4 maskTextureColor; 
        #endif

        #ifdef METALLICGLOSSTEXTURE
            uniform sampler2D u_MetallicGlossTexture;
        #endif
        uniform float u_Metallic;

        #ifdef SPECULARGLOSSTEXTURE
            uniform sampler2D u_SpecGlossTexture;
        #endif
        #ifdef ALBEDOALPHATEXTURE
            uniform sampler2D u_AlbedoAlphaTexture;
        #endif

        uniform float u_SPSmoothness;
        uniform float u_SPMetallic;

        uniform float u_occlusionStrength;

        #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)
            varying vec2 v_Texcoord0;
        #endif

        varying vec3 v_Normal; 

        varying mat3 v_worldMat;
        varying vec3 v_CameraPos;

        // #if defined(DIRECTIONLIGHT)

        //     #if defined(LEGACYSINGLELIGHTING)
                uniform DirectionLight u_SunLight;
            // #else
                uniform int u_DirationLightCount;
                uniform sampler2D u_LightBuffer;
        //     #endif
                
        // #endif

        varying vec3 v_EyeVec;

        #ifdef NORMALTEXTURE
            varying vec3 v_Tangent;
            varying vec3 v_Binormal;
        #endif

		uniform sampler2D u_PaintLayer1Texture;
		uniform vec4 u_PaintLayer1TilingOffset;

		#ifdef WHOLE_ALPHA
		uniform float u_alpha;
		#endif

        varying vec3 v_PositionWorld;

        #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
            varying vec4 v_ShadowCoord;

        #endif

        #ifdef CALCULATE_SPOTSHADOWS
            varying vec4 v_SpotShadowCoord;
        #endif

    vec4 albedoRgba;


        uniform float u_SPUTiling;
        uniform float u_SPPBRInstensity;
        uniform float u_SPHairAlbedoAO;
        uniform float u_SPAnisotropyBiasG;
        uniform float u_SPAnisotropyBiasR;
        uniform float u_SPHairSpecularAO;
        uniform float u_SPAnisotropyRang1;
        uniform float u_SPAnisotropyRang2;
        uniform float u_SPHLFrePower;
        uniform float u_SPSpecularInDarkAlpha;
        uniform vec4 u_SPR1SpecalurColor;
        uniform vec4 u_SPR2SpecalurColor;
        uniform vec4 u_SPSpecularInDark;
        uniform float u_SPPBRFinalLightRatio;
        uniform float u_LightResultIntensity;
        uniform float u_specularIntensity;
        uniform float u_SPPBRSecondLightYValue;

        mediump float lerpOneTo(mediump float b, mediump float t)
        {
            mediump float oneMinusT = 1.0 - t;
            return oneMinusT + b * t;
        }

        mediump float getOcclusion(vec2 uv)
        {
            #ifdef OCCLUSIONTEXTURE
                mediump float occ = texture2D(u_OcclusionTexture, uv).g;
                return lerpOneTo(occ, u_occlusionStrength);
            #else
                return 1.0;
            #endif 
        }

        mediump vec4 albedo(vec2 uv)
        {
            vec3 tmpMaskedColor;
            #ifdef MASKTEXTURE
                tmpMaskedColor = ( lerpOneTo( maskTextureColor.b , u_SPHairAlbedoAO) * u_AlbedoColor.rgb );
            #endif

            vec3 originRgb;
            #ifdef ALBEDOTEXTURE
                originRgb = tmpMaskedColor.rgb * texture2D(u_AlbedoTexture, uv).rgb;
            #else
                originRgb = tmpMaskedColor.rgb;
            #endif

            vec4 computeRgba = vec4(originRgb.rgb,u_AlbedoColor.a);

			#ifdef LAYER1_TEXTURE
				vec2 texcoordL1 = TransformUV(uv, u_PaintLayer1TilingOffset);
				vec4 paintLayer1Color = texture2D(u_PaintLayer1Texture, texcoordL1);
				
				computeRgba.rgb = computeRgba.rgb * (1.0 - paintLayer1Color.a) + paintLayer1Color.rgb;
				computeRgba.a = computeRgba.a * (1.0 - paintLayer1Color.a) + paintLayer1Color.a * paintLayer1Color.a;
            #endif

            return computeRgba;

        }
        float random(float x, float y){
			return fract(cos(x * (12.9898) + y * (4.1414)) * 43758.5453);
		}
        mediump vec2 getMetallicGloss(vec2 uv)
        {
            mediump vec2 ms;//x is metallic,y is smoothness
            //lhcadd
            ms.x = u_SPMetallic;//0.7639677;//0.7639677/2.0;
            ms.y = u_SPSmoothness;

            return ms;
        }

        #ifdef NORMALTEXTURE
            mediump vec3 unpackScaleNormal(mediump vec3 packednormal, mediump float bumpScale)
            {
                mediump vec3 normal = packednormal.xyz * 2.0 - 1.0;
                normal.y=-normal.y;//NOTE:because unity to LayaAir coordSystem.
                normal.xy *= bumpScale;
                return normal;
            }
            vec4 lerpVec4(vec4 a, vec4 b, float w) {
                if(w<=0.0){
                    return a;
                }else if(w>=1.0){
                    return b;
                }else{
                    return w*b +(1.0-w)*a;
                }
            }
            vec3 lerpVec3(vec3 a, vec3 b, float w) {
                if(w<=0.0){
                    return a;
                }else if(w>=1.0){
                    return b;
                }else{
                    return w*b +(1.0-w)*a;
                }
            }

            mediump vec3 normalInTangentSpace(vec2 texcoords)
            {
                return unpackScaleNormal(texture2D(u_NormalTexture, texcoords).rgb,u_NormalScale);
            }
        #endif

        struct FragmentCommonData{
            vec3 diffColor;
            vec3 specColor;
            float oneMinusReflectivity;
            float smoothness;
        };
        
        #ifndef SETUP_BRDF_INPUT
        #define SETUP_BRDF_INPUT metallicSetup//default is metallicSetup,also can be other.    specularSetup / metallicSetup
        #endif
        
        const mediump vec4 dielectricSpecularColor = vec4(0.220916301, 0.220916301, 0.220916301, 1.0 - 0.220916301);
        
        mediump vec3 diffuseAndSpecularFromMetallic(mediump vec3 albedo,mediump float metallic, out mediump vec3 specColor, out mediump float oneMinusReflectivity)
        {
                specColor = mix(dielectricSpecularColor.rgb, albedo, metallic);
            oneMinusReflectivity= dielectricSpecularColor.a*(1.0-metallic);//diffuse proportion
            return albedo * oneMinusReflectivity;
        }
        
        mediump float specularStrength(mediump vec3 specular)
        {
            return max (max (specular.r, specular.g), specular.b);
        }
        
        // Diffuse/Spec Energy conservation
        mediump vec3 energyConservationBetweenDiffuseAndSpecular (mediump vec3 albedo, mediump vec3 specColor, out mediump float oneMinusReflectivity)
        {
                oneMinusReflectivity = 1.0 - specularStrength(specColor);
            return albedo * (vec3(1.0) - specColor);
        }
        
        #ifdef TRANSPARENTBLEND
            mediump vec3 preMultiplyAlpha (mediump vec3 diffColor, mediump float alpha, mediump float oneMinusReflectivity,out mediump float modifiedAlpha)
            {
                // Transparency 'removes' from Diffuse component
                diffColor *= alpha;
                // Reflectivity 'removes' from the rest of components, including Transparency
                // modifiedAlpha = 1.0-(1.0-alpha)*(1.0-reflectivity) = 1.0-(oneMinusReflectivity - alpha*oneMinusReflectivity) = 1.0-oneMinusReflectivity + alpha*oneMinusReflectivity
                modifiedAlpha = 1.0 - oneMinusReflectivity + alpha*oneMinusReflectivity;
                return diffColor;
            }
        #endif
        
        FragmentCommonData metallicSetup(vec2 uv)
        {
            mediump vec2 metallicGloss = getMetallicGloss(uv);
            mediump float metallic = metallicGloss.x;
            mediump float smoothness = metallicGloss.y; // this is 1 minus the square root of real roughness m.
            mediump float oneMinusReflectivity;
            mediump vec3 specColor;
            mediump vec3 diffColor = diffuseAndSpecularFromMetallic(albedoRgba.rgb, metallic,/*out*/specColor,/*out*/oneMinusReflectivity);
        
            FragmentCommonData o;
            o.diffColor = diffColor;
            o.specColor = specColor;
            o.oneMinusReflectivity = oneMinusReflectivity;
            o.smoothness = smoothness;
            return o;
        }
        
        LayaGI fragmentGI(float smoothness,vec3 eyeVec,mediump float occlusion,mediump vec2 lightmapUV,vec3 worldnormal)
        {
            LayaGIInput giInput;
        
            vec3 worldViewDir = -eyeVec;
            mediump vec4 uvwRoughness;
            uvwRoughness.rgb = reflect(worldViewDir, worldnormal);//reflectUVW
            uvwRoughness.a= smoothnessToPerceptualRoughness(smoothness);//perceptualRoughness
        
            return layaGlobalIllumination(giInput,occlusion, worldnormal, uvwRoughness);
        }
        
        
        vec3 perPixelWorldNormal(vec2 uv,vec3 normal,vec3 binormal,vec3 tangent)
        {
            #ifdef NORMALTEXTURE
                mediump vec3 normalTangent=normalInTangentSpace(uv);
                vec3 normalWorld = normalize(tangent * normalTangent.x + binormal * normalTangent.y + normal * normalTangent.z);
                
            #else
                vec3 normalWorld = normalize(normal);
            #endif
                return normalWorld;
        }
        vec3 perPixelWorldNormalByNormalTanget(vec2 uv,vec3 normal,vec3 binormal,vec3 tangent,vec3 normalTangent)
        {
            #ifdef NORMALTEXTURE
                vec3 normalWorld = normalize(tangent * normalTangent.x + binormal * normalTangent.y + normal * normalTangent.z);
                
            #else
                vec3 normalWorld = normalize(normal);
            #endif
                return normalWorld;
        }
        
        void main_paint_mask(){
			gl_FragColor = vec4(v_Texcoord0.xy,0.0,1.0);
        }
        
        void fragmentForward()
        {
            vec2 uv;
            #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)
                    uv = v_Texcoord0;
            #endif
            
            #ifdef MASKTEXTURE
                vec2 tmpTiling = (vec2(u_SPUTiling , 1.0));
                vec2 tmpUv = uv * tmpTiling;
                maskTextureColor =texture2D(u_MaskTexture, tmpUv);
            #endif

            albedoRgba = albedo(uv);

            #ifdef ALBEDOALPHATEXTURE
                vec4 tex2DAlphaControl = texture2D(u_AlbedoAlphaTexture, uv);
                if(tex2DAlphaControl.r<0.1)
                    discard;
            #endif
            mediump float alpha = albedoRgba.a;//getAlpha(uv);
            #ifdef ALPHATEST
                if(alpha<u_AlphaTestValue)
                    discard;
            #endif

            FragmentCommonData o = SETUP_BRDF_INPUT(uv);
            
            vec3 binormal;
            vec3 tangent;
            #ifdef NORMALTEXTURE
                tangent = v_Tangent;
                binormal = v_Binormal;
            #endif

            vec3 normal = v_Normal;
            vec3 normalWorld = perPixelWorldNormal(uv,normal,binormal,tangent);//In FS if the normal use mediump before normalize will cause precision prolem in mobile device.
            vec3 eyeVec = normalize(v_EyeVec);
            vec3 posworld = v_PositionWorld;
            
            #ifdef TRANSPARENTBLEND
                o.diffColor=preMultiplyAlpha(o.diffColor,alpha,o.oneMinusReflectivity,/*out*/alpha);// shader relies on pre-multiply alpha-blend (srcBlend = One, dstBlend = OneMinusSrcAlpha)
            #endif

            mediump float occlusion = getOcclusion(uv);
            mediump vec2 lightMapUV;

            float perceptualRoughness = smoothnessToPerceptualRoughness(o.smoothness);
            float roughness = perceptualRoughnessToRoughness(perceptualRoughness);
            float nv = abs(dot(normalWorld, eyeVec));
            LayaGI gi =fragmentGI(o.smoothness,eyeVec,occlusion,lightMapUV,normalWorld);
            vec4 color = LAYA_BRDF_GI(o.diffColor,o.specColor,o.oneMinusReflectivity,o.smoothness,perceptualRoughness,roughness,nv,normalWorld,eyeVec,gi);
            

            
            #ifdef DIRECTIONLIGHT

                vec4 lightResultColor = vec4(0.0,0.0,0.0,0.0);

                vec3 dirLightFirst;
                vec3 dirLightSecond;

                float shadowAttenuationGlobal = 1.0;


                // #if defined(LEGACYSINGLELIGHTING)

                //     #ifdef CALCULATE_SHADOWS
                       
                //             #ifdef SHADOW_CASCADE
                //                 vec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
                //             #else
                //                 vec4 shadowCoord = v_ShadowCoord;
                //             #endif
                //             sampleShadowmap(shadowCoord);
                        
                //     #endif
                //     DirectionLight directionLight;
                //     directionLight.color=u_SunLight.color;
                //     directionLight.direction = u_SunLight.direction;

                //     LayaLight dirLight = layaDirectionLightToLight(directionLight,shadowAttenuationGlobal);
                //     lightResultColor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);

                //     // dirLightFirst =  u_SunLight.direction;
                //     // dirLightSecond =  vec3(-0.3090169948284817,0.0,0.9510565161477913);
                // #else
                //     for (int i = 0; i < MAX_LIGHT_COUNT; i++) 
                //     {
                //         float shadowAttenuation = 1.0;
                //         if(i >= u_DirationLightCount)
                //             break;
                //         #ifdef CALCULATE_SHADOWS
                //             if(i == 0)
                //             {
                //                 #ifdef SHADOW_CASCADE
                //                     vec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
                //                 #else
                //                     vec4 shadowCoord = v_ShadowCoord;
                //                 #endif
                //                 shadowAttenuation *= sampleShadowmap(shadowCoord);
                //             }
                //         #endif
                //         DirectionLight directionLight = getDirectionLight(u_LightBuffer,i);
                //         LayaLight dirLight = layaDirectionLightToLight(directionLight,shadowAttenuation);
                //         lightResultColor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);

                //         // if(i==0){
                //         //     dirLightFirst  = dirLight.dir;
                //         //     shadowAttenuationGlobal = shadowAttenuation;
                //         // }
                //         // if(i==1 || MAX_LIGHT_COUNT==1){
                //         //     dirLightSecond = dirLight.dir;
                //         // }

                //     }
                // #endif

                // color += vec4( max(lightResultColor.r,albedoRgba.r*u_LightResultIntensity),max(lightResultColor.g,albedoRgba.g*u_LightResultIntensity),max(lightResultColor.b,albedoRgba.b*u_LightResultIntensity),lightResultColor.a );
                color += lightResultColor * u_LightResultIntensity;




                // dirLightSecond =  vec3(-0.3090169948284817,0.0,0.9510565161477913);
                dirLightFirst =  u_SunLight.direction;
                dirLightSecond =  vec3(-0.3090169948284817,u_SPPBRSecondLightYValue,0.9510565161477913);

                vec3 surfResult105 = vec3(color.rgb);

                vec3 albedoResult = albedoRgba.rgb;

                vec3 clampResult226 = vec3(clamp(surfResult105.r,0.0,1.0),clamp(surfResult105.g,0.0,1.0),clamp(surfResult105.b,0.0,1.0));
                vec3 lerpResult125 = vec3(mix(albedoResult.r,clampResult226.r,u_SPPBRInstensity),mix(albedoResult.g,clampResult226.g,u_SPPBRInstensity),mix(albedoResult.b,clampResult226.b,u_SPPBRInstensity));

                color.rgb = lerpResult125.rgb;


                #ifdef MASKTEXTURE
                    vec4 _SpecularInDark = u_SPSpecularInDark;
                    _SpecularInDark.a = u_SPSpecularInDarkAlpha;
                    
                    vec3 ase_worldBitangent = perPixelWorldNormalByNormalTanget(uv,normal,binormal,tangent,vec3( 0.0, 1.0, 0.0 ));
                    vec3 ase_worldNormal = perPixelWorldNormalByNormalTanget(uv,normal,binormal,tangent,vec3( 0.0, 0.0, 1.0 ));

                    vec3 ase_normWorldNormal = ase_worldNormal;
                    vec3 normalizeResult243 = normalize(dirLightSecond);

                    vec3 lightDir = normalize(dirLightFirst);
                    
                    vec3 normalizeResult246 =lightDir;
                    float dotResult156 = dot( ( ase_worldBitangent + ( ase_normWorldNormal * ( ( maskTextureColor.r * u_SPAnisotropyBiasR ) + ( maskTextureColor.g * u_SPAnisotropyBiasG ) ) ) ) , normalizeResult246 );
                    float temp_output_186_0 = sqrt( sqrt( ( 1.0 - ( dotResult156 * dotResult156 ) ) ) );
                    
                    float lerpResult274 = lerpOneTo(maskTextureColor.b , u_SPHairSpecularAO);
                    vec3 ase_worldViewDir = normalizeResult243;
                    float dotResult117 = dot( ase_worldViewDir , ase_worldNormal );
                    vec4 temp_output_76_0 = ( ( ( pow( temp_output_186_0 , u_SPAnisotropyRang1 ) * u_SPR1SpecalurColor ) + ( pow( temp_output_186_0 , ( u_SPAnisotropyRang2 * maskTextureColor.r ) ) * u_SPR2SpecalurColor * maskTextureColor.r ) ) * lerpResult274 * pow( dotResult117 , u_SPHLFrePower ) );
                    
                    float lightAttenRatio =  mix(shadowAttenuationGlobal,1.0,_SpecularInDark.a);
                    vec4 lerpResult279 = lerpVec4( ( _SpecularInDark * temp_output_76_0 ) , temp_output_76_0 , lightAttenRatio);
                    
                    vec4 color241 = vec4(1.51,1.51,1.51,0) ;
                    vec3 clampResult240 = vec3(clamp(lerpResult279.r,0.0,color241.r),clamp(lerpResult279.g,0.0,color241.g),clamp(lerpResult279.b,0.0,color241.b));
                    clampResult240 = clampResult240.rgb*u_SPPBRFinalLightRatio;

                    color.rgb += clampResult240.rgb;
                #endif


                color.rgb = ( lerpResult125 + clampResult240 ).rgb;
            #endif

            gl_FragColor=vec4(color.rgb,alpha);
        }

        void main()
        {
            #ifdef SHADERDEFINE_DRAWING_MASK
				main_paint_mask();
			#else
                fragmentForward();
            #endif
        }`;
                var shader3D = Laya.Shader3D.add("HairShader", attributeMap, uniformMap, true);
                var subShader = new Laya.SubShader(attributeMap, uniformMap);
                shader3D.addSubShader(subShader);
                subShader.addShaderPass(vs1, ps1, stateMap, "Forward");
                if (Const.bHighShadowQuality) {
                    subShader.addShaderPass(PBRShadowCasterVS$1, PBRShadowCasterPS$1, stateMap, "ShadowCaster");
                }
            }
            get normalTextureScale() {
                return this._shaderValues.getNumber(HairMaterial.NORMALTEXTURESCALE);
            }
            set normalTextureScale(value) {
                value = this.clampKeyValueByKey(HairMaterial.NORMALTEXTURESCALE, value);
                this._shaderValues.setNumber(HairMaterial.NORMALTEXTURESCALE, value);
            }
            get maskTexture() {
                return this._shaderValues.getTexture(HairMaterial.MASKTEXTURE);
            }
            set maskTexture(value) {
                if (value)
                    this._defineDatas.add(HairMaterial.SHADERDEFINE_MASKTEXTURE);
                else
                    this._defineDatas.remove(HairMaterial.SHADERDEFINE_MASKTEXTURE);
                this._shaderValues.setTexture(HairMaterial.MASKTEXTURE, value);
            }
            get AlbedoAlphaTexture() {
                return this._shaderValues.getTexture(HairMaterial.ALBEDOALPHATEXTURE);
            }
            set AlbedoAlphaTexture(value) {
                if (value)
                    this._defineDatas.add(HairMaterial.SHADERDEFINE_ALBEDOALPHATEXTURE);
                else
                    this._defineDatas.remove(HairMaterial.SHADERDEFINE_ALBEDOALPHATEXTURE);
                this._shaderValues.setTexture(HairMaterial.ALBEDOALPHATEXTURE, value);
            }
            set specularIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(HairMaterial.SPECULARINTENSITY, value);
            }
            get specularIntensity() {
                return this._shaderValues.getNumber(HairMaterial.SPECULARINTENSITY);
            }
            get paintLayer1Texture() {
                return this._shaderValues.getTexture(HairMaterial.PAINT_LAYER1_TEXTURE);
            }
            set paintLayer1Texture(value) {
                if (value != null) {
                    this._defineDatas.add(HairMaterial.SHADERDEFINE_LAYER1_TEXTURE);
                }
                else {
                    this._defineDatas.remove(HairMaterial.SHADERDEFINE_LAYER1_TEXTURE);
                }
                this._shaderValues.setTexture(HairMaterial.PAINT_LAYER1_TEXTURE, value);
            }
            get paintLayer1TilingOffset() {
                return this._shaderValues.getVector(HairMaterial.PAINT_LAYER1_TILINGOFFSET);
            }
            set paintLayer1TilingOffset(value) {
                this._shaderValues.setVector(HairMaterial.PAINT_LAYER1_TILINGOFFSET, value);
            }
            get LightResultIntensity() {
                return this._shaderValues.getNumber(HairMaterial.LIGHTRESULTINTENSITY);
            }
            set LightResultIntensity(value) {
                value = this.clampKeyValueByKey(HairMaterial.LIGHTRESULTINTENSITY, value);
                this._shaderValues.setNumber(HairMaterial.LIGHTRESULTINTENSITY, value);
            }
            getShaderValueRangeWithKey(key) {
                switch (key) {
                    case HairMaterial.SPUTILING:
                        return [0.0, 2.0];
                        break;
                    case HairMaterial.SPANISOTROPYBIASG:
                        return [-2.0, 2.0];
                        break;
                    case HairMaterial.SPANISOTROPYBIASR:
                        return [-2.0, 2.0];
                        break;
                    case HairMaterial.SPANISOTROPYRANG1:
                        return [0.0, 100.0];
                        break;
                    case HairMaterial.SPANISOTROPYRANG2:
                        return [0.0, 1000.0];
                        break;
                    case HairMaterial.SPHLFREPOWER:
                        return [0.0, 5.0];
                        break;
                    case HairMaterial.NORMALTEXTURESCALE:
                        return [0.0, 2.0];
                        break;
                    case HairMaterial.SPPBRFINALLIGHTRATIO:
                        return [0.0, 2.0];
                        break;
                    case HairMaterial.SPPBRSECONDLIGHTYVALUE:
                        return [-1.0, 1.0];
                    default:
                        break;
                }
                return [0.0, 1.0];
            }
            clampKeyValueByKey(key, value) {
                return Math.max(this.getShaderValueRangeWithKey(key)[0], Math.min(this.getShaderValueRangeWithKey(key)[1], value));
            }
            get SPMetallic() {
                return this._shaderValues.getNumber(HairMaterial.SPMETALLIC);
            }
            set SPMetallic(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPMETALLIC, value);
                this._shaderValues.setNumber(HairMaterial.SPMETALLIC, value);
            }
            get SPSmoothness() {
                return this._shaderValues.getNumber(HairMaterial.SPSMOOTHNESS);
            }
            set SPSmoothness(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPSMOOTHNESS, value);
                this._shaderValues.setNumber(HairMaterial.SPSMOOTHNESS, value);
            }
            get SPUTiling() {
                return this._shaderValues.getNumber(HairMaterial.SPUTILING);
            }
            set SPUTiling(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPUTILING, value);
                this._shaderValues.setNumber(HairMaterial.SPUTILING, value);
            }
            get SPPBRInstensity() {
                return this._shaderValues.getNumber(HairMaterial.SPPBRINSTENSITY);
            }
            set SPPBRInstensity(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPPBRINSTENSITY, value);
                this._shaderValues.setNumber(HairMaterial.SPPBRINSTENSITY, value);
            }
            get SPHairAlbedoAO() {
                return this._shaderValues.getNumber(HairMaterial.SPHAIRALBEDOAO);
            }
            set SPHairAlbedoAO(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPHAIRALBEDOAO, value);
                this._shaderValues.setNumber(HairMaterial.SPHAIRALBEDOAO, value);
            }
            get SPAnisotropyBiasG() {
                return this._shaderValues.getNumber(HairMaterial.SPANISOTROPYBIASG);
            }
            set SPAnisotropyBiasG(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPANISOTROPYBIASG, value);
                this._shaderValues.setNumber(HairMaterial.SPANISOTROPYBIASG, value);
            }
            get SPAnisotropyBiasR() {
                return this._shaderValues.getNumber(HairMaterial.SPANISOTROPYBIASR);
            }
            set SPAnisotropyBiasR(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPANISOTROPYBIASR, value);
                this._shaderValues.setNumber(HairMaterial.SPANISOTROPYBIASR, value);
            }
            get SPHairSpecularAO() {
                return this._shaderValues.getNumber(HairMaterial.SPHAIRSPECULARAO);
            }
            set SPHairSpecularAO(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPHAIRSPECULARAO, value);
                this._shaderValues.setNumber(HairMaterial.SPHAIRSPECULARAO, value);
            }
            get SPAnisotropyRang1() {
                return this._shaderValues.getNumber(HairMaterial.SPANISOTROPYRANG1);
            }
            set SPAnisotropyRang1(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPANISOTROPYRANG1, value);
                this._shaderValues.setNumber(HairMaterial.SPANISOTROPYRANG1, value);
            }
            get SPAnisotropyRang2() {
                return this._shaderValues.getNumber(HairMaterial.SPANISOTROPYRANG2);
            }
            set SPAnisotropyRang2(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPANISOTROPYRANG2, value);
                this._shaderValues.setNumber(HairMaterial.SPANISOTROPYRANG2, value);
            }
            get SPHLFrePower() {
                return this._shaderValues.getNumber(HairMaterial.SPHLFREPOWER);
            }
            set SPHLFrePower(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPHLFREPOWER, value);
                this._shaderValues.setNumber(HairMaterial.SPHLFREPOWER, value);
            }
            get SPSpecularInDarkAlpha() {
                return this._shaderValues.getNumber(HairMaterial.SPSPECULARINDARKALPHA);
            }
            set SPSpecularInDarkAlpha(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPSPECULARINDARKALPHA, value);
                this._shaderValues.setNumber(HairMaterial.SPSPECULARINDARKALPHA, value);
            }
            get SPR1SpecalurColor() {
                return this._shaderValues.getVector(HairMaterial.SPR1SPECALURCOLOR);
            }
            set SPR1SpecalurColor(value) {
                this._shaderValues.setVector(HairMaterial.SPR1SPECALURCOLOR, value);
            }
            get SPR2SpecalurColor() {
                return this._shaderValues.getVector(HairMaterial.SPR2SPECALURCOLOR);
            }
            set SPR2SpecalurColor(value) {
                this._shaderValues.setVector(HairMaterial.SPR2SPECALURCOLOR, value);
            }
            get SPSpecularInDark() {
                return this._shaderValues.getVector(HairMaterial.SPSPECULARINDARK);
            }
            set SPSpecularInDark(value) {
                this._shaderValues.setVector(HairMaterial.SPSPECULARINDARK, value);
            }
            get SPPBRFinalLightRatio() {
                return this._shaderValues.getNumber(HairMaterial.SPPBRFINALLIGHTRATIO);
            }
            set SPPBRFinalLightRatio(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPPBRFINALLIGHTRATIO, value);
                this._shaderValues.setNumber(HairMaterial.SPPBRFINALLIGHTRATIO, value);
            }
            get SPPBRSecondLightYValue() {
                return this._shaderValues.getNumber(HairMaterial.SPPBRSECONDLIGHTYVALUE);
            }
            set SPPBRSecondLightYValue(value) {
                value = this.clampKeyValueByKey(HairMaterial.SPPBRSECONDLIGHTYVALUE, value);
                this._shaderValues.setNumber(HairMaterial.SPPBRSECONDLIGHTYVALUE, value);
            }
            get tilingOffset() {
                return this._shaderValues.getVector(HairMaterial.TILINGOFFSET);
            }
            set tilingOffset(value) {
                if (value) {
                    if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
                        this._defineDatas.add(HairMaterial.SHADERDEFINE_TILINGOFFSET);
                    else
                        this._defineDatas.remove(HairMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                else {
                    this._defineDatas.remove(HairMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                this._shaderValues.setVector(HairMaterial.TILINGOFFSET, value);
            }
            get cull() {
                return this._shaderValues.getInt(HairMaterial.CULL);
            }
            set cull(value) {
                this._shaderValues.setInt(HairMaterial.CULL, value);
            }
            get blend() {
                return this._shaderValues.getInt(HairMaterial.BLEND);
            }
            set blend(value) {
                this._shaderValues.setInt(HairMaterial.BLEND, value);
            }
            get blendSrc() {
                return this._shaderValues.getInt(HairMaterial.BLEND_SRC);
            }
            set blendSrc(value) {
                this._shaderValues.setInt(HairMaterial.BLEND_SRC, value);
            }
            get blendDst() {
                return this._shaderValues.getInt(HairMaterial.BLEND_DST);
            }
            set blendDst(value) {
                this._shaderValues.setInt(HairMaterial.BLEND_DST, value);
            }
            get depthTest() {
                return this._shaderValues.getInt(HairMaterial.DEPTH_TEST);
            }
            set depthTest(value) {
                this._shaderValues.setInt(HairMaterial.DEPTH_TEST, value);
            }
            get depthWrite() {
                return this._shaderValues.getBool(HairMaterial.DEPTH_WRITE);
            }
            set depthWrite(value) {
                this._shaderValues.setBool(HairMaterial.DEPTH_WRITE, value);
            }
            get materialType() {
                return CustomMaterialType.pbrHair;
            }
            get renderMode() {
                return this.__render_mode__;
            }
            set renderMode(value) {
                this.__render_mode__ = value;
                switch (value) {
                    case CustomMaterialRenderMode.unknown:
                    case CustomMaterialRenderMode.RENDERMODE_OPAQUE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_CUTOUT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_TRANSPARENT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    default:
                        throw new Error("CustomMaterialRenderMode : renderMode value error.");
                }
            }
        }
        HairMaterial.ALBEDOTEXTURE = Laya.Shader3D.propertyNameToID("u_AlbedoTexture");
        HairMaterial.ALBEDOCOLOR = Laya.Shader3D.propertyNameToID("u_AlbedoColor");
        HairMaterial.NORMALTEXTURE = Laya.Shader3D.propertyNameToID("u_NormalTexture");
        HairMaterial.NORMALTEXTURESCALE = Laya.Shader3D.propertyNameToID("u_NormalScale");
        HairMaterial.MASKTEXTURE = Laya.Shader3D.propertyNameToID("u_MaskTexture");
        HairMaterial.ALBEDOALPHATEXTURE = Laya.Shader3D.propertyNameToID("u_AlbedoAlphaTexture");
        HairMaterial.AMBIENTCOLOR = Laya.Shader3D.propertyNameToID("u_AmbientColor");
        HairMaterial.SPECULARINTENSITY = Laya.Shader3D.propertyNameToID("u_specularIntensity");
        HairMaterial.PAINT_LAYER1_TEXTURE = Laya.Shader3D.propertyNameToID("u_PaintLayer1Texture");
        HairMaterial.PAINT_LAYER1_TILINGOFFSET = Laya.Shader3D.propertyNameToID("u_PaintLayer1TilingOffset");
        HairMaterial.SPMETALLIC = Laya.Shader3D.propertyNameToID(`u_SPMetallic`);
        HairMaterial.SPSMOOTHNESS = Laya.Shader3D.propertyNameToID(`u_SPSmoothness`);
        HairMaterial.SPUTILING = Laya.Shader3D.propertyNameToID("u_SPUTiling");
        HairMaterial.SPPBRINSTENSITY = Laya.Shader3D.propertyNameToID("u_SPPBRInstensity");
        HairMaterial.SPHAIRALBEDOAO = Laya.Shader3D.propertyNameToID("u_SPHairAlbedoAO");
        HairMaterial.SPANISOTROPYBIASG = Laya.Shader3D.propertyNameToID("u_SPAnisotropyBiasG");
        HairMaterial.SPANISOTROPYBIASR = Laya.Shader3D.propertyNameToID("u_SPAnisotropyBiasR");
        HairMaterial.SPHAIRSPECULARAO = Laya.Shader3D.propertyNameToID("u_SPHairSpecularAO");
        HairMaterial.SPANISOTROPYRANG1 = Laya.Shader3D.propertyNameToID("u_SPAnisotropyRang1");
        HairMaterial.SPANISOTROPYRANG2 = Laya.Shader3D.propertyNameToID("u_SPAnisotropyRang2");
        HairMaterial.SPHLFREPOWER = Laya.Shader3D.propertyNameToID("u_SPHLFrePower");
        HairMaterial.SPSPECULARINDARKALPHA = Laya.Shader3D.propertyNameToID("u_SPSpecularInDarkAlpha");
        HairMaterial.SPR1SPECALURCOLOR = Laya.Shader3D.propertyNameToID("u_SPR1SpecalurColor");
        HairMaterial.SPR2SPECALURCOLOR = Laya.Shader3D.propertyNameToID("u_SPR2SpecalurColor");
        HairMaterial.SPSPECULARINDARK = Laya.Shader3D.propertyNameToID("u_SPSpecularInDark");
        HairMaterial.SPPBRFINALLIGHTRATIO = Laya.Shader3D.propertyNameToID("u_SPPBRFinalLightRatio");
        HairMaterial.LIGHTRESULTINTENSITY = Laya.Shader3D.propertyNameToID(`u_LightResultIntensity`);
        HairMaterial.SPPBRSECONDLIGHTYVALUE = Laya.Shader3D.propertyNameToID(`u_SPPBRSecondLightYValue`);
        HairMaterial.CULL = Laya.Shader3D.propertyNameToID("s_Cull");
        HairMaterial.BLEND = Laya.Shader3D.propertyNameToID("s_Blend");
        HairMaterial.BLEND_SRC = Laya.Shader3D.propertyNameToID("s_BlendSrc");
        HairMaterial.BLEND_DST = Laya.Shader3D.propertyNameToID("s_BlendDst");
        HairMaterial.DEPTH_TEST = Laya.Shader3D.propertyNameToID("s_DepthTest");
        HairMaterial.DEPTH_WRITE = Laya.Shader3D.propertyNameToID("s_DepthWrite");

        class SkinMaterial extends Laya.PBRMaterial {
            constructor() {
                super();
                this.setShaderName("SkinShader");
                this._shaderValues.setVector(SkinMaterial.SHADOWCOLOR, new Laya.Vector4(0.6663285, 0.6544118, 1, 1));
                this._shaderValues.setNumber(SkinMaterial.SHADOWRANGE, 0.002);
                this._shaderValues.setNumber(SkinMaterial.SHADOWINTENSITY, 0.98);
                this._shaderValues.setNumber(SkinMaterial.SHADOWBOUNDARY, 0.015);
                this._shaderValues.setNumber(SkinMaterial.SPECULARRANGE, 0.99);
                this._shaderValues.setNumber(SkinMaterial.SPECULARINTENSITY, 1.0);
                this._shaderValues.setVector(SkinMaterial.SPECULARCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setNumber(SkinMaterial.OUTLINEWIDTH, 0.001);
                this._shaderValues.setNumber(SkinMaterial.OUTLINELIGHTNESS, 0.25);
                this._shaderValues.setVector(SkinMaterial.OUTLINECOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setVector(SkinMaterial.ALBEDOCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this._shaderValues.setVector(SkinMaterial.SECOND_SHADOWCOLOR, new Laya.Vector4(1, 1, 1, 1));
                this._shaderValues.setNumber(SkinMaterial.SECOND_SHADOWRANGE, 0.00);
                this._shaderValues.setNumber(SkinMaterial.SECOND_SHADOWINTENSITY, 0.98);
                this._shaderValues.setNumber(SkinMaterial.SECOND_SHADOWBOUNDARY, 0.0);
                this._shaderValues.setVector(SkinMaterial.EDGE_HIGHLIGHT_COLOR, new Laya.Vector4(0, 1, 0, 1));
                this._shaderValues.setNumber(SkinMaterial.EDGE_HIGHLIGHT_RANGE, 0.00);
                this._shaderValues.setNumber(SkinMaterial.EDGE_HIGHLIGHT_INTENSITY, 0.98);
                this._shaderValues.setNumber(SkinMaterial.EDGE_HIGHLIGHT_BOUNDARY, 0.0);
                this._shaderValues.setNumber(SkinMaterial.RANDOM_DISCARD_FACTOR, 1.0);
                this._shaderValues.setNumber(SkinMaterial.SPOCCLUSIONSTRENGTH, 0.25);
                this._shaderValues.setNumber(SkinMaterial.SPMETALLIC, 0.0);
                this._shaderValues.setNumber(SkinMaterial.SPSMOOTHNESS, 1.13);
                this._shaderValues.setNumber(SkinMaterial.SPMETALLIC2, 0.0);
                this._shaderValues.setNumber(SkinMaterial.SPSMOOTHNESS2, 0.0);
                this._shaderValues.setNumber(SkinMaterial.SPNOISEBUMP, 1.2);
                this._shaderValues.setNumber(SkinMaterial.SPNOISEBUMPTILING, 8.0);
                this._shaderValues.setNumber(SkinMaterial.SPNOISEBUMPBASICAO, 2.0);
                this._shaderValues.setNumber(SkinMaterial.SPSHADOWATTEN, 1.0);
                this._shaderValues.setVector(SkinMaterial.SPEMISSIONCOLORBACK, new Laya.Vector4(0.65, 0.53, 0.53, 1.0));
                this._shaderValues.setNumber(SkinMaterial.SPEMISSIONCOLORBACKINTENSITY, 0.5);
                this._shaderValues.setNumber(SkinMaterial.SPBORDEROFFSETAO, -0.43);
                this._shaderValues.setNumber(SkinMaterial.SPEMISSIONCOLORBACKINTENSITY2, 1.0);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSLUCENCY, 5.0);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSSHADOW, 0.496);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSNORMALDISTORTION, 0.273);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSSCATTERING, 2.2);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSDIRECT, 0.651);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSAMBIENT, 0.715);
                this._shaderValues.setNumber(SkinMaterial.SPRED3SOFFSET, 0.41);
                this._shaderValues.setVector(SkinMaterial.SPRED3SCOLOR, new Laya.Vector4(1.0, 0.0, 0.0, 1.0));
                this._shaderValues.setVector(SkinMaterial.CUSTOMDIRECTLIGHTCOLOR, new Laya.Vector4(0.5, 0.5, 0.5, 1.0));
                this._shaderValues.setNumber(SkinMaterial.NORMALTEXTURESCALE, 1.0);
                this._shaderValues.setNumber(SkinMaterial.LIGHTRESULTINTENSITY, 1.0);
                this._shaderValues.setNumber(SkinMaterial.GRIDTEXTURESCALE, 1.0);
                this._shaderValues.setNumber(SkinMaterial.SHINETEXTURESCALE, 1.0);
                this._shaderValues.setNumber(SkinMaterial.ALPHATESTVALUE, 0.0);
                this._shaderValues.setNumber(SkinMaterial.ALBEDOTILLINGX, 1.0);
                this._shaderValues.setNumber(SkinMaterial.ALBEDOTILLINGY, 1.0);
                this._shaderValues.setNumber(SkinMaterial.CUSTOMCOLORSECTIONSTEP, Const.CREAM_COLOR_CHANGE_STEP);
                this._shaderValues.setNumber(SkinMaterial.GRIDTEXTUREISMULTIPLY, 0.0);
                this._shaderValues.setNumber(SkinMaterial.SHINETEXTUREISMULTIPLY, 0.0);
            }
            static __init__() {
                SkinMaterial.SHADERDEFINE_ALBEDOTEXTURE = Laya.Shader3D.getDefineByName("ALBEDOTEXTURE");
                SkinMaterial.SHADERDEFINE_NORMALTEXTURE = Laya.Shader3D.getDefineByName("NORMALTEXTURE");
                SkinMaterial.SHADERDEFINE_MASKTEXTURE = Laya.Shader3D.getDefineByName("MASKTEXTURE");
                SkinMaterial.SHADERDEFINE_MASKDETAILTEXTURE = Laya.Shader3D.getDefineByName("MASKDETAILTEXTURE");
                SkinMaterial.SHADERDEFINE_RAMPMAPTEXTURE = Laya.Shader3D.getDefineByName("RAMPMAPTEXTURE");
                SkinMaterial.SHADERDEFINE_TILINGOFFSET = Laya.Shader3D.getDefineByName("TILINGOFFSET");
                SkinMaterial.SHADERDEFINE_BONE = Laya.Shader3D.getDefineByName("BONE");
                SkinMaterial.SHADERDEFINE_GRIDTEXTURE = Laya.Shader3D.getDefineByName("GRIDTEXTURE");
                SkinMaterial.SHADERDEFINE_SHINETEXTURE = Laya.Shader3D.getDefineByName("SHINETEXTURE");
                SkinMaterial.SHADERDEFINE_CONTROLDETAILTEXTURE = Laya.Shader3D.getDefineByName("CONTROLDETAILTEXTURE");
                SkinMaterial.SHADERDEFINE_DRAWING_MASK = Laya.Shader3D.getDefineByName("SHADERDEFINE_DRAWING_MASK");
                SkinMaterial.SHADERDEFINE_LAYER1_TEXTURE = Laya.Shader3D.getDefineByName("LAYER1_TEXTURE");
                SkinMaterial.SHADERDEFINE_CUSTOMCREAMCOLORTEXTURE = Laya.Shader3D.getDefineByName("CUSTOMCREAMCOLORTEXTURE");
            }
            static initShader() {
                SkinMaterial.__init__();
                var stateMap = {
                    's_Cull': Laya.Shader3D.RENDER_STATE_CULL,
                    's_Blend': Laya.Shader3D.RENDER_STATE_BLEND,
                    's_BlendSrc': Laya.Shader3D.RENDER_STATE_BLEND_SRC,
                    's_BlendDst': Laya.Shader3D.RENDER_STATE_BLEND_DST,
                    's_DepthTest': Laya.Shader3D.RENDER_STATE_DEPTH_TEST,
                    's_DepthWrite': Laya.Shader3D.RENDER_STATE_DEPTH_WRITE
                };
                var attributeMap = {
                    'a_Position': Laya.VertexMesh.MESH_POSITION0,
                    'a_Normal': Laya.VertexMesh.MESH_NORMAL0,
                    'a_Texcoord0': Laya.VertexMesh.MESH_TEXTURECOORDINATE0,
                    'a_Texcoord1': Laya.VertexMesh.MESH_TEXTURECOORDINATE1,
                    'a_BoneWeights': Laya.VertexMesh.MESH_BLENDWEIGHT0,
                    'a_BoneIndices': Laya.VertexMesh.MESH_BLENDINDICES0,
                    'a_MvpMatrix': Laya.VertexMesh.MESH_MVPMATRIX_ROW0,
                    'a_WorldMat': Laya.VertexMesh.MESH_WORLDMATRIX_ROW0
                };
                var uniformMap = {
                    'u_Bones': Laya.Shader3D.PERIOD_CUSTOM,
                    'u_MvpMatrix': Laya.Shader3D.PERIOD_SPRITE,
                    'u_WorldMat': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorTexture': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorParams': Laya.Shader3D.PERIOD_SPRITE,
                    'u_SimpleAnimatorTextureSize': Laya.Shader3D.PERIOD_SPRITE,
                    'u_CameraPos': Laya.Shader3D.PERIOD_CAMERA,
                    'u_AlphaTestValue': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_EmissionColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_NormalTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ParallaxTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_OcclusionTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_EmissionTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_Smoothness': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SmoothnessScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPOcclusionStrength': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPMetallic': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPSmoothness': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPMetallic2': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPSmoothness2': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPNoiseBump': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPNoiseBumpTiling': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPNoiseBumpBasicAO': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPShadowAtten': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPEmissionColorBack': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPEmissionColorBackIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPEmissionColorBackIntensity2': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPBorderOffsetAO': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_NormalScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ParallaxScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_MaskTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_MaskDetailTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_RampMapTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPRedTranslucency': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPRedTransShadow': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPRedTransNormalDistortion': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPRedTransScattering': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPRedTransDirect': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPRedTransAmbient': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPRed3SOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SPRed3SColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_CustomDirectLightColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightResultIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoTillingX': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoTillingY': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_specularIntensity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_gridTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_shineTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_gridTextureScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_shineTextureScale': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_gridTextureIsMultiply': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_shineTextureIsMultiply': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_controlDetailTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PlayerCustomChangeFlag': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ReflectTexture': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectIntensity': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientColor': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirationLightCount': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAr': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAg': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHAb': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBr': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBg': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHBb': Laya.Shader3D.PERIOD_SCENE,
                    'u_AmbientSHC': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectionProbe': Laya.Shader3D.PERIOD_SCENE,
                    'u_ReflectCubeHDRParams': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirectionLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_DirectionLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_PaintLayer1Texture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintLayer1TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintLayer2Texture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintLayer2TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_CustomColorSectionStep': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_CustomCreamColorTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FarPlaneWorldPositionZ': Laya.Shader3D.PERIOD_SCENE,
                };
                var PBRShadowCasterPS$1 = "#ifdef GL_FRAGMENT_PRECISION_HIGH\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
                var PBRShadowCasterVS$1 = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS =  shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
                var vs1 = `
        #include "Lighting.glsl";
        // #include "Shadow.glsl";
        // #include "PBRVSInput.glsl";
        //#include "PBRVertex.glsl";

        attribute vec4 a_Position;

        #ifdef GPU_INSTANCE
            attribute mat4 a_MvpMatrix;
            attribute mat4 a_WorldMat;
        #else
            uniform mat4 u_MvpMatrix;
            uniform mat4 u_WorldMat;
        #endif

        #ifdef BONE
            const int c_MaxBoneCount = 24;
            attribute vec4 a_BoneIndices;
            attribute vec4 a_BoneWeights;
            uniform mat4 u_Bones[c_MaxBoneCount];
        #endif
        attribute vec3 a_Normal;
        varying vec3 v_Normal; 

        #if defined(NORMALTEXTURE)||defined(PARALLAXTEXTURE)
            attribute vec4 a_Tangent0;
            varying vec3 v_Tangent;
            varying vec3 v_Binormal;
            // #ifdef PARALLAXTEXTURE
            //         varying vec3 v_ViewDirForParallax;
            // #endif
            #endif

        // #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)||(defined(LIGHTMAP)&&defined(UV))
            attribute vec2 a_Texcoord0;
            varying vec2 v_Texcoord0;
        // #endif

        uniform vec3 u_CameraPos;
        varying vec3 v_EyeVec;
        varying vec3 v_PositionWorld;
        varying vec3 v_Position;
        // varying float v_posViewZ;

        #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
            varying vec4 v_ShadowCoord;
        #endif

        #ifdef TILINGOFFSET
            uniform vec4 u_TilingOffset;
        #endif

        void vertexForward()
        {
            vec4 position;
            #ifdef BONE
                mat4 skinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;
                skinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;
                skinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;
                skinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;
                position=skinTransform*a_Position;
            #else
                position=a_Position;
            #endif

            #ifdef GPU_INSTANCE
                gl_Position = a_MvpMatrix * position;
            #else
                gl_Position = u_MvpMatrix * position;
            #endif

            mat4 worldMat;
            #ifdef GPU_INSTANCE
                worldMat = a_WorldMat;
            #else
                worldMat = u_WorldMat;
            #endif
            v_Position = position.xyz;
            v_PositionWorld=(worldMat*position).xyz;

            v_Texcoord0=a_Texcoord0;
            // #ifdef TILINGOFFSE
                // v_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);
            // #else
                // v_Texcoord0=a_Texcoord0;
            // #endif
// 
            v_EyeVec =u_CameraPos-v_PositionWorld;//will normalize per-pixel

            mat3 worldInvMat;
            #ifdef BONE
                worldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));
            #else
                worldInvMat=INVERSE_MAT(mat3(worldMat));
            #endif

            v_Normal=normalize(a_Normal*worldInvMat);//if no normalize will cause precision problem.

            #ifdef NORMALTEXTURE
                v_Tangent=normalize(a_Tangent0.xyz*worldInvMat);
                v_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;
            #endif

            #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
                v_ShadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
            #endif

        }
        
        void main()
        {
            vertexForward();
            gl_Position=remapGLPositionZ(gl_Position);
        }`;
                var ps1 = `
        #ifdef GL_FRAGMENT_PRECISION_HIGH
            precision highp float;
            precision highp int;
        #else
            precision mediump float;
            precision mediump int;
        #endif
        
        #include "Lighting.glsl";
        // #include "Shadow.glsl";
        #include "LayaPBRBRDF.glsl";
        #include "GlobalIllumination.glsl";

        #ifdef ALPHATEST
            uniform float u_AlphaTestValue;
        #endif

        uniform vec4 u_AlbedoColor;

        #ifdef NORMALTEXTURE
            uniform sampler2D u_NormalTexture;
            uniform float u_NormalScale;
        #endif

        #ifdef ALBEDOTEXTURE
            uniform sampler2D u_AlbedoTexture;
            vec4 albedoTextureColor;
        #endif

        #ifdef MASKTEXTURE
            uniform sampler2D u_MaskTexture;
            vec4 maskTextureColor;
        #endif
        #ifdef MASKDETAILTEXTURE
            uniform sampler2D u_MaskDetailTexture;
        #endif
        
        #ifdef RAMPMAPTEXTURE
            uniform sampler2D u_RampMapTexture; 
        #endif

        uniform vec3 u_SpecularColor;

        uniform float u_Smoothness;
        uniform float u_SmoothnessScale;

        // #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)
            varying vec2 v_Texcoord0;
        // #endif

        varying vec3 v_Normal; 

    //    #if defined(DIRECTIONLIGHT)

    //         #if defined(LEGACYSINGLELIGHTING)
                uniform DirectionLight u_SunLight;
            // #else
                uniform int u_DirationLightCount;
                uniform sampler2D u_LightBuffer;
        //     #endif
                
        // #endif

        varying vec3 v_EyeVec;
        varying vec3 v_PositionWorld;
        varying vec3 v_Position;

        #ifdef NORMALTEXTURE
            varying vec3 v_Tangent;
            varying vec3 v_Binormal;
        #endif

        #if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)
            varying vec4 v_ShadowCoord;

        #endif

        uniform float u_SPOcclusionStrength;
        uniform float u_SPMetallic;
        uniform float u_SPSmoothness;
        uniform float u_SPNoiseBump;
        uniform float u_SPNoiseBumpTiling;
        uniform float u_SPNoiseBumpBasicAO;
        uniform float u_SPShadowAtten;
        uniform vec4 u_SPEmissionColorBack;
        uniform float u_SPEmissionColorBackIntensity;
        
        uniform float u_SPBorderOffsetAO;

        uniform float u_FarPlaneWorldPositionZ;

        vec4 albedoRgba;

        #if defined(RAMPMAPTEXTURE)//&&defined(MASKTEXTURE)
            uniform float u_SPRedTranslucency;
            uniform float u_SPRedTransShadow;
            uniform float u_SPRedTransNormalDistortion;
            uniform float u_SPRedTransScattering;
            uniform float u_SPRedTransDirect;
            uniform float u_SPRedTransAmbient;
            uniform float u_SPRed3SOffset;
            uniform vec4 u_SPRed3SColor;
        
        #endif
	    uniform vec4 u_CustomDirectLightColor;

        uniform float u_LightResultIntensity;
        uniform float u_specularIntensity;
        uniform float u_AlbedoTillingX;
        uniform float u_AlbedoTillingY;
        #ifdef GRIDTEXTURE
            uniform sampler2D u_gridTexture;
            uniform float u_gridTextureScale;
            uniform float u_gridTextureIsMultiply;
        #endif
        #ifdef SHINETEXTURE
            uniform sampler2D u_shineTexture;
            uniform float u_shineTextureScale;
            uniform float u_shineTextureIsMultiply;
        #endif

        vec4 controlDetailColor;
        #ifdef CONTROLDETAILTEXTURE
            uniform sampler2D u_controlDetailTexture;
            
            uniform float u_SPMetallic2;
            uniform float u_SPSmoothness2;
            uniform float u_SPEmissionColorBackIntensity2;
        #endif

        uniform sampler2D u_PaintLayer1Texture;
		uniform vec4 u_PaintLayer1TilingOffset;
        // #ifdef MODELPROGRESSDATA
        //     uniform vec4 u_ModelProgressData;
        // #endif
        #ifdef CUSTOMCREAMCOLORTEXTURE 
            // uniform float u_CustomColorSection[288];
            uniform float u_CustomColorSectionStep;
            uniform sampler2D u_CustomCreamColorTexture;
        #endif

        mediump float lerpOneTo(mediump float b, mediump float t)
        {
            mediump float oneMinusT = 1.0 - t;
            return oneMinusT + b * t;
        }

        mediump float getOcclusion(vec2 uv)
        {
            #ifdef MASKTEXTURE
                mediump float occ = maskTextureColor.b;//texture2D(u_MaskTexture, uv).b;
                return lerpOneTo(occ, u_SPOcclusionStrength);
            #else
                return u_SPOcclusionStrength;
            #endif 
        }

        mediump vec4 albedo(vec2 uv)
        {
            #ifdef ALBEDOTEXTURE
                return u_AlbedoColor * albedoTextureColor;
            #else
                return u_AlbedoColor;
            #endif
            
        }
        mediump vec2 getMetallicGloss(vec2 uv,float customMetallic,float customSmoothness)
        {
            mediump vec2 ms;//x is metallic,y is smoothness
            //lhcadd
            
            #ifdef MASKTEXTURE
                //vec4 maskRgb = texture2D(u_MaskTexture, uv);
                ms.y =maskTextureColor.r*customSmoothness;

                ms.x =maskTextureColor.g*customMetallic;;//ms.x =maskTextureColor.g*customMetallic;
            #else 
                ms.y = customSmoothness;

                ms.x =customMetallic;//0.7639677;//0.7639677/2.0;
            #endif
            
            return ms;
        }

        mediump vec3 unpackScaleNormal(mediump vec3 packednormal, mediump float bumpScale)
        {
            mediump vec3 normal = packednormal.xyz * 2.0 - 1.0;
            normal.y=-normal.y;//NOTE:because unity to LayaAir coordSystem.
            normal.xy *= bumpScale;
            return normal;
        }
        
        vec3 lerpVec3(vec3 a, vec3 b, float w) {
            if(w<=0.0){
                return a;
            }else if(w>=1.0){
                return b;
            }else{
                return w*b +(1.0-w)*a;
            }
        }
        
        #ifdef NORMALTEXTURE
            
            mediump vec3 normalInTangentSpace(vec2 texcoords)
            {
                mediump vec3 normalTangent = unpackScaleNormal(texture2D(u_NormalTexture, texcoords).rgb,u_NormalScale);
                
                //这里让阴影左移，边缘留光
                #if defined(MASKTEXTURE) && defined(MASKDETAILTEXTURE)
                    float _NoiseBump = u_SPNoiseBump;//0.3;
                    vec3 color93 = vec3(0.5019608,0.5019608,1.0) ;//////////: vec4(0.2158605,0.2158605,1,0);
                    vec2 detailTexcoords=TransformUV(texcoords,vec4(u_SPNoiseBumpTiling,u_SPNoiseBumpTiling,0.0,0.0));
                    vec4 tex2DNode60 = texture2D( u_MaskDetailTexture, detailTexcoords );
                    float lerpRatio =  clamp( ( _NoiseBump * ( 1.0 - ( maskTextureColor.g * u_SPNoiseBumpBasicAO ) ) ) ,0.0,1.0);
                    vec3 lerpResult94 = lerpVec3( color93 , tex2DNode60.rgb ,lerpRatio);
                    vec3 appendResult78 = (vec3(( normalTangent.r + lerpResult94.r ) , ( lerpResult94.g + normalTangent.g ) , ( normalTangent.b + tex2DNode60.b )));
                    vec3 normalizeResult85 = normalize( ( 2.0 * appendResult78 ) + u_SPBorderOffsetAO );
                   
                    normalTangent = normalizeResult85;
                
                #endif
                
                
                return normalTangent;
            }
        #endif

        struct FragmentCommonData{
            vec3 diffColor;
            vec3 specColor;
            float oneMinusReflectivity;
            float smoothness;
        };
        
        const mediump vec4 dielectricSpecularColor = vec4(0.220916301, 0.220916301, 0.220916301, 1.0 - 0.220916301);
        
        mediump vec3 diffuseAndSpecularFromMetallic(mediump vec3 albedo,mediump float metallic, out mediump vec3 specColor, out mediump float oneMinusReflectivity)
        {
                specColor = mix(dielectricSpecularColor.rgb, albedo, metallic);
            oneMinusReflectivity= dielectricSpecularColor.a*(1.0-metallic);//diffuse proportion
            return albedo * oneMinusReflectivity;
        }
        
        mediump float specularStrength(mediump vec3 specular)
        {
            return max (max (specular.r, specular.g), specular.b);
        }
        
        // Diffuse/Spec Energy conservation
        mediump vec3 energyConservationBetweenDiffuseAndSpecular (mediump vec3 albedo, mediump vec3 specColor, out mediump float oneMinusReflectivity)
        {
                oneMinusReflectivity = 1.0 - specularStrength(specColor);
            return albedo * (vec3(1.0) - specColor);
        }
        
        #ifdef TRANSPARENTBLEND
            mediump vec3 preMultiplyAlpha (mediump vec3 diffColor, mediump float alpha, mediump float oneMinusReflectivity,out mediump float modifiedAlpha)
            {
                // Transparency 'removes' from Diffuse component
                diffColor *= alpha;
                // Reflectivity 'removes' from the rest of components, including Transparency
                // modifiedAlpha = 1.0-(1.0-alpha)*(1.0-reflectivity) = 1.0-(oneMinusReflectivity - alpha*oneMinusReflectivity) = 1.0-oneMinusReflectivity + alpha*oneMinusReflectivity
                modifiedAlpha = 1.0 - oneMinusReflectivity + alpha*oneMinusReflectivity;
                return diffColor;
            }
        #endif
        
        FragmentCommonData metallicSetup(vec2 uv,float customMetallic,float customSmoothness)
        {
            mediump vec2 metallicGloss = getMetallicGloss(uv,customMetallic,customSmoothness);
            mediump float metallic = metallicGloss.x;
            mediump float smoothness = metallicGloss.y; // this is 1 minus the square root of real roughness m.
            mediump float oneMinusReflectivity;
            mediump vec3 specColor;
            mediump vec3 diffColor = diffuseAndSpecularFromMetallic(albedoRgba.rgb, metallic,/*out*/specColor,/*out*/oneMinusReflectivity);
        
            FragmentCommonData o;
            o.diffColor = diffColor;
            o.specColor = specColor;
            o.oneMinusReflectivity = oneMinusReflectivity;
            o.smoothness = smoothness;
            return o;
        }
        
        LayaGI fragmentGI(float smoothness,vec3 eyeVec,mediump float occlusion,mediump vec2 lightmapUV,vec3 worldnormal)
        {
            LayaGIInput giInput;
        
            vec3 worldViewDir = -eyeVec;
            mediump vec4 uvwRoughness;
            uvwRoughness.rgb = reflect(worldViewDir, worldnormal);//reflectUVW
            uvwRoughness.a= smoothnessToPerceptualRoughness(smoothness);//perceptualRoughness
        
            return layaGlobalIllumination(giInput,occlusion, worldnormal, uvwRoughness);
        }
        
        vec3 perPixelWorldNormalByNormalTanget(vec2 uv,vec3 normal,vec3 binormal,vec3 tangent,vec3 normalTangent)
        {
            #ifdef NORMALTEXTURE
                vec3 normalWorld = normalize(tangent * normalTangent.x + binormal * normalTangent.y + normal * normalTangent.z);
            #else
                vec3 normalWorld = normalize(normal);
            #endif
                return normalWorld;
        }
        
        void main_paint_mask(){
			gl_FragColor = vec4(v_Texcoord0.xy,0.0,1.0);
        }

        void fragmentForward()
        {
            vec2 uv;
            // #if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)
                uv=TransformUV(v_Texcoord0,vec4(u_AlbedoTillingX,u_AlbedoTillingY,0.0,0.0));
            // #endif

            #ifdef ALBEDOTEXTURE
                albedoTextureColor = texture2D(u_AlbedoTexture,uv);
            #endif
            
            albedoRgba = albedo(uv);
            // mediump float alpha = getAlpha(uv);
            #ifdef ALPHATEST
                if(albedoRgba.a<u_AlphaTestValue)
                    discard;
            #endif

            #ifdef FARPLANEWORLDPOSITIONZ
                if(v_PositionWorld.z < u_FarPlaneWorldPositionZ){
                    discard;
                }
            #endif
            // if(v_PositionWorld.z < -10.0){
            //     discard;
            // }

            #ifdef MASKTEXTURE
                maskTextureColor = texture2D(u_MaskTexture,uv);
            #endif

            vec3 lightDir = normalize(u_SunLight.direction);
            
            vec3 binormal;
            vec3 tangent;
            vec3 normal = v_Normal;
            vec3 normalTangent;

            #ifdef NORMALTEXTURE
                tangent = v_Tangent;
                binormal = v_Binormal;
           
                normalTangent=normalInTangentSpace(uv);
            #else
                normalTangent = normalize(normal);
            #endif

            vec3 normalWorld = perPixelWorldNormalByNormalTanget(uv,normal,binormal,tangent,normalTangent);//In FS if the normal use mediump before normalize will cause precision prolem in mobile device.
            vec3 eyeVec = normalize(v_EyeVec);
            vec4 color = vec4(0.0);
           
            #ifdef CUSTOMCREAMCOLORTEXTURE

                vec2 texcoordCreamColor = vec2(0.5,1.0-uv.y);
                // vec2 texcoordCreamColor = vec2(mod(colorIndex, 64.0)/64.0, floor(colorIndex / 64.0)/64.0);
                // vec2 texcoordCreamColor = TransformUV(texcoordCreamColor0, vec4(1.0,1.0,0.0,0.0));
                vec4 creamColor = texture2D(u_CustomCreamColorTexture, texcoordCreamColor);

                float flag = step(0.01,creamColor.a);
                vec3 tmpColor = (creamColor.rgb) * flag;
                
                albedoRgba.rgb = tmpColor.rgb + step(1.0,1.0-flag)*albedoRgba.rgb;

            #endif
            #ifdef LAYER1_TEXTURE
                vec2 texcoordL1 = TransformUV(uv, u_PaintLayer1TilingOffset);
                vec4 paintLayer1Color = texture2D(u_PaintLayer1Texture, texcoordL1);

                albedoRgba.rgb = albedoRgba.rgb * (1.0 - paintLayer1Color.a) + paintLayer1Color.rgb;
				albedoRgba.a = albedoRgba.a * (1.0 - paintLayer1Color.a) + paintLayer1Color.a;

            #endif

            #ifdef CONTROLDETAILTEXTURE
            
                controlDetailColor =texture2D(u_controlDetailTexture, uv);

                #ifdef GRIDTEXTURE
                    vec2 tmpCoord1=TransformUV(uv,vec4(u_gridTextureScale,u_gridTextureScale,0.0,0.0));
                   
                    vec4 gridColor =texture2D(u_gridTexture, tmpCoord1);
                    gridColor = gridColor * controlDetailColor.b;

                    // albedoRgba.rgb = albedoRgba.rgb * (1.0 - gridColor.a) + gridColor.rgb;
                    // albedoRgba.a = albedoRgba.a * (1.0 - gridColor.a) + gridColor.a * gridColor.a;

                    float flagGridTexture = step(0.5,u_gridTextureIsMultiply);

                    //vec4 multiplyGridRgba = (albedoRgba+gridColor)*flagGridTexture;

                    vec4 ifflagGrid = vec4( step(albedoRgba.r,0.5),step(albedoRgba.g,0.5),step(albedoRgba.b,0.5),step(albedoRgba.a,0.5) );
                    vec4 multiplyGridRgba = (ifflagGrid*albedoRgba*gridColor*2.0+(vec4(1.0,1.0,1.0,1.0)-ifflagGrid)*(vec4(1.0,1.0,1.0,1.0)-(vec4(1.0,1.0,1.0,1.0)-albedoRgba)*(vec4(1.0,1.0,1.0,1.0)-gridColor)*2.0))*flagGridTexture;
                    
                    vec4 commonGridRgba = vec4(0.0);
                    commonGridRgba.rgb = albedoRgba.rgb * (1.0 - gridColor.a) + gridColor.rgb;
                    commonGridRgba.a = albedoRgba.a * (1.0 - gridColor.a) + gridColor.a * gridColor.a;
                    commonGridRgba = commonGridRgba * (1.0-flagGridTexture);

                    albedoRgba = commonGridRgba + multiplyGridRgba;

                #endif

                #ifdef SHINETEXTURE
                    vec2 tmpCoord2=TransformUV(uv,vec4(u_shineTextureScale,u_shineTextureScale,0.0,0.0));
                    vec4 shineColor =texture2D(u_shineTexture, tmpCoord2);
                    
                    float nl = max(dot(normal, -lightDir), 0.0);
                    float shadow_boundary = 0.2 + 0.01;
                    float shadow_allin = step(nl, 0.3 - shadow_boundary*0.5);
                    float shadow_partin = step(nl, 0.3 + shadow_boundary*0.5);
                    float shadow = shadow_allin + (0.3 + shadow_boundary*0.5 - nl)/shadow_boundary * (shadow_partin - shadow_allin);

                    shadow *= 0.1;
                    
                    float specular = pow(nl,10.0);
                    vec3 speculAreaColor = (1.0 - shadow) * shineColor.rgb * 1.0 * specular * vec4(1.0,1.0,1.0,1.0).rgb ;

                    shineColor.rgb +=speculAreaColor;

                    shineColor = shineColor * controlDetailColor.g;

                    // albedoRgba.rgb = albedoRgba.rgb * (1.0 - shineColor.a) + shineColor.rgb;
                    // albedoRgba.a = albedoRgba.a * (1.0 - shineColor.a) + shineColor.a * shineColor.a;

                    float flagShineTexture = step(0.5,u_shineTextureIsMultiply);

                    // vec4 multiplyShineRgba = (albedoRgba+shineColor)*flagShineTexture;
                    vec4 ifflagShine = vec4( step(albedoRgba.r,0.5),step(albedoRgba.g,0.5),step(albedoRgba.b,0.5),step(albedoRgba.a,0.5) );
                    vec4 multiplyShineRgba = (ifflagShine*albedoRgba*shineColor*2.0+(vec4(1.0,1.0,1.0,1.0)-ifflagShine)*(vec4(1.0,1.0,1.0,1.0)-(vec4(1.0,1.0,1.0,1.0)-albedoRgba)*(vec4(1.0,1.0,1.0,1.0)-shineColor)*2.0))*flagShineTexture;
                    

                    vec4 commonShineRgba = vec4(0.0);
                    commonShineRgba.rgb = albedoRgba.rgb * (1.0 - shineColor.a) + shineColor.rgb;
                    commonShineRgba.a = albedoRgba.a * (1.0 - shineColor.a) + shineColor.a * shineColor.a;
                    commonShineRgba = commonShineRgba * (1.0-flagShineTexture);

                    albedoRgba = commonShineRgba + multiplyShineRgba;
                    
                #endif

                
            #endif


            if(controlDetailColor.r>0.0){
                #ifdef CONTROLDETAILTEXTURE
                    float _AnisoOffset = -u_SPMetallic2;
                    float Specular=u_SPSmoothness2;
                    
                    float HdotA = dot(normalize(normal), -lightDir);
                    float aniso = max(0.0, sin(radians((HdotA + _AnisoOffset) * 180.0)));
                    float spec = min(max(pow(aniso, 128.0) * Specular,0.0),1.0);
                    color.rgb = albedoRgba.rgb * u_SPEmissionColorBackIntensity2 + spec ;
                #endif
            }else{
                FragmentCommonData o = metallicSetup(uv,u_SPMetallic,u_SPSmoothness);
            
                #ifdef TRANSPARENTBLEND
                    o.diffColor=preMultiplyAlpha(o.diffColor,albedoRgba.a,o.oneMinusReflectivity,/*out*/albedoRgba.a);// shader relies on pre-multiply alpha-blend (srcBlend = One, dstBlend = OneMinusSrcAlpha)
                #endif
    
                mediump float occlusion = getOcclusion(uv);
                mediump vec2 lightMapUV;
               
                float perceptualRoughness = smoothnessToPerceptualRoughness(o.smoothness);
                float roughness = perceptualRoughnessToRoughness(perceptualRoughness);
                float nv = abs(dot(normalWorld, eyeVec));
                LayaGI gi =fragmentGI(o.smoothness,eyeVec,occlusion,lightMapUV,normalWorld);
                color = LAYA_BRDF_GI(o.diffColor,o.specColor,o.oneMinusReflectivity,o.smoothness,perceptualRoughness,roughness,nv,normalWorld,eyeVec,gi);
                
    
                o.specColor*=u_specularIntensity;
    
                vec4 lightResultColor = vec4(0.0,0.0,0.0,0.0);
    
                // #ifdef DIRECTIONLIGHT
                //     #if defined(LEGACYSINGLELIGHTING)
                //         #ifdef CALCULATE_SHADOWS
                        
                //                 #ifdef SHADOW_CASCADE
                //                     vec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
                //                 #else
                //                     vec4 shadowCoord = v_ShadowCoord;
                //                 #endif
                //                 sampleShadowmap(shadowCoord);
                            
                //         #endif
                //         DirectionLight directionLight;
                //         directionLight.color=u_SunLight.color;
                //         directionLight.direction = u_SunLight.direction;
        
                //         LayaLight dirLight = layaDirectionLightToLight(directionLight,1.0);
                //         dirLight.color = u_CustomDirectLightColor.rgb;
                //         lightResultColor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);
        
                //     #else
                        // for (int i = 0; i < MAX_LIGHT_COUNT; i++) 
                        // {
                        //     float shadowAttenuation = 1.0;
                        //     if(i >= u_DirationLightCount)
                        //         break;
                        //     #ifdef CALCULATE_SHADOWS
                        //         if(i == 0)
                        //         {
                        //             #ifdef SHADOW_CASCADE
                        //                 vec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));
                        //             #else
                        //                 vec4 shadowCoord = v_ShadowCoord;
                        //             #endif
                        //             shadowAttenuation *= sampleShadowmap(shadowCoord);
                        //         }
                        //     #endif
                        //     DirectionLight directionLight = getDirectionLight(u_LightBuffer,i);
                        //     LayaLight dirLight = layaDirectionLightToLight(directionLight,shadowAttenuation*u_SPShadowAtten);
                        //     if(i==0){
                        //         dirLight.color = u_CustomDirectLightColor.rgb;
                        //     }
                        //     lightResultColor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);
        
                        // }
                        DirectionLight directionLight;
                        directionLight.color = u_SunLight.color;
                        directionLight.direction = u_SunLight.direction;

                        LayaLight dirLight = layaDirectionLightToLight(directionLight,u_SPShadowAtten);
                        dirLight.color = u_CustomDirectLightColor.rgb;
                        lightResultColor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);
                //     #endif
                // #endif
                    
                color += vec4( max(lightResultColor.r,albedoRgba.r*u_LightResultIntensity),max(lightResultColor.g,albedoRgba.g*u_LightResultIntensity),max(lightResultColor.b,albedoRgba.b*u_LightResultIntensity),lightResultColor.a );
            
                vec3 emissionColorBack = u_SPEmissionColorBack.rgb;
                
                float emissionClampRatio = u_SPEmissionColorBackIntensity;
                vec3 emissionColorResult = ( ( 1.0 - emissionClampRatio ) * albedoRgba.rgb * emissionColorBack ).rgb;
                color.rgb += emissionColorResult;
                
                #if defined(RAMPMAPTEXTURE)//&&defined(MASKTEXTURE)
                    
                    vec3 lightColor=vec3(0.0, 0.0, 0.0);
                    
                    vec3 emissionWorldNormal = perPixelWorldNormalByNormalTanget(uv,normal,binormal,tangent,vec3( 0.0, 0.0, 1.0 ));
                    float dotResult32 = dot( lightDir , emissionWorldNormal );//lightDir
                    float tempOutValue = clamp( (dotResult32*u_SPRed3SOffset + 0.5),0.0,1.0 );
                    
                    vec2 tempCastUv = vec2(tempOutValue,tempOutValue);
    
                    vec4 tex2dNodeRamp = texture2D(u_RampMapTexture, tempCastUv);
    
                    vec4 customTranslucencyBasicColor = u_SPRed3SColor * tex2dNodeRamp * (dotResult32*0.85 + 0.27);
                    vec3 customTranslucencyColor = vec3(clamp( customTranslucencyBasicColor.r,0.0,1.0 ),clamp( customTranslucencyBasicColor.g,0.0,1.0 ),clamp( customTranslucencyBasicColor.b,0.0,1.0 ));
    
    
                    vec3 lightColorCaculated =  lerpVec3(lightColor.rgb, vec3(1.0,1.0,1.0), u_SPRedTransShadow );
                    vec3 lightDirCaculated = lightDir + normalTangent * u_SPRedTransNormalDistortion;
                    float transVdotL = pow( clamp( dot( eyeVec, -lightDirCaculated ),0.0,1.0 ), u_SPRedTransScattering );
                    vec3 translucency = lightColorCaculated * (transVdotL * u_SPRedTransDirect + o.oneMinusReflectivity * u_SPRedTransAmbient) * customTranslucencyColor;
                    vec4 c = vec4(albedoRgba.rgb * translucency * u_SPRedTranslucency,0.0);
                    color+=c;
                #endif
            }


            
            // #ifdef MODELPROGRESSDATA

            //     // u_ModelProgressData
            //     float progress = u_ModelProgressData.x;
            //     // float startValue = u_ModelProgressData.y;
            //     // float endValue = u_ModelProgressData.z;
            //     // float pType = u_ModelProgressData.w;

            //     // if(v_PositionWorld.y>progress){

            //         float flag = step(progress,v_PositionWorld.y);
            //         color.rgb = vec3(0.6,0.31,0.82) * flag + color.rgb*(1.0-flag);
            //     // }
            // #endif

            gl_FragColor=vec4(color.rgb,albedoRgba.a);
        }

        void main()
        {
            #ifdef SHADERDEFINE_DRAWING_MASK
				main_paint_mask();
			#else
                fragmentForward();
            #endif
        }`;
                var shader3D = Laya.Shader3D.add("SkinShader", attributeMap, uniformMap, true);
                var subShader = new Laya.SubShader(attributeMap, uniformMap);
                shader3D.addSubShader(subShader);
                subShader.addShaderPass(vs1, ps1, stateMap, "Forward");
                if (Const.bHighShadowQuality) {
                    subShader.addShaderPass(PBRShadowCasterVS$1, PBRShadowCasterPS$1, stateMap, "ShadowCaster");
                }
            }
            get albedoTexture() {
                return this._shaderValues.getTexture(SkinMaterial.ALBEDOTEXTURE);
            }
            set albedoTexture(value) {
                if (value)
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_ALBEDOTEXTURE);
                else
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_ALBEDOTEXTURE);
                this._shaderValues.setTexture(SkinMaterial.ALBEDOTEXTURE, value);
            }
            get normalTextureScale() {
                return this._shaderValues.getNumber(SkinMaterial.NORMALTEXTURESCALE);
            }
            set normalTextureScale(value) {
                value = this.clampKeyValueByKey(SkinMaterial.NORMALTEXTURESCALE, value);
                this._shaderValues.setNumber(SkinMaterial.NORMALTEXTURESCALE, value);
            }
            get maskTexture() {
                return this._shaderValues.getTexture(SkinMaterial.MASKTEXTURE);
            }
            set maskTexture(value) {
                if (value)
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_MASKTEXTURE);
                else
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_MASKTEXTURE);
                this._shaderValues.setTexture(SkinMaterial.MASKTEXTURE, value);
            }
            get maskDetailTexture() {
                return this._shaderValues.getTexture(SkinMaterial.MASKDETAILTEXTURE);
            }
            set maskDetailTexture(value) {
                if (value)
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_MASKDETAILTEXTURE);
                else
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_MASKDETAILTEXTURE);
                this._shaderValues.setTexture(SkinMaterial.MASKDETAILTEXTURE, value);
            }
            get rampMapTexture() {
                return this._shaderValues.getTexture(SkinMaterial.RAMPMAPTEXTURE);
            }
            set rampMapTexture(value) {
                if (value)
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_RAMPMAPTEXTURE);
                else
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_RAMPMAPTEXTURE);
                this._shaderValues.setTexture(SkinMaterial.RAMPMAPTEXTURE, value);
            }
            get gridTexture() {
                return this._shaderValues.getTexture(SkinMaterial.GRIDTEXTURE);
            }
            set gridTexture(value) {
                if (value)
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_GRIDTEXTURE);
                else
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_GRIDTEXTURE);
                this._shaderValues.setTexture(SkinMaterial.GRIDTEXTURE, value);
            }
            get shineTexture() {
                return this._shaderValues.getTexture(SkinMaterial.SHINETEXTURE);
            }
            set shineTexture(value) {
                if (value)
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_SHINETEXTURE);
                else
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_SHINETEXTURE);
                this._shaderValues.setTexture(SkinMaterial.SHINETEXTURE, value);
            }
            get gridTextureScale() {
                return this._shaderValues.getNumber(SkinMaterial.GRIDTEXTURESCALE);
            }
            set gridTextureScale(value) {
                value = this.clampKeyValueByKey(SkinMaterial.GRIDTEXTURESCALE, value);
                this._shaderValues.setNumber(SkinMaterial.GRIDTEXTURESCALE, value);
            }
            get shineTextureScale() {
                return this._shaderValues.getNumber(SkinMaterial.SHINETEXTURESCALE);
            }
            set shineTextureScale(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SHINETEXTURESCALE, value);
                this._shaderValues.setNumber(SkinMaterial.SHINETEXTURESCALE, value);
            }
            get gridTextureIsMultiply() {
                return this._shaderValues.getNumber(SkinMaterial.GRIDTEXTUREISMULTIPLY);
            }
            set gridTextureIsMultiply(value) {
                value = this.clampKeyValueByKey(SkinMaterial.GRIDTEXTUREISMULTIPLY, value);
                this._shaderValues.setNumber(SkinMaterial.GRIDTEXTUREISMULTIPLY, value);
            }
            get shineTextureIsMultiply() {
                return this._shaderValues.getNumber(SkinMaterial.SHINETEXTUREISMULTIPLY);
            }
            set shineTextureIsMultiply(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SHINETEXTUREISMULTIPLY, value);
                this._shaderValues.setNumber(SkinMaterial.SHINETEXTUREISMULTIPLY, value);
            }
            get controlDetailTexture() {
                return this._shaderValues.getTexture(SkinMaterial.CONTROLDETAILTEXTURE);
            }
            set controlDetailTexture(value) {
                if (value)
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_CONTROLDETAILTEXTURE);
                else
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_CONTROLDETAILTEXTURE);
                this._shaderValues.setTexture(SkinMaterial.CONTROLDETAILTEXTURE, value);
            }
            get shadowColor() {
                return this._shaderValues.getVector(SkinMaterial.SHADOWCOLOR);
            }
            set shadowColor(value) {
                this._shaderValues.setVector(SkinMaterial.SHADOWCOLOR, value);
            }
            get shadowRange() {
                return this._shaderValues.getNumber(SkinMaterial.SHADOWRANGE);
            }
            set shadowRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.SHADOWRANGE, value);
            }
            get shadowIntensity() {
                return this._shaderValues.getNumber(SkinMaterial.SHADOWINTENSITY);
            }
            set shadowIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.SHADOWINTENSITY, value);
            }
            get shadowBoundary() {
                return this._shaderValues.getNumber(SkinMaterial.SHADOWBOUNDARY);
            }
            set shadowBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.SHADOWBOUNDARY, value);
            }
            get specularRange() {
                return this._shaderValues.getNumber(SkinMaterial.SPECULARRANGE);
            }
            set specularRange(value) {
                value = Math.max(0.9, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.SPECULARRANGE, value);
            }
            set specularIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.SPECULARINTENSITY, value);
            }
            get specularIntensity() {
                return this._shaderValues.getNumber(SkinMaterial.SPECULARINTENSITY);
            }
            get specularColor() {
                return this._shaderValues.getVector(SkinMaterial.SPECULARCOLOR);
            }
            set specularColor(value) {
                this._shaderValues.setVector(SkinMaterial.SPECULARCOLOR, value);
            }
            get outlineWidth() {
                return this._shaderValues.getNumber(SkinMaterial.OUTLINEWIDTH);
            }
            set outlineWidth(value) {
                value = Math.max(0.0, Math.min(0.05, value));
                this._shaderValues.setNumber(SkinMaterial.OUTLINEWIDTH, value);
            }
            get outlineColor() {
                return this._shaderValues.getVector(SkinMaterial.OUTLINECOLOR);
            }
            set outlineColor(value) {
                this._shaderValues.setVector(SkinMaterial.OUTLINECOLOR, value);
            }
            get outlineLightness() {
                return this._shaderValues.getNumber(SkinMaterial.OUTLINELIGHTNESS);
            }
            set outlineLightness(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.OUTLINELIGHTNESS, value);
            }
            get secondShadowColor() {
                return this._shaderValues.getVector(SkinMaterial.SECOND_SHADOWCOLOR);
            }
            set secondShadowColor(value) {
                this._shaderValues.setVector(SkinMaterial.SECOND_SHADOWCOLOR, value);
            }
            get secondShadowRange() {
                return this._shaderValues.getNumber(SkinMaterial.SECOND_SHADOWRANGE);
            }
            set secondShadowRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.SECOND_SHADOWRANGE, value);
            }
            get secondShadowIntensity() {
                return this._shaderValues.getNumber(SkinMaterial.SECOND_SHADOWINTENSITY);
            }
            set secondShadowIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.SECOND_SHADOWINTENSITY, value);
            }
            get secondShadowBoundary() {
                return this._shaderValues.getNumber(SkinMaterial.SECOND_SHADOWBOUNDARY);
            }
            set secondShadowBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.SECOND_SHADOWBOUNDARY, value);
            }
            get EdgeHightColor() {
                return this._shaderValues.getVector(SkinMaterial.EDGE_HIGHLIGHT_COLOR);
            }
            set EdgeHightColor(value) {
                this._shaderValues.setVector(SkinMaterial.EDGE_HIGHLIGHT_COLOR, value);
            }
            get EdgeHightRange() {
                return this._shaderValues.getNumber(SkinMaterial.EDGE_HIGHLIGHT_RANGE);
            }
            set EdgeHightRange(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.EDGE_HIGHLIGHT_RANGE, value);
            }
            get EdgeHightIntensity() {
                return this._shaderValues.getNumber(SkinMaterial.EDGE_HIGHLIGHT_INTENSITY);
            }
            set EdgeHightIntensity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.EDGE_HIGHLIGHT_INTENSITY, value);
            }
            get EdgeHightBoundary() {
                return this._shaderValues.getNumber(SkinMaterial.EDGE_HIGHLIGHT_BOUNDARY);
            }
            set EdgeHightBoundary(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(SkinMaterial.EDGE_HIGHLIGHT_BOUNDARY, value);
            }
            get SPOcclusionStrength() {
                return this._shaderValues.getNumber(SkinMaterial.SPOCCLUSIONSTRENGTH);
            }
            set SPOcclusionStrength(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPOCCLUSIONSTRENGTH, value);
                this._shaderValues.setNumber(SkinMaterial.SPOCCLUSIONSTRENGTH, value);
            }
            get SPMetallic() {
                return this._shaderValues.getNumber(SkinMaterial.SPMETALLIC);
            }
            set SPMetallic(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPMETALLIC, value);
                this._shaderValues.setNumber(SkinMaterial.SPMETALLIC, value);
            }
            get SPSmoothness() {
                return this._shaderValues.getNumber(SkinMaterial.SPSMOOTHNESS);
            }
            set SPSmoothness(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPSMOOTHNESS, value);
                this._shaderValues.setNumber(SkinMaterial.SPSMOOTHNESS, value);
            }
            get SPMetallic2() {
                return this._shaderValues.getNumber(SkinMaterial.SPMETALLIC2);
            }
            set SPMetallic2(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPMETALLIC2, value);
                this._shaderValues.setNumber(SkinMaterial.SPMETALLIC2, value);
            }
            get SPSmoothness2() {
                return this._shaderValues.getNumber(SkinMaterial.SPSMOOTHNESS2);
            }
            set SPSmoothness2(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPSMOOTHNESS2, value);
                this._shaderValues.setNumber(SkinMaterial.SPSMOOTHNESS2, value);
            }
            get SPNoiseBump() {
                return this._shaderValues.getNumber(SkinMaterial.SPNOISEBUMP);
            }
            set SPNoiseBump(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPNOISEBUMP, value);
                this._shaderValues.setNumber(SkinMaterial.SPNOISEBUMP, value);
            }
            get SPNoiseBumpTiling() {
                return this._shaderValues.getNumber(SkinMaterial.SPNOISEBUMPTILING);
            }
            set SPNoiseBumpTiling(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPNOISEBUMPTILING, value);
                this._shaderValues.setNumber(SkinMaterial.SPNOISEBUMPTILING, value);
            }
            get SPNoiseBumpBasicAO() {
                return this._shaderValues.getNumber(SkinMaterial.SPNOISEBUMPBASICAO);
            }
            set SPNoiseBumpBasicAO(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPNOISEBUMPBASICAO, value);
                this._shaderValues.setNumber(SkinMaterial.SPNOISEBUMPBASICAO, value);
            }
            get SPShadowAtten() {
                return this._shaderValues.getNumber(SkinMaterial.SPSHADOWATTEN);
            }
            set SPShadowAtten(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPSHADOWATTEN, value);
                this._shaderValues.setNumber(SkinMaterial.SPSHADOWATTEN, value);
            }
            get SPEmissionColorBack() {
                return this._shaderValues.getVector(SkinMaterial.SPEMISSIONCOLORBACK);
            }
            set SPEmissionColorBack(value) {
                this._shaderValues.setVector(SkinMaterial.SPEMISSIONCOLORBACK, value);
            }
            get SPEmissionColorBackIntensity() {
                return this._shaderValues.getNumber(SkinMaterial.SPEMISSIONCOLORBACKINTENSITY);
            }
            set SPEmissionColorBackIntensity(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPEMISSIONCOLORBACKINTENSITY, value);
                this._shaderValues.setNumber(SkinMaterial.SPEMISSIONCOLORBACKINTENSITY, value);
            }
            get SPBorderOffsetAO() {
                return this._shaderValues.getNumber(SkinMaterial.SPBORDEROFFSETAO);
            }
            set SPBorderOffsetAO(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPBORDEROFFSETAO, value);
                this._shaderValues.setNumber(SkinMaterial.SPBORDEROFFSETAO, value);
            }
            get SPEmissionColorBackIntensity2() {
                return this._shaderValues.getNumber(SkinMaterial.SPEMISSIONCOLORBACKINTENSITY2);
            }
            set SPEmissionColorBackIntensity2(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPEMISSIONCOLORBACKINTENSITY2, value);
                this._shaderValues.setNumber(SkinMaterial.SPEMISSIONCOLORBACKINTENSITY2, value);
            }
            get SPRedTranslucency() {
                return this._shaderValues.getNumber(SkinMaterial.SPREDTRANSLUCENCY);
            }
            set SPRedTranslucency(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPREDTRANSLUCENCY, value);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSLUCENCY, value);
            }
            get SPRedTransShadow() {
                return this._shaderValues.getNumber(SkinMaterial.SPREDTRANSSHADOW);
            }
            set SPRedTransShadow(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPREDTRANSSHADOW, value);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSSHADOW, value);
            }
            get SPRedTransNormalDistortion() {
                return this._shaderValues.getNumber(SkinMaterial.SPREDTRANSNORMALDISTORTION);
            }
            set SPRedTransNormalDistortion(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPREDTRANSNORMALDISTORTION, value);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSNORMALDISTORTION, value);
            }
            get SPRedTransScattering() {
                return this._shaderValues.getNumber(SkinMaterial.SPREDTRANSSCATTERING);
            }
            set SPRedTransScattering(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPREDTRANSSCATTERING, value);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSSCATTERING, value);
            }
            get SPRedTransDirect() {
                return this._shaderValues.getNumber(SkinMaterial.SPREDTRANSDIRECT);
            }
            set SPRedTransDirect(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPREDTRANSDIRECT, value);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSDIRECT, value);
            }
            get SPRedTransAmbient() {
                return this._shaderValues.getNumber(SkinMaterial.SPREDTRANSAMBIENT);
            }
            set SPRedTransAmbient(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPREDTRANSAMBIENT, value);
                this._shaderValues.setNumber(SkinMaterial.SPREDTRANSAMBIENT, value);
            }
            get SPRed3SOffset() {
                return this._shaderValues.getNumber(SkinMaterial.SPRED3SOFFSET);
            }
            set SPRed3SOffset(value) {
                value = this.clampKeyValueByKey(SkinMaterial.SPRED3SOFFSET, value);
                this._shaderValues.setNumber(SkinMaterial.SPRED3SOFFSET, value);
            }
            get SPRed3SColor() {
                return this._shaderValues.getVector(SkinMaterial.SPRED3SCOLOR);
            }
            set SPRed3SColor(value) {
                this._shaderValues.setVector(SkinMaterial.SPRED3SCOLOR, value);
            }
            get CustomDirectLightColor() {
                return this._shaderValues.getVector(SkinMaterial.CUSTOMDIRECTLIGHTCOLOR);
            }
            set CustomDirectLightColor(value) {
                this._shaderValues.setVector(SkinMaterial.CUSTOMDIRECTLIGHTCOLOR, value);
            }
            get LightResultIntensity() {
                return this._shaderValues.getNumber(SkinMaterial.LIGHTRESULTINTENSITY);
            }
            set LightResultIntensity(value) {
                value = this.clampKeyValueByKey(SkinMaterial.LIGHTRESULTINTENSITY, value);
                this._shaderValues.setNumber(SkinMaterial.LIGHTRESULTINTENSITY, value);
            }
            get AlbedoTillingX() {
                return this._shaderValues.getNumber(SkinMaterial.ALBEDOTILLINGX);
            }
            set AlbedoTillingX(value) {
                value = this.clampKeyValueByKey(SkinMaterial.ALBEDOTILLINGX, value);
                this._shaderValues.setNumber(SkinMaterial.ALBEDOTILLINGX, value);
            }
            get AlbedoTillingY() {
                return this._shaderValues.getNumber(SkinMaterial.ALBEDOTILLINGY);
            }
            set AlbedoTillingY(value) {
                value = this.clampKeyValueByKey(SkinMaterial.ALBEDOTILLINGY, value);
                this._shaderValues.setNumber(SkinMaterial.ALBEDOTILLINGY, value);
            }
            get tilingOffset() {
                return this._shaderValues.getVector(SkinMaterial.TILINGOFFSET);
            }
            set tilingOffset(value) {
                if (value) {
                    if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
                        this._defineDatas.add(SkinMaterial.SHADERDEFINE_TILINGOFFSET);
                    else
                        this._defineDatas.remove(SkinMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                else {
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                this._shaderValues.setVector(SkinMaterial.TILINGOFFSET, value);
            }
            get CustomColorSectionStep() {
                return this._shaderValues.getNumber(SkinMaterial.CUSTOMCOLORSECTIONSTEP);
            }
            set CustomColorSectionStep(value) {
                value = this.clampKeyValueByKey(SkinMaterial.CUSTOMCOLORSECTIONSTEP, value);
                this._shaderValues.setNumber(SkinMaterial.CUSTOMCOLORSECTIONSTEP, value);
            }
            get CustomCreamColorTexture() {
                return this._shaderValues.getTexture(SkinMaterial.CUSTOMCREAMCOLORTEXTURE);
            }
            set CustomCreamColorTexture(value) {
                if (value != null) {
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_CUSTOMCREAMCOLORTEXTURE);
                }
                else {
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_CUSTOMCREAMCOLORTEXTURE);
                }
                this._shaderValues.setTexture(SkinMaterial.CUSTOMCREAMCOLORTEXTURE, value);
            }
            get paintLayer1Texture() {
                return this._shaderValues.getTexture(SkinMaterial.PAINT_LAYER1_TEXTURE);
            }
            set paintLayer1Texture(value) {
                if (value != null) {
                    this._defineDatas.add(SkinMaterial.SHADERDEFINE_LAYER1_TEXTURE);
                }
                else {
                    this._defineDatas.remove(SkinMaterial.SHADERDEFINE_LAYER1_TEXTURE);
                }
                this._shaderValues.setTexture(SkinMaterial.PAINT_LAYER1_TEXTURE, value);
            }
            get paintLayer1TilingOffset() {
                return this._shaderValues.getVector(SkinMaterial.PAINT_LAYER1_TILINGOFFSET);
            }
            set paintLayer1TilingOffset(value) {
                this._shaderValues.setVector(SkinMaterial.PAINT_LAYER1_TILINGOFFSET, value);
            }
            get PlayerCustomChangeFlag() {
                return this._shaderValues.getNumber(SkinMaterial.PLAYERCUSTOMCHANGEFLAG);
            }
            set PlayerCustomChangeFlag(value) {
                value = this.clampKeyValueByKey(SkinMaterial.PLAYERCUSTOMCHANGEFLAG, value);
                this._shaderValues.setNumber(SkinMaterial.PLAYERCUSTOMCHANGEFLAG, value);
            }
            getShaderValueRangeWithKey(key) {
                switch (key) {
                    case SkinMaterial.SPOCCLUSIONSTRENGTH:
                        return [0.0, 2.0];
                        break;
                    case SkinMaterial.SPMETALLIC:
                        return [0.0, 1.0];
                        break;
                    case SkinMaterial.SPSMOOTHNESS:
                        return [0.0, 2.0];
                        break;
                    case SkinMaterial.SPMETALLIC2:
                        return [0.0, 1.0];
                        break;
                    case SkinMaterial.SPSMOOTHNESS2:
                        return [0.0, 2.0];
                        break;
                    case SkinMaterial.SPNOISEBUMP:
                        return [0.0, 2.0];
                        break;
                    case SkinMaterial.SPNOISEBUMPTILING:
                        return [0.0, 16.0];
                        break;
                    case SkinMaterial.SPNOISEBUMPBASICAO:
                        return [0.0, 5.0];
                        break;
                    case SkinMaterial.SPSHADOWATTEN:
                        return [0.0, 2.0];
                        break;
                    case SkinMaterial.SPEMISSIONCOLORBACKINTENSITY:
                        return [0.0, 1.0];
                        break;
                    case SkinMaterial.SPEMISSIONCOLORBACKINTENSITY2:
                        return [0.0, 2.0];
                        break;
                    case SkinMaterial.SPBORDEROFFSETAO:
                        return [-2.0, 2.0];
                        break;
                    case SkinMaterial.SPREDTRANSLUCENCY:
                        return [0.0, 50.0];
                        break;
                    case SkinMaterial.SPREDTRANSSHADOW:
                        return [0.0, 1.0];
                        break;
                    case SkinMaterial.SPREDTRANSNORMALDISTORTION:
                        return [0.0, 1.0];
                        break;
                    case SkinMaterial.SPREDTRANSSCATTERING:
                        return [1.0, 50.0];
                        break;
                    case SkinMaterial.SPREDTRANSDIRECT:
                        return [0.0, 1.0];
                        break;
                    case SkinMaterial.SPREDTRANSAMBIENT:
                        return [0.0, 1.0];
                        break;
                    case SkinMaterial.SPRED3SOFFSET:
                        return [0.0, 1.0];
                        break;
                    case SkinMaterial.NORMALTEXTURESCALE:
                        return [0.0, 2.0];
                        break;
                    case SkinMaterial.SPECULARINTENSITY:
                        return [0.0, 2.0];
                        break;
                    case SkinMaterial.GRIDTEXTURESCALE:
                        return [0.0, 20.0];
                        break;
                    case SkinMaterial.SHINETEXTURESCALE:
                        return [0.0, 20.0];
                        break;
                    case SkinMaterial.ALBEDOTILLINGX:
                        return [0.0, 20.0];
                        break;
                    case SkinMaterial.ALBEDOTILLINGY:
                        return [0.0, 20.0];
                        break;
                    default:
                        break;
                }
                return [0.0, 1.0];
            }
            clampKeyValueByKey(key, value) {
                return Math.max(this.getShaderValueRangeWithKey(key)[0], Math.min(this.getShaderValueRangeWithKey(key)[1], value));
            }
            get cull() {
                return this._shaderValues.getInt(SkinMaterial.CULL);
            }
            set cull(value) {
                this._shaderValues.setInt(SkinMaterial.CULL, value);
            }
            get blend() {
                return this._shaderValues.getInt(SkinMaterial.BLEND);
            }
            set blend(value) {
                this._shaderValues.setInt(SkinMaterial.BLEND, value);
            }
            get blendSrc() {
                return this._shaderValues.getInt(SkinMaterial.BLEND_SRC);
            }
            set blendSrc(value) {
                this._shaderValues.setInt(SkinMaterial.BLEND_SRC, value);
            }
            get blendDst() {
                return this._shaderValues.getInt(SkinMaterial.BLEND_DST);
            }
            set blendDst(value) {
                this._shaderValues.setInt(SkinMaterial.BLEND_DST, value);
            }
            get depthTest() {
                return this._shaderValues.getInt(SkinMaterial.DEPTH_TEST);
            }
            set depthTest(value) {
                this._shaderValues.setInt(SkinMaterial.DEPTH_TEST, value);
            }
            get depthWrite() {
                return this._shaderValues.getBool(SkinMaterial.DEPTH_WRITE);
            }
            set depthWrite(value) {
                this._shaderValues.setBool(SkinMaterial.DEPTH_WRITE, value);
            }
            get randomDiscardFactor() {
                return this._shaderValues.getNumber(SkinMaterial.RANDOM_DISCARD_FACTOR);
            }
            set randomDiscardFactor(value) {
                this._shaderValues.setNumber(SkinMaterial.RANDOM_DISCARD_FACTOR, value);
            }
            get materialType() {
                return CustomMaterialType.pbrSkin;
            }
            get renderMode() {
                return this.__render_mode__;
            }
            set renderMode(value) {
                this.__render_mode__ = value;
                switch (value) {
                    case CustomMaterialRenderMode.unknown:
                    case CustomMaterialRenderMode.RENDERMODE_OPAQUE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_CUTOUT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_TRANSPARENT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    default:
                        throw new Error("CustomMaterialRenderMode : renderMode value error.");
                }
            }
        }
        SkinMaterial.ALBEDOTEXTURE = Laya.Shader3D.propertyNameToID("u_AlbedoTexture");
        SkinMaterial.ALBEDOCOLOR = Laya.Shader3D.propertyNameToID("u_AlbedoColor");
        SkinMaterial.NORMALTEXTURE = Laya.Shader3D.propertyNameToID("u_NormalTexture");
        SkinMaterial.NORMALTEXTURESCALE = Laya.Shader3D.propertyNameToID("u_NormalScale");
        SkinMaterial.MASKTEXTURE = Laya.Shader3D.propertyNameToID("u_MaskTexture");
        SkinMaterial.MASKDETAILTEXTURE = Laya.Shader3D.propertyNameToID("u_MaskDetailTexture");
        SkinMaterial.RAMPMAPTEXTURE = Laya.Shader3D.propertyNameToID("u_RampMapTexture");
        SkinMaterial.SMOOTHNESS = Laya.Shader3D.propertyNameToID("u_Smoothness");
        SkinMaterial.AMBIENTCOLOR = Laya.Shader3D.propertyNameToID("u_AmbientColor");
        SkinMaterial.GRIDTEXTURE = Laya.Shader3D.propertyNameToID("u_gridTexture");
        SkinMaterial.SHINETEXTURE = Laya.Shader3D.propertyNameToID("u_shineTexture");
        SkinMaterial.CONTROLDETAILTEXTURE = Laya.Shader3D.propertyNameToID("u_controlDetailTexture");
        SkinMaterial.GRIDTEXTURESCALE = Laya.Shader3D.propertyNameToID("u_gridTextureScale");
        SkinMaterial.SHINETEXTURESCALE = Laya.Shader3D.propertyNameToID("u_shineTextureScale");
        SkinMaterial.GRIDTEXTUREISMULTIPLY = Laya.Shader3D.propertyNameToID("u_gridTextureIsMultiply");
        SkinMaterial.SHINETEXTUREISMULTIPLY = Laya.Shader3D.propertyNameToID("u_shineTextureIsMultiply");
        SkinMaterial.OUTLINEWIDTH = Laya.Shader3D.propertyNameToID("u_OutlineWidth");
        SkinMaterial.OUTLINELIGHTNESS = Laya.Shader3D.propertyNameToID("u_OutlineLightness");
        SkinMaterial.OUTLINECOLOR = Laya.Shader3D.propertyNameToID("u_OutlineColor");
        SkinMaterial.SHADOWCOLOR = Laya.Shader3D.propertyNameToID("u_ShadowColor");
        SkinMaterial.SHADOWRANGE = Laya.Shader3D.propertyNameToID("u_ShadowRange");
        SkinMaterial.SHADOWINTENSITY = Laya.Shader3D.propertyNameToID("u_ShadowIntensity");
        SkinMaterial.SHADOWBOUNDARY = Laya.Shader3D.propertyNameToID("u_ShadowBoundary");
        SkinMaterial.SECOND_SHADOWCOLOR = Laya.Shader3D.propertyNameToID("u_Second_ShadowColor");
        SkinMaterial.SECOND_SHADOWRANGE = Laya.Shader3D.propertyNameToID("u_Second_ShadowRange");
        SkinMaterial.SECOND_SHADOWINTENSITY = Laya.Shader3D.propertyNameToID("u_Second_ShadowIntensity");
        SkinMaterial.SECOND_SHADOWBOUNDARY = Laya.Shader3D.propertyNameToID("u_Second_ShadowBoundary");
        SkinMaterial.EDGE_HIGHLIGHT_COLOR = Laya.Shader3D.propertyNameToID("u_Edge_HighlightColor");
        SkinMaterial.EDGE_HIGHLIGHT_RANGE = Laya.Shader3D.propertyNameToID("u_Edge_HighlightRange");
        SkinMaterial.EDGE_HIGHLIGHT_INTENSITY = Laya.Shader3D.propertyNameToID("u_Edge_HighlightIntensity");
        SkinMaterial.EDGE_HIGHLIGHT_BOUNDARY = Laya.Shader3D.propertyNameToID("u_Edge_HighlightBoundary");
        SkinMaterial.SPECULARRANGE = Laya.Shader3D.propertyNameToID("u_SpecularRange");
        SkinMaterial.SPECULARINTENSITY = Laya.Shader3D.propertyNameToID("u_specularIntensity");
        SkinMaterial.SPECULARCOLOR = Laya.Shader3D.propertyNameToID("u_SpecularColor");
        SkinMaterial.RANDOM_DISCARD_FACTOR = Laya.Shader3D.propertyNameToID(`u_RandomDiscardFactor`);
        SkinMaterial.SPOCCLUSIONSTRENGTH = Laya.Shader3D.propertyNameToID(`u_SPOcclusionStrength`);
        SkinMaterial.SPMETALLIC = Laya.Shader3D.propertyNameToID(`u_SPMetallic`);
        SkinMaterial.SPSMOOTHNESS = Laya.Shader3D.propertyNameToID(`u_SPSmoothness`);
        SkinMaterial.SPMETALLIC2 = Laya.Shader3D.propertyNameToID(`u_SPMetallic2`);
        SkinMaterial.SPSMOOTHNESS2 = Laya.Shader3D.propertyNameToID(`u_SPSmoothness2`);
        SkinMaterial.SPNOISEBUMP = Laya.Shader3D.propertyNameToID(`u_SPNoiseBump`);
        SkinMaterial.SPNOISEBUMPTILING = Laya.Shader3D.propertyNameToID(`u_SPNoiseBumpTiling`);
        SkinMaterial.SPNOISEBUMPBASICAO = Laya.Shader3D.propertyNameToID(`u_SPNoiseBumpBasicAO`);
        SkinMaterial.SPSHADOWATTEN = Laya.Shader3D.propertyNameToID(`u_SPShadowAtten`);
        SkinMaterial.SPEMISSIONCOLORBACK = Laya.Shader3D.propertyNameToID(`u_SPEmissionColorBack`);
        SkinMaterial.SPEMISSIONCOLORBACKINTENSITY = Laya.Shader3D.propertyNameToID(`u_SPEmissionColorBackIntensity`);
        SkinMaterial.SPBORDEROFFSETAO = Laya.Shader3D.propertyNameToID(`u_SPBorderOffsetAO`);
        SkinMaterial.SPEMISSIONCOLORBACKINTENSITY2 = Laya.Shader3D.propertyNameToID(`u_SPEmissionColorBackIntensity2`);
        SkinMaterial.SPREDTRANSLUCENCY = Laya.Shader3D.propertyNameToID(`u_SPRedTranslucency`);
        SkinMaterial.SPREDTRANSSHADOW = Laya.Shader3D.propertyNameToID(`u_SPRedTransShadow`);
        SkinMaterial.SPREDTRANSNORMALDISTORTION = Laya.Shader3D.propertyNameToID(`u_SPRedTransNormalDistortion`);
        SkinMaterial.SPREDTRANSSCATTERING = Laya.Shader3D.propertyNameToID(`u_SPRedTransScattering`);
        SkinMaterial.SPREDTRANSDIRECT = Laya.Shader3D.propertyNameToID(`u_SPRedTransDirect`);
        SkinMaterial.SPREDTRANSAMBIENT = Laya.Shader3D.propertyNameToID(`u_SPRedTransAmbient`);
        SkinMaterial.SPRED3SOFFSET = Laya.Shader3D.propertyNameToID(`u_SPRed3SOffset`);
        SkinMaterial.SPRED3SCOLOR = Laya.Shader3D.propertyNameToID(`u_SPRed3SColor`);
        SkinMaterial.CUSTOMDIRECTLIGHTCOLOR = Laya.Shader3D.propertyNameToID(`u_CustomDirectLightColor`);
        SkinMaterial.LIGHTRESULTINTENSITY = Laya.Shader3D.propertyNameToID(`u_LightResultIntensity`);
        SkinMaterial.ALBEDOTILLINGX = Laya.Shader3D.propertyNameToID(`u_AlbedoTillingX`);
        SkinMaterial.ALBEDOTILLINGY = Laya.Shader3D.propertyNameToID(`u_AlbedoTillingY`);
        SkinMaterial.CUSTOMCOLORSECTIONSTEP = Laya.Shader3D.propertyNameToID(`u_CustomColorSectionStep`);
        SkinMaterial.CUSTOMCREAMCOLORTEXTURE = Laya.Shader3D.propertyNameToID("u_CustomCreamColorTexture");
        SkinMaterial.PAINT_LAYER1_TEXTURE = Laya.Shader3D.propertyNameToID("u_PaintLayer1Texture");
        SkinMaterial.PAINT_LAYER1_TILINGOFFSET = Laya.Shader3D.propertyNameToID("u_PaintLayer1TilingOffset");
        SkinMaterial.PLAYERCUSTOMCHANGEFLAG = Laya.Shader3D.propertyNameToID(`u_PlayerCustomChangeFlag`);
        SkinMaterial.CULL = Laya.Shader3D.propertyNameToID("s_Cull");
        SkinMaterial.BLEND = Laya.Shader3D.propertyNameToID("s_Blend");
        SkinMaterial.BLEND_SRC = Laya.Shader3D.propertyNameToID("s_BlendSrc");
        SkinMaterial.BLEND_DST = Laya.Shader3D.propertyNameToID("s_BlendDst");
        SkinMaterial.DEPTH_TEST = Laya.Shader3D.propertyNameToID("s_DepthTest");
        SkinMaterial.DEPTH_WRITE = Laya.Shader3D.propertyNameToID("s_DepthWrite");

        class mgrMaterial extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static setMaterialInfos(value) {
                this.materialInfos = value;
            }
            static setPrecompileShaderInfos(value) {
                this.precompileShaderInfos = value;
            }
            static setMaterial(modelId, modelMaterialNo, skinName, index, materialInfo) {
                modelMaterialNo = modelMaterialNo || 0;
                if (!this.materialInfos[modelId])
                    this.materialInfos[modelId] = {};
                if (!this.materialInfos[modelId][modelMaterialNo])
                    this.materialInfos[modelId][modelMaterialNo] = {};
                if (!this.materialInfos[modelId][modelMaterialNo][skinName])
                    this.materialInfos[modelId][modelMaterialNo][skinName] = {};
                this.materialInfos[modelId][modelMaterialNo][skinName][index] = materialInfo;
            }
            static getMaterial(modelId, modelMaterialNo, skinName, index, materialType, bFixWidthDefault = false) {
                modelMaterialNo = modelMaterialNo || 0;
                if (!this.materialInfos[modelId])
                    this.materialInfos[modelId] = {};
                if (!this.materialInfos[modelId][modelMaterialNo])
                    this.materialInfos[modelId][modelMaterialNo] = {};
                if (!this.materialInfos[modelId][modelMaterialNo][skinName])
                    this.materialInfos[modelId][modelMaterialNo][skinName] = {};
                if (!this.materialInfos[modelId][modelMaterialNo][skinName][index]) {
                    if (bFixWidthDefault) {
                        return this.materialInfos[modelId][modelMaterialNo][skinName][index] = this.getDefaultMaterialDataByMaterialType(materialType, modelId, skinName);
                    }
                    else {
                        return null;
                    }
                }
                return this.materialInfos[modelId][modelMaterialNo][skinName][index];
            }
            static getDefaultMaterialDataByMaterialType(materialType, modelId, skinName) {
                switch (materialType) {
                    case CustomMaterialType.pbrHair:
                        return {
                            materialType: CustomMaterialType.pbrHair,
                            SPMetallic: 0.0,
                            SPSmoothness: 1,
                            SPUTiling: 1.4,
                            SPPBRInstensity: 0.2,
                            SPHairAlbedoAO: 0.597,
                            SPAnisotropyBiasG: -1.6,
                            SPAnisotropyBiasR: 0.36,
                            SPHairSpecularAO: 0.694,
                            SPAnisotropyRang1: 7.0,
                            SPAnisotropyRang2: 781.0,
                            SPHLFrePower: 2.0,
                            SPSpecularInDarkAlpha: 0.0588,
                            SPR1SpecalurColor: [0.3, 0.18, 0.18, 0.0],
                            SPR2SpecalurColor: [1.0, 1.0, 1.0, 0.0],
                            SPSpecularInDark: [0.247, 0.235, 0.294, 0.0588],
                            albedoColor: [0.4, 0.25, 0.25, 1],
                            albedoIdensity: 0.5,
                            normalTextureScale: 1.0,
                            SPPBRFinalLightRatio: 1.0,
                            SPPBRSecondLightYValue: 0.0,
                            bCastShadow: false,
                            bReceiveShadow: false,
                            specularIntensity: 1.0,
                            alphaTestValue: 0.0,
                            renderMode: CustomMaterialRenderMode.RENDERMODE_OPAQUE,
                            renderQueue: 0,
                        };
                        break;
                    case CustomMaterialType.pbrSkin:
                        return {
                            materialType: CustomMaterialType.pbrSkin,
                            albedoColor: [1, 1, 1, 1],
                            albedoIdensity: 1.0,
                            SPOcclusionStrength: 0.25,
                            SPMetallic: 0.0,
                            SPSmoothness: 0.1,
                            SPMetallic2: 0.0,
                            SPSmoothness2: 0.1,
                            SPNoiseBump: 1.2,
                            SPNoiseBumpTiling: 4.0,
                            SPNoiseBumpBasicAO: 2.0,
                            SPShadowAtten: 1.0,
                            SPEmissionColorBack: [0.65, 0.53, 0.53, 1.0],
                            SPEmissionColorBackIntensity: 0.5,
                            SPBorderOffsetAO: -0.43,
                            SPRedTranslucency: 5.0,
                            SPRedTransShadow: 0.496,
                            SPRedTransNormalDistortion: 0.273,
                            SPRedTransScattering: 2.2,
                            SPRedTransDirect: 0.651,
                            SPRedTransAmbient: 0.715,
                            SPRed3SOffset: 0.41,
                            SPRed3SColor: [1.0, 0.0, 0.0, 1.0],
                            CustomDirectLightColor: [0.5, 0.5, 0.5, 1.0],
                            normalTextureScale: 1.0,
                            LightResultIntensity: 0.0,
                            specularIntensity: 1.0,
                            alphaTestValue: 0.0,
                            gridTextureScale: 1.0,
                            shineTextureScale: 1.0,
                            AlbedoTillingX: 1.0,
                            AlbedoTillingY: 1.0,
                            SPEmissionColorBackIntensity2: 1.0,
                            gridTextureIsMultiply: 0.0,
                            shineTextureIsMultiply: 0.0,
                            PlayerCustomChangeFlag: 0.0,
                            bCastShadow: false,
                            bReceiveShadow: false,
                            renderMode: CustomMaterialRenderMode.RENDERMODE_OPAQUE,
                            renderQueue: 0,
                        };
                        break;
                    case CustomMaterialType.pbrCloth:
                        return {
                            materialType: CustomMaterialType.pbrCloth,
                            albedoColor: [1.0, 1.0, 1.0, 1],
                            albedoIdensity: 0.5,
                            SPOcclusionStrength: 0.25,
                            SPMetallic: 0.0,
                            SPSmoothness: 0.1,
                            SPShadowAtten: 1.0,
                            SPSideLightColor: [0.843, 0.921, 0.949, 1.0],
                            SPSideLightScale: 0.5,
                            SPPBRResultMaxColor: [1.0, 1.0, 1.0, 1],
                            normalTextureScale: 1.0,
                            gridTextureScale: 1.0,
                            shineTextureScale: 1.0,
                            CustomDirectLightColor: [1.0, 1.0, 1.0, 1.0],
                            LightResultIntensity: 0.0,
                            specularIntensity: 1.0,
                            bCastShadow: false,
                            bReceiveShadow: false,
                            alphaTestValue: 0.0,
                            renderMode: CustomMaterialRenderMode.RENDERMODE_OPAQUE,
                            renderQueue: 0,
                        };
                        break;
                    default:
                        return {
                            materialType: CustomMaterialType.unlitCartoon,
                            onlyChangeBonePosFlag: 0.0,
                            albedoColor: [1, 1, 1, 1],
                            albedoIdentity: 0.5,
                            shadowRange: 0,
                            shadowIntensity: 0,
                            shadowColor: [0, 0, 0, 0],
                            shadowBoundary: 0,
                            specularRange: 0,
                            specularIdensity: 0,
                            specularColor: [1, 1, 1, 1],
                            outlineWidth: 0,
                            outlineIdensity: 1,
                            outlineColor: [0, 0, 0, 0],
                            secondShadowRange: 0,
                            secondShadowIntensity: 1,
                            secondShadowBoundary: 0,
                            secondShadowColor: [1, 1, 1, 1],
                            EdgeHightRange: 0,
                            EdgeHightBoundary: 0,
                            EdgeHightColor: [1, 1, 1, 1],
                            EdgeHightIntensity: 1,
                            renderMode: CustomMaterialRenderMode.RENDERMODE_OPAQUE,
                            renderQueue: 0,
                            alphaTestValue: 0.5,
                        };
                        break;
                }
            }
            static getDefaultCartonMateril() {
                return {
                    onlyChangeBonePosFlag: 0.0,
                    albedoColor: [1, 1, 1, 1],
                    albedoIdentity: 0.5,
                    shadowRange: 0,
                    shadowIntensity: 0,
                    shadowColor: [0, 0, 0, 0],
                    shadowBoundary: 0,
                    specularRange: 0,
                    specularIdensity: 0,
                    specularColor: [1, 1, 1, 1],
                    outlineWidth: 0,
                    outlineIdensity: 1,
                    outlineColor: [0, 0, 0, 0],
                    secondShadowRange: 0,
                    secondShadowIntensity: 1,
                    secondShadowBoundary: 0,
                    secondShadowColor: [1, 1, 1, 1],
                    EdgeHightRange: 0,
                    EdgeHightBoundary: 0,
                    EdgeHightColor: [1, 1, 1, 1],
                    EdgeHightIntensity: 1,
                    alphaTestValue: 0.5,
                    renderMode: CartoonMaterial.RENDERMODE_OPAQUE,
                };
            }
            static setMaterialType(modelId, modelMaterialNo, skinName, materialIndex, materialType) {
                modelMaterialNo = modelMaterialNo || 0;
                if (!this.materialInfos[modelId])
                    this.materialInfos[modelId] = {};
                if (!this.materialInfos[modelId][modelMaterialNo]) {
                    this.materialInfos[modelId][modelMaterialNo] = {};
                }
                if (!this.materialInfos[modelId][modelMaterialNo][skinName]) {
                    this.materialInfos[modelId][modelMaterialNo][skinName] = {};
                }
                let materialData = this.getDefaultMaterialDataByMaterialType(materialType, modelId, skinName);
                this.setMaterial(modelId, modelMaterialNo, skinName, materialIndex, materialData);
            }
            static getMaterialType(modelId, modelMaterialNo, skinName, materialIndex) {
                modelMaterialNo = modelMaterialNo || 0;
                materialIndex = materialIndex || "0";
                if (!this.materialInfos[modelId])
                    this.materialInfos[modelId] = {};
                if (!this.materialInfos[modelId][modelMaterialNo]) {
                    this.materialInfos[modelId][modelMaterialNo] = {};
                }
                if (!this.materialInfos[modelId][modelMaterialNo][skinName]) {
                    this.materialInfos[modelId][modelMaterialNo][skinName] = {};
                }
                if (!this.materialInfos[modelId][modelMaterialNo][skinName][materialIndex]) {
                    return CustomMaterialType.unknown;
                }
                let materialData = this.materialInfos[modelId][modelMaterialNo][skinName][materialIndex];
                return materialData.materialType || CustomMaterialType.unknown;
            }
            static setCustomMaterial(model, modelId, modelMaterialNo, bForPlayerCustom) {
                if (!model)
                    return [];
                modelMaterialNo = modelMaterialNo || 0;
                let materials = [];
                for (let i = 0; i < model.numChildren; i++) {
                    let child = model.getChildAt(i);
                    let renderer = Tools.getMeshRender(child);
                    if (renderer) {
                        let shadowParams = {
                            bReceiveShadow: false,
                            bCastShadow: false,
                        };
                        let material = null;
                        material = this.__setCustomMaterial(renderer, modelId, modelMaterialNo, child.name, shadowParams, bForPlayerCustom);
                        materials = materials.concat(material);
                        renderer.receiveShadow = false;
                        renderer.castShadow = false;
                    }
                }
                return materials;
            }
            static __setCustomMaterial(render, modelId, modelMaterialNo, skinName, shadowParams, bForPlayerCustom) {
                let newMaterials = [];
                for (let i = 0; i < render.sharedMaterials.length; i++) {
                    let oldMaterial = render.sharedMaterials[i];
                    let materialType = this.getMaterialType(modelId, modelMaterialNo, skinName, i.toString());
                    let materialDatas = null;
                    if (!oldMaterial.__originMaterialData) {
                        materialDatas = {
                            albedoTexture: oldMaterial.albedoTexture,
                            normalTexture: oldMaterial.normalTexture,
                            maskTexture: oldMaterial.metallicGlossTexture || oldMaterial.maskTexture,
                            maskDetailTexture: oldMaterial.occlusionTexture || oldMaterial.maskDetailTexture,
                            rampMapTexture: oldMaterial.emissionTexture || oldMaterial.rampMapTexture,
                            name: oldMaterial.name || ""
                        };
                        oldMaterial.__originMaterialData = materialDatas;
                    }
                    else {
                        materialDatas = oldMaterial.__originMaterialData;
                    }
                    if (materialType && materialType == CustomMaterialType.pbrHair) {
                        newMaterials[i] = this.__setToHairMaterial(materialDatas, modelId, modelMaterialNo, skinName, i);
                        if (shadowParams) {
                            shadowParams.bCastShadow = false;
                        }
                    }
                    else if (materialType && materialType == CustomMaterialType.pbrSkin) {
                        newMaterials[i] = this.__setToSkinMaterial(materialDatas, modelId, modelMaterialNo, skinName, i, bForPlayerCustom);
                        if (shadowParams && Const.bHighShadowQuality) {
                            shadowParams.bReceiveShadow = false;
                            shadowParams.bCastShadow = false;
                        }
                    }
                    else if (materialType && materialType == CustomMaterialType.pbrCloth) {
                        newMaterials[i] = this.__setToClothMaterial(materialDatas, modelId, modelMaterialNo, skinName, i);
                        if (shadowParams && Const.bHighShadowQuality) {
                            shadowParams.bReceiveShadow = false;
                            shadowParams.bCastShadow = false;
                        }
                    }
                    else {
                        newMaterials[i] = this.__setToCustomCartonMaterial(oldMaterial, modelId, modelMaterialNo, skinName, i);
                    }
                    newMaterials[i].name = oldMaterial.name;
                    newMaterials[i].__originMaterialData = materialDatas;
                }
                render.sharedMaterials = newMaterials;
                return newMaterials;
            }
            static __setToCustomCartonMaterial(originMatrial, modelId, modelMaterialNo, skinName, index) {
                const oldMaterial = originMatrial;
                let customMaterial = new CartoonMaterial;
                customMaterial.albedoTexture = oldMaterial.albedoTexture;
                let materialData = mgrMaterial.getMaterial(modelId, modelMaterialNo, skinName, index, CustomMaterialType.unlitCartoon);
                if (!materialData) {
                    return oldMaterial;
                }
                customMaterial.name = oldMaterial.name;
                customMaterial.onlyChangeBonePosFlag = materialData.onlyChangeBonePosFlag;
                customMaterial.shadowIntensity = materialData.shadowIntensity;
                customMaterial.shadowRange = materialData.shadowRange;
                materialData.shadowColor && materialData.shadowColor.length > 0 && (customMaterial.shadowColor = new Laya.Vector4(materialData.shadowColor[0], materialData.shadowColor[1], materialData.shadowColor[2], 1.0));
                customMaterial.shadowBoundary = materialData.shadowBoundary;
                customMaterial.albedoIdentity = materialData.albedoIdentity;
                materialData.albedoColor && materialData.albedoColor.length > 0 && (customMaterial.albedoColor = new Laya.Vector4(materialData.albedoColor[0], materialData.albedoColor[1], materialData.albedoColor[2], 1.0));
                customMaterial.specularRange = materialData.specularRange;
                customMaterial.specularIntensity = materialData.specularIdensity;
                materialData.specularColor && materialData.specularColor.length > 0 && (customMaterial.specularColor = new Laya.Vector4(materialData.specularColor[0], materialData.specularColor[1], materialData.specularColor[2], 1.0));
                customMaterial.outlineLightness = materialData.outlineIdensity;
                customMaterial.outlineWidth = materialData.outlineWidth;
                materialData.outlineColor && materialData.outlineColor.length > 0 && (customMaterial.outlineColor = new Laya.Vector4(materialData.outlineColor[0], materialData.outlineColor[1], materialData.outlineColor[2], 1.0));
                customMaterial.secondShadowIntensity = materialData.secondShadowIntensity;
                customMaterial.secondShadowRange = materialData.secondShadowRange;
                materialData.secondShadowColor && materialData.secondShadowColor.length > 0 && (customMaterial.secondShadowColor = new Laya.Vector4(materialData.secondShadowColor[0], materialData.secondShadowColor[1], materialData.secondShadowColor[2], 1.0));
                customMaterial.secondShadowBoundary = materialData.secondShadowBoundary;
                customMaterial.EdgeHightIntensity = materialData.EdgeHightIntensity;
                customMaterial.EdgeHightRange = materialData.EdgeHightRange;
                materialData.EdgeHightColor && materialData.EdgeHightColor.length > 0 && (customMaterial.EdgeHightColor = new Laya.Vector4(materialData.EdgeHightColor[0], materialData.EdgeHightColor[1], materialData.EdgeHightColor[2], 1.0));
                customMaterial.EdgeHightBoundary = materialData.EdgeHightBoundary;
                customMaterial.alphaTestValue = materialData.alphaTestValue || 0.5;
                customMaterial.renderMode = materialData.renderMode;
                customMaterial.renderMode = materialData.renderMode;
                customMaterial.renderQueue = materialData.renderQueue || customMaterial.renderQueue;
                return customMaterial;
            }
            static __setToSkinMaterial(originMatrial, modelId, modelMaterialNo, skinName, index, bForPlayerCustom) {
                let customMaterial = new SkinMaterial;
                customMaterial.albedoTexture = originMatrial.albedoTexture;
                let materialData = mgrMaterial.getMaterial(modelId, modelMaterialNo, skinName, index, CustomMaterialType.pbrSkin);
                Tools.loadMaterialTexture(materialData["normalTexturePath"], customMaterial, "normalTexture");
                Tools.loadMaterialTexture(materialData["rampMapTexturePath"], customMaterial, "rampMapTexture");
                if (!bForPlayerCustom || materialData.PlayerCustomChangeFlag < 0.5) {
                    Tools.loadMaterialTexture(materialData["albedoTexturePath"], customMaterial, "albedoTexture");
                    Tools.loadMaterialTexture(materialData["gridTexturePath"], customMaterial, "gridTexture");
                    Tools.loadMaterialTexture(materialData["shineTexturePath"], customMaterial, "shineTexture");
                    Tools.loadMaterialTexture(materialData["controlDetailTexturePath"], customMaterial, "controlDetailTexture");
                }
                customMaterial.normalTextureScale = materialData.normalTextureScale;
                if (materialData.albedoColor && materialData.albedoColor.length > 0) {
                    customMaterial.albedoColor = new Laya.Vector4(materialData.albedoColor[0], materialData.albedoColor[1], materialData.albedoColor[2], 1.0);
                }
                customMaterial.SPOcclusionStrength = materialData.SPOcclusionStrength || 0;
                customMaterial.SPMetallic = materialData.SPMetallic || 0;
                customMaterial.SPSmoothness = materialData.SPSmoothness || 0;
                customMaterial.SPMetallic2 = materialData.SPMetallic2 || 0;
                customMaterial.SPSmoothness2 = materialData.SPSmoothness2 || 0;
                customMaterial.SPNoiseBump = materialData.SPNoiseBump || 0;
                customMaterial.SPNoiseBumpTiling = materialData.SPNoiseBumpTiling || 0;
                customMaterial.SPShadowAtten = materialData.SPShadowAtten || 1.0;
                if (materialData.SPEmissionColorBack && materialData.SPEmissionColorBack.length > 0) {
                    customMaterial.SPEmissionColorBack = new Laya.Vector4(materialData.SPEmissionColorBack[0], materialData.SPEmissionColorBack[1], materialData.SPEmissionColorBack[2], 1.0);
                }
                customMaterial.SPEmissionColorBackIntensity = materialData.SPEmissionColorBackIntensity;
                customMaterial.SPBorderOffsetAO = materialData.SPBorderOffsetAO;
                customMaterial.SPRedTranslucency = materialData.SPRedTranslucency;
                customMaterial.SPRedTransShadow = materialData.SPRedTransShadow;
                customMaterial.SPRedTransNormalDistortion = materialData.SPRedTransNormalDistortion;
                customMaterial.SPRedTransScattering = materialData.SPRedTransScattering;
                customMaterial.SPRedTransDirect = materialData.SPRedTransDirect;
                customMaterial.SPRedTransAmbient = materialData.SPRedTransAmbient;
                customMaterial.SPRed3SOffset = materialData.SPRed3SOffset;
                if (materialData.SPRed3SColor && materialData.SPRed3SColor.length > 0) {
                    customMaterial.SPRed3SColor = new Laya.Vector4(materialData.SPRed3SColor[0], materialData.SPRed3SColor[1], materialData.SPRed3SColor[2], 1.0);
                }
                if (materialData.CustomDirectLightColor && materialData.CustomDirectLightColor.length > 0) {
                    customMaterial.CustomDirectLightColor = new Laya.Vector4(materialData.CustomDirectLightColor[0], materialData.CustomDirectLightColor[1], materialData.CustomDirectLightColor[2], 1.0);
                }
                customMaterial.LightResultIntensity = materialData.LightResultIntensity || 0;
                customMaterial.specularIntensity = materialData.specularIntensity || 0;
                customMaterial.alphaTestValue = materialData.alphaTestValue || 0.0;
                customMaterial.gridTextureScale = materialData.gridTextureScale || 1.0;
                customMaterial.shineTextureScale = materialData.shineTextureScale || 1.0;
                customMaterial.AlbedoTillingX = materialData.AlbedoTillingX || 1.0;
                customMaterial.AlbedoTillingY = materialData.AlbedoTillingY || 1.0;
                customMaterial.SPEmissionColorBackIntensity2 = materialData.SPEmissionColorBackIntensity2 || 1.0;
                customMaterial.gridTextureIsMultiply = materialData.gridTextureIsMultiply || 0.0;
                customMaterial.shineTextureIsMultiply = materialData.shineTextureIsMultiply || 0.0;
                customMaterial.PlayerCustomChangeFlag = materialData.PlayerCustomChangeFlag || 0.0;
                customMaterial.renderMode = materialData.renderMode || CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                customMaterial.renderQueue = materialData.renderQueue || customMaterial.renderQueue;
                return customMaterial;
            }
            static __setToClothMaterial(originMatrial, modelId, modelMaterialNo, skinName, index) {
                let customMaterial = new ClothMaterial;
                customMaterial.albedoTexture = originMatrial.albedoTexture;
                customMaterial.normalTexture = originMatrial.normalTexture;
                let materialData = mgrMaterial.getMaterial(modelId, modelMaterialNo, skinName, index, CustomMaterialType.pbrCloth);
                Tools.loadMaterialTexture(materialData["albedoTexturePath"], customMaterial, "albedoTexture");
                Tools.loadMaterialTexture(materialData["gridTexturePath"], customMaterial, "gridTexture");
                Tools.loadMaterialTexture(materialData["shineTexturePath"], customMaterial, "shineTexture");
                Tools.loadMaterialTexture(materialData["controlDetailTexturePath"], customMaterial, "controlDetailTexture");
                customMaterial.normalTextureScale = materialData.normalTextureScale;
                if (materialData.albedoColor && materialData.albedoColor.length > 0) {
                    customMaterial.albedoColor = new Laya.Vector4(materialData.albedoColor[0], materialData.albedoColor[1], materialData.albedoColor[2], 1.0);
                }
                customMaterial.SPOcclusionStrength = materialData.SPOcclusionStrength;
                customMaterial.SPMetallic = materialData.SPMetallic;
                customMaterial.SPSmoothness = materialData.SPSmoothness;
                customMaterial.SPShadowAtten = materialData.SPShadowAtten || 1.0;
                if (materialData.SPSideLightColor && materialData.SPSideLightColor.length > 0) {
                    customMaterial.SPSideLightColor = new Laya.Vector4(materialData.SPSideLightColor[0], materialData.SPSideLightColor[1], materialData.SPSideLightColor[2], 1.0);
                }
                customMaterial.SPSideLightScale = materialData.SPSideLightScale;
                if (materialData.SPPBRResultMaxColor && materialData.SPPBRResultMaxColor.length > 0) {
                    customMaterial.SPPBRResultMaxColor = new Laya.Vector4(materialData.SPPBRResultMaxColor[0], materialData.SPPBRResultMaxColor[1], materialData.SPPBRResultMaxColor[2], 1.0);
                }
                if (materialData.CustomDirectLightColor && materialData.CustomDirectLightColor.length > 0) {
                    customMaterial.CustomDirectLightColor = new Laya.Vector4(materialData.CustomDirectLightColor[0], materialData.CustomDirectLightColor[1], materialData.CustomDirectLightColor[2], 1.0);
                }
                customMaterial.LightResultIntensity = materialData.LightResultIntensity || 0;
                customMaterial.specularIntensity = materialData.specularIntensity || 0;
                customMaterial.alphaTestValue = materialData.alphaTestValue || 0.0;
                customMaterial.renderMode = materialData.renderMode || CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                customMaterial.renderQueue = materialData.renderQueue || customMaterial.renderQueue;
                return customMaterial;
            }
            static __setToHairMaterial(originMatrial, modelId, modelMaterialNo, skinName, index) {
                console.log("----------------__setToHairMaterial modelId=", modelId, skinName);
                let customMaterial = new HairMaterial;
                customMaterial.normalTexture = originMatrial.normalTexture;
                customMaterial.maskTexture = originMatrial.maskTexture;
                let materialData = mgrMaterial.getMaterial(modelId, modelMaterialNo, skinName, index, CustomMaterialType.pbrHair);
                if (!materialData) {
                    return originMatrial;
                }
                Tools.loadMaterialTexture("res/material/al/toufa_control.jpg", customMaterial, "AlbedoAlphaTexture");
                customMaterial.normalTextureScale = materialData.normalTextureScale;
                customMaterial.SPMetallic = materialData.SPMetallic;
                customMaterial.SPSmoothness = materialData.SPSmoothness;
                customMaterial.SPUTiling = materialData.SPUTiling;
                customMaterial.SPPBRInstensity = materialData.SPPBRInstensity;
                customMaterial.SPHairAlbedoAO = materialData.SPHairAlbedoAO;
                customMaterial.SPAnisotropyBiasG = materialData.SPAnisotropyBiasG;
                customMaterial.SPAnisotropyBiasR = materialData.SPAnisotropyBiasR;
                customMaterial.SPHairSpecularAO = materialData.SPHairSpecularAO;
                customMaterial.SPAnisotropyRang1 = materialData.SPAnisotropyRang1;
                customMaterial.SPAnisotropyRang2 = materialData.SPAnisotropyRang2;
                customMaterial.SPHLFrePower = materialData.SPHLFrePower;
                customMaterial.SPSpecularInDarkAlpha = materialData.SPSpecularInDarkAlpha;
                if (materialData.albedoColor && materialData.albedoColor.length > 0) {
                    customMaterial.albedoColor = new Laya.Vector4(materialData.albedoColor[0], materialData.albedoColor[1], materialData.albedoColor[2], 1.0);
                }
                if (materialData.SPR1SpecalurColor && materialData.SPR1SpecalurColor.length > 0) {
                    customMaterial.SPR1SpecalurColor = new Laya.Vector4(materialData.SPR1SpecalurColor[0], materialData.SPR1SpecalurColor[1], materialData.SPR1SpecalurColor[2], 1.0);
                }
                if (materialData.SPR2SpecalurColor && materialData.SPR2SpecalurColor.length > 0) {
                    customMaterial.SPR2SpecalurColor = new Laya.Vector4(materialData.SPR2SpecalurColor[0], materialData.SPR2SpecalurColor[1], materialData.SPR2SpecalurColor[2], 1.0);
                }
                if (materialData.SPSpecularInDark && materialData.SPSpecularInDark.length > 0) {
                    customMaterial.SPSpecularInDark = new Laya.Vector4(materialData.SPSpecularInDark[0], materialData.SPSpecularInDark[1], materialData.SPSpecularInDark[2], 1.0);
                }
                customMaterial.alphaTestValue = materialData.alphaTestValue || 0.0;
                customMaterial.SPPBRFinalLightRatio = materialData.SPPBRFinalLightRatio || 1.0;
                customMaterial.LightResultIntensity = materialData.LightResultIntensity || 0;
                customMaterial.renderMode = materialData.renderMode || CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                customMaterial.renderQueue = materialData.renderQueue || customMaterial.renderQueue;
                return customMaterial;
            }
            static playAnimation(animator, animationId, mixFactor, loadEndCallback, playEndCallback) {
                if (!animator) {
                    console.warn("-------[ERROR]----No Animator");
                }
                let animationData = mgrCfg.get_from_animation_db(animationId);
                let animatorState = animator.getControllerLayer(0).getAnimatorState(animationId);
                if (!animatorState) {
                    Laya.AnimationClip.load(animationData.path, new Laya.Handler(this, (clip) => {
                        let __temp = animator.getControllerLayer(0).getAnimatorState(animationId);
                        if (__temp)
                            return;
                        animatorState = new Laya.AnimatorState();
                        animatorState.clip = clip;
                        animatorState.clipStart = 0;
                        animatorState.clipEnd = 1;
                        animatorState.name = animationId;
                        animator.getControllerLayer(0).addState(animatorState);
                        if (mixFactor == 0) {
                            animator.play(animationId, 0, 0);
                        }
                        else {
                            animator.crossFade(animationId, mixFactor);
                        }
                        loadEndCallback && loadEndCallback();
                        Timer.callLater(clip.duration(), () => {
                            playEndCallback && playEndCallback();
                        }, animator.owner);
                    }));
                }
                else {
                    let clip = animator.getControllerLayer(0).getAnimatorState(animationId).clip;
                    if (animator.getCurrentAnimatorPlayState(0).animatorState.name == animationId && clip.islooping == true) {
                        return;
                    }
                    if (mixFactor == 0) {
                        animator.play(animationId, 0, 0);
                    }
                    else {
                        animator.crossFade(animationId, mixFactor);
                    }
                    loadEndCallback && loadEndCallback();
                    Timer.callLater(clip.duration(), () => {
                        playEndCallback && playEndCallback();
                    }, animator.owner);
                }
            }
            static playLayerAnimation(animator, animationId, controllerLayer = 0, mixFactor = 0, loadEndCallback, playEndCallback) {
                let animationData = mgrCfg.get_from_animation_db(animationId);
                let animatorState = animator.getControllerLayer(controllerLayer).getAnimatorState(animationId);
                if (!animatorState) {
                    Laya.AnimationClip.load(animationData.path, new Laya.Handler(this, (clip) => {
                        let __temp = animator.getControllerLayer(controllerLayer).getAnimatorState(animationId);
                        if (__temp)
                            return;
                        animatorState = new Laya.AnimatorState();
                        animatorState.clip = clip;
                        animatorState.clipStart = 0;
                        animatorState.clipEnd = 1;
                        animatorState.name = animationId;
                        animator.getControllerLayer(controllerLayer).addState(animatorState);
                        animator.crossFade(animationId, mixFactor, controllerLayer, 0);
                        loadEndCallback && loadEndCallback();
                        Timer.callLater(clip.duration(), () => {
                            playEndCallback && playEndCallback();
                        }, animator.owner);
                    }));
                }
                else {
                    let clip = animator.getControllerLayer(controllerLayer).getAnimatorState(animationId).clip;
                    if (animator.getControllerLayer(controllerLayer).getCurrentPlayState().animatorState.name == animationId && clip.islooping == true) {
                        return;
                    }
                    animator.crossFade(animationId, mixFactor, controllerLayer, 0);
                    loadEndCallback && loadEndCallback();
                    Timer.callLater(clip.duration(), () => {
                        playEndCallback && playEndCallback();
                    }, animator.owner);
                }
            }
            static precompileShaderByViewName(viewName, callback) {
                let infos = this.precompileShaderInfos || {};
                let res = infos[viewName];
                if (!res || res.length == 0) {
                    callback && callback();
                    return;
                }
                for (let i = 0; i < res.length; i++) {
                    const element = res[i];
                    Laya.Shader3D.compileShaderByDefineNames(element.shaderName, element.subShaderIndex, element.passIndex, element.defineNames);
                }
                callback && callback();
            }
            static enableShaderDebugMode() {
                Laya.Shader3D.debugMode = true;
            }
            static disableShaderDebugMode() {
                Laya.Shader3D.debugMode = false;
            }
        }

        const TASKS = [
            ["achievement_db", "m"],
            ["achievement_target_db", "m"],
            ["quest_achievement_db", "a"],
            ["ad_event_db", "m"],
            ["alu_db", "m"],
            ["cop_db", "m"],
            ["cop_process_db", "m"],
            ["guide_db", "m"],
            ["inner_cdk_db", "m"],
            ["item_template_db", "m"],
            ["item_recover_db", "m"],
            ["item_router_go_db", "ma"],
            ["item_box_db", "m"],
            ["item_type_db", "m"],
            ["sign_db", "ma"],
            ["sound_db", "m"],
            ["shop_template_db", "m"],
            ["random_name_db", "a"],
            ["stage_chapter_db", "m"],
            ["stage_db", "m"],
            ["stage_result_dress_part_config", 'm'],
            ["online_reward_db", "ma"],
            ["random_tip_db", "a"],
            ["part_type_db", "m"],
            ["part_db", "m"],
            ["part_tag_db", "m"],
            ["suit_db", "m"],
            ["suit_type_db", "m"],
            ["story_db", "ma"],
            ["pvp_offline_subject_db", "a"],
            ["pvp_offline_db", "m"],
            ["pvp_offline_photo_bg_db", "m"],
            ["pvp_offline_photo_mask_db", "m"],
            ["pvp_offline_photo_recipe_db", "m"],
            ["pvp_offline_preset_photo_db", "m"],
            ["pvp_offline_lottery_db", "m"],
            ["pvp_offline_role_power_base_db", "m"],
            ["alert_router_db", "ma"],
            ["cake_stage_db", "m"],
            ["cake_cream_combine_db", "ma"],
            ["cake_paint_color_db", "m"],
            ["cake_deco_db", "m"],
            ["cake_sticker_db", "m"],
            ["cake_cream_color_db", "m"],
            ["cake_shape_db", "m"],
            ["world_color_db", "m"],
            ["world_daily_quest", "m"],
            ["world_daily_quest_config", "m"],
            ["cake_daily_quest_config", "m"],
            ["pen_daily_quest_config", "m"],
            ["cloth_daily_quest_config", "m"],
            ["world_game_db", "m"],
            ["custom_made_cloth_daily_quest_config", "m"],
            ["custom_made_clothes_stage_db", "m"],
            ["parkour_daily_quest_config", "m"],
            ["cloth_crossing_daily_quest_config", "m"],
            ["amaze_pen_part_reward_config", "m"],
            ["amaze_pen_stage_db", "m"],
            ["amaze_pen_select_role_db", "m"],
            ["amaze_parkour_skin_db", "m"],
            ["amaze_cloth_crossing_stage_db", "m"],
            ["amaze_cloth_crossing_skin_db", "m"],
            ["amuse_cloth_crossing_photo_recipe_db", "m"],
            ["amuse_card_npc_db", "m"],
            ["amaze_card_stage_db", "m"],
            ["amuse_card_style_db", "m"],
            ["amuse_card_photo_recipe_db", "m"],
            ["amuse_card_part_reward_config", "m"],
            ["amuse_player_make_card_db", "m"],
            ["amuse_double_card_npc_db", "m"],
            ["amuse_double_npc_card_role_pic_db", "m"],
            ["amuse_double_npc_card_currency_reward_db", "m"],
            ["amuse_card_skill_db", "m"],
            ["amuse_card_skil_collection_db", "m"],
            ["amuse_card_new_year_reward_config_db", "m"],
            ["amuse_card_skill_effect_db", "m"],
            ["design_part_config", "m"],
            ["design_part_color_db", "m"],
            ["design_shine_db", "m"],
            ["design_grid_db", "m"],
            ["amaze_parkour_stage_db", "m"],
            ["role_db", "m"],
            ["role_face_animation", "m"],
            ["role_face_body_animation_relation_db", "m"],
            ["role_collect_jump_db", "m"],
            ["center_role_click_feedback_db", "ma"],
            ["left_right_role_click_feedback_db", "ma"],
            ["room_dress_role_feedback_db", "ma"],
            ["hub_role_standby_feedback_db", "ma"],
            ["spine_db", "m"],
            ["animation_db", "m"],
            ["model_db", "m"],
            ["barrage_db", "m"],
            ["barrage_color_db", "m"],
            ["imoge_db", "m"],
            ["ad_suit_config_db", "m"],
            ["ad_banner_int_ui_db", "m"],
            ["ui_open_close_point_event_db", "m"],
            ["ui_button_click_point_event_db", "mma"],
            ["jump_banner_icon_db", "m"],
            ["item_change_point_event_db", "m"],
            ["view_method_call_point_event_db", "mm"],
            ["follow_rewards_db", "m"],
            ["suit_lottery_price_db", "mm"],
            ["hot_activity_db", "ma"],
            ["hot_activity_leaflet_db", "m"],
            ["material_img_db", "m"],
            ["timeline_template_db", "m"],
            ["role_event_db", "a"],
            ["event_db", "m"],
            ["double_card_lottery_ratio_db", "m"],
            ["double_card_extract_rule_db", "m"]
        ];
        class mgrCfg extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("mgrCfg.onLoad");
            }
            static getLoadUrls() {
                return [
                    `res/cfg/mergeForm.json`,
                    `res/cfg/materialInfo.json`,
                    `res/cfg/dynamicBoneInfo.json`,
                    `res/cfg/shader_compile.json`,
                ];
            }
            static processDb() {
                let datas = Laya.loader.getRes("res/cfg/mergeForm.json");
                for (let index = 0; index < TASKS.length; index++) {
                    const element = TASKS[index];
                    const name = element[0];
                    const rule = element[1];
                    let data = datas[name];
                    if (!data) {
                        console.warn(`mgrCfg processDb error, data is null, url:${name}`);
                        continue;
                    }
                    let db = CfgParser.parseCfgByJsonObj(name, data, rule);
                    if (db) {
                        console.log("配置表加载成功：", name);
                        this.allDbs[name] = db;
                    }
                    else {
                        console.warn("警告] 配置表加载失败！", name);
                        continue;
                    }
                }
                mgrMaterial.setMaterialInfos(Laya.loader.getRes("res/cfg/materialInfo.json"));
                mgrDynamicBone.setDynamicBoneInfos(Laya.loader.getRes("res/cfg/dynamicBoneInfo.json"));
                mgrMaterial.setPrecompileShaderInfos(Laya.loader.getRes("res/cfg/shader_compile.json") || {});
                this._combineItemTemplatedb();
                this._processTextDb();
                this._processAchievementDb();
                this._processStageDb();
                this._processItemBoxDb();
                this._validateCfg();
            }
            static getDb(dbName) {
                let db = this.allDbs[dbName || ""];
                if (!db) {
                    console.warn(`[警告] mgrCfg.getDb db not found! dbName=[${dbName}]`);
                }
                return db;
            }
            static getDbArr(dbName, filterFunc) {
                let db = this.getDb(dbName);
                if (!db)
                    return [];
                let arr = [];
                Tools.forEachMap(db, (k, v) => {
                    if (!filterFunc || filterFunc(v)) {
                        arr.push(v);
                    }
                });
                return arr;
            }
            static getDbAndSortByField(dbName, fields) {
                let db = this.getDb(dbName);
                if (!db)
                    return [];
                let arr = [];
                Tools.forEachMap(db, (k, v) => {
                    arr.push(v);
                });
                if (typeof (fields) == "string") {
                    fields = [fields];
                }
                else {
                    fields = fields;
                }
                return Tools.sortArrayByField(arr, fields);
            }
            static get(dbName, key1, key2 = null, key3 = null, bQuiet = true) {
                let db = this.getDb(dbName);
                if (!db)
                    return null;
                let value = db[key1];
                if (value == null) {
                    if (!bQuiet)
                        console.warn(`[警告] mgrCfg.get [${dbName}.csv]中数据未找到, key1=[${key1}]`);
                    return value;
                }
                if (key2 != null) {
                    value = value[key2];
                    if (value == null) {
                        if (!bQuiet)
                            console.warn(`[警告] mgrCfg.get [${dbName}.csv]中数据未找到, key1=[${key1}], key2=[${key2}]`);
                        return value;
                    }
                }
                if (key3 != null) {
                    value = value[key3];
                    if (value == null) {
                        if (!bQuiet)
                            console.warn(`[警告] mgrCfg.get [${dbName}.csv]中数据未找到, key1=[${key1}], key2=[${key2}], key3=[${key3}]`);
                        return value;
                    }
                }
                return value;
            }
            static quietGet(dbName, key1, key2 = null, key3 = null) {
                return this.get(dbName, key1, key2, key3, true);
            }
            static forDb(dbName, callback) {
                let db = this.getDb(dbName);
                if (db) {
                    Tools.forEachMap(db, callback);
                }
            }
            static _validateCfg() {
                if (!Laya.Browser.onPC) {
                    return;
                }
                console.warn("----------------BEGIN--------role_db------");
                mgrCfg.forDb_from_role_db((k, v) => {
                    for (let k in v.partIds) {
                        if (!this.get_from_part_db(v.partIds[k])) {
                            console.warn("----------------role_db表不存在id,partId=", v.id, v.partIds[k]);
                        }
                    }
                });
                console.warn("----------------END--------role_db------");
                console.warn("----------------BEGIN--------suit_db------");
                mgrCfg.forDb_from_suit_db((k, v) => {
                    for (let k in v.partIds) {
                        if (!this.get_from_part_db(v.partIds[k])) {
                            console.warn("---------------suit_db表不存在id,partId=", v.id, v.partIds[k]);
                        }
                    }
                });
                console.warn("----------------END--------suit_db------");
                console.warn("----------------BEGIN--------pvp_offline_preset_photo_db------");
                console.warn("----------------END--------pvp_offline_preset_photo_db------");
                console.warn("----------------BEGIN--------part_db------");
                mgrCfg.forDb_from_part_db((k, v) => {
                    if (!this.get_from_model_db(v.modelId)) {
                        console.warn("----------------model_db表不存在id,modelId=", v.id, v.modelId);
                    }
                    if (!v.icon || v.icon == "") {
                        console.warn("----------------part_db部件icon没有", v.id);
                    }
                });
                console.warn("----------------END--------part_db------");
                console.warn("----------------BEGIN--------shop_template_db------");
                mgrCfg.forDb_from_shop_template_db((k, v) => {
                    if (v.priceUnit && !this.get_from_item_template_db(v.priceUnit)) {
                        console.warn("----------------item_template_db表不存在v.id,v.priceUnit=", v.id, v.priceUnit);
                    }
                });
                console.warn("----------------END--------shop_template_db------");
                console.warn("----------------BEGIN--------role_face_animation------");
                mgrCfg.forDb_from_role_face_animation((k, v) => {
                    for (let k in v) {
                        if (k == "id") {
                            continue;
                        }
                        if (!this.get_from_animation_db(v[k])) {
                            console.warn("----------------animation_db表不存在id,aniId=", v.id, v[k]);
                        }
                    }
                });
                console.warn("----------------END--------role_face_animation------");
            }
            static _combineItemTemplatedb() {
                let item_template_db = this.getDb("item_template_db");
                mgrCfg.forDb_from_part_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("部件id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: 0,
                        defaultAmount: v.bDefaultHave ? 1 : 0,
                        sellItemId: v.sellItemId || 0,
                        sellItemAmount: v.sellItemAmount || 0,
                        router: v.router || 0
                    };
                });
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("角色id与物品id冲突: ", v);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.headIcon,
                        flag: 0,
                        defaultAmount: v.bDefaultHave ? 1 : 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: v.router || 0
                    };
                });
                mgrCfg.forDb_from_design_part_color_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("服装设计id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_MAKE_CLOTH,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_design_shine_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("服装设计id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_MAKE_CLOTH,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: 0,
                        sellItemAmount: 0,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_design_grid_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("服装设计id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_MAKE_CLOTH,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_amuse_card_style_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("卡面样式id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_CARD,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_amuse_card_photo_recipe_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("卡牌动作id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_CARD,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_cake_cream_color_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("蛋糕制作id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_CAKE,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_cake_paint_color_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("蛋糕制作id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_CAKE,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_cake_deco_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("蛋糕制作id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_CAKE,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_cake_sticker_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("蛋糕制作id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        type: v.type,
                        unlockColorPoint: v.unlockColorPoint,
                        flag: Const.ITEM_FLAG_CAKE,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_cake_shape_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("蛋糕制作id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        unlockColorPoint: 0,
                        flag: Const.ITEM_FLAG_CAKE,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 3,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("玩家卡槽id与物品id冲突: ", v.id);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: "",
                        icon: "",
                        type: 0,
                        unlockColorPoint: 0,
                        flag: 0,
                        defaultAmount: v.defaultAmount || 0,
                        sellItemId: Const.ITEM_ID_DIAMONDS,
                        sellItemAmount: 1,
                        router: 0
                    };
                });
                mgrCfg.forDb_from_item_box_db((k, v) => {
                    if (item_template_db[v.id]) {
                        console.warn("掉落id与物品id冲突: ", v);
                        return;
                    }
                    item_template_db[v.id] = {
                        id: v.id,
                        name: v.name,
                        icon: v.icon,
                        flag: 0,
                        defaultAmount: 0,
                        sellItemId: 0,
                        sellItemAmount: 0,
                        router: 0
                    };
                });
            }
            static _processItemBoxDb() {
                let ratioKeys = [];
                let itemIdKeys = [];
                let minAmountKeys = [];
                let maxAmountKeys = [];
                let bNoRepeatKeys = [];
                for (let i = 1; i <= 10; i++) {
                    ratioKeys.push("ratio_" + i);
                    itemIdKeys.push("itemId_" + i);
                    minAmountKeys.push("minAmount_" + i);
                    maxAmountKeys.push("maxAmount_" + i);
                    bNoRepeatKeys.push("bNoRepeat_" + i);
                }
                let item_template_db = this.allDbs["item_template_db"];
                let newDb = [];
                this.forDb("item_box_db", (k, v) => {
                    let items = [];
                    let newData = {
                        boxId: v.boxId,
                        ratioType: v.ratioType,
                        triggerRatio: v.triggerRatio,
                        items: items,
                    };
                    newDb.push(newData);
                    for (let i = 0; i < ratioKeys.length; i++) {
                        let ratio = v[ratioKeys[i]];
                        let itemId = v[itemIdKeys[i]];
                        let minAmount = v[minAmountKeys[i]];
                        let maxAmount = v[maxAmountKeys[i]];
                        let bNoRepeat = !!v[bNoRepeatKeys[i]];
                        if (itemId > 0) {
                            let itemTemplate = item_template_db[itemId];
                            if (!itemTemplate) {
                            }
                            else {
                                if (maxAmount < minAmount)
                                    maxAmount = minAmount;
                                items.push({
                                    ratio: ratio,
                                    itemId: itemId,
                                    minAmount: minAmount,
                                    maxAmount: maxAmount,
                                    bNoRepeat: bNoRepeat,
                                });
                            }
                        }
                    }
                });
                let allHeadDatas = {};
                for (let i = 0; i < newDb.length; i++) {
                    const v = newDb[i];
                    allHeadDatas[v.boxId] = v;
                }
                this.allDbs["item_box_db"] = allHeadDatas;
            }
            static _processStageDb() {
                Laya.ClassUtils.regClass("StageScriptBase", StageScriptBase);
                Laya.ClassUtils.regClass("StageScriptGuide1", StageScriptGuide1);
                Laya.ClassUtils.regClass("StageScriptPvp", StageScriptPvp);
                Laya.ClassUtils.regClass("StageScriptMakeCard", StageScriptMakeCard);
                let db = this.getDb("stage_db");
                for (let k in db) {
                    let stage = db[k];
                    if (!stage.scriptName || stage.scriptName == "") {
                        stage.scriptName = "StageScriptBase";
                    }
                    let scriptClass = Laya.ClassUtils.getClass(stage.scriptName);
                    let script = new scriptClass();
                    stage["script"] = script;
                }
            }
            static _processTextDb() {
                let arr = [];
                this.allDbs["badword_db"] = arr;
            }
            static _processAchievementDb() {
                Tools.forEachMap(this.getDb("achievement_target_db"), (k, v) => {
                    let cmdHash = {};
                    for (let i = 0; i < v.cmds.length; i++) {
                        const cmd = v.cmds[i];
                        cmdHash[cmd] = true;
                    }
                    v.cmdHash = cmdHash;
                });
            }
            static get_from_alu_db(key1, key2, key3) { return this.get("alu_db", key1, key2, key3); }
            static forDb_from_alu_db(callback) { this.forDb("alu_db", callback); }
            static get_from_part_db(key1, key2, key3) { return this.get("part_db", key1, key2, key3); }
            static forDb_from_part_db(callback) { this.forDb("part_db", callback); }
            static get_from_part_type_db(key1, key2, key3) { return this.get("part_type_db", key1, key2, key3); }
            static forDb_from_part_type_db(callback) { this.forDb("part_type_db", callback); }
            static get_from_part_tag_db(key1, key2, key3) { return this.get("part_tag_db", key1, key2, key3); }
            static forDb_from_part_tag_db(callback) { this.forDb("part_tag_db", callback); }
            static get_from_suit_db(key1, key2, key3) { return this.get("suit_db", key1, key2, key3); }
            static forDb_from_suit_db(callback) { this.forDb("suit_db", callback); }
            static get_from_suit_type_db(key1, key2, key3) { return this.get("suit_type_db", key1, key2, key3); }
            static forDb_from_suit_type_db(callback) { this.forDb("suit_type_db", callback); }
            static get_from_part_animation_change_db(key1, key2, key3) { return this.get("part_animation_change_db", key1, key2, key3); }
            static forDb_from_part_animation_change_db(callback) { this.forDb("part_animation_change_db", callback); }
            static get_from_suit_lottery_price_db(key1, key2, key3) { return this.get("suit_lottery_price_db", key1, key2, key3); }
            static forDb_from_suit_lottery_price_db(callback) { this.forDb("suit_lottery_price_db", callback); }
            static get_from_item_type_db(key1, key2, key3) { return this.get("item_type_db", key1, key2, key3); }
            static forDb_from_item_type_db(callback) { this.forDb("item_type_db", callback); }
            static get_from_cop_db(key1, key2, key3) { return this.get("cop_db", key1, key2, key3); }
            static forDb_from_cop_db(callback) { this.forDb("cop_db", callback); }
            static get_from_cop_process_db(key1, key2, key3) { return this.get("cop_process_db", key1, key2, key3); }
            static forDb_from_cop_process_db(callback) { this.forDb("cop_process_db", callback); }
            static get_from_amuse_card_part_reward_config(key1, key2, key3) { return this.get("amuse_card_part_reward_config", key1, key2, key3); }
            static forDb_from_amuse_card_part_reward_config(callback) { this.forDb("amuse_card_part_reward_config", callback); }
            static get_from_amuse_card_npc_db(key1, key2, key3) { return this.get("amuse_card_npc_db", key1, key2, key3); }
            static forDb_from_amuse_card_npc_db(callback) { this.forDb("amuse_card_npc_db", callback); }
            static get_from_amaze_card_stage_db(key1, key2, key3) { return this.get("amaze_card_stage_db", key1, key2, key3); }
            static forDb_from_amaze_card_stage_db(callback) { this.forDb("amaze_card_stage_db", callback); }
            static get_from_amuse_card_style_db(key1, key2, key3) { return this.get("amuse_card_style_db", key1, key2, key3); }
            static forDb_from_amuse_card_style_db(callback) { this.forDb("amuse_card_style_db", callback); }
            static get_from_amuse_card_photo_recipe_db(key1, key2, key3) { return this.get("amuse_card_photo_recipe_db", key1, key2, key3); }
            static forDb_from_amuse_card_photo_recipe_db(callback) { this.forDb("amuse_card_photo_recipe_db", callback); }
            static get_from_amuse_player_make_card_db(key1, key2, key3) { return this.get("amuse_player_make_card_db", key1, key2, key3); }
            static forDb_from_amuse_player_make_card_db(callback) { this.forDb("amuse_player_make_card_db", callback); }
            static get_from_pvp_offline_lottery_db(key1, key2, key3) { return this.get("pvp_offline_lottery_db", key1, key2, key3); }
            static forDb_from_pvp_offline_lottery_db(callback) { this.forDb("pvp_offline_lottery_db", callback); }
            static get_from_pvp_offline_db(key1, key2, key3) { return this.get("pvp_offline_db", key1, key2, key3); }
            static forDb_from_pvp_offline_db(callback) { this.forDb("pvp_offline_db", callback); }
            static get_from_pvp_offline_subject_db(key1, key2, key3) { return this.get("pvp_offline_subject_db", key1, key2, key3); }
            static forDb_from_pvp_offline_subject_db(callback) { this.forDb("pvp_offline_subject_db", callback); }
            static get_from_barrage_db(key1, key2, key3) { return this.get("barrage_db", key1, key2, key3); }
            static forDb_from_barrage_db(callback) { this.forDb("barrage_db", callback); }
            static get_from_imoge_db(key1, key2, key3) { return this.get("imoge_db", key1, key2, key3); }
            static forDb_from_imoge_db(callback) { this.forDb("imoge_db", callback); }
            static get_from_barrage_color_db(key1, key2, key3) { return this.get("barrage_color_db", key1, key2, key3); }
            static forDb_from_barrage_color_db(callback) { this.forDb("barrage_color_db", callback); }
            static get_from_pvp_offline_photo_bg_db(key1, key2, key3) { return this.get("pvp_offline_photo_bg_db", key1, key2, key3); }
            static forDb_from_pvp_offline_photo_bg_db(callback) { this.forDb("pvp_offline_photo_bg_db", callback); }
            static get_from_pvp_offline_photo_mask_db(key1, key2, key3) { return this.get("pvp_offline_photo_mask_db", key1, key2, key3); }
            static forDb_from_pvp_offline_photo_mask_db(callback) { this.forDb("pvp_offline_photo_mask_db", callback); }
            static get_from_pvp_offline_photo_recipe_db(key1, key2, key3) { return this.get("pvp_offline_photo_recipe_db", key1, key2, key3); }
            static forDb_from_pvp_offline_photo_recipe_db(callback) { this.forDb("pvp_offline_photo_recipe_db", callback); }
            static get_from_pvp_offline_preset_photo_db(key1, key2, key3) { return this.get("pvp_offline_preset_photo_db", key1, key2, key3); }
            static forDb_from_pvp_offline_preset_photo_db(callback) { this.forDb("pvp_offline_preset_photo_db", callback); }
            static get_from_pvp_offline_role_power_base_db(key1, key2, key3) { return this.get("pvp_offline_role_power_base_db", key1, key2, key3); }
            static forDb_from_pvp_offline_role_power_base_db(callback) { this.forDb("pvp_offline_role_power_base_db", callback); }
            static get_from_achievement_db(key1, key2, key3) { return this.get("achievement_db", key1, key2, key3); }
            static forDb_from_achievement_db(callback) { this.forDb("achievement_db", callback); }
            static get_from_achievement_target_db(key1, key2, key3) { return this.get("achievement_target_db", key1, key2, key3); }
            static forDb_from_achievement_target_db(callback) { this.forDb("achievement_target_db", callback); }
            static get_from_quest_achievement_db(key1, key2, key3) { return this.get("quest_achievement_db", key1, key2, key3); }
            static forDb_from_quest_achievement_db(callback) { this.forDb("quest_achievement_db", callback); }
            static get_from_design_part_config(key1, key2, key3) { return this.get("design_part_config", key1, key2, key3); }
            static forDb_from_design_part_config(callback) { this.forDb("design_part_config", callback); }
            static get_from_design_part_color_db(key1, key2, key3) { return this.get("design_part_color_db", key1, key2, key3); }
            static forDb_from_design_part_color_db(callback) { this.forDb("design_part_color_db", callback); }
            static get_from_design_grid_db(key1, key2, key3) { return this.get("design_grid_db", key1, key2, key3); }
            static forDb_from_design_grid_db(callback) { this.forDb("design_grid_db", callback); }
            static get_from_design_shine_db(key1, key2, key3) { return this.get("design_shine_db", key1, key2, key3); }
            static forDb_from_design_shine_db(callback) { this.forDb("design_shine_db", callback); }
            static get_from_custom_made_clothes_stage_db(key1, key2, key3) { return this.get("custom_made_clothes_stage_db", key1, key2, key3); }
            static forDb_from_custom_made_clothes_stage_db(callback) { this.forDb("custom_made_clothes_stage_db", callback); }
            static get_from_material_img_db(key1, key2, key3) { return this.get("material_img_db", key1, key2, key3); }
            static forDb_from_material_img_db(callback) { this.forDb("material_img_db", callback); }
            static get_from_amaze_pen_part_reward_config(key1, key2, key3) { return this.get("amaze_pen_part_reward_config", key1, key2, key3); }
            static forDb_from_amaze_pen_part_reward_config(callback) { this.forDb("amaze_pen_part_reward_config", callback); }
            static get_from_amaze_pen_stage_db(key1, key2, key3) { return this.get("amaze_pen_stage_db", key1, key2, key3); }
            static forDb_from_amaze_pen_stage_db(callback) { this.forDb("amaze_pen_stage_db", callback); }
            static get_from_amaze_pen_select_role_db(key1, key2, key3) { return this.get("amaze_pen_select_role_db", key1, key2, key3); }
            static forDb_from_amaze_pen_select_role_db(callback) { this.forDb("amaze_pen_select_role_db", callback); }
            static get_from_amaze_parkour_stage_db(key1, key2, key3) { return this.get("amaze_parkour_stage_db", key1, key2, key3); }
            static forDb_from_amaze_parkour_stage_db(callback) { this.forDb("amaze_parkour_stage_db", callback); }
            static get_from_amaze_parkour_skin_db(key1, key2, key3) { return this.get("amaze_parkour_skin_db", key1, key2, key3); }
            static forDb_from_amaze_parkour_skin_db(callback) { this.forDb("amaze_parkour_skin_db", callback); }
            static get_from_amaze_cloth_crossing_stage_db(key1, key2, key3) { return this.get("amaze_cloth_crossing_stage_db", key1, key2, key3); }
            static forDb_from_amaze_cloth_crossing_stage_db(callback) { this.forDb("amaze_cloth_crossing_stage_db", callback); }
            static get_from_amaze_cloth_crossing_skin_db(key1, key2, key3) { return this.get("amaze_cloth_crossing_skin_db", key1, key2, key3); }
            static forDb_from_amaze_cloth_crossing_skin_db(callback) { this.forDb("amaze_cloth_crossing_skin_db", callback); }
            static get_from_amuse_cloth_crossing_photo_recipe_db(key1, key2, key3) { return this.get("amuse_cloth_crossing_photo_recipe_db", key1, key2, key3); }
            static forDb_from_amuse_cloth_crossing_photo_recipe_db(callback) { this.forDb("amuse_cloth_crossing_photo_recipe_db", callback); }
            static get_from_cake_stage_db(key1, key2, key3) { return this.get("cake_stage_db", key1, key2, key3); }
            static forDb_from_cake_stage_db(callback) { this.forDb("cake_stage_db", callback); }
            static get_from_cake_cream_combine_db(key1, key2, key3) { return this.get("cake_cream_combine_db", key1, key2, key3); }
            static forDb_from_cake_cream_combine_db(callback) { this.forDb("cake_cream_combine_db", callback); }
            static get_from_cake_cream_color_db(key1, key2, key3) { return this.get("cake_cream_color_db", key1, key2, key3); }
            static forDb_from_cake_cream_color_db(callback) { this.forDb("cake_cream_color_db", callback); }
            static get_from_cake_paint_color_db(key1, key2, key3) { return this.get("cake_paint_color_db", key1, key2, key3); }
            static forDb_from_cake_paint_color_db(callback) { this.forDb("cake_paint_color_db", callback); }
            static get_from_cake_deco_db(key1, key2, key3) { return this.get("cake_deco_db", key1, key2, key3); }
            static forDb_from_cake_deco_db(callback) { this.forDb("cake_deco_db", callback); }
            static get_from_cake_sticker_db(key1, key2, key3) { return this.get("cake_sticker_db", key1, key2, key3); }
            static forDb_from_cake_sticker_db(callback) { this.forDb("cake_sticker_db", callback); }
            static get_from_stage_db(key1, key2, key3) { return this.get("stage_db", key1, key2, key3); }
            static forDb_from_stage_db(callback) { this.forDb("stage_db", callback); }
            static get_from_stage_chapter_db(key1, key2, key3) { return this.get("stage_chapter_db", key1, key2, key3); }
            static forDb_from_stage_chapter_db(callback) { this.forDb("stage_chapter_db", callback); }
            static get_from_story_db(key1, key2, key3) { return this.get("story_db", key1, key2, key3); }
            static forDb_from_story_db(callback) { this.forDb("story_db", callback); }
            static get_from_stage_result_dress_part_config(key1, key2, key3) { return this.get("stage_result_dress_part_config", key1, key2, key3); }
            static forDb_from_stage_result_dress_part_config(callback) { this.forDb("stage_result_dress_part_config", callback); }
            static get_from_ad_event_db(key1, key2, key3) { return this.get("ad_event_db", key1, key2, key3); }
            static forDb_from_ad_event_db(callback) { this.forDb("ad_event_db", callback); }
            static get_from_ad_banner_int_ui_db(key1, key2, key3) { return this.get("ad_banner_int_ui_db", key1, key2, key3); }
            static forDb_from_ad_banner_int_ui_db(callback) { this.forDb("ad_banner_int_ui_db", callback); }
            static get_from_ad_suit_config_db(key1, key2, key3) { return this.get("ad_suit_config_db", key1, key2, key3); }
            static forDb_from_ad_suit_config_db(callback) { this.forDb("ad_suit_config_db", callback); }
            static get_from_hot_activity_db(key1, key2, key3) { return this.get("hot_activity_db", key1, key2, key3); }
            static forDb_from_hot_activity_db(callback) { this.forDb("hot_activity_db", callback); }
            static get_from_hot_activity_leaflet_db(key1, key2, key3) { return this.get("hot_activity_leaflet_db", key1, key2, key3); }
            static forDb_from_hot_activity_leaflet_db(callback) { this.forDb("hot_activity_leaflet_db", callback); }
            static get_from_model_db(key1, key2, key3) { return this.get("model_db", key1, key2, key3); }
            static forDb_from_model_db(callback) { this.forDb("model_db", callback); }
            static get_from_animation_db(key1, key2, key3) { return this.get("animation_db", key1, key2, key3); }
            static forDb_from_animation_db(callback) { this.forDb("animation_db", callback); }
            static get_from_spine_db(key1, key2, key3) { return this.get("spine_db", key1, key2, key3); }
            static forDb_from_spine_db(callback) { this.forDb("spine_db", callback); }
            static get_from_role_db(key1, key2, key3) { return this.get("role_db", key1, key2, key3); }
            static forDb_from_role_db(callback) { this.forDb("role_db", callback); }
            static get_from_center_role_click_feedback_db(key1, key2, key3) { return this.get("center_role_click_feedback_db", key1, key2, key3); }
            static forDb_from_center_role_click_feedback_db(callback) { this.forDb("center_role_click_feedback_db", callback); }
            static get_from_left_right_role_click_feedback_db(key1, key2, key3) { return this.get("left_right_role_click_feedback_db", key1, key2, key3); }
            static forDb_from_left_right_role_click_feedback_db(callback) { this.forDb("left_right_role_click_feedback_db", callback); }
            static get_from_room_dress_role_feedback_db(key1, key2, key3) { return this.get("room_dress_role_feedback_db", key1, key2, key3); }
            static forDb_from_room_dress_role_feedback_db(callback) { this.forDb("room_dress_role_feedback_db", callback); }
            static get_from_hub_role_standby_feedback_db(key1, key2, key3) { return this.get("hub_role_standby_feedback_db", key1, key2, key3); }
            static forDb_from_hub_role_standby_feedback_db(callback) { this.forDb("hub_role_standby_feedback_db", callback); }
            static get_from_role_face_animation(key1, key2, key3) { return this.get("role_face_animation", key1, key2, key3); }
            static forDb_from_role_face_animation(callback) { this.forDb("role_face_animation", callback); }
            static get_from_role_face_body_animation_relation_db(key1, key2, key3) { return this.get("role_face_body_animation_relation_db", key1, key2, key3); }
            static forDb_from_role_face_body_animation_relation_db(callback) { this.forDb("role_face_body_animation_relation_db", callback); }
            static get_from_sign_db(key1, key2, key3) { return this.get("sign_db", key1, key2, key3); }
            static forDb_from_sign_db(callback) { this.forDb("sign_db", callback); }
            static get_from_online_reward_db(key1, key2, key3) { return this.get("online_reward_db", key1, key2, key3); }
            static forDb_from_online_reward_db(callback) { this.forDb("online_reward_db", callback); }
            static get_from_world_daily_quest(key1, key2, key3) { return this.get("world_daily_quest", key1, key2, key3); }
            static forDb_from_world_daily_quest(callback) { this.forDb("world_daily_quest", callback); }
            static get_from_world_daily_quest_config(key1, key2, key3) { return this.get("world_daily_quest_config", key1, key2, key3); }
            static forDb_from_world_daily_quest_config(callback) { this.forDb("world_daily_quest_config", callback); }
            static get_from_cake_daily_quest_config(key1, key2, key3) { return this.get("cake_daily_quest_config", key1, key2, key3); }
            static forDb_from_cake_daily_quest_config(callback) { this.forDb("cake_daily_quest_config", callback); }
            static get_from_pen_daily_quest_config(key1, key2, key3) { return this.get("pen_daily_quest_config", key1, key2, key3); }
            static forDb_from_pen_daily_quest_config(callback) { this.forDb("pen_daily_quest_config", callback); }
            static get_from_cloth_daily_quest_config(key1, key2, key3) { return this.get("cloth_daily_quest_config", key1, key2, key3); }
            static forDb_from_cloth_daily_quest_config(callback) { this.forDb("cloth_daily_quest_config", callback); }
            static get_from_world_game_db(key1, key2, key3) { return this.get("world_game_db", key1, key2, key3); }
            static forDb_from_world_game_db(callback) { this.forDb("world_game_db", callback); }
            static get_from_custom_made_cloth_daily_quest_config(key1, key2, key3) { return this.get("custom_made_cloth_daily_quest_config", key1, key2, key3); }
            static forDb_from_custom_made_cloth_daily_quest_config(callback) { this.forDb("custom_made_cloth_daily_quest_config", callback); }
            static get_from_parkour_daily_quest_config(key1, key2, key3) { return this.get("parkour_daily_quest_config", key1, key2, key3); }
            static forDb_from_parkour_daily_quest_config(callback) { this.forDb("parkour_daily_quest_config", callback); }
            static get_from_cloth_crossing_daily_quest_config(key1, key2, key3) { return this.get("cloth_crossing_daily_quest_config", key1, key2, key3); }
            static forDb_from_cloth_crossing_daily_quest_config(callback) { this.forDb("cloth_crossing_daily_quest_config", callback); }
            static get_from_timeline_template_db(key1, key2, key3) { return this.get("timeline_template_db", key1, key2, key3); }
            static forDb_from_timeline_template_db(callback) { this.forDb("timeline_template_db", callback); }
            static get_from_alert_router_db(key1, key2, key3) { return this.get("alert_router_db", key1, key2, key3); }
            static forDb_from_alert_router_db(callback) { this.forDb("alert_router_db", callback); }
            static get_from_ui_button_click_point_event_db(key1, key2, key3) { return this.get("ui_button_click_point_event_db", key1, key2, key3); }
            static forDb_from_ui_button_click_point_event_db(callback) { this.forDb("ui_button_click_point_event_db", callback); }
            static get_from_ui_open_close_point_event_db(key1, key2, key3) { return this.get("ui_open_close_point_event_db", key1, key2, key3); }
            static forDb_from_ui_open_close_point_event_db(callback) { this.forDb("ui_open_close_point_event_db", callback); }
            static get_from_jump_banner_icon_db(key1, key2, key3) { return this.get("jump_banner_icon_db", key1, key2, key3); }
            static forDb_from_jump_banner_icon_db(callback) { this.forDb("jump_banner_icon_db", callback); }
            static get_from_item_change_point_event_db(key1, key2, key3) { return this.get("item_change_point_event_db", key1, key2, key3); }
            static forDb_from_item_change_point_event_db(callback) { this.forDb("item_change_point_event_db", callback); }
            static get_from_view_method_call_point_event_db(key1, key2, key3) { return this.get("view_method_call_point_event_db", key1, key2, key3); }
            static forDb_from_view_method_call_point_event_db(callback) { this.forDb("view_method_call_point_event_db", callback); }
            static get_from_random_name_db(key1, key2, key3) { return this.get("random_name_db", key1, key2, key3); }
            static forDb_from_random_name_db(callback) { this.forDb("random_name_db", callback); }
            static get_from_random_tip_db(key1, key2, key3) { return this.get("random_tip_db", key1, key2, key3); }
            static forDb_from_random_tip_db(callback) { this.forDb("random_tip_db", callback); }
            static get_from_item_template_db(key1, key2, key3) { return this.get("item_template_db", key1, key2, key3); }
            static forDb_from_item_template_db(callback) { this.forDb("item_template_db", callback); }
            static get_from_shop_template_db(key1, key2, key3) { return this.get("shop_template_db", key1, key2, key3); }
            static forDb_from_shop_template_db(callback) { this.forDb("shop_template_db", callback); }
            static get_from_item_recover_db(key1, key2, key3) { return this.get("item_recover_db", key1, key2, key3); }
            static forDb_from_item_recover_db(callback) { this.forDb("item_recover_db", callback); }
            static get_from_item_box_db(key1, key2, key3) { return this.get("item_box_db", key1, key2, key3); }
            static forDb_from_item_box_db(callback) { this.forDb("item_box_db", callback); }
            static get_from_follow_rewards_db(key1, key2, key3) { return this.get("follow_rewards_db", key1, key2, key3); }
            static forDb_from_follow_rewards_db(callback) { this.forDb("follow_rewards_db", callback); }
            static get_from_item_router_go_db(key1, key2, key3) { return this.get("item_router_go_db", key1, key2, key3); }
            static forDb_from_item_router_go_db(callback) { this.forDb("item_router_go_db", callback); }
            static get_from_guide_db(key1, key2, key3) { return this.get("guide_db", key1, key2, key3); }
            static forDb_from_guide_db(callback) { this.forDb("guide_db", callback); }
            static get_from_sound_db(key1, key2, key3) { return this.get("sound_db", key1, key2, key3); }
            static forDb_from_sound_db(callback) { this.forDb("sound_db", callback); }
            static get_from_world_color_db(key1, key2, key3) { return this.get("world_color_db", key1, key2, key3); }
            static forDb_from_world_color_db(callback) { this.forDb("world_color_db", callback); }
            static get_from_cake_shape_db(key1, key2, key3) { return this.get("cake_shape_db", key1, key2, key3); }
            static forDb_from_cake_shape_db(callback) { this.forDb("cake_shape_db", callback); }
            static get_from_amuse_double_card_npc_db(key1, key2, key3) { return this.get("amuse_double_card_npc_db", key1, key2, key3); }
            static forDb_from_amuse_double_card_npc_db(callback) { this.forDb("amuse_double_card_npc_db", callback); }
            static get_from_amuse_double_npc_card_role_pic_db(key1, key2, key3) { return this.get("amuse_double_npc_card_role_pic_db", key1, key2, key3); }
            static forDb_from_amuse_double_npc_card_role_pic_db(callback) { this.forDb("amuse_double_npc_card_role_pic_db", callback); }
            static get_from_role_event_db(key1, key2, key3) { return this.get("role_event_db", key1, key2, key3); }
            static forDb_from_role_event_db(callback) { this.forDb("role_event_db", callback); }
            static get_from_event_db(key1, key2, key3) { return this.get("event_db", key1, key2, key3); }
            static forDb_from_event_db(callback) { this.forDb("event_db", callback); }
            static get_from_double_card_lottery_ratio_db(key1, key2, key3) { return this.get("double_card_lottery_ratio_db", key1, key2, key3); }
            static forDb_from_double_card_lottery_ratio_db(callback) { this.forDb("double_card_lottery_ratio_db", callback); }
            static get_from_double_card_extract_rule_db(key1, key2, key3) { return this.get("double_card_extract_rule_db", key1, key2, key3); }
            static forDb_from_double_card_extract_rule_db(callback) { this.forDb("double_card_extract_rule_db", callback); }
            static get_from_amuse_card_skill_db(key1, key2, key3) { return this.get("amuse_card_skill_db", key1, key2, key3); }
            static forDb_from_amuse_card_skill_db(callback) { this.forDb("amuse_card_skill_db", callback); }
            static get_from_amuse_card_skil_collection_db(key1, key2, key3) { return this.get("amuse_card_skil_collection_db", key1, key2, key3); }
            static forDb_from_amuse_card_skil_collection_db(callback) { this.forDb("amuse_card_skil_collection_db", callback); }
            static get_from_amuse_card_new_year_reward_config_db(key1, key2, key3) { return this.get("amuse_card_new_year_reward_config_db", key1, key2, key3); }
            static forDb_from_amuse_card_new_year_reward_config_db(callback) { this.forDb("amuse_card_new_year_reward_config_db", callback); }
            static get_from_role_collect_jump_db(key1, key2, key3) { return this.get("role_collect_jump_db", key1, key2, key3); }
            static forDb_from_role_collect_jump_db(callback) { this.forDb("role_collect_jump_db", callback); }
            static get_from_amuse_card_skill_effect_db(key1, key2, key3) { return this.get("amuse_card_skill_effect_db", key1, key2, key3); }
            static forDb_from_amuse_card_skill_effect_db(callback) { this.forDb("amuse_card_skill_effect_db", callback); }
        }
        mgrCfg.allDbs = {};
        mgrCfg.dbRules = {};

        class PoolManager {
            constructor() {
                this.pool = {};
            }
            getAllocCount(poolId) {
                let pool = this.pool[poolId];
                if (!pool)
                    return 0;
                if (!pool.objs)
                    return 0;
                return pool.allocCount;
            }
            preAllocModel(modelId, count, finishCallback) {
                if (this.isHaveClone(modelId.toString())) {
                    finishCallback();
                    return;
                }
                let model = this.getModel(modelId);
                mgrDirector.get3DRoot().addChild(model);
                if (PoolManager.loadedModelIds.indexOf(modelId) == -1) {
                    PoolManager.loadedModelIds.push(modelId);
                    Timer.callLater(0.5, () => {
                        this.recoverModel(model);
                        finishCallback();
                    }, this);
                }
                else {
                    this.recoverModel(model);
                    finishCallback();
                }
            }
            getModel(modelId) {
                if (!this.pool[modelId]) {
                    this.pool[modelId] = {
                        lastGetTime: Tools.gameExecuteTime(),
                        allocCount: 0,
                        objs: [],
                        poolId: modelId,
                    };
                }
                if (this.pool[modelId].objs.length <= 0) {
                    this.pool[modelId].objs.push(mgrLoader.getModeWithModeId(modelId));
                    this.pool[modelId].allocCount++;
                }
                this.pool[modelId].lastGetTime = Tools.gameExecuteTime();
                let model = this.pool[modelId].objs.shift();
                model.transform.position = new Laya.Vector3();
                model.transform.rotationEuler = new Laya.Vector3();
                model.transform.setWorldLossyScale(new Laya.Vector3(1, 1, 1));
                model.layer = 0;
                model.active = true;
                return model;
            }
            containModel(modelId) {
                if (!this.pool[modelId]) {
                    return false;
                }
                if (this.pool[modelId].objs.length <= 0) {
                    return false;
                }
                return true;
            }
            recoverModel(model) {
                let modelId = model["__modelId"];
                if (!modelId) {
                    return;
                }
                if (this.pool[modelId].objs.indexOf(model) >= 0)
                    return;
                let animator = model.getComponent(Laya.Animator);
                if (!!animator) {
                    animator.enabled = false;
                }
                cc.tween(model.transform).removeAllActions();
                model.removeSelf();
                Tools.changeParticleSimulationSpeed(model, 1);
                this.pool[modelId].objs.push(model);
                return true;
            }
            clearAll() {
                Tools.forEachMap(this.pool, (poolId, pool) => {
                    if (pool.allocCount > pool.objs.length) {
                        console.warn(`warning resource isn't full recover, please checkout alloc/cur: ${poolId}:${pool.allocCount}/${pool.objs.length}`);
                    }
                    else {
                        for (let index = 0; index < pool.objs.length; index++) {
                            const obj = pool.objs[index];
                            if (obj instanceof Laya.Sprite3D) {
                                if (!obj.destroyed)
                                    obj.destroy();
                            }
                            else {
                            }
                        }
                        pool.objs = [];
                        pool.allocCount = 0;
                    }
                });
            }
            _releaseResourceWithPoolId(poolId, leftCount = 0) {
                let pool = this.pool[poolId];
                let newObjs = [];
                for (let index = 0; index < pool.objs.length; index++) {
                    const obj = pool.objs[index];
                    if (index < leftCount) {
                        newObjs.push(obj);
                        continue;
                    }
                    ;
                    if (obj instanceof Laya.Sprite3D) {
                        if (!obj.destroyed)
                            obj.destroy();
                    }
                    else {
                    }
                }
                this.pool[poolId].objs = newObjs;
                pool.allocCount = leftCount;
            }
            _autoReleaseWithPoolId(poolId) {
                let pool = this.pool[poolId];
                if (pool.allocCount == 0) {
                    return false;
                }
                if (Tools.gameExecuteTime() - pool.lastGetTime < 100) {
                    return true;
                }
                this._releaseResourceWithPoolId(poolId);
                return false;
            }
            autoRelease() {
                let count = 0;
                let maxCount = 100;
                let pools = [];
                Tools.forEachMap(this.pool, (poolId, pool) => {
                    pools.push(pool);
                });
                pools = Tools.sortArrayByField(pools, "lastGetTime");
                Tools.forEachMap(pools, (index, pool) => {
                    let poolId = pool.poolId;
                    if (pool.allocCount > pool.objs.length) {
                        return;
                    }
                    if (count <= maxCount) {
                        if (this._autoReleaseWithPoolId(poolId)) {
                            count++;
                        }
                    }
                    else {
                        this._releaseResourceWithPoolId(poolId);
                    }
                });
            }
            isHaveClone(poolId) {
                let pool = this.pool[poolId];
                if (!pool)
                    return false;
                if (!pool.objs)
                    return false;
                return pool.allocCount > 0;
            }
        }
        PoolManager.loadedModelIds = [];

        class mgrLoader extends Manager {
            static onLoad() {
                super.onLoad();
            }
            static get Pool() {
                if (!this.__pool__)
                    this.__pool__ = new PoolManager;
                return this.__pool__;
            }
            static markPartResLoaded(partId) {
                this.loadedResPartIdDict[partId || 0] = true;
            }
            static isLoadedResPartId(partId) {
                return !!this.loadedResPartIdDict[partId || 0];
            }
            static getLoadedResPartIdDict() {
                return this.loadedResPartIdDict || {};
            }
            static isLoadedWithModelId(modeId) {
                let modeData = mgrCfg.get_from_model_db(modeId);
                if (!modeData) {
                    return false;
                }
                let url = `${modeData.modelPath}${modeData.modelName}.lh`;
                if (this.allRess[url]) {
                    return true;
                }
                return false;
            }
            static loadModeWithModeId(modeId, callback, caller, tag) {
                let modeData = mgrCfg.get_from_model_db(modeId);
                if (!modeData) {
                    console.warn("[error]:找不到模型配置:" + modeId);
                    callback(false);
                    return;
                }
                let url = `${modeData.modelPath}${modeData.modelName}.lh`;
                if (this.allRess[url]) {
                    callback(true);
                    return;
                }
                ;
                this.LoadRes(url, (bSuccessful) => {
                    if (bSuccessful) {
                        let model = this.allRess[url];
                        model["__modelId"] = modeId;
                        callback(true);
                    }
                    else {
                        callback(false);
                    }
                }, caller, tag);
            }
            static getModeWithModeId(modeId) {
                let modeData = mgrCfg.get_from_model_db(modeId);
                if (!modeData) {
                    console.warn("[error]:找不到模型配置:" + modeId);
                    return new Laya.Sprite3D;
                }
                let res = this.GetRes(`${modeData.modelPath}${modeData.modelName}.lh`, modeId);
                if (!res) {
                    console.warn("[error]:资源尚未加载" + modeId);
                    res = new Laya.Sprite3D;
                }
                return res;
            }
            static GetRes(url, modelId) {
                let res = this.allRess[url];
                if (res) {
                    let _instantiateRes = Laya.Sprite3D.instantiate(res.res);
                    _instantiateRes["__modelId"] = modelId;
                    return _instantiateRes;
                }
                return null;
            }
            static LoadRes(url, callback, caller, tag) {
                Laya.Sprite3D.load(url, new Laya.Handler(this, (res) => {
                    if (res) {
                        this.allRess[url] = {
                            tag: tag,
                            res: res,
                        };
                        if (!caller) {
                            return;
                        }
                        else if (caller instanceof Laya.Node) {
                            if (!caller.parent) {
                                return;
                            }
                        }
                        else if (caller["destroyed"]) {
                            return;
                        }
                        callback(true);
                    }
                    else {
                        if (!caller) {
                            return;
                        }
                        else if (caller instanceof Laya.Node) {
                            if (!caller.parent) {
                                return;
                            }
                        }
                        else if (caller["destroyed"]) {
                            return;
                        }
                        console.warn("[error] 加载资源失败 再次尝试: " + url);
                        Timer.callLater(0.01, () => {
                            this.LoadRes(url, callback, caller, tag);
                        }, this);
                    }
                }));
            }
            static releaseAllRes(tag) {
            }
            static autoReleaseRes() {
                return;
                this.Pool.autoRelease();
                Tools.forEachMap(this.allRess, (k, v) => {
                    let modelId = v.__modelId;
                    if (!this.Pool.isHaveClone(modelId) && v.tag == 1) {
                        console.log(`mgrloader->autorelease : ${modelId}`);
                        v.res.destroy();
                        this.allRess[k] = null;
                    }
                });
                Laya.Resource.destroyUnusedResources();
            }
            static releseAllResourceByModelId(modelId) {
                let modelData = mgrCfg.get_from_model_db(modelId);
                let url = `${modelData.modelPath}${modelData.modelName}.lh`;
                Laya.loader.load(url, new Laya.Handler(this, (json) => {
                    let resourceUrls = this.findAllResources(json);
                    for (let index = 0; index < resourceUrls.length; index++) {
                        const url = resourceUrls[index];
                        let resource = Laya.Resource.getResourceByURL(url);
                        if (resource) {
                            resource.destroy();
                            console.log(`释放资源: ${url}`);
                        }
                    }
                }), null, Laya.Loader.JSON);
            }
            static findAllResources(json) {
                let resources = [];
                for (const k in json) {
                    let content = json[k];
                    if (content) {
                        let type = ul.getType(content);
                        if (type === "object" || type == `array`) {
                            resources = resources.concat(this.findAllResources(content));
                        }
                        else {
                            let resourceKeys = [
                                'mesh',
                                'material',
                                'path',
                                'clipPath',
                                'meshPath'
                            ];
                            if (resourceKeys.indexOf(k) >= 0) {
                                resources.push(content);
                            }
                        }
                    }
                }
                return resources;
            }
            static get2dRes(url) {
                return Laya.Loader.getRes(url);
            }
            static Load2dRes(url, type, caller, callback, progress) {
                if (type == Laya.Loader.PREFAB || type == Laya.Loader.JSON) {
                    if (!/.json/.test(url))
                        url += ".json";
                }
                if (/http/.test(url) || /https/.test(url)) {
                }
                else {
                    if (url.substring(0, url.indexOf("/")) != "res")
                        url = "res/" + url;
                }
                Laya.loader.load(url, new Laya.Handler(this, (res) => {
                    if (!this.checkCaller(caller))
                        return;
                    if (!res) {
                        Timer.callLater(0.3, () => {
                            console.warn("[error] 加载资源失败 再次尝试: " + url);
                            this.Load2dRes(url, type, caller, callback, progress);
                        }, caller);
                    }
                    else {
                        callback(res);
                    }
                }), new Laya.Handler(this, (pr) => {
                    progress && progress(pr);
                }), type);
            }
            static checkCaller(caller) {
                if (!caller) {
                    return false;
                }
                else if (caller["destroyed"]) {
                    return false;
                }
                return true;
            }
            static processRemoteResLoad() {
                if (this.curLoadingRemoteResInfo) {
                    console.log(`正在加载远程资源...: url:${this.curLoadingRemoteResInfo.url}`);
                    return;
                }
                else {
                    if (this.RemoteResLoadQueue.length <= 0) {
                        return;
                    }
                    else {
                        this.curLoadingRemoteResInfo = this.RemoteResLoadQueue.shift();
                        console.log(`开始加载远程资源:${this.curLoadingRemoteResInfo.url}`);
                        try {
                            this.loadRemoteResQg(this.curLoadingRemoteResInfo.url, (err, tex) => {
                                if (this.curLoadingRemoteResInfo.bHaveCaller && !this.checkCaller(this.curLoadingRemoteResInfo.caller)) {
                                    console.log(`远程资源:${this.curLoadingRemoteResInfo.url} 调用者销毁`);
                                    this.curLoadingRemoteResInfo = null;
                                    return;
                                }
                                if (err) {
                                    console.log(`远程资源加载失败: 放在队尾重试: ${this.curLoadingRemoteResInfo.url}`);
                                    this.RemoteResLoadQueue.push(this.curLoadingRemoteResInfo);
                                    this.curLoadingRemoteResInfo = null;
                                }
                                else {
                                    console.log(`远程资源加载成功: ${this.curLoadingRemoteResInfo.url}`);
                                    this.curLoadingRemoteResInfo.callback(err, tex);
                                }
                            });
                        }
                        catch (error) {
                            console.log(error);
                            console.log(`远程资源加载失败: 放在队尾重试: ${this.curLoadingRemoteResInfo.url}`);
                            this.RemoteResLoadQueue.push(this.curLoadingRemoteResInfo);
                            this.curLoadingRemoteResInfo = null;
                        }
                    }
                }
            }
            static loadRemoteResQg(url, callback) {
                if (this.__cachedRemoteTexture[url]) {
                    callback(null, this.__cachedRemoteTexture[url]);
                    return;
                }
                let img = new Image();
                let loadedCallback = () => {
                    img.removeEventListener("load", loadedCallback);
                    img.removeEventListener("error", errorCallback);
                    console.log("IMAGE 加载成功!!", url);
                    let texture = new Laya.Texture2D();
                    texture.loadImageSource(texture);
                    this.__cachedRemoteTexture[url] = texture;
                    callback(null, texture);
                };
                let errorCallback = () => {
                    img.removeEventListener("load", loadedCallback);
                    img.removeEventListener("error", errorCallback);
                    console.log("IMAGE 加载失败!!", url);
                    callback({ error: "error" }, null);
                };
                img.addEventListener('load', loadedCallback);
                img.addEventListener('error', errorCallback);
                img.src = url;
            }
            static loadFont(fontName, label, callback) {
                if (!label)
                    return;
                if (this.loadedFontname[fontName]) {
                    label.font = fontName;
                    let tmp = label.text;
                    label.text = "";
                    label.text = tmp;
                    callback && callback();
                    return;
                }
                console.log(`开始加载字体:${fontName}`);
                let bmFont = new Laya.BitmapFont();
                bmFont.loadFont(`res/font/${fontName}.fnt`, new Laya.Handler(this, () => {
                    Laya.Text.registerBitmapFont(fontName, bmFont);
                    this.loadedFontname[fontName] = true;
                    if (!label || label.destroyed)
                        return;
                    label.font = fontName;
                    let tmp = label.text;
                    label.text = "";
                    label.text = tmp;
                    callback && callback();
                }));
            }
            static batchLoadResources(modelIds, animationIds, imagePaths, callback) {
                modelIds = modelIds || [];
                animationIds = animationIds || [];
                imagePaths = imagePaths || [];
                let taskManager = new TaskManager();
                let taskSamples = [];
                for (let i = 0; i < modelIds.length; i++) {
                    const modelId = modelIds[i];
                    taskSamples.push((endCallback) => {
                        mgrLoader.loadModeWithModeId(modelId, () => {
                            endCallback();
                        }, this, 1);
                    });
                }
                for (let i = 0; i < animationIds.length; i++) {
                    const animationId = animationIds[i];
                    let animationData = mgrCfg.get_from_animation_db(animationId);
                    taskSamples.push((endCallback) => {
                        Laya.AnimationClip.load(animationData.path, new Laya.Handler(this, (clip) => {
                            endCallback();
                        }));
                    });
                }
                for (let i = 0; i < imagePaths.length; i++) {
                    const path = imagePaths[i];
                    taskSamples.push((endCallback) => {
                        this.Load2dRes(path, Laya.Loader.IMAGE, this, (res) => {
                            endCallback();
                        });
                    });
                }
                taskManager.push(taskSamples);
                taskManager.start(() => {
                    callback && callback();
                });
            }
            static batchTaskSamples(sampleCallbackArr, completeCallback) {
                let taskManager = new TaskManager;
                let taskSamples = [];
                for (let i = 0; i < sampleCallbackArr.length; i++) {
                    taskSamples.push(sampleCallbackArr[i]);
                }
                taskManager.push(taskSamples);
                taskManager.start(() => {
                    if (completeCallback) {
                        completeCallback();
                    }
                });
            }
        }
        mgrLoader.loadedResPartIdDict = {};
        mgrLoader.allRess = {};
        mgrLoader.RemoteResLoadQueue = [];
        mgrLoader.curLoadingRemoteResInfo = null;
        mgrLoader.__cachedRemoteTexture = {};
        mgrLoader.loadedFontname = {};

        class SceneBase extends ViewBase {
        }
        SceneBase.showingSceneName = null;

        class mgrActivingBanner extends Manager {
            static onLoad() {
                super.onLoad();
                this.enterGameTime = Tools.time();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                this.registerListeners({
                    MSG_NATIVE_DATA_REFRESH: this.onMsgNativeDataRefresh,
                });
            }
            static saveRecord() {
                super.saveRecord();
            }
            static onMsgNativeDataRefresh(e) {
                if (this.nativeBanner) {
                    console.log("执行刷新", this.nativeBanner.adEventId);
                    this.nativeBanner.refreshBanner();
                }
            }
            static checkCouldActivingBanner() {
                if (Tools.time() < this.enterGameTime + mgrSdk.getCopNumberValueByKey("activing_not_show_time")) {
                    return false;
                }
                let cd = mgrSdk.getCopNumberValueByKey("activing_mode_cd");
                if (Tools.time() > this.lastActivingBannerTime + cd) {
                    this.lastActivingBannerTime = Tools.time();
                    return true;
                }
                else {
                    return false;
                }
            }
            static activingAlertBanner(index, caller) {
                let viewName = mgrBannerInt.activingViewNameArr[index];
                let adEventId = "banner_active_" + viewName;
                let switcher = mgrSdk.getCopByKey("activing_mode_switch").split(";")[index] == "1";
                if (switcher && this.checkCouldActivingBanner()) {
                    let delay_time_open = parseInt(mgrSdk.getCopByKey("activing_mode_delay_time_open").split(";")[index]);
                    let delay_time_close = parseInt(mgrSdk.getCopByKey("activing_mode_delay_time_close").split(";")[index]);
                    let nativeAdBanner = new vNativeBanner({}, true);
                    let root = mgrDirector.get2DDialogLayer();
                    root.addChild(nativeAdBanner);
                    nativeAdBanner.zOrder = 100000;
                    this.nativeBanner = nativeAdBanner;
                    Timer.callLater(delay_time_open, () => {
                        this.nativeBanner.show(adEventId);
                        console.log("执行打开", adEventId);
                        Timer.callLater(delay_time_close, () => {
                            mgrAd.closeAdv(adEventId);
                            mgrAdNative.onNativeAdViewClenup(adEventId, true, false);
                            if (this.nativeBanner) {
                                this.nativeBanner.removeSelf();
                                this.nativeBanner.destroy();
                                this.nativeBanner = null;
                            }
                            console.log("执行关闭", adEventId);
                        }, caller);
                    }, caller);
                    return nativeAdBanner;
                }
            }
        }
        mgrActivingBanner.enterGameTime = 0;
        mgrActivingBanner.lastActivingBannerTime = 0;

        class mgrSign extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("sign") || {};
                this.signedDay = record.signedDay || 0;
                this.signedIndex = record.signedIndex || 0;
                this.lastSignTime = record.lastSignTime || 0;
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    signedDay: this.signedDay,
                    signedIndex: this.signedIndex,
                    lastSignTime: this.lastSignTime,
                };
                mgrRecord.setData("sign", record);
            }
            static getState() {
                if (Tools.isOneDay(Tools.time(), this.lastSignTime)) {
                    let day = this.getSignDay();
                    let index = this.getSignIndex();
                    let dayDatas = mgrCfg.get("sign_db", day) || [];
                    let data = dayDatas[index];
                    if (!data) {
                        return SignState.signed;
                    }
                    else {
                        if (this.lastSignTime + data.rewardGap <= Tools.time()) {
                            return SignState.canSign;
                        }
                        else {
                            return SignState.waitGap;
                        }
                    }
                }
                else {
                    let day = this.getSignDay();
                    let data = mgrCfg.quietGet("sign_db", day, 0);
                    if (!data) {
                        return SignState.signOver;
                    }
                    else {
                        return SignState.canSign;
                    }
                }
            }
            static getSignDay() {
                if (Tools.isOneDay(Tools.time(), this.lastSignTime)) {
                    return this.signedDay;
                }
                else {
                    let day = this.signedDay + 1;
                    if (day > 8) {
                        day = 8;
                    }
                    return day;
                }
            }
            static getSignIndex() {
                if (Tools.isOneDay(Tools.time(), this.lastSignTime)) {
                    return this.signedIndex;
                }
                else {
                    return 0;
                }
            }
            static getSignedDayCount() {
                return this.signedDay;
            }
            static sign(bHavePart = true) {
                let result = { bSuccessd: false };
                let state = this.getState();
                if (state != SignState.canSign)
                    return result;
                let day = this.getSignDay();
                let index = this.getSignIndex();
                let data = mgrCfg.get_from_sign_db(day, index);
                this.lastSignTime = Tools.time();
                this.signedDay = day;
                this.signedIndex = index + 1;
                this.saveRecord();
                let rewardItemId = [];
                let rewardAmount = [];
                for (let index = 0; index < data.rewardItemId.length; index++) {
                    let itemId = data.rewardItemId[index];
                    let amount = data.rewardAmount[index];
                    let partData = mgrCfg.get_from_part_db(itemId);
                    if (partData) {
                        rewardItemId.push(itemId);
                        rewardAmount.push(amount);
                        if (itemId == Const.ITEM_ID_DIAMONDS) {
                            mgrPlayer.addItemAmount(itemId, amount, "签到");
                        }
                        else {
                            mgrPlayer.addItemAmount(itemId, amount, "签到");
                        }
                        mgrTip.addGotItemTip(itemId, amount);
                    }
                    else {
                        if (bHavePart && data.rewardItemId.length == 1) {
                        }
                        rewardItemId.push(itemId);
                        rewardAmount.push(amount);
                        mgrPlayer.addItemAmount(itemId, amount, "签到");
                        mgrTip.addGotItemTip(itemId, amount);
                    }
                }
                result.bSuccessd = true;
                result.rewardItemId = rewardItemId;
                result.rewardAmount = rewardAmount;
                this.sendMsg(`MSG_SIGN`);
                return result;
            }
            static signTodayAll(bFromAd) {
                let result = { bSuccessd: false };
                let state = this.getState();
                if (state == SignState.signOver)
                    return result;
                let day = this.getSignDay();
                let dataArr = mgrCfg.get("sign_db", day);
                let signIndex = this.getSignIndex();
                let rewardItemArr = [];
                for (let i = signIndex; i < dataArr.length; i++) {
                    let data = dataArr[i];
                    for (let index = 0; index < data.rewardItemId.length; index++) {
                        let itemId = data.rewardItemId[index];
                        let amount = data.rewardAmount[index];
                        rewardItemArr.push({ itemId: itemId, amount: amount });
                        mgrPlayer.addItemAmount(itemId, amount, "签到");
                        mgrTip.addGotItemTip(itemId, amount, null, { bFromAd: bFromAd });
                    }
                    this.sendMsg(`MSG_SIGN`);
                }
                result.bSuccessd = true;
                result.rewardItemArr = rewardItemArr;
                this.lastSignTime = Tools.time();
                this.signedDay = day;
                this.signedIndex = dataArr.length;
                this.saveRecord();
                return result;
            }
            static getRemainTime() {
                let state = this.getState();
                if (state != SignState.waitGap)
                    return 0;
                let day = this.getSignDay();
                let index = this.getSignIndex();
                let dayDatas = mgrCfg.get("sign_db", day) || [];
                let data = dayDatas[index];
                if (!data)
                    return 0;
                let receiveTime = this.lastSignTime + data.rewardGap;
                return Math.max(0, receiveTime - Tools.time());
            }
            static getBadgeCout() {
                if (mgrSign.getState() == SignState.canSign) {
                    return 1;
                }
                else {
                    return 0;
                }
            }
            static getAllRewardParts() {
                let partIds = [];
                mgrCfg.forDb("sign_db", (key, datas) => {
                    for (let index = 0; index < datas.length; index++) {
                        const element = datas[index];
                        let itemId = element.rewardItemId;
                        let itemData = mgrCfg.get_from_item_template_db(itemId);
                        if (!!itemData && itemData.flag == Const.ITEM_FLAG_PART) {
                            partIds.push(itemId);
                        }
                    }
                });
                return partIds;
            }
        }
        mgrSign.signedDay = null;
        mgrSign.signedIndex = null;
        mgrSign.lastSignTime = null;

        const DEBUG$1 = false;
        class mgrAlertRouter extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化loadRecord");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("alertRouter") || {};
                this.lastAlertTimeLog = record.lastAlertTimeLog || {};
                this.hubTipDialogLastAlertTime = record.hubTipDialogLastAlertTime || 0;
                mgrCfg.forDb("alert_router_db", (k, datas) => {
                    for (let i = 0; i < datas.length; i++) {
                        const data = datas[i];
                        if (!data.bRecordLastAlertTime) {
                            this.setLastAlertTime(data.routerId, data.index, 0);
                        }
                    }
                });
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    lastAlertTimeLog: this.lastAlertTimeLog,
                    hubTipDialogLastAlertTime: this.hubTipDialogLastAlertTime,
                };
                mgrRecord.setData("alertRouter", record);
            }
            static getLastAlertTime(routerId, index) {
                let v = this.lastAlertTimeLog[routerId];
                if (!v)
                    return 0;
                return v[index] || 0;
            }
            static setLastAlertTime(routerId, index, time) {
                if (!this.lastAlertTimeLog[routerId]) {
                    this.lastAlertTimeLog[routerId] = {};
                }
                this.lastAlertTimeLog[routerId][index] = time;
                console.log("查看lastAlertTimeLog", this.lastAlertTimeLog);
            }
            static isCanShowSign(routerData) {
                return mgrSign.getBadgeCout() > 0;
            }
            static openSign(routerData) {
                mgrDirector.openDialog("vSignDialog");
            }
            static isCanShowSinging(routerData) {
                return true;
            }
            static openSinging(routerData) {
                mgrDirector.openDialog("vAmuseDanceLeafletDialog");
            }
            static isCanShowDouyinFollow(routerData) {
                mgrSdk.getFollowOfficialAccountState();
                return (mgrPlayer.getItemAmount(99) <= 0 && !!mgrChannel._isSupportFollowOfficialAccount);
            }
            static openDouyinFollow(routerData) {
                mgrDirector.openDialog("vDouyinFollow");
            }
            static isCanShowDesktop(routerData) {
                return mgrChannel.checkInstallShortCut();
            }
            static openDesktop(routerData) {
                mgrChannel.tipInstallShortCut();
            }
            static isCanShowFShoe(routerData) {
                return true;
            }
            static openFShoe(routerData) {
                mgrDirector.openDialog("vAmuseFashionShoeLeafletDialog");
            }
            static isCanShowLessonMusic(routerData) {
                return true;
            }
            static openLessonMusic(routerData) {
                mgrDirector.openDialog("vAmuseLessonMusicLeafletDialog");
            }
            static calcRouterDatas(routerId) {
                let datas = [];
                let oldRawDatas = mgrCfg.get("alert_router_db", routerId);
                let rawDatas = [];
                oldRawDatas.forEach(v => {
                    if (v && v.gameResVersion && !mgrGameResVersion.isValidGameResVersion(v.gameResVersion)) {
                    }
                    else {
                        rawDatas.push(v);
                    }
                });
                if (DEBUG$1) {
                    console.log("mgrAlertRouter.calcRouterDatas", routerId);
                    console.log("  rawDatas", rawDatas);
                }
                for (let i = 0; i < rawDatas.length; i++) {
                    const data = Tools.deepCopy(rawDatas[i]);
                    data.weight = mgrSdk.getCopNumberValueByKey(data.weightFromCopKey);
                    data.order = mgrSdk.getCopNumberValueByKey(data.orderFromCopKey);
                    data.cd = mgrSdk.getCopNumberValueByKey(data.cdFromCopKey);
                    if (!data.weight) {
                        continue;
                    }
                    if (DEBUG$1)
                        console.log("  check", data);
                    if (data.conditionFunctionName) {
                        if (this[data.conditionFunctionName] instanceof Function) {
                            if (!this[data.conditionFunctionName](data)) {
                                if (DEBUG$1)
                                    console.log("  条件未通过");
                                continue;
                            }
                        }
                        else {
                            console.warn("mgrAlertRouter conditionFunction not found", routerId, data.index, data.conditionFunctionName);
                        }
                    }
                    else {
                    }
                    if (!data.openViewFunctionName || !(this[data.openViewFunctionName] instanceof Function)) {
                        console.warn("mgrAlertRouter openViewFunction not found", routerId, data.index, data.openViewFunctionName);
                        continue;
                    }
                    let lastAlertTime = this.getLastAlertTime(routerId, data.index);
                    if (DEBUG$1)
                        console.log("lastAlertTime", lastAlertTime, Tools.time(), lastAlertTime);
                    if (Tools.time() - lastAlertTime <= data.cd) {
                        continue;
                    }
                    datas.push(data);
                }
                datas = Tools.sortArrayByField(datas, ["-order", "index"]);
                if (DEBUG$1)
                    console.log("  datas", datas);
                return datas;
            }
            static tryAlertView(routerId) {
                let routerDatas = this.calcRouterDatas(routerId);
                let totalWeight = 0;
                for (let i = 0; i < routerDatas.length; i++) {
                    const v = routerDatas[i];
                    totalWeight += v.weight;
                }
                let r = Tools.random(Math.min(totalWeight, 100));
                let routerData = null;
                for (let i = 0; i < routerDatas.length; i++) {
                    const data = routerDatas[i];
                    if (r <= data.weight) {
                        routerData = data;
                        break;
                    }
                    r -= data.weight;
                }
                if (routerData && routerData.openViewFunctionName && this[routerData.openViewFunctionName] instanceof Function) {
                    this[routerData.openViewFunctionName]();
                    this.setLastAlertTime(routerData.routerId, routerData.index, Tools.time());
                    this.saveRecord();
                }
            }
            static setHubSceneTipDialogShowTime(time) {
                this.hubTipDialogLastAlertTime = time;
                this.saveRecord();
            }
            static getHubSceneTipDialogShowTime() {
                return this.hubTipDialogLastAlertTime;
            }
        }

        var FS3StageRating;
        (function (FS3StageRating) {
            FS3StageRating[FS3StageRating["unpass"] = 0] = "unpass";
            FS3StageRating[FS3StageRating["pass1"] = 1] = "pass1";
            FS3StageRating[FS3StageRating["pass2"] = 2] = "pass2";
            FS3StageRating[FS3StageRating["pass3"] = 3] = "pass3";
        })(FS3StageRating || (FS3StageRating = {}));
        class mgrAmaze extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("mgrAmaze") || {};
                this.penStageId = record.penStageId || 0;
                this.penModeStageIdDict = record.penModeStageIdDict || {};
                this.penShowingStageIdDict = record.penShowingStageIdDict || {};
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    penStageId: this.penStageId || 0,
                    penModeStageIdDict: this.penModeStageIdDict || {},
                    penShowingStageIdDict: this.penShowingStageIdDict || {},
                };
                mgrRecord.setData("mgrAmaze", record);
            }
            static getCompletedPenStageId(mode = 1) {
                if (mode == 1) {
                    return this.penModeStageIdDict[mode] || this.penStageId || 0;
                }
                else {
                    return this.penModeStageIdDict[mode] || 1;
                }
            }
            static setCompletedPenStageId(id, mode = 1) {
                this.penShowingStageIdDict[mode] = this.penShowingStageIdDict[mode] || this.penModeStageIdDict[mode] || 0;
                if (mode != 2) {
                    this.penModeStageIdDict[mode] = Math.max(this.penModeStageIdDict[mode] || 0, id || 0);
                    this.penShowingStageIdDict[mode]++;
                }
                else {
                    this.penModeStageIdDict[mode] = id;
                    this.penShowingStageIdDict[mode] = id;
                }
                this.saveRecord();
            }
            static getPenShowingStageId(mode = 1) {
                return this.penShowingStageIdDict[mode] || this.getCompletedPenStageId(mode);
            }
        }
        mgrAmaze.penStageId = 0;
        mgrAmaze.penModeStageIdDict = {};
        mgrAmaze.penShowingStageIdDict = {};

        class mgrAmazePen extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("mgrAmazePen") || {};
                this.unlockedRoleDict = record.unlockedRoleDict || {};
                this.roleAdTrialDict = record.roleAdTrialDict || {};
                mgrCfg.forDb_from_amaze_pen_select_role_db((k, v) => {
                    if (v.bDefaultOwn && !this.unlockedRoleDict[k]) {
                        this.unlockedRoleDict[k] = true;
                    }
                });
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    unlockedRoleDict: this.unlockedRoleDict,
                    roleAdTrialDict: this.roleAdTrialDict
                };
                mgrRecord.setData("mgrAmazePen", record);
            }
            static isUnlockedRole(roleId) {
                return !!this.unlockedRoleDict[roleId];
            }
            static unlockRole(roleId) {
                this.unlockedRoleDict[roleId] = true;
                this.saveRecord();
                this.sendMsg("MSG_AMAZE_PEN_UNLOCK_ROLE_SUCCESS");
            }
            static addPenRoleAdTrialedCount(id, amount) {
                this.roleAdTrialDict[id] = this.roleAdTrialDict[id] || 0;
                this.roleAdTrialDict[id] += (amount || 0);
                this.saveRecord();
            }
            static getPenRoleAdTrialedCount(id) {
                return this.roleAdTrialDict[id] || 0;
            }
            static isPenRoleArrivedTrialAutoGetCondition(id) {
                let partData = mgrCfg.get_from_amaze_pen_select_role_db(id);
                let adTrialedCount = this.getPenRoleAdTrialedCount(id);
                if (adTrialedCount >= (partData.unlockAdTrialCount || 2)) {
                    return true;
                }
                return false;
            }
        }
        mgrAmazePen.unlockedRoleDict = {};
        mgrAmazePen.roleAdTrialDict = {};

        class mgrBoneBinder extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static link2Node(linkPointName, model, serialNumber) {
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return false;
                }
                let mainBoneMap = boneBinderInfo.mainBoneMap;
                let linkTargetNode = mainBoneMap[linkPointName];
                if (linkTargetNode) {
                    linkTargetNode.addChild(model);
                    model.transform.localPosition = new Laya.Vector3();
                    return true;
                }
                return false;
            }
            static addMainAvatar(avatar, baseBody) {
                this.boneBinderSerialNumber += 1;
                let mainBone = baseBody.getChildByName(Const.BASE_BONE_NAME);
                if (!mainBone) {
                    return this.boneBinderSerialNumber;
                }
                this.boneBinderDict[this.boneBinderSerialNumber] = {
                    avatar: avatar,
                    relateAvatarArr: [],
                    mainBone: mainBone,
                    mainBoneMap: {
                        [mainBone.name]: mainBone
                    },
                    newBuildBoneMap: {},
                };
                this.initMainBoneMap(mainBone, this.boneBinderSerialNumber);
                return this.boneBinderSerialNumber;
            }
            static addRelateAvatar(avatar, serialNumber) {
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return;
                }
                if (boneBinderInfo.relateAvatarArr.length != 0) {
                    for (let i = 0; i < boneBinderInfo.relateAvatarArr.length; i++) {
                        let tmp = boneBinderInfo.relateAvatarArr[i];
                        if (tmp.id == avatar.id) {
                            return;
                        }
                    }
                }
                boneBinderInfo.relateAvatarArr.push(avatar);
            }
            static removeRelateAvatar(avatar, serialNumber) {
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return;
                }
                let relateAvatarArr = boneBinderInfo.relateAvatarArr || [];
                for (let i = relateAvatarArr.length - 1; i >= 0; i--) {
                    let avatarRelated = relateAvatarArr[i];
                    if (avatarRelated.id == avatar.id) {
                        relateAvatarArr.splice(i, 1);
                        break;
                    }
                }
            }
            static relateModelBone(model, serialNumber, bMainAvatar) {
                if (!model) {
                    return;
                }
                let otherBone = model.getChildByName(Const.BASE_BONE_NAME);
                if (!otherBone) {
                    console.log("-----未找到对应的Bone=model.name=", model.name);
                    return;
                }
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return;
                }
                let otherRenders = Tools.findAllSkinnedMeshRenderers(model);
                let currNewBoneDict = {};
                this.buildNewBone(boneBinderInfo.mainBone, otherBone, currNewBoneDict, serialNumber, model.name, bMainAvatar);
                for (let i = 0; i < otherRenders.length; i++) {
                    this.syncBones(otherRenders[i], serialNumber);
                }
                model["_serialNumber"] = serialNumber;
                model["_currNewBoneDict"] = currNewBoneDict;
            }
            static unbindAllBone(serialNumber) {
                let unbindFunc = (sn) => {
                    let boneBinderInfo = this.boneBinderDict[sn];
                    if (!boneBinderInfo) {
                        return;
                    }
                    let relateAvatarArr = boneBinderInfo.relateAvatarArr || [];
                    for (let i = relateAvatarArr.length - 1; i >= 0; i--) {
                        let avatarRelated = relateAvatarArr[i];
                        avatarRelated.destroy();
                    }
                    if (boneBinderInfo.newBuildBoneMap) {
                        let deleteBoneNameDict = {};
                        for (let k in boneBinderInfo.newBuildBoneMap) {
                            let data = boneBinderInfo.newBuildBoneMap[k];
                            if (!data || !data.node || data.node.destroyed) {
                                deleteBoneNameDict[k] = true;
                                continue;
                            }
                            deleteBoneNameDict[k] = true;
                        }
                        for (let k in deleteBoneNameDict) {
                            let data = boneBinderInfo.newBuildBoneMap[k];
                            if (data && data.node && !data.node.destroyed) {
                                data.node.destroy(true);
                            }
                            delete boneBinderInfo.newBuildBoneMap[k];
                        }
                    }
                    boneBinderInfo.relateAvatarArr = [];
                    boneBinderInfo.newBuildBoneMap = {};
                    boneBinderInfo.mainBoneMap = {};
                    boneBinderInfo.mainBone = null;
                    boneBinderInfo.avatar = null;
                    delete this.boneBinderDict[serialNumber];
                };
                if (serialNumber) {
                    unbindFunc(serialNumber);
                }
                else {
                    for (let k in this.boneBinderDict) {
                        unbindFunc(k);
                    }
                }
            }
            static unbindModelBone(model) {
                let otherRenders = Tools.findAllSkinnedMeshRenderers(model);
                for (let i = 0; i < otherRenders.length; i++) {
                    let meshRender = otherRenders[i];
                    if (!meshRender["_originBones"]) {
                        continue;
                    }
                    meshRender["_bones"] = meshRender["_originBones"];
                    delete meshRender["_originBones"];
                }
                let serialNumber = model["_serialNumber"];
                if (!serialNumber) {
                    return;
                }
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return;
                }
                let dict = model["_currNewBoneDict"];
                if (!dict || Tools.getObjSize(dict) <= 0) {
                    model["_currNewBoneDict"] = null;
                    return;
                }
                let deleteBoneNameDict = {};
                for (let k in dict) {
                    let data = boneBinderInfo.newBuildBoneMap[k];
                    if (!data) {
                        console.warn("删除一定不存在的骨骼数据，实际不应该存在这种情况");
                        continue;
                    }
                    data.refCount--;
                    if (!data.refCount || data.refCount <= 0) {
                        deleteBoneNameDict[k] = true;
                    }
                }
                for (let k in deleteBoneNameDict) {
                    let data = boneBinderInfo.newBuildBoneMap[k];
                    if (data && data.node && !data.node.destroyed) {
                        this.destroyNodeSafe(data.node, model.name);
                    }
                    delete boneBinderInfo.newBuildBoneMap[k];
                }
                delete model["_serialNumber"];
                delete model["_currNewBoneDict"];
            }
            static getMainBoneByName(name, serialNumber) {
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return;
                }
                return boneBinderInfo.mainBoneMap[name];
            }
            static getMainAvatar(serialNumber) {
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return;
                }
                return boneBinderInfo.avatar;
            }
            static destroyNodeSafe(node, modelName) {
                while (node.numChildren > 0) {
                    for (let i = node.numChildren - 1; i >= 0; i--) {
                        this.destroyNodeSafe(node.getChildAt(i), modelName);
                    }
                }
                node.destroy();
            }
            static initMainBoneMap(mainBone, serialNumber) {
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return;
                }
                for (var i = 0; i < mainBone.numChildren; i++) {
                    var child = mainBone.getChildAt(i);
                    if (child["particleSystem"]) {
                        continue;
                    }
                    if (!boneBinderInfo.mainBoneMap[child.name]) {
                        boneBinderInfo.mainBoneMap[child.name] = child;
                    }
                    else {
                        console.warn("-----------initMainBoneMap骨骼重名.", child.name);
                    }
                    this.initMainBoneMap(child, serialNumber);
                }
            }
            static buildNewBone(mainSprite, otherSprite, currNewBoneDict, serialNumber, modelName, bMainAvatar) {
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    console.log("------------------buildNewBone no boneBinderInfo-");
                    return;
                }
                for (var i = 0; i < otherSprite.numChildren; i++) {
                    var otherChild = otherSprite.getChildAt(i);
                    let particleSystem = otherChild["particleSystem"];
                    if (!!particleSystem && !bMainAvatar) {
                        continue;
                    }
                    let mainChild = mainSprite.getChildByName(otherChild.name);
                    if (!mainChild && !otherChild["_originBoneName"]) {
                        let checkBoneName = `${otherChild.name}_${modelName}`;
                        if (!!particleSystem) {
                            this.renameBoneSerialNumber++;
                            checkBoneName = `${checkBoneName}_${this.renameBoneSerialNumber}`;
                        }
                        otherChild["_originBoneName"] = otherChild.name;
                        otherChild.name = checkBoneName;
                        mainChild = mainSprite.getChildByName(otherChild.name);
                    }
                    if (!mainChild) {
                        if (!!particleSystem) {
                            mainChild = Laya.ShuriKenParticle3D.instantiate(otherChild);
                            particleSystem.stop();
                        }
                        else {
                            mainChild = new Laya.Sprite3D();
                        }
                        mainChild.name = otherChild.name;
                        mainSprite.addChild(mainChild);
                        mainChild.transform.localPosition = otherChild.transform.localPosition;
                        mainChild.transform.localRotation = otherChild.transform.localRotation;
                        mainChild.transform.localScale = otherChild.transform.localScale;
                        if (boneBinderInfo.newBuildBoneMap[mainChild.name]) {
                            console.error("---------------------前面已经创建了同名的bone=", mainChild.name);
                        }
                        boneBinderInfo.newBuildBoneMap[mainChild.name] = { node: mainChild, refCount: 1 };
                        currNewBoneDict[mainChild.name] = true;
                        if (particleSystem) {
                            continue;
                        }
                    }
                    else if (!boneBinderInfo.mainBoneMap[mainChild.name]) {
                        boneBinderInfo.newBuildBoneMap[mainChild.name].refCount += 1;
                        currNewBoneDict[mainChild.name] = true;
                    }
                    this.buildNewBone(mainChild, otherChild, currNewBoneDict, serialNumber, modelName, bMainAvatar);
                }
            }
            static syncBones(meshRender, serialNumber) {
                let boneBinderInfo = this.boneBinderDict[serialNumber];
                if (!boneBinderInfo) {
                    return;
                }
                let destBones = meshRender.bones;
                let newBones = [];
                for (var i = 0; i < destBones.length; i++) {
                    var destBone = destBones[i];
                    if (boneBinderInfo.mainBoneMap[destBone.name]) {
                        newBones.push(boneBinderInfo.mainBoneMap[destBone.name]);
                    }
                    else if (boneBinderInfo.newBuildBoneMap[destBone.name]) {
                        newBones.push(boneBinderInfo.newBuildBoneMap[destBone.name].node);
                    }
                    else {
                        console.error("找不到骨骼:", destBone.name);
                    }
                }
                if (destBones.length != newBones.length) {
                    console.error("骨骼数不一致.");
                    return;
                }
                meshRender["_originBones"] = destBones;
                meshRender["_bones"] = newBones;
            }
        }
        mgrBoneBinder.boneBinderSerialNumber = 0;
        mgrBoneBinder.boneBinderDict = {};
        mgrBoneBinder.renameBoneSerialNumber = 0;

        var EnumSkillSpecialEffect;
        (function (EnumSkillSpecialEffect) {
            EnumSkillSpecialEffect[EnumSkillSpecialEffect["freeze"] = 0] = "freeze";
        })(EnumSkillSpecialEffect || (EnumSkillSpecialEffect = {}));
        class mgrCardFightSkill extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化mgrCardFightSkill loadRecord");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("card_fight_skill_record") || {};
                this._ownedTeamSkill = record.ownedTeamSkill || {};
                this._curTeamSkillId = record.curTeamSkillId || null;
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    ownedTeamSkill: this._ownedTeamSkill,
                    curTeamSkillId: this._curTeamSkillId,
                };
                mgrRecord.setData("card_fight_skill_record", record);
            }
            static factoryRenderSkill(effNodeArr, effCardDataArr, screenNode, view, skillId) {
                let skillData = this.getSkillTemplateData(skillId);
                let skillEffArr = skillData.start3DModelEffPlayData;
                let durTime = 0;
                let sequnceRenderFunData = [];
                console.log("factoryRenderSkill-- cardIdArr", effCardDataArr);
                console.log("factoryRenderSkill-- nodeArr", effNodeArr);
                for (let i = 0; i < skillEffArr.length; i++) {
                    let skillEffId = skillEffArr[i];
                    let skillEffData = mgrCfg.get_from_amuse_card_skill_effect_db(skillEffId);
                    let childRenderFun = () => {
                        let targetArr = effNodeArr;
                        let cardDataArr = effCardDataArr;
                        if (skillEffData.target == "screen") {
                            targetArr = [screenNode];
                        }
                        console.log("renderSkil-- doSkillEff -- skillEffId, targetArr", skillEffId, targetArr);
                        for (let i = 0; i < targetArr.length; i++) {
                            let node = targetArr[i];
                            let cardId = cardDataArr[i].cardId;
                            let changeFields = cardDataArr[i].changeFields;
                            let bEff = false;
                            if (!skillEffData.relationField || skillEffData.relationField == "") {
                                bEff = true;
                            }
                            else {
                                for (let i = 0; i < changeFields.length; i++) {
                                    let field = changeFields[i];
                                    if (field == skillEffData.relationField) {
                                        bEff = true;
                                    }
                                }
                            }
                            if (bEff) {
                                view.add3DEffectAtFront(skillEffData.modelEffName, node, 0, 1, (model) => {
                                    this._skillEffFrontMap[`${model.name}_${cardId}`] = model;
                                    console.log("renderSkil-- add3DEffectAtFront  skillEffData.modelEffName, node, skillEffData.durTime, `${model.id}_${cardId}`", skillEffData.modelEffName, node, skillEffData.durTime, `${model.name}_${cardId}`);
                                    if (skillEffData.durTime && skillEffData.durTime > 0) {
                                        Timer.callLater(skillEffData.durTime, () => {
                                            mgrLoader.Pool.recoverModel(model);
                                            delete this._skillEffFrontMap[`${model.name}_${cardId}`];
                                            console.log("renderSkil-- delete3DEffectAtFront `${model.id}_${cardId}`", `${model.name}_${cardId}`);
                                        });
                                    }
                                });
                            }
                        }
                        return skillEffData.durTime;
                    };
                    sequnceRenderFunData.push({
                        fun: childRenderFun,
                        costTime: skillEffData.durTime,
                    });
                    durTime += skillEffData.durTime;
                }
                let result = () => {
                    let time = 0;
                    for (let i = 0; i < sequnceRenderFunData.length; i++) {
                        let funData = sequnceRenderFunData[i];
                        let fun = funData.fun;
                        let costTime = funData.costTime;
                        Timer.callLater(time, () => {
                            fun();
                            console.log("renderSkil-- preDoSkillEff -- index, sequnceRenderFunArr", i, sequnceRenderFunData);
                        });
                        time += costTime;
                    }
                    return durTime;
                };
                return result;
            }
            static factoryRelieveFroze(effNode, view, cardId) {
                let oldSkillEffData = mgrCfg.get_from_amuse_card_skill_effect_db(103);
                let oldModelId = oldSkillEffData.modelEffName;
                let newSkillEffData = mgrCfg.get_from_amuse_card_skill_effect_db(104);
                let newModelId = newSkillEffData.modelEffName;
                let fun = () => {
                    view.add3DEffectAtFront(newModelId, effNode, 0, 1, (model) => {
                        this._skillEffFrontMap[`${model.name}_${cardId}`] = model;
                        if (newSkillEffData.durTime && newSkillEffData.durTime > 0) {
                            Timer.callLater(newSkillEffData.durTime, () => {
                                mgrLoader.Pool.recoverModel(model);
                                delete this._skillEffFrontMap[`${model.name}_${cardId}`];
                                console.log("renderSkil-- delete3DEffectAtFront `${model.id}_${cardId}`", `${model.name}_${cardId}`);
                            });
                        }
                    });
                    let oldModel = this._skillEffFrontMap[`${oldModelId}_${cardId}`];
                    if (oldModel) {
                        mgrLoader.Pool.recoverModel(oldModel);
                        delete this._skillEffFrontMap[`${oldModelId}_${cardId}`];
                    }
                    return newSkillEffData.durTime;
                };
                return fun;
            }
            static isExistFrozenEff(cardId) {
                let oldSkillEffData = mgrCfg.get_from_amuse_card_skill_effect_db(103);
                let oldModelId = oldSkillEffData.modelEffName;
                console.log("解冻判断-- isExistFrozenEff", `${oldModelId}_${cardId}`, this._skillEffFrontMap[`${oldModelId}_${cardId}`], this._skillEffFrontMap);
                return !!this._skillEffFrontMap[`${oldModelId}_${cardId}`];
            }
            static calcSkillData(skillId, userArr, effectorArr) {
                let skillTemplateData = this.getSkillTemplateData(skillId);
                let defaultResult = {
                    userData: userArr,
                    effectorData: effectorArr,
                    changeData: {},
                    durTime: 0,
                };
                if (!skillTemplateData) {
                    return defaultResult;
                }
                if (!userArr || !effectorArr) {
                    return defaultResult;
                }
                if (userArr.length <= 0 || effectorArr.length <= 0) {
                    return defaultResult;
                }
                let calcFunNameArr = skillTemplateData.calcFuns;
                if (!calcFunNameArr || !calcFunNameArr.length) {
                    return defaultResult;
                }
                let param1 = JSON.parse(JSON.stringify(userArr));
                let param2 = JSON.parse(JSON.stringify(effectorArr));
                let effIds = skillTemplateData.start3DModelEffPlayData;
                let durTime = 0;
                for (let i = 0; i < effIds.length; i++) {
                    let effId = effIds[i];
                    let effData = mgrCfg.get_from_amuse_card_skill_effect_db(effId);
                    durTime += effData.durTime;
                }
                let defaultCalcResult = {
                    userData: param1,
                    effectorData: param2,
                    changeData: {},
                    durTime: durTime,
                };
                console.log("skill--- 准备执行", calcFunNameArr);
                for (let i = 0; i < calcFunNameArr.length; i++) {
                    let calcFunName = calcFunNameArr[i];
                    let calcFun = this[calcFunName];
                    if (!calcFun) {
                        continue;
                    }
                    console.log("skill--- find calcFun", calcFunName);
                    let calcResult = calcFun(defaultCalcResult.userData, defaultCalcResult.effectorData, skillTemplateData);
                    if (calcResult.changeData) {
                        for (let cardId in calcResult.changeData) {
                            let kvArr = calcResult.changeData[cardId];
                            if (!defaultCalcResult.changeData[cardId]) {
                                defaultCalcResult.changeData[cardId] = kvArr;
                            }
                            else {
                                let defaultKvArr = defaultCalcResult.changeData[cardId];
                                for (let i = 0; i < kvArr.length; i++) {
                                    let kvData = kvArr[i];
                                    defaultKvArr.push(kvData);
                                }
                            }
                        }
                    }
                }
                return defaultCalcResult;
            }
            static unlockSkillAsTeamSkill(skillId) {
                if (!skillId) {
                    return null;
                }
                let skillTemplateData = this.getSkillTemplateData(skillId);
                if (!skillTemplateData) {
                    return null;
                }
                let curSkillInfo = this.getCurTeamSkillInfo();
                if (curSkillInfo && curSkillInfo.id == skillId) {
                    return curSkillInfo;
                }
                this._ownedTeamSkill[skillId] = {
                    id: skillId,
                };
                this._curTeamSkillId = skillId;
                this.saveRecord();
                console.log("unlockSkillAsTeamSkill--", skillTemplateData);
                return skillTemplateData;
            }
            static getCurTeamSkillInfo() {
                let curTeamSkillId = this._curTeamSkillId;
                if (!curTeamSkillId) {
                    return null;
                }
                let skillInfo = this.getSkillTemplateData(curTeamSkillId);
                return skillInfo;
            }
            static getSkillTemplateData(skillId) {
                if (!skillId) {
                    return null;
                }
                let skillData = mgrCfg.get_from_amuse_card_skill_db(skillId);
                return skillData;
            }
        }
        mgrCardFightSkill._ownedTeamSkill = {};
        mgrCardFightSkill._curTeamSkillId = null;
        mgrCardFightSkill._skillEffFrontMap = {};
        mgrCardFightSkill.reduceOneEnemyHp = (userArr, effectorArr, skillTemplateData) => {
            let defaultResult = {
                userData: userArr,
                effectorData: effectorArr,
                changeData: {},
                durTime: 0,
            };
            let randomObj = Tools.randomGotOneArrayData(effectorArr);
            let curHp = randomObj.hp;
            randomObj.hp = Mathf.clamp(curHp - skillTemplateData.damage, 0, curHp);
            if (!defaultResult.changeData[randomObj.id]) {
                defaultResult.changeData[randomObj.id] = [];
            }
            defaultResult.changeData[randomObj.id].push({ dataKey: "hp", dataValue: -skillTemplateData.damage });
            console.log("skill--- calcFun-- reduceOneEnemyHp", randomObj.hp, defaultResult.changeData, skillTemplateData.name);
            return defaultResult;
        };
        mgrCardFightSkill.reduceAllEnemyHp = (userArr, effectorArr, skillTemplateData) => {
            let defaultResult = {
                userData: userArr,
                effectorData: effectorArr,
                changeData: {},
                durTime: 0,
            };
            for (let i = 0; i < effectorArr.length; i++) {
                let fightData = effectorArr[i];
                let curHp = fightData.hp;
                fightData.hp = Mathf.clamp(curHp - skillTemplateData.damage, 0, curHp);
                if (!defaultResult.changeData[fightData.id]) {
                    defaultResult.changeData[fightData.id] = [];
                }
                defaultResult.changeData[fightData.id].push({ dataKey: "hp", dataValue: -skillTemplateData.damage });
            }
            console.log("skill--- calcFun-- reduceAllEnemyHp", defaultResult.effectorData, defaultResult.changeData, skillTemplateData.name);
            return defaultResult;
        };
        mgrCardFightSkill.fFreezeOneEnemy = (userArr, effectorArr, skillTemplateData) => {
            let defaultResult = {
                userData: userArr,
                effectorData: effectorArr,
                changeData: {},
                durTime: 0,
            };
            let randomObj = Tools.randomGotOneArrayData(effectorArr);
            let remainFreezeRound = randomObj.remainFreezeRound ? randomObj.remainFreezeRound : 0;
            randomObj.remainFreezeRound = Math.max(remainFreezeRound + skillTemplateData.freezeTime, 0);
            if (!defaultResult.changeData[randomObj.id]) {
                defaultResult.changeData[randomObj.id] = [];
            }
            defaultResult.changeData[randomObj.id].push({ dataKey: "remainFreezeRound", dataValue: skillTemplateData.freezeTime });
            console.log("skill--- calcFun-- fFreezeOneEnemy", randomObj.remainFreezeRound, defaultResult.changeData, skillTemplateData.name);
            return defaultResult;
        };
        mgrCardFightSkill.addAllTeammateFightPower = (userArr, effectorArr, skillTemplateData) => {
            let defaultResult = {
                userData: userArr,
                effectorData: effectorArr,
                changeData: {},
                durTime: 0,
            };
            for (let i = 0; i < userArr.length; i++) {
                let fightData = userArr[i];
                let fightPower = fightData.fightPower;
                fightData.fightPower = Math.max(0, fightPower + fightData.fightPower);
                if (!defaultResult.changeData[fightData.id]) {
                    defaultResult.changeData[fightData.id] = [];
                }
                defaultResult.changeData[fightData.id].push({ dataKey: "fightPower", dataValue: fightData.fightPower });
            }
            console.log("skill--- calcFun-- addAllTeammateFightPower", defaultResult.effectorData, defaultResult.changeData, skillTemplateData.name);
            return defaultResult;
        };

        class mgrDesign extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化mgrDesign loadRecord");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("design_record") || {};
                this.customPartDataDict = record.customPartDataDict || {};
                this.unlockedCellPartIdDict = record.unlockedCellPartIdDict || {};
                for (let i = 0; i < Const.CUSTOM_DESIGN_PART_COUNT; i++) {
                    let tmpPartId = this.CUSTOM_PART_ID_START_VALUE + i;
                    this.customPartDataDict[tmpPartId] = this.customPartDataDict[tmpPartId] || null;
                    if (i < 2) {
                        this.unlockedCellPartIdDict[tmpPartId] = true;
                    }
                    else {
                        this.unlockedCellPartIdDict[tmpPartId] = this.unlockedCellPartIdDict[tmpPartId] || false;
                    }
                }
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    customPartDataDict: this.customPartDataDict,
                    unlockedCellPartIdDict: this.unlockedCellPartIdDict
                };
                mgrRecord.setData("design_record", record);
            }
            static getUnusedPartId() {
                for (let i = this.CUSTOM_PART_ID_START_VALUE; i <= this.CUSTOM_PART_ID_END_VALUE; i++) {
                    if (!this.customPartDataDict[i]) {
                        return i;
                    }
                }
                return 0;
            }
            static getTmpDesignPartId() {
                for (let i = this.CUSTOM_PART_ID_START_VALUE; i <= this.CUSTOM_PART_ID_END_VALUE; i++) {
                    if (!this.customPartDataDict[i]) {
                        return i;
                    }
                }
                return 0;
            }
            static isUnlockedPartCell(partId) {
                return !!this.unlockedCellPartIdDict[partId];
            }
            static unlockPartCellByPartId(partId) {
                this.unlockedCellPartIdDict[partId] = true;
                this.saveRecord();
            }
            static getEmptyUnlockedPartCellPartId() {
                let arr = [];
                let dict = mgrDesign.getDesignPartDataDict();
                for (let k in dict) {
                    let partId = parseInt(k);
                    arr.push({
                        partId: partId,
                    });
                }
                arr = Tools.sortArrayByField(arr, "partId");
                for (let i = 0; i < arr.length; i++) {
                    let tmpData = arr[i];
                    if (!!this.isUnlockedPartCell(tmpData.partId) && !this.isDesignPart(tmpData.partId)) {
                        return tmpData.partId;
                    }
                }
                return null;
            }
            static getMinLockPartCellPartId() {
                let arr = [];
                let dict = mgrDesign.getDesignPartDataDict();
                for (let k in dict) {
                    let partId = parseInt(k);
                    arr.push({
                        partId: partId,
                    });
                }
                arr = Tools.sortArrayByField(arr, "partId");
                for (let i = 0; i < arr.length; i++) {
                    let tmpData = arr[i];
                    if (!this.isUnlockedPartCell(tmpData.partId)) {
                        return tmpData.partId;
                    }
                }
                return null;
            }
            static randomGetUnlockedPartCellPartId() {
                let arr = [];
                let dict = mgrDesign.getDesignPartDataDict();
                for (let k in dict) {
                    let partId = parseInt(k);
                    arr.push({
                        partId: partId,
                    });
                }
                let data = Tools.randomGotOneArrayData(arr);
                return data.partId;
            }
            static isDesignPart(partId) {
                return (!!this.customPartDataDict[partId] || (!!this.tmpCustomPartData && this.tmpCustomPartData.newPartId == partId)) ? true : false;
            }
            static getDesignPartDataDict() {
                return this.customPartDataDict;
            }
            static getDesignPartDataByPartId(partId) {
                let data = this.customPartDataDict[partId];
                if (!!data) {
                    return data;
                }
                if (this.tmpCustomPartData && this.tmpCustomPartData.newPartId == partId) {
                    return this.tmpCustomPartData;
                }
            }
            static getDesignPartCount() {
                let count = 0;
                let dict = this.customPartDataDict || {};
                for (let k in dict) {
                    if (!!dict[k]) {
                        count++;
                    }
                }
                return count;
            }
            static getDesignPartIconKey(partId) {
                return `custom_design_part_icon${partId}`;
            }
            static updateDesignPart(newPartId, originPartId, designColorId, designGridId, designShineId, designGridScale = 1, designShineScale = 1) {
                newPartId = newPartId || this.getUnusedPartId();
                let data = {
                    originPartId: originPartId,
                    designColorId: designColorId,
                    designGridId: designGridId,
                    designShineId: designShineId,
                    designGridScale: designGridScale || 1,
                    designShineScale: designShineScale || 1,
                    newPartId: newPartId,
                };
                this.customPartDataDict[newPartId] = data;
                this.saveRecord();
                this.updatePartDbByDesignedPart();
                mgrPlayer.addItemAmount(newPartId, 1, "");
                return newPartId;
            }
            static addTempDesignPart(originPartId, designColorId, designGridId, designShineId, designGridScale = 1, designShineScale = 1) {
                let data = {
                    originPartId: originPartId,
                    designColorId: designColorId,
                    designGridId: designGridId,
                    designShineId: designShineId,
                    designGridScale: designGridScale || 1,
                    designShineScale: designShineScale || 1,
                    newPartId: this.TMP_CUSTOM_PART_ID_VALUE,
                };
                this.tmpCustomPartData = data;
                this.updatePartDbByDesignedPart();
                return data.newPartId;
            }
            static getTempDesignPartData() {
                return this.tmpCustomPartData;
            }
            static deleteTempDesignPart() {
                if (!this.tmpCustomPartData) {
                    return;
                }
                let partId = this.TMP_CUSTOM_PART_ID_VALUE;
                let db = mgrCfg.getDb("part_db");
                delete db[partId];
            }
            static updatePartDbByDesignedPart() {
                let db = mgrCfg.getDb("part_db");
                let doUpdate = (data) => {
                    if (!data) {
                        return;
                    }
                    let partData = Tools.deepCopy(mgrCfg.get_from_part_db(data.originPartId));
                    partData.bDisableShowInRoom = false;
                    partData.id = data.newPartId;
                    partData["originPartId"] = data.originPartId;
                    db[data.newPartId] = partData;
                    let item_template_db = mgrCfg.getDb("item_template_db");
                    item_template_db[partData.id] = {
                        id: partData.id,
                        name: partData.name,
                        icon: partData.icon,
                        flag: 0,
                        defaultAmount: partData.bDefaultHave ? 1 : 0,
                        sellItemId: partData.sellItemId || 0,
                        sellItemAmount: partData.sellItemAmount || 0,
                        router: partData.router || 0
                    };
                };
                for (let k in this.customPartDataDict) {
                    let data = this.customPartDataDict[k];
                    if (!data) {
                        continue;
                    }
                    doUpdate(data);
                }
                doUpdate(this.tmpCustomPartData);
            }
            static tryAdaptDesignPartModelMaterial(model, partId, bForceUseTextureColor) {
                if (!this.isDesignPart(partId)) {
                    return;
                }
                let data = this.customPartDataDict[partId];
                if (!data) {
                    if (this.TMP_CUSTOM_PART_ID_VALUE == partId && !!this.tmpCustomPartData) {
                        data = this.tmpCustomPartData;
                    }
                    else {
                        return;
                    }
                }
                let colorData = mgrCfg.get_from_design_part_color_db(data.designColorId);
                let gridData = mgrCfg.get_from_design_grid_db(data.designGridId);
                let shineData = mgrCfg.get_from_design_shine_db(data.designShineId);
                let callback = () => {
                    for (let i = 0; i < model.numChildren; i++) {
                        let child = model.getChildAt(i);
                        let renderer = Tools.getMeshRender(child);
                        if (renderer) {
                            for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                let material = renderer.sharedMaterials[j];
                                if (material.PlayerCustomChangeFlag < 0.5) {
                                    continue;
                                }
                                Tools.loadMaterialTexture(Const.SKIN_CONTROL_GRID_SHINE_PATH, material, "controlDetailTexture");
                                material.albedoColor = new Laya.Vector4(0.88, 0.88, 0.88, 1.0);
                                material.albedoTexture = null;
                                material.AlbedoTillingX = 1.0;
                                material.AlbedoTillingY = 1.0;
                                material.gridTexture = null;
                                material.shineTexture = null;
                                material.gridTextureScale = 1.0;
                                material.shineTextureScale = 1.0;
                                if (!!colorData) {
                                    if (colorData.paint == "" && !bForceUseTextureColor) {
                                        material.albedoTexture = null;
                                        material.AlbedoTillingX = 1;
                                        material.AlbedoTillingY = 1;
                                        material.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                    }
                                    else {
                                        let texture = null;
                                        if (colorData.paint == "") {
                                            texture = Tools.createPureColorTexture(new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1));
                                        }
                                        else {
                                            texture = mgrLoader.get2dRes(colorData.paint);
                                        }
                                        let tex2d = texture.bitmap;
                                        if (tex2d.wrapModeU != Laya.WarpMode.Repeat) {
                                            tex2d.wrapModeU = Laya.WarpMode.Repeat;
                                            tex2d.wrapModeV = Laya.WarpMode.Repeat;
                                            tex2d.filterMode = Laya.FilterMode.Bilinear;
                                            tex2d.generateMipmap();
                                        }
                                        material.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                        material.albedoTexture = tex2d;
                                        material.AlbedoTillingX = colorData.tillingOffset[0] || 1;
                                        material.AlbedoTillingY = colorData.tillingOffset[1] || 1;
                                    }
                                }
                                if (!!gridData) {
                                    material.gridTextureScale = (data.designGridScale || 1) * (gridData.tillingOffset[0] || 1);
                                    Tools.loadMaterialTexture(gridData.paint, material, "gridTexture");
                                }
                                if (!!shineData) {
                                    material.shineTextureScale = (data.designShineScale || 1) * (shineData.tillingOffset[0] || 1);
                                    Tools.loadMaterialTexture(shineData.paint, material, "shineTexture");
                                }
                            }
                        }
                    }
                };
                if (!!colorData && colorData.paint) {
                    mgrLoader.batchLoadResources([], [], [colorData.paint], () => {
                        callback();
                    });
                }
                else {
                    callback();
                }
            }
            static calcCustomMadeStageScore(stageId, partIds) {
                let stageData = mgrCfg.get_from_custom_made_clothes_stage_db(stageId);
                let tagWeights = stageData.tagWeights;
                let score = 0;
                for (let i = 0; i < partIds.length; i++) {
                    const partId = partIds[i];
                    if (!partId) {
                        continue;
                    }
                    let partData = mgrCfg.get_from_part_db(partId) || mgrCfg.get_from_design_part_color_db(partId) || mgrCfg.get_from_design_shine_db(partId) || mgrCfg.get_from_design_grid_db(partId);
                    for (let index = 0; index < 10; index++) {
                        const partTagScore = partData["score" + (index + 1)] || 0;
                        score += partTagScore * (tagWeights[index] || 0);
                    }
                }
                return Math.floor(score);
            }
        }
        mgrDesign.CUSTOM_PART_ID_START_VALUE = 24000;
        mgrDesign.CUSTOM_PART_ID_END_VALUE = 24900;
        mgrDesign.TMP_CUSTOM_PART_ID_VALUE = 24999;

        class mgrEffect extends Manager {
            static onLoad() {
                super.onLoad();
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
            }
            static shineNode(node, dur = 0.2, scaleOffset = 0.1, repeatCount) {
                if (node["__bShining"]) {
                    return;
                }
                dur = dur || 0.5;
                scaleOffset = scaleOffset || 0.1;
                node["__shineOriginScale"] = node.scaleX;
                node["__bShining"] = true;
                if (!repeatCount || repeatCount <= 0) {
                    cc.tween(node)
                        .repeatForever(cc.tween().toScale(dur, (1 + scaleOffset), cc.Ease.linear).toScale(dur, (1 - scaleOffset), cc.Ease.linear))
                        .start();
                }
                else {
                    cc.tween(node)
                        .repeat(repeatCount, cc.tween().toScale(dur, (1 + scaleOffset), cc.Ease.linear).toScale(dur, (1 - scaleOffset), cc.Ease.linear))
                        .call(() => {
                        this.stopShineNode(node);
                    })
                        .start();
                }
            }
            static stopShineNode(node) {
                cc.tween(node).removeAllActions();
                node["__bShining"] = false;
                if (node["__shineOriginScale"]) {
                    node.scaleX = node["__shineOriginScale"];
                    node.scaleY = node["__shineOriginScale"];
                }
            }
            static shakeNodeXOnce(node, shakeCount = 3, dur = 0.01, dis = 10) {
                if (node["__bShakingX"]) {
                    return;
                }
                node["__shakeOriginX"] = node["__shakeOriginX"] || node.x;
                node["__bShakingX"] = true;
                node.x = node["__shakeOriginX"];
                let ox = node["__shakeOriginX"];
                let oy = node.y;
                cc.tween(node)
                    .repeat(shakeCount || 3, cc.tween()
                    .toPos(dur, ox - dis, oy).toPos(dur * 2, ox + dis, oy).toPos(dur, ox, oy)
                    .toPos(dur, ox - dis, oy).toPos(dur * 2, ox + dis, oy).toPos(dur, ox, oy)
                    .toPos(dur, ox - dis, oy).toPos(dur * 2, ox + dis, oy).toPos(dur, ox, oy))
                    .call(() => {
                    if (!node || node.destroyed) {
                        return;
                    }
                    this.stopsShakeNodeX(node);
                })
                    .start();
            }
            static shakeNodeX(node, dur = 0.01, dis = 10) {
                if (node["__bShakingX"]) {
                    return;
                }
                node["__shakeOriginX"] = node["__shakeOriginX"] || node.x;
                node["__bShakingX"] = true;
                node.x = node["__shakeOriginX"];
                let ox = node["__shakeOriginX"];
                let oy = node.y;
                cc.tween(node)
                    .repeatForever(cc.tween()
                    .toPos(dur, ox - dis, oy).toPos(dur * 2, ox + dis, oy).toPos(dur, ox, oy)
                    .toPos(dur, ox - dis, oy).toPos(dur * 2, ox + dis, oy).toPos(dur, ox, oy)
                    .toPos(dur, ox - dis, oy).toPos(dur * 2, ox + dis, oy).toPos(dur, ox, oy))
                    .start();
            }
            static stopsShakeNodeX(node) {
                cc.tween(node).removeAllActions();
                node["__bShakingX"] = false;
                if (node["__shakeOriginX"]) {
                    node.x = node["__shakeOriginX"];
                }
            }
            static filterGlow(sprite, color = "ffff00", blur = 10, offX = 0, offY = 0) {
                let filter = new Laya.GlowFilter(color, blur, offX, offY);
                sprite.filters = [filter];
            }
            static filterBlur(sprite, strength) {
                let filter = new Laya.BlurFilter(strength);
                sprite.filters = [filter];
            }
            static filterGray(sprite, scale = 1) {
                scale = scale || 1;
                var grayscaleMat = [
                    0.3086 * scale, 0.6094 * scale, 0.0820 * scale, 0, 0,
                    0.3086 * scale, 0.6094 * scale, 0.0820 * scale, 0, 0,
                    0.3086 * scale, 0.6094 * scale, 0.0820 * scale, 0, 0,
                    0, 0, 0, 1, 0
                ];
                var filter = new Laya.ColorFilter(grayscaleMat);
                sprite.filters = [filter];
            }
            static filterBCSH(sprite, brightness, contrast, saturation, hue) {
                var filter = new Laya.ColorFilter();
                filter.adjustColor(brightness, contrast, saturation, hue);
                sprite.filters = [filter];
            }
            static filterColor(sprite, red, green, blue, alpha = 255) {
                var filter = new Laya.ColorFilter();
                filter.color(red, green, blue, alpha);
                sprite.filters = [filter];
            }
            static playComebackAction(nodes, xOffset, yOffset, delayTime = 0, dur = 0.5, callback, ease) {
                if (!nodes || nodes.length == 0) {
                    if (callback) {
                        callback();
                    }
                    return;
                }
                for (let i = 0; i < nodes.length; i++) {
                    let nodeEffect = nodes[i];
                    nodeEffect["_originPos"] = nodeEffect["_originPos"] || new Laya.Vector2(nodeEffect.x, nodeEffect.y);
                    nodeEffect.x = nodeEffect["_originPos"].x + xOffset;
                    nodeEffect.y = nodeEffect["_originPos"].y + yOffset;
                    nodeEffect.visible = true;
                    cc.tween(nodeEffect)
                        .delay(delayTime)
                        .call(() => {
                        nodeEffect.alpha = 1;
                    })
                        .toPos(dur, nodeEffect["_originPos"].x, nodeEffect["_originPos"].y, ease || cc.Ease.elasticOut)
                        .call(() => {
                        if (i == 0 && callback) {
                            callback();
                        }
                    })
                        .start();
                }
            }
            static playQuitbackAction(nodes, xOffset, yOffset, delayTime = 0, dur = 0.5, callback) {
                if (!nodes || nodes.length == 0) {
                    if (callback) {
                        callback();
                    }
                    return;
                }
                for (let i = 0; i < nodes.length; i++) {
                    let nodeEffect = nodes[i];
                    nodeEffect["_originPos"] = nodeEffect["_originPos"] || new Laya.Vector2(nodeEffect.x, nodeEffect.y);
                    nodeEffect.visible = true;
                    cc.tween(nodeEffect)
                        .delay(delayTime)
                        .call(() => {
                        nodeEffect.alpha = 1;
                    })
                        .toPos(dur, nodeEffect["_originPos"].x + xOffset, nodeEffect["_originPos"].y + yOffset, cc.Ease.elasticIn)
                        .call(() => {
                        if (i == 0 && callback) {
                            callback();
                        }
                    })
                        .start();
                }
            }
            static easeUpFlutter(node, endCallback, duration = 2, distance = 40) {
                if (!node || node.destroyed) {
                    return;
                }
                node.alpha = 0;
                cc.tween(node, true).parallel(cc.tween().toPos(duration / 2, node.x, node.y - distance, cc.Ease.sineOut), cc.tween().toAlpha(duration / 2 * 0.2, 1).delay(duration / 2 * 0.5).toAlpha(duration / 2 * 0.3, 0).call(() => { endCallback && endCallback(); })).start();
            }
            static easeUpDownFlutter(node, topCallback, duration = 4, distance = 30) {
                if (!node || node.destroyed) {
                    return;
                }
                cc.tween(node, true).repeatForever(cc.tween().byPos(duration / 2, 0, -distance, cc.Ease.sineIn).call(() => { topCallback && topCallback(); }).byPos(duration / 2, 0, distance, cc.Ease.sineOut)).start();
            }
            static roke(node, duration = 0.1) {
                if (!node || node.destroyed) {
                    return;
                }
                cc.tween(node, true).repeatForever(cc.tween().byRotation(duration, 5).byRotation(duration, -5).byRotation(duration, -5).byRotation(duration, 5).delay(0.2)).start();
            }
            static scalePop(node, duration = 0.25, callback) {
                node.scale(0, 0);
                cc.tween(node, true).toScale(duration, 1, cc.Ease.backOut).call(() => {
                    if (callback) {
                        callback();
                    }
                }).start();
            }
            static rotateForever(node, duration = 6, deltaAngel = -360) {
                if (!node || node.destroyed)
                    return;
                cc.tween(node, true).repeatForever(cc.tween().byRotation(duration, deltaAngel))
                    .start();
            }
        }

        class mgrInnerCdk extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("innerCdkData") || {};
                this.receiveCount = record;
            }
            static saveRecord() {
                super.saveRecord();
                let record = this.receiveCount;
                mgrRecord.setData("innerCdkData", record);
            }
            static isInnerCdk(key) {
                let indnerDb = mgrCfg.get("inner_cdk_db", key);
                if (indnerDb && mgrSdk.getCopNumberValueByKey(indnerDb.copSwitchKey) == 1) {
                    console.log("获取到内置cdk数据");
                    return true;
                }
                else {
                    return false;
                }
            }
            static receiveInnerCdk(key) {
                console.log("领取Cdk");
                if (!this.receiveCount) {
                    this.receiveCount = {};
                }
                if (this.isInnerCdk(key)) {
                    let indnerDb = mgrCfg.get("inner_cdk_db", key);
                    let cdkReceiveCount = indnerDb.receiveCount;
                    let rewards = indnerDb.rewards;
                    if (this.receiveCount[key]) {
                        if (this.receiveCount[key] >= cdkReceiveCount) {
                            mgrTip.showMsgTip("您已经领过了");
                            if (indnerDb.pointEventId) {
                                mgrSdk.statisCommonEvent(indnerDb.pointEventId, "1");
                            }
                        }
                        else {
                            this.receiveCount[key]++;
                            mgrTip.showMsgTip("领取cdk成功");
                            let items = [];
                            for (let index = 0; index < rewards.length; index++) {
                                const goodsInfo = rewards[index];
                                let itemId = goodsInfo[0];
                                let count = goodsInfo[1];
                                mgrPlayer.addItemAmount(itemId, count, "cdk");
                                mgrTip.addGotItemTip(itemId, count);
                                items.push({
                                    itemId: itemId,
                                    amount: count,
                                });
                            }
                            this.sendMsg('MSG_SDK_USE_CDK_SUCCESSFUL', {
                                items: items,
                            });
                            if (indnerDb.pointEventId) {
                                mgrSdk.statisCommonEvent(indnerDb.pointEventId, "0");
                            }
                        }
                    }
                    else {
                        this.receiveCount[key] = 1;
                        mgrTip.showMsgTip("领取cdk成功");
                        let items = [];
                        for (let index = 0; index < rewards.length; index++) {
                            const goodsInfo = rewards[index];
                            let itemId = goodsInfo[0];
                            let count = goodsInfo[1];
                            mgrPlayer.addItemAmount(itemId, count, "cdk");
                            mgrTip.addGotItemTip(itemId, count);
                            items.push({
                                itemId: itemId,
                                amount: count,
                            });
                        }
                        this.sendMsg('MSG_SDK_USE_CDK_SUCCESSFUL', {
                            items: items,
                        });
                        if (indnerDb.pointEventId) {
                            mgrSdk.statisCommonEvent(indnerDb.pointEventId, "0");
                        }
                    }
                    this.saveRecord();
                }
                else {
                    console.log("没有此内置cdk");
                    mgrSdk.useCdk(key);
                }
            }
        }

        class mgrMutualSing extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.registerListeners({
                    MSG_ITEM_AMOUNT_CHANGED: this.onMsgItemAmountChanged.bind(this),
                });
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("mgr_mutual_sing") || {};
            }
            static saveRecord() {
                super.saveRecord();
                let record = {};
                mgrRecord.setData("mgr_mutual_sing", record);
            }
            static onMsgItemAmountChanged(e) {
            }
        }

        class mgrOfflinePartRank extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.tryUpdateDatas();
                this.registerListeners({
                    MSG_ITEM_AMOUNT_CHANGED: this.onMsgItemAmountChanged.bind(this),
                });
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("offline_part_rank") || {};
                this._partRankDatas = record._partRankDatas || {};
                this._lastRefreshTime = record._lastRefreshTime || 0;
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    _partRankDatas: this._partRankDatas,
                    _lastRefreshTime: this._lastRefreshTime,
                };
                mgrRecord.setData("offline_part_rank", record);
            }
            static tryUpdateDatas() {
                let curTime = Tools.time();
                if (Tools.isOneDay(curTime, this._lastRefreshTime)) {
                    return;
                }
                let pvpDatas = mgrOfflinePvp.getPvpDatas();
                let maxPartNum = mgrPart.getMaxPartNum();
                for (let index = 0; index < pvpDatas.length; index++) {
                    const element = pvpDatas[index];
                    let player = this._partRankDatas[element.uid];
                    if (!player) {
                        let partNum = this.getInitPartNum();
                        if (element.rank < 100) {
                            partNum += (100 - element.rank) + Tools.random(-5, 5);
                        }
                        if (partNum > maxPartNum) {
                            partNum = maxPartNum;
                        }
                        player = {
                            uid: element.uid,
                            name: element.name,
                            partNum: partNum,
                            rank: 0,
                        };
                        this._partRankDatas[element.uid] = player;
                    }
                    else {
                        player.partNum += Tools.random(0, 5);
                        if (player.partNum > maxPartNum) {
                            player.partNum = maxPartNum;
                        }
                    }
                }
                this.updateOwnData();
                this._lastRefreshTime = curTime;
                this.saveRecord();
            }
            static getInitPartNum() {
                return Tools.random(5, 10);
            }
            static updateOwnData() {
                let ownUid = mgrPlayer.getUid();
                let own = this._partRankDatas[ownUid];
                let name = mgrPlayer.getName();
                if (!name)
                    return;
                if (!own) {
                    own = {
                        uid: ownUid,
                        name: mgrPlayer.getName(),
                        partNum: mgrPart.getOwnPartNum(),
                        rank: 0,
                    };
                    this._partRankDatas[ownUid] = own;
                }
                else {
                    own.name = mgrPlayer.getName();
                    own.partNum = mgrPart.getOwnPartNum();
                }
                this.saveRecord();
            }
            static getAllDatas() {
                let datas = [];
                for (const key in this._partRankDatas) {
                    const element = this._partRankDatas[key];
                    datas.push(element);
                }
                datas = Tools.sortArrayByField(datas, "-partNum");
                for (let index = 0; index < datas.length; index++) {
                    const element = datas[index];
                    element.rank = index + 1;
                }
                return datas;
            }
            static getOwnData() {
                let uid = mgrPlayer.getUid();
                return this._partRankDatas[uid];
            }
            static onMsgItemAmountChanged(e) {
                let itemId = e.itemId;
                if (!!mgrCfg.get_from_part_db(itemId)) {
                    this.updateOwnData();
                }
            }
        }
        mgrOfflinePartRank._partRankDatas = {};
        mgrOfflinePartRank._lastRefreshTime = 0;

        class mgrRole extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("mgrRole") || {};
                this.bUnitOutputUnlocked = record.bUnitOutputUnlocked || false;
                this.lastSettlementOutputTime = record.lastSettlementOutputTime || 0;
                this.bBorn = record.bBorn || false;
                this.showingRoleId = record.showingRoleId || 0;
                this.saveRecord();
                this.savedPhotoDataDict = {};
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    bUnitOutputUnlocked: this.bUnitOutputUnlocked,
                    lastSettlementOutputTime: this.lastSettlementOutputTime,
                    bBorn: this.bBorn,
                    showingRoleId: this.showingRoleId,
                };
                mgrRecord.setData("mgrRole", record);
                for (const key in this.savedPhotoDataDict) {
                    let data = this.savedPhotoDataDict[key];
                    if (data) {
                        let recordText = JSON.stringify(data);
                        Laya.LocalStorage.setItem(key, recordText);
                    }
                }
            }
            static changeShowingRoleId(roleId) {
                if (this.showingRoleId == roleId) {
                    return;
                }
                this.showingRoleId = roleId;
                let soundId = mgrCfg.get_from_role_db(roleId).soundId;
                if (soundId) {
                    mgrSound.play(soundId);
                }
                this.saveRecord();
                this.sendMsg("MSG_TEAM_LEADER_CHANGED");
            }
            static setBornStatus(value) {
                this.bBorn = value || false;
                this.saveRecord();
            }
            static isBorn() {
                return !!this.bBorn;
            }
            static getUnitOutPut() {
                return 1;
            }
            static savePhoto(key, texture) {
                let base65Str = Tools.encodeTexture(texture);
                let data = {
                    width: texture.width,
                    height: texture.height,
                    base65Str: base65Str,
                };
                this.cachedPhotoTextureDict[key] = texture;
                this.savedPhotoDataDict[key] = data;
                this.saveRecord();
            }
            static savePhotoData(key, dataDict) {
                this.savedPhotoDataDict[key] = dataDict;
                this.saveRecord();
            }
            static getPhotoData(key) {
                if (!this.savedPhotoDataDict[key]) {
                    let recordText = Laya.LocalStorage.getItem(key);
                    if (recordText) {
                        this.savedPhotoDataDict[key] = JSON.parse(recordText);
                    }
                }
                return this.savedPhotoDataDict[key];
            }
            static getPhotoTexture2D(key, texFormat = Laya.TextureFormat.R8G8B8A8) {
                if (!key) {
                    return null;
                }
                if (this.cachedPhotoTextureDict[key])
                    return this.cachedPhotoTextureDict[key];
                let data = this.getPhotoData(key);
                if (!data)
                    return null;
                let texture = Tools.decodeTexture(data.base65Str, data.width, data.height, texFormat);
                this.cachedPhotoTextureDict[key] = texture;
                return texture;
            }
        }
        mgrRole.cachedPhotoTextureDict = {};

        var MINUTE_INCOME = 0;
        const OFFLINE_MAX_TIME = 60 * 60 * 5;
        const OFFLINE_SETTLE_MIN_TIME = 60 * 60;
        class mgrOfflineReward extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
                this.trySettlementLastOfflineTime();
                this.goOfflineTime = Tools.time();
                Timer.callLoop(60, () => {
                    this.goOfflineTime = Tools.time();
                    this.saveRecord();
                }, true);
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("offline_reward") || {};
                this.goOfflineTime = record.goOfflineTime || Tools.time();
                this.willSettlementOfflineTimeQueue = record.willSettlementOfflineTimeQueue || [];
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    goOfflineTime: this.goOfflineTime,
                    willSettlementOfflineTimeQueue: this.willSettlementOfflineTimeQueue,
                };
                mgrRecord.setData("offline_reward", record);
            }
            static trySettlementLastOfflineTime() {
                let goOnlineTime = Tools.time();
                let deltaTime = Math.floor(goOnlineTime - this.goOfflineTime);
                if (deltaTime >= OFFLINE_SETTLE_MIN_TIME) {
                    this.willSettlementOfflineTimeQueue.push(deltaTime);
                    return true;
                }
                else {
                    return false;
                }
            }
            static getOfflineReward() {
                let pastTime = 0;
                let income = 0;
                for (let index = 0; index < this.willSettlementOfflineTimeQueue.length; index++) {
                    const time = this.willSettlementOfflineTimeQueue[index];
                    pastTime += time;
                }
                MINUTE_INCOME = mgrRole.getUnitOutPut() * 0.2 * 60;
                pastTime = pastTime > OFFLINE_MAX_TIME ? OFFLINE_MAX_TIME : pastTime;
                income = Math.ceil(pastTime / 60 * MINUTE_INCOME);
                return [pastTime, income];
            }
            static markOfflineRewardGeted() {
                this.willSettlementOfflineTimeQueue = [];
                this.goOfflineTime = Tools.time();
                this.saveRecord();
            }
        }
        mgrOfflineReward.goOfflineTime = 0;
        mgrOfflineReward.willSettlementOfflineTimeQueue = [];

        class mgrPartTrial extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化loadRecord");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("alertPartTrial") || {};
                this.trialPartLog = record.trialPartLog || {};
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    trialPartLog: this.trialPartLog
                };
                mgrRecord.setData("alertPartTrial", record);
            }
            static canTrialGetPart() {
                return mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAdFreeTrialPartDialog_trial);
            }
            static getPartTrialCount(partId) {
                return this.trialPartLog[partId] || 0;
            }
            static addPartTrialCount(partId) {
                if (!this.canTrialGetPart()) {
                    return;
                }
                if (!this.trialPartLog[partId]) {
                    this.trialPartLog[partId] = 1;
                }
                else {
                    this.trialPartLog[partId]++;
                }
                if (this.checkPartTrialUnlock(partId)) {
                    mgrPlayer.addItemAmount(partId, 1, "试用多次解锁部件");
                    mgrTip.addGotItemTip(partId, 1);
                }
                this.saveRecord();
            }
            static checkPartTrialUnlock(partId) {
                this.trialToUnlockCount = mgrSdk.getCopNumberValueByKey("trial_to_unlock_count") || 0;
                if (!this.canTrialGetPart()) {
                    return;
                }
                if (!this.trialToUnlockCount) {
                    return false;
                }
                if (!this.trialPartLog[partId]) {
                    return false;
                }
                return this.trialPartLog[partId] >= this.trialToUnlockCount ? true : false;
            }
            static getPartUnlockNeedTrialCount() {
                this.trialToUnlockCount = mgrSdk.getCopNumberValueByKey("trial_to_unlock_count") || 0;
                return this.trialToUnlockCount;
            }
        }
        mgrPartTrial.trialToUnlockCount = 0;

        class mgrQuest extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {};
                mgrRecord.setData("mgrquest", record);
            }
            static getCurrentQuestId() {
                let data = this.getMinUncompletedQuestData();
                if (!data) {
                    return 0;
                }
                return data.id;
            }
            static getCurrentQuestAchievement() {
                let data = this.getMinUncompletedQuestData();
                if (!data) {
                    return null;
                }
                return mgrAchievement.getAchievement(data.achievementId);
            }
            static getMinUncompletedQuestData() {
                let arr = mgrCfg.getDbArr("quest_achievement_db");
                arr = Tools.sortArrayByField(arr, "id");
                for (let i = 0; i < arr.length; i++) {
                    let data = arr[i];
                    let achievement = mgrAchievement.getAchievement(data.achievementId);
                    if (achievement.state < AchievementState.received) {
                        return data;
                    }
                }
                return null;
            }
        }

        class mgrReview extends Manager {
            static onLoad() {
                super.onLoad();
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("review") || {};
                this.lastAlertTime = record.lastAlertTime || 0;
                this.lastReviewTime = record.lastReviewTime || 0;
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    lastAlertTime: this.lastAlertTime || 0,
                    lastReviewTime: this.lastReviewTime || 0,
                };
                mgrRecord.setData("review", record);
            }
            static tryShowReviewDialog() {
                if (!window[`conch`]) {
                    return;
                }
                let os = window[`conchConfig`].getOS();
                if (os != "Conch-ios") {
                    console.log("[warn] mgrReview.tryShowReviewDialog mgrSdk.bHasReviewModule is false");
                    return;
                }
                if (this.lastReviewTime != 0) {
                    console.log("[warn] mgrReview.tryShowReviewDialog already reviewd");
                    return;
                }
                if (Tools.isOneDay(Tools.time(), this.lastAlertTime || 0)) {
                    console.log("[warn] mgrReview.tryShowReviewDialog today already alerted");
                    return;
                }
                this.showReviewDialog();
            }
            static showReviewDialog() {
                this.recordReview();
                this.lastAlertTime = Tools.time();
                this.saveRecord();
            }
            static recordReview() {
                this.lastReviewTime = Tools.time();
                this.saveRecord();
                let cmd = "/c/openInviteComment";
                let msgData = {
                    cmd: cmd,
                    data: {},
                };
                mgrSdk.sendMsgToSdk(msgData);
            }
            static markUnreview() {
                this.lastAlertTime = 0;
                this.lastReviewTime = 0;
                this.saveRecord();
            }
        }

        class mgrWorldDaily extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化mgrWorldDaily loadRecord");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("world_daily") || {};
                this.currWorldDay = record.currWorldDay || 1;
                this.rewardedDayDict = record.rewardedDayDict || {};
                this.cardFightDayDict = record.cardFightDayDict || {};
                this.cardFightShowDayDict = record.cardFightShowDayDict || {};
                this.gameType2PlayedStageIdDict = record.gameType2PlayedStageIdDict || {};
                this.gameType2VipShowedCountDict = record.gameType2VipShowedCountDict || {};
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {
                    currWorldDay: this.currWorldDay,
                    rewardedDayDict: this.rewardedDayDict,
                    cardFightDayDict: this.cardFightDayDict,
                    cardFightShowDayDict: this.cardFightShowDayDict,
                    gameType2PlayedStageIdDict: this.gameType2PlayedStageIdDict,
                    gameType2VipShowedCountDict: this.gameType2VipShowedCountDict
                };
                mgrRecord.setData("world_daily", record);
            }
            static addWorldDay() {
                let worldDay = (this.currWorldDay || 1) + 1;
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                if (!!template) {
                    this.currWorldDay = worldDay;
                    this.saveRecord();
                    mgrSdk.statisCommonEvent(template.statisPointId);
                }
                return this.currWorldDay;
            }
            static getWorldDay() {
                return this.currWorldDay || 1;
            }
            static getWorldDayRoleReward(worldDay) {
                worldDay = worldDay || this.getWorldDay();
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                let bRoleGot = false;
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (v.unlockItemId == template.rewardItemId && mgrPlayer.getItemAmount(v.id) > 0) {
                        bRoleGot = true;
                    }
                });
                if (!bRoleGot) {
                    return { itemId: template.rewardItemId, amount: template.rewardItemAmount };
                }
                else {
                    return { itemId: template.alternateRewardItemId, amount: template.alternateRewardItemAmount };
                }
            }
            static tryReceiveWorldDayRoleReward(worldDay) {
                worldDay = worldDay || this.getWorldDay();
                let bRewarded = this.rewardedDayDict[worldDay];
                if (!!bRewarded) {
                    return null;
                }
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                let bRoleGot = false;
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (v.unlockItemId == template.rewardItemId && mgrPlayer.getItemAmount(v.id) > 0) {
                        bRoleGot = true;
                    }
                });
                if (!bRoleGot) {
                    mgrPlayer.addItemAmount(template.rewardItemId, template.rewardItemAmount, "日程奖励");
                    return { itemId: template.rewardItemId, amount: template.rewardItemAmount };
                }
                else {
                    mgrPlayer.addItemAmount(template.alternateRewardItemId, template.alternateRewardItemAmount, "日程奖励");
                    return { itemId: template.alternateRewardItemId, amount: template.alternateRewardItemAmount };
                }
            }
            static getNextRewardPartId(rewardType) {
                let template = mgrCfg.get_from_world_daily_quest_config(rewardType || 1);
                let partIds = template.partIds || [];
                for (let i = 0; i < partIds.length; i++) {
                    if (mgrPlayer.getItemAmount(partIds[i]) <= 0 && !!mgrCfg.get_from_item_template_db(partIds[i])) {
                        return partIds[i];
                    }
                }
                return 0;
            }
            static getUnownedVipPart(rewardType) {
                let config = mgrCfg.get_from_world_daily_quest_config(rewardType || 1);
                for (let i = 0; i < config.vipPartIds.length; i++) {
                    let partId = config.vipPartIds[i];
                    if (mgrPlayer.getItemAmount(partId) <= 0) {
                        return partId;
                    }
                }
                return null;
            }
            static markCardFightShowed(worldDay) {
                worldDay = worldDay || this.getWorldDay();
                this.cardFightShowDayDict[worldDay] = true;
                this.saveRecord();
            }
            static isCardFightShowedDay(worldDay) {
                worldDay = worldDay || this.getWorldDay();
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                if (!template.cardFightStageId) {
                    return true;
                }
                return !!this.cardFightShowDayDict[worldDay];
            }
            static markCardFighted(worldDay) {
                worldDay = worldDay || this.getWorldDay();
                this.cardFightDayDict[worldDay] = true;
                this.saveRecord();
            }
            static isCardFightedDay(worldDay) {
                worldDay = worldDay || this.getWorldDay();
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                if (!template.cardFightStageId) {
                    return true;
                }
                return !!this.cardFightDayDict[worldDay];
            }
            static getFirstTimeRewardWorldDayByRoleId(roleId) {
                let unlockItemId = 0;
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (roleId == v.id && !unlockItemId) {
                        unlockItemId = v.unlockItemId;
                    }
                });
                let worldDay = 0;
                mgrCfg.forDb_from_world_daily_quest((k, v) => {
                    if (unlockItemId == v.rewardItemId && !worldDay) {
                        worldDay = v.id;
                    }
                });
                return worldDay;
            }
            static getDailyQuestDataByPartId(partId) {
                let data = null;
                mgrCfg.forDb_from_world_daily_quest_config((k, v) => {
                    let partIds = v.partIds;
                    let vipPartId = v.vipPartIds;
                    let totalPartIds = partIds.concat(vipPartId);
                    if (totalPartIds.indexOf(partId) > 0) {
                        data = v;
                        return;
                    }
                });
                return data;
            }
            static addPlayedGameStageId(gameType, stageId) {
                this.gameType2PlayedStageIdDict[gameType] = this.gameType2PlayedStageIdDict[gameType] || {};
                this.gameType2PlayedStageIdDict[gameType][stageId] = true;
                this.saveRecord();
            }
            static getStageIdByGameTypeAndMaxStageId(gameType, maxStageId) {
                let playStageIdDict = this.gameType2PlayedStageIdDict[gameType] || {};
                for (let i = 1; i <= maxStageId; i++) {
                    if (!playStageIdDict[i]) {
                        return i;
                    }
                }
                return Tools.random(1, maxStageId);
            }
            static addVipShowCountByGameType(gameType) {
                this.gameType2VipShowedCountDict[gameType] = this.gameType2VipShowedCountDict[gameType] || 0;
                this.gameType2VipShowedCountDict[gameType] += 1;
                this.saveRecord();
            }
            static getVipShowCountByGameType(gameType) {
                return this.gameType2VipShowedCountDict[gameType] || 0;
            }
            static canFreePlayVipByGameType(gameType) {
                let showCount = this.getVipShowCountByGameType(gameType);
                let template = mgrCfg.get_from_world_daily_quest_config(gameType);
                if (!template) {
                    return false;
                }
                let vipFreePlayInShowCountArr = template.vipFreePlayInShowCountArr || [];
                if (vipFreePlayInShowCountArr.length == 0) {
                    return false;
                }
                let dict = {};
                for (let i = 0; i < vipFreePlayInShowCountArr.length; i++) {
                    let count = vipFreePlayInShowCountArr[i];
                    dict[count] = true;
                }
                return !!dict[showCount];
            }
            static getGameTempParms(gameType) {
                return this.gameType2TempParamDict[gameType];
            }
            static setGameTempParms(gameType, params) {
                this.gameType2TempParamDict[gameType] = params;
            }
            static cleanGameTempParms(gameType) {
                this.gameType2TempParamDict[gameType] = null;
            }
        }
        mgrWorldDaily.currWorldDay = 1;
        mgrWorldDaily.rewardedDayDict = {};
        mgrWorldDaily.cardFightDayDict = {};
        mgrWorldDaily.cardFightShowDayDict = {};
        mgrWorldDaily.gameType2TempParamDict = {};

        class LightMapMaterial extends Laya.Material {
            constructor() {
                super();
                this.setShaderName("lightMapMaterial");
                this._shaderValues.setNumber(LightMapMaterial.ALBEDOIDENTITY, 0.5);
                this._shaderValues.setVector(LightMapMaterial.ALBEDOCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this.fakeShadowFactor = 0.5;
                this.alpha = 1;
                this.lightMapFactor = 1;
            }
            static __init__() {
                LightMapMaterial.SHADERDEFINE_BONE = Laya.Shader3D.getDefineByName("BONE");
                LightMapMaterial.SHADERDEFINE_REALTIME_SHADOW = Laya.Shader3D.getDefineByName("REALTIME_SHADOW");
                LightMapMaterial.SHADERDEFINE_TILINGOFFSET = Laya.Shader3D.getDefineByName("TILINGOFFSET");
                LightMapMaterial.SHADERDEFINE_FAKE_SHADOW = Laya.Shader3D.getDefineByName("FAKE_SHADOW");
                LightMapMaterial.SHADERDEFINE_WHOLE_ALPHA = Laya.Shader3D.getDefineByName("WHOLE_ALPHA");
                LightMapMaterial.SHADERDEFINE_ALBEDOTEXTURE = Laya.Shader3D.getDefineByName("ALBEDOTEXTURE");
                LightMapMaterial.SHADERDEFINE_ALBEDOCOLOR = Laya.Shader3D.getDefineByName("ALBEDOCOLOR");
            }
            static initShader() {
                LightMapMaterial.__init__();
                var stateMap = {
                    's_Cull': Laya.Shader3D.RENDER_STATE_CULL,
                    's_Blend': Laya.Shader3D.RENDER_STATE_BLEND,
                    's_BlendSrc': Laya.Shader3D.RENDER_STATE_BLEND_SRC,
                    's_BlendDst': Laya.Shader3D.RENDER_STATE_BLEND_DST,
                    's_DepthTest': Laya.Shader3D.RENDER_STATE_DEPTH_TEST,
                    's_DepthWrite': Laya.Shader3D.RENDER_STATE_DEPTH_WRITE
                };
                var attributeMap = {
                    'a_Position': Laya.VertexMesh.MESH_POSITION0,
                    'a_Normal': Laya.VertexMesh.MESH_NORMAL0,
                    'a_Texcoord0': Laya.VertexMesh.MESH_TEXTURECOORDINATE0,
                    'a_Texcoord1': Laya.VertexMesh.MESH_TEXTURECOORDINATE1,
                    'a_BoneWeights': Laya.VertexMesh.MESH_BLENDWEIGHT0,
                    'a_BoneIndices': Laya.VertexMesh.MESH_BLENDINDICES0,
                };
                var uniformMap = {
                    'u_MvpMatrix': Laya.Shader3D.PERIOD_SPRITE,
                    'u_WorldMat': Laya.Shader3D.PERIOD_SPRITE,
                    'u_CameraPos': Laya.Shader3D.PERIOD_CAMERA,
                    'u_AlbedoTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoIdentity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SunLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_Bones': Laya.Shader3D.PERIOD_CUSTOM,
                    'u_alpha': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ShadowMap': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightvpMatrix': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightmapScaleOffset': Laya.Shader3D.PERIOD_SPRITE,
                    'u_LightMap': Laya.Shader3D.PERIOD_SPRITE,
                    'u_TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowInnerRadius': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowOuterRadius': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowPoint1': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowPoint2': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowFactor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightMapFactor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SpotLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.range': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.spot': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.position': Laya.Shader3D.PERIOD_SCENE,
                };
                var lightMapMaterial3D = Laya.Shader3D.add("lightMapMaterial");
                var subShader = new Laya.SubShader(attributeMap, uniformMap);
                lightMapMaterial3D.addSubShader(subShader);
                var vs1 = `
		attribute vec4 a_Position; 
		attribute vec3 a_Normal; 
		attribute vec2 a_Texcoord0;
		uniform mat4 u_MvpMatrix; 
		uniform mat4 u_WorldMat;
		uniform vec3 u_CameraPos;
		varying vec2 v_Texcoord0;    
		varying vec3 v_PositionWorld;

		#ifdef CASTSHADOW
			varying vec4 v_posView;
		#endif

		#ifdef BONE
			const int c_MaxBoneCount = 24;
			attribute vec4 a_BoneIndices;
			attribute vec4 a_BoneWeights;
			uniform mat4 u_Bones[c_MaxBoneCount];
		#endif

		#if defined(LIGHTMAP)&&defined(UV1)
			attribute vec2 a_Texcoord1;
		#endif

		#ifdef LIGHTMAP
			uniform vec4 u_LightmapScaleOffset;
			varying vec2 v_LightMapUV;
        #endif
        
        #ifdef TILINGOFFSET
            uniform vec4 u_TilingOffset;
		#endif

        vec2 TransformUV(vec2 texcoord,vec4 tilingOffset) {
            vec2 transTexcoord=vec2(texcoord.x,texcoord.y-1.0)*tilingOffset.xy+vec2(tilingOffset.z,-tilingOffset.w);
            transTexcoord.y+=1.0;
            return transTexcoord;
        }

		void main() 
		{ 
			#ifdef BONE
				mat4 skinTransform=mat4(0.0);
				skinTransform += u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;
				skinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;
				skinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;
				skinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;
				vec4 position = skinTransform * a_Position;
				gl_Position=u_MvpMatrix * position;
				mat3 worldMat=mat3(u_WorldMat * skinTransform);
			#else
				gl_Position=u_MvpMatrix * a_Position;
				mat3 worldMat=mat3(u_WorldMat);
			#endif

            #ifdef TILINGOFFSET
                v_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);
            #else
                v_Texcoord0=a_Texcoord0;
			#endif	
			
			#ifdef BONE
				v_PositionWorld=(u_WorldMat*position).xyz;
			#else
				v_PositionWorld=(u_WorldMat*a_Position).xyz;
			#endif

			#ifdef LIGHTMAP
				#ifdef UV1
					v_LightMapUV=vec2(a_Texcoord1.x,1.0-a_Texcoord1.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;
				#else
					v_LightMapUV=vec2(a_Texcoord0.x,1.0-a_Texcoord0.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;
				#endif 
				v_LightMapUV.y=1.0-v_LightMapUV.y;

			#endif

			#ifdef CASTSHADOW
				v_posView = gl_Position.xyzw;
			#endif

			gl_Position.z=gl_Position.z * 2.0 - gl_Position.w;
		}`;
                var ps1 = `
		precision lowp float;

		varying vec3 v_PositionWorld;
	
		varying vec2 v_Texcoord0; 
		struct DirectionLight
		{
			vec3 color;
			vec3 direction;
		};
		uniform DirectionLight u_SunLight;

		#ifdef WHOLE_ALPHA
			uniform float u_alpha;
		#endif
		uniform sampler2D u_AlbedoTexture;
		uniform float u_AlbedoIdentity;
		uniform vec4 u_AlbedoColor;

		#ifdef LIGHTMAP
			varying vec2 v_LightMapUV;
			uniform sampler2D u_LightMap;
			uniform float u_LightMapFactor;
		#endif

		#ifdef CASTSHADOW
			varying vec4 v_posView;
		#endif
		
		vec3 DecodeLightmap(vec4 color) {
			return color.rgb*color.a*5.0;
		}

		void main_castshadow(){
			#ifdef CASTSHADOW
				float z = v_posView.z/v_posView.w;
				z = z*0.5 + 0.5;
				gl_FragColor = vec4(0.0, 0, z, 1.0);
			#endif
		}

		void main_normal(){
			vec4 albedoTextureColor = vec4(1.0);
			#ifdef ALBEDOTEXTURE
				albedoTextureColor = texture2D(u_AlbedoTexture, v_Texcoord0);
			#endif

			#ifdef ALBEDOCOLOR
				albedoTextureColor *= u_AlbedoColor * u_AlbedoIdentity;
			#endif

			#ifdef ALPHATEST
			if(albedoTextureColor.a <= 0.1){
				discard;
			}
			#endif

			#ifdef LIGHTMAP    
				albedoTextureColor.rgb *= DecodeLightmap(texture2D(u_LightMap, v_LightMapUV)) * u_LightMapFactor;
			#endif

			#ifdef WHOLE_ALPHA
				//叠加全局透明度
				gl_FragColor = vec4(albedoTextureColor.rgb, albedoTextureColor.a*u_alpha);
			#else
				gl_FragColor = vec4(albedoTextureColor.rgb, albedoTextureColor.a);
			#endif

				gl_FragColor.rgb *= u_SunLight.color;
		}
	
		void main() 
		{ 
			#ifdef CASTSHADOW
				main_castshadow();
			#else
				main_normal();
			#endif
		}`;
                subShader.addShaderPass(vs1, ps1, stateMap);
            }
            get albedoTexture() {
                return this._shaderValues.getTexture(LightMapMaterial.ALBEDOTEXTURE);
            }
            set albedoTexture(value) {
                if (value) {
                    this._shaderValues.addDefine(LightMapMaterial.SHADERDEFINE_ALBEDOTEXTURE);
                }
                else {
                    this._shaderValues.removeDefine(LightMapMaterial.SHADERDEFINE_ALBEDOTEXTURE);
                }
                this._shaderValues.setTexture(LightMapMaterial.ALBEDOTEXTURE, value);
            }
            get albedoColor() {
                return this._shaderValues.getVector(LightMapMaterial.ALBEDOCOLOR);
            }
            set albedoColor(value) {
                if (value) {
                    this._defineDatas.add(LightMapMaterial.SHADERDEFINE_ALBEDOCOLOR);
                }
                else {
                    this._defineDatas.remove(LightMapMaterial.SHADERDEFINE_ALBEDOCOLOR);
                }
                this._shaderValues.setVector(LightMapMaterial.ALBEDOCOLOR, value);
            }
            get albedoIdentity() {
                return this._shaderValues.getNumber(LightMapMaterial.ALBEDOIDENTITY);
            }
            set albedoIdentity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(LightMapMaterial.ALBEDOIDENTITY, value);
            }
            get shadowMap() {
                return this._shaderValues.getTexture(LightMapMaterial.SHADOW_MAP);
            }
            set shadowMap(value) {
                if (value) {
                    this._defineDatas.add(LightMapMaterial.SHADERDEFINE_REALTIME_SHADOW);
                }
                else {
                    this._defineDatas.remove(LightMapMaterial.SHADERDEFINE_REALTIME_SHADOW);
                }
                this._shaderValues.setTexture(LightMapMaterial.SHADOW_MAP, value);
            }
            get lightvp() {
                return this._shaderValues.getMatrix4x4(LightMapMaterial.LIGHT_VP);
            }
            set lightvp(value) {
                this._shaderValues.setMatrix4x4(LightMapMaterial.LIGHT_VP, value);
            }
            get tilingOffset() {
                return this._shaderValues.getVector(LightMapMaterial.TILINGOFFSET);
            }
            set tilingOffset(value) {
                if (value) {
                    if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
                        this._shaderValues.addDefine(LightMapMaterial.SHADERDEFINE_TILINGOFFSET);
                    else
                        this._shaderValues.removeDefine(LightMapMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                else {
                    this._shaderValues.removeDefine(LightMapMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                this._shaderValues.setVector(LightMapMaterial.TILINGOFFSET, value);
            }
            get fakeShadowInnerRadius() {
                return this._shaderValues.getNumber(LightMapMaterial.FAKE_SHADOW_INNER_RADIUS);
            }
            set fakeShadowInnerRadius(value) {
                this._shaderValues.setNumber(LightMapMaterial.FAKE_SHADOW_INNER_RADIUS, value);
                this.__refresh_fake_shadow_define_();
            }
            get fakeShadowOuterRadius() {
                return this._shaderValues.getNumber(LightMapMaterial.FAKE_SHADOW_OUTER_RADIUS);
            }
            set fakeShadowOuterRadius(value) {
                this._shaderValues.setNumber(LightMapMaterial.FAKE_SHADOW_OUTER_RADIUS, value);
                this.__refresh_fake_shadow_define_();
            }
            get fakeShadowPoint1() {
                return this._shaderValues.getVector3(LightMapMaterial.FAKE_SHADOW_POINT1);
            }
            set fakeShadowPoint1(value) {
                this._shaderValues.setVector3(LightMapMaterial.FAKE_SHADOW_POINT1, value);
                this.__refresh_fake_shadow_define_();
            }
            get fakeShadowPoint2() {
                return this._shaderValues.getVector3(LightMapMaterial.FAKE_SHADOW_POINT2);
            }
            set fakeShadowPoint2(value) {
                this._shaderValues.setVector3(LightMapMaterial.FAKE_SHADOW_POINT2, value);
                this.__refresh_fake_shadow_define_();
            }
            get fakeShadowFactor() {
                return this._shaderValues.getNumber(LightMapMaterial.FAKE_SHADOW_FACTOR);
            }
            set fakeShadowFactor(value) {
                this._shaderValues.setNumber(LightMapMaterial.FAKE_SHADOW_FACTOR, value);
                this.__refresh_fake_shadow_define_();
            }
            __refresh_fake_shadow_define_() {
                if (this.fakeShadowInnerRadius && this.fakeShadowOuterRadius && this.fakeShadowPoint1 && this.fakeShadowPoint2) {
                    this._shaderValues.addDefine(LightMapMaterial.SHADERDEFINE_FAKE_SHADOW);
                }
                else {
                    this._shaderValues.removeDefine(LightMapMaterial.SHADERDEFINE_FAKE_SHADOW);
                }
            }
            setFakeShadowPoint(p1, p2) {
                this.__point1__ = p1;
                this.__point2__ = p2;
                if (!this.__point1__ || !this.__point2__) {
                    this.fakeShadowPoint1 = null;
                    this.fakeShadowPoint2 = null;
                    if (this.__timer__) {
                        this.__timer__.stop();
                        this.__timer__ = null;
                    }
                    return;
                }
                this.fakeShadowPoint1 = this.__point1__.transform.position;
                this.fakeShadowPoint2 = this.__point2__.transform.position;
                Timer.callLoop(0.016, (timer) => {
                    if (this.__point1__.destroyed) {
                        timer.stop();
                        return;
                    }
                    this.fakeShadowPoint1 = this.__point1__.transform.position;
                    this.fakeShadowPoint2 = this.__point2__.transform.position;
                }, this);
            }
            get alpha() {
                return this._shaderValues.getNumber(LightMapMaterial.WHOLE_ALPHA);
            }
            set alpha(value) {
                if (value != null) {
                    this._defineDatas.add(LightMapMaterial.SHADERDEFINE_WHOLE_ALPHA);
                }
                else {
                    this._defineDatas.remove(LightMapMaterial.SHADERDEFINE_WHOLE_ALPHA);
                }
                this._shaderValues.setNumber(LightMapMaterial.WHOLE_ALPHA, value);
            }
            get lightMapFactor() {
                return this._shaderValues.getNumber(LightMapMaterial.LIGHT_MAP_FACTOR);
            }
            set lightMapFactor(value) {
                this._shaderValues.setNumber(LightMapMaterial.LIGHT_MAP_FACTOR, value);
                this.__refresh_fake_shadow_define_();
            }
            get cull() {
                return this._shaderValues.getInt(LightMapMaterial.CULL);
            }
            set cull(value) {
                this._shaderValues.setInt(LightMapMaterial.CULL, value);
            }
            get blend() {
                return this._shaderValues.getInt(LightMapMaterial.BLEND);
            }
            set blend(value) {
                this._shaderValues.setInt(LightMapMaterial.BLEND, value);
            }
            get blendSrc() {
                return this._shaderValues.getInt(LightMapMaterial.BLEND_SRC);
            }
            set blendSrc(value) {
                this._shaderValues.setInt(LightMapMaterial.BLEND_SRC, value);
            }
            get blendDst() {
                return this._shaderValues.getInt(LightMapMaterial.BLEND_DST);
            }
            set blendDst(value) {
                this._shaderValues.setInt(LightMapMaterial.BLEND_DST, value);
            }
            get depthTest() {
                return this._shaderValues.getInt(LightMapMaterial.DEPTH_TEST);
            }
            set depthTest(value) {
                this._shaderValues.setInt(LightMapMaterial.DEPTH_TEST, value);
            }
            get depthWrite() {
                return this._shaderValues.getBool(LightMapMaterial.DEPTH_WRITE);
            }
            set depthWrite(value) {
                this._shaderValues.setBool(LightMapMaterial.DEPTH_WRITE, value);
            }
            set renderMode(value) {
                switch (value) {
                    case LightMapMaterial.RENDERMODE_OPAQUE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case LightMapMaterial.RENDERMODE_CUTOUT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case LightMapMaterial.RENDERMODE_CUTOUT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case LightMapMaterial.RENDERMODE_TRANSPARENT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case LightMapMaterial.RENDERMODE_TRANSPARENT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    default:
                        throw new Error("LightMapMaterial : renderMode value error.");
                }
            }
        }
        LightMapMaterial.ALBEDOTEXTURE = Laya.Shader3D.propertyNameToID("u_AlbedoTexture");
        LightMapMaterial.ALBEDOIDENTITY = Laya.Shader3D.propertyNameToID("u_AlbedoIdentity");
        LightMapMaterial.ALBEDOCOLOR = Laya.Shader3D.propertyNameToID("u_AlbedoColor");
        LightMapMaterial.SHADOW_MAP = Laya.Shader3D.propertyNameToID("u_ShadowMap");
        LightMapMaterial.LIGHT_VP = Laya.Shader3D.propertyNameToID("u_LightvpMatrix");
        LightMapMaterial.TILINGOFFSET = Laya.Shader3D.propertyNameToID("u_TilingOffset");
        LightMapMaterial.FAKE_SHADOW_INNER_RADIUS = Laya.Shader3D.propertyNameToID("u_FakeShadowInnerRadius");
        LightMapMaterial.FAKE_SHADOW_OUTER_RADIUS = Laya.Shader3D.propertyNameToID("u_FakeShadowOuterRadius");
        LightMapMaterial.FAKE_SHADOW_POINT1 = Laya.Shader3D.propertyNameToID("u_FakeShadowPoint1");
        LightMapMaterial.FAKE_SHADOW_POINT2 = Laya.Shader3D.propertyNameToID("u_FakeShadowPoint2");
        LightMapMaterial.FAKE_SHADOW_FACTOR = Laya.Shader3D.propertyNameToID("u_FakeShadowFactor");
        LightMapMaterial.WHOLE_ALPHA = Laya.Shader3D.propertyNameToID("u_alpha");
        LightMapMaterial.LIGHT_MAP_FACTOR = Laya.Shader3D.propertyNameToID("u_LightMapFactor");
        LightMapMaterial.SPOT_LIGHT_COLOR = Laya.Shader3D.propertyNameToID("u_SpotLight.color");
        LightMapMaterial.SPOT_LIGHT_DIRECTION = Laya.Shader3D.propertyNameToID("u_SpotLight.direction");
        LightMapMaterial.SPOT_LIGHT_RANGE = Laya.Shader3D.propertyNameToID("u_SpotLight.range");
        LightMapMaterial.SPOT_LIGHT_SPOT = Laya.Shader3D.propertyNameToID("u_SpotLight.spot");
        LightMapMaterial.SPOT_LIGHT_POSITION = Laya.Shader3D.propertyNameToID("u_SpotLight.position");
        LightMapMaterial.CULL = Laya.Shader3D.propertyNameToID("s_Cull");
        LightMapMaterial.BLEND = Laya.Shader3D.propertyNameToID("s_Blend");
        LightMapMaterial.BLEND_SRC = Laya.Shader3D.propertyNameToID("s_BlendSrc");
        LightMapMaterial.BLEND_DST = Laya.Shader3D.propertyNameToID("s_BlendDst");
        LightMapMaterial.DEPTH_TEST = Laya.Shader3D.propertyNameToID("s_DepthTest");
        LightMapMaterial.DEPTH_WRITE = Laya.Shader3D.propertyNameToID("s_DepthWrite");
        LightMapMaterial.RENDERMODE_OPAQUE = 1;
        LightMapMaterial.RENDERMODE_CUTOUT = 2;
        LightMapMaterial.RENDERMODE_CUTOUT_CULL_NONE = 3;
        LightMapMaterial.RENDERMODE_TRANSPARENT = 4;
        LightMapMaterial.RENDERMODE_TRANSPARENT_CULL_NONE = 5;

        class NormalMaterial extends Laya.Material {
            constructor() {
                super();
                this.setShaderName("NormalMaterial");
                this._shaderValues.setNumber(NormalMaterial.ALBEDOIDENTITY, 0.5);
                this._shaderValues.setVector(NormalMaterial.ALBEDOCOLOR, new Laya.Vector4(1.0, 1.0, 1.0, 1.0));
                this.alpha = 1;
            }
            static __init__() {
                NormalMaterial.SHADERDEFINE_BONE = Laya.Shader3D.getDefineByName("BONE");
                NormalMaterial.SHADERDEFINE_TILINGOFFSET = Laya.Shader3D.getDefineByName("TILINGOFFSET");
                NormalMaterial.SHADERDEFINE_WHOLE_ALPHA = Laya.Shader3D.getDefineByName("WHOLE_ALPHA");
                NormalMaterial.SHADERDEFINE_ALBEDOTEXTURE = Laya.Shader3D.getDefineByName("ALBEDOTEXTURE");
                NormalMaterial.SHADERDEFINE_ALBEDOCOLOR = Laya.Shader3D.getDefineByName("ALBEDOCOLOR");
            }
            static initShader() {
                NormalMaterial.__init__();
                var stateMap = {
                    's_Cull': Laya.Shader3D.RENDER_STATE_CULL,
                    's_Blend': Laya.Shader3D.RENDER_STATE_BLEND,
                    's_BlendSrc': Laya.Shader3D.RENDER_STATE_BLEND_SRC,
                    's_BlendDst': Laya.Shader3D.RENDER_STATE_BLEND_DST,
                    's_DepthTest': Laya.Shader3D.RENDER_STATE_DEPTH_TEST,
                    's_DepthWrite': Laya.Shader3D.RENDER_STATE_DEPTH_WRITE
                };
                var attributeMap = {
                    'a_Position': Laya.VertexMesh.MESH_POSITION0,
                    'a_Normal': Laya.VertexMesh.MESH_NORMAL0,
                    'a_Texcoord0': Laya.VertexMesh.MESH_TEXTURECOORDINATE0,
                    'a_Texcoord1': Laya.VertexMesh.MESH_TEXTURECOORDINATE1,
                    'a_BoneWeights': Laya.VertexMesh.MESH_BLENDWEIGHT0,
                    'a_BoneIndices': Laya.VertexMesh.MESH_BLENDINDICES0,
                };
                var uniformMap = {
                    'u_MvpMatrix': Laya.Shader3D.PERIOD_SPRITE,
                    'u_WorldMat': Laya.Shader3D.PERIOD_SPRITE,
                    'u_CameraPos': Laya.Shader3D.PERIOD_CAMERA,
                    'u_AlbedoTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoIdentity': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_AlbedoColor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SunLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SunLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_Bones': Laya.Shader3D.PERIOD_CUSTOM,
                    'u_alpha': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_ShadowMap': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightvpMatrix': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightmapScaleOffset': Laya.Shader3D.PERIOD_SPRITE,
                    'u_LightMap': Laya.Shader3D.PERIOD_SPRITE,
                    'u_TilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowInnerRadius': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowOuterRadius': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowPoint1': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowPoint2': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_FakeShadowFactor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_LightMapFactor': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_SpotLight.color': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.direction': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.range': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.spot': Laya.Shader3D.PERIOD_SCENE,
                    'u_SpotLight.position': Laya.Shader3D.PERIOD_SCENE,
                };
                var NormalMaterial3D = Laya.Shader3D.add("NormalMaterial");
                var subShader = new Laya.SubShader(attributeMap, uniformMap);
                NormalMaterial3D.addSubShader(subShader);
                var vs1 = `
		attribute vec4 a_Position; 
		attribute vec3 a_Normal; 
		attribute vec2 a_Texcoord0;
		uniform mat4 u_MvpMatrix; 
		uniform mat4 u_WorldMat;
		uniform vec3 u_CameraPos;
		varying vec2 v_Texcoord0;    
		varying vec3 v_PositionWorld;

		#ifdef BONE
			const int c_MaxBoneCount = 24;
			attribute vec4 a_BoneIndices;
			attribute vec4 a_BoneWeights;
			uniform mat4 u_Bones[c_MaxBoneCount];
		#endif
        
        #ifdef TILINGOFFSET
            uniform vec4 u_TilingOffset;
		#endif
		
        vec2 TransformUV(vec2 texcoord,vec4 tilingOffset) {
            vec2 transTexcoord=vec2(texcoord.x,texcoord.y-1.0)*tilingOffset.xy+vec2(tilingOffset.z,-tilingOffset.w);
            transTexcoord.y+=1.0;
            return transTexcoord;
        }

		void main() 
		{ 
			#ifdef BONE
				mat4 skinTransform=mat4(0.0);
				skinTransform += u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;
				skinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;
				skinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;
				skinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;
				vec4 position = skinTransform * a_Position;
				gl_Position=u_MvpMatrix * position;
				mat3 worldMat=mat3(u_WorldMat * skinTransform);
			#else
				gl_Position=u_MvpMatrix * a_Position;
				mat3 worldMat=mat3(u_WorldMat);
			#endif

            #ifdef TILINGOFFSET
                v_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);
            #else
                v_Texcoord0=a_Texcoord0;
			#endif	
			
			#ifdef BONE
				v_PositionWorld=(u_WorldMat*position).xyz;
			#else
				v_PositionWorld=(u_WorldMat*a_Position).xyz;
			#endif

			gl_Position.z=gl_Position.z * 2.0 - gl_Position.w;
		}`;
                var ps1 = `
		#ifdef GL_FRAGMENT_PRECISION_HIGH
            precision highp float;
            precision highp int;
        #else
            precision mediump float;
            precision mediump int;
        #endif

		varying vec3 v_PositionWorld;
	
		varying vec2 v_Texcoord0; 

		#ifdef WHOLE_ALPHA
			uniform float u_alpha;
		#endif
		uniform sampler2D u_AlbedoTexture;
		uniform float u_AlbedoIdentity;
		uniform vec4 u_AlbedoColor;

		void main_normal(){
			vec4 albedoTextureColor = vec4(1.0);
			#ifdef ALBEDOTEXTURE
				albedoTextureColor = texture2D(u_AlbedoTexture, v_Texcoord0);
			#endif

			#ifdef ALBEDOCOLOR
				albedoTextureColor *= u_AlbedoColor * u_AlbedoIdentity;
			#endif

			#ifdef ALPHATEST
			if(albedoTextureColor.a <= 0.1){
				discard;
			}
			#endif

			#ifdef WHOLE_ALPHA
				//叠加全局透明度
				gl_FragColor = vec4(albedoTextureColor.rgb, albedoTextureColor.a*u_alpha);
			#else
				gl_FragColor = vec4(albedoTextureColor.rgb, albedoTextureColor.a);
			#endif

		}
	
		void main() 
		{ 
			main_normal();
		}`;
                subShader.addShaderPass(vs1, ps1, stateMap);
            }
            get albedoTexture() {
                return this._shaderValues.getTexture(NormalMaterial.ALBEDOTEXTURE);
            }
            set albedoTexture(value) {
                if (value) {
                    this._shaderValues.addDefine(NormalMaterial.SHADERDEFINE_ALBEDOTEXTURE);
                }
                else {
                    this._shaderValues.removeDefine(NormalMaterial.SHADERDEFINE_ALBEDOTEXTURE);
                }
                this._shaderValues.setTexture(NormalMaterial.ALBEDOTEXTURE, value);
            }
            get albedoColor() {
                return this._shaderValues.getVector(NormalMaterial.ALBEDOCOLOR);
            }
            set albedoColor(value) {
                if (value) {
                    this._defineDatas.add(NormalMaterial.SHADERDEFINE_ALBEDOCOLOR);
                }
                else {
                    this._defineDatas.remove(NormalMaterial.SHADERDEFINE_ALBEDOCOLOR);
                }
                this._shaderValues.setVector(NormalMaterial.ALBEDOCOLOR, value);
            }
            get albedoIdentity() {
                return this._shaderValues.getNumber(NormalMaterial.ALBEDOIDENTITY);
            }
            set albedoIdentity(value) {
                value = Math.max(0.0, Math.min(1.0, value));
                this._shaderValues.setNumber(NormalMaterial.ALBEDOIDENTITY, value);
            }
            get tilingOffset() {
                return this._shaderValues.getVector(NormalMaterial.TILINGOFFSET);
            }
            set tilingOffset(value) {
                if (value) {
                    if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
                        this._shaderValues.addDefine(NormalMaterial.SHADERDEFINE_TILINGOFFSET);
                    else
                        this._shaderValues.removeDefine(NormalMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                else {
                    this._shaderValues.removeDefine(NormalMaterial.SHADERDEFINE_TILINGOFFSET);
                }
                this._shaderValues.setVector(NormalMaterial.TILINGOFFSET, value);
            }
            get alpha() {
                return this._shaderValues.getNumber(NormalMaterial.WHOLE_ALPHA);
            }
            set alpha(value) {
                if (value != null) {
                    this._defineDatas.add(NormalMaterial.SHADERDEFINE_WHOLE_ALPHA);
                }
                else {
                    this._defineDatas.remove(NormalMaterial.SHADERDEFINE_WHOLE_ALPHA);
                }
                this._shaderValues.setNumber(NormalMaterial.WHOLE_ALPHA, value);
            }
            get cull() {
                return this._shaderValues.getInt(NormalMaterial.CULL);
            }
            set cull(value) {
                this._shaderValues.setInt(NormalMaterial.CULL, value);
            }
            get blend() {
                return this._shaderValues.getInt(NormalMaterial.BLEND);
            }
            set blend(value) {
                this._shaderValues.setInt(NormalMaterial.BLEND, value);
            }
            get blendSrc() {
                return this._shaderValues.getInt(NormalMaterial.BLEND_SRC);
            }
            set blendSrc(value) {
                this._shaderValues.setInt(NormalMaterial.BLEND_SRC, value);
            }
            get blendDst() {
                return this._shaderValues.getInt(NormalMaterial.BLEND_DST);
            }
            set blendDst(value) {
                this._shaderValues.setInt(NormalMaterial.BLEND_DST, value);
            }
            get depthTest() {
                return this._shaderValues.getInt(NormalMaterial.DEPTH_TEST);
            }
            set depthTest(value) {
                this._shaderValues.setInt(NormalMaterial.DEPTH_TEST, value);
            }
            get depthWrite() {
                return this._shaderValues.getBool(NormalMaterial.DEPTH_WRITE);
            }
            set depthWrite(value) {
                this._shaderValues.setBool(NormalMaterial.DEPTH_WRITE, value);
            }
            set renderMode(value) {
                switch (value) {
                    case NormalMaterial.RENDERMODE_OPAQUE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case NormalMaterial.RENDERMODE_CUTOUT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case NormalMaterial.RENDERMODE_CUTOUT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case NormalMaterial.RENDERMODE_TRANSPARENT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case NormalMaterial.RENDERMODE_TRANSPARENT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case NormalMaterial.RENDERMODE_TRANSPARENT_BLEND_ADD:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_ONE_MINUS_DST_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    default:
                        throw new Error("NormalMaterial : renderMode value error.");
                }
            }
        }
        NormalMaterial.ALBEDOTEXTURE = Laya.Shader3D.propertyNameToID("u_AlbedoTexture");
        NormalMaterial.ALBEDOIDENTITY = Laya.Shader3D.propertyNameToID("u_AlbedoIdentity");
        NormalMaterial.ALBEDOCOLOR = Laya.Shader3D.propertyNameToID("u_AlbedoColor");
        NormalMaterial.TILINGOFFSET = Laya.Shader3D.propertyNameToID("u_TilingOffset");
        NormalMaterial.WHOLE_ALPHA = Laya.Shader3D.propertyNameToID("u_alpha");
        NormalMaterial.CULL = Laya.Shader3D.propertyNameToID("s_Cull");
        NormalMaterial.BLEND = Laya.Shader3D.propertyNameToID("s_Blend");
        NormalMaterial.BLEND_SRC = Laya.Shader3D.propertyNameToID("s_BlendSrc");
        NormalMaterial.BLEND_DST = Laya.Shader3D.propertyNameToID("s_BlendDst");
        NormalMaterial.DEPTH_TEST = Laya.Shader3D.propertyNameToID("s_DepthTest");
        NormalMaterial.DEPTH_WRITE = Laya.Shader3D.propertyNameToID("s_DepthWrite");
        NormalMaterial.RENDERMODE_OPAQUE = 1;
        NormalMaterial.RENDERMODE_CUTOUT = 2;
        NormalMaterial.RENDERMODE_CUTOUT_CULL_NONE = 3;
        NormalMaterial.RENDERMODE_TRANSPARENT = 4;
        NormalMaterial.RENDERMODE_TRANSPARENT_CULL_NONE = 5;
        NormalMaterial.RENDERMODE_TRANSPARENT_BLEND_ADD = 6;

        class PaintMaterial extends Laya.Material {
            constructor() {
                super();
                this.setShaderName("PaintMaterial");
                this.alpha = 1;
            }
            static __init__() {
                PaintMaterial.SHADERDEFINE_PAGE_BASE = Laya.Shader3D.getDefineByName("PAGE_BASE");
                PaintMaterial.SHADERDEFINE_PAINT_TEXTURE = Laya.Shader3D.getDefineByName("PAINT_TEXTURE");
                PaintMaterial.SHADERDEFINE_PAINT_TILINGOFFSET = Laya.Shader3D.getDefineByName("PAINT_TILINGOFFSET");
                PaintMaterial.SHADERDEFINE_PAINT_MASK = Laya.Shader3D.getDefineByName("PAINT_MASK");
                PaintMaterial.SHADERDEFINE_WHOLE_ALPHA = Laya.Shader3D.getDefineByName("WHOLE_ALPHA");
            }
            static initShader() {
                PaintMaterial.__init__();
                var stateMap = {
                    's_Cull': Laya.Shader3D.RENDER_STATE_CULL,
                    's_Blend': Laya.Shader3D.RENDER_STATE_BLEND,
                    's_BlendSrc': Laya.Shader3D.RENDER_STATE_BLEND_SRC,
                    's_BlendDst': Laya.Shader3D.RENDER_STATE_BLEND_DST,
                    's_DepthTest': Laya.Shader3D.RENDER_STATE_DEPTH_TEST,
                    's_DepthWrite': Laya.Shader3D.RENDER_STATE_DEPTH_WRITE
                };
                var attributeMap = {
                    'a_Position': Laya.VertexMesh.MESH_POSITION0,
                    'a_Normal': Laya.VertexMesh.MESH_NORMAL0,
                    'a_Texcoord0': Laya.VertexMesh.MESH_TEXTURECOORDINATE0,
                    'a_Texcoord1': Laya.VertexMesh.MESH_TEXTURECOORDINATE1,
                    'a_BoneWeights': Laya.VertexMesh.MESH_BLENDWEIGHT0,
                    'a_BoneIndices': Laya.VertexMesh.MESH_BLENDINDICES0,
                };
                var uniformMap = {
                    'u_MvpMatrix': Laya.Shader3D.PERIOD_SPRITE,
                    'u_WorldMat': Laya.Shader3D.PERIOD_SPRITE,
                    'u_CameraPos': Laya.Shader3D.PERIOD_CAMERA,
                    'u_alpha': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PageBase': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintTexture': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintTilingOffset': Laya.Shader3D.PERIOD_MATERIAL,
                    'u_PaintMask': Laya.Shader3D.PERIOD_MATERIAL,
                };
                var PaintMaterial3D = Laya.Shader3D.add("PaintMaterial");
                var subShader = new Laya.SubShader(attributeMap, uniformMap);
                PaintMaterial3D.addSubShader(subShader);
                var vs1 = `
		attribute vec4 a_Position; 
		attribute vec3 a_Normal; 
		attribute vec2 a_Texcoord0;
		uniform mat4 u_MvpMatrix; 
		uniform mat4 u_WorldMat;
		uniform vec3 u_CameraPos;
		varying vec2 v_Texcoord0;

		void main() 
		{ 
			gl_Position=u_MvpMatrix * a_Position;
			mat3 worldMat=mat3(u_WorldMat);

            v_Texcoord0=a_Texcoord0;

			gl_Position.z=gl_Position.z * 2.0 - gl_Position.w;
		}`;
                var ps1 = `
		#ifdef GL_FRAGMENT_PRECISION_HIGH
            precision highp float;
            precision highp int;
        #else
            precision mediump float;
            precision mediump int;
        #endif
	
        varying vec2 v_Texcoord0; 
        
        #ifdef PAGE_BASE
            uniform sampler2D u_PageBase;
        #endif

        #ifdef PAINT_TEXTURE
			uniform sampler2D u_PaintTexture;
        #endif
        
        #ifdef PAINT_TILINGOFFSET
			uniform vec4 u_PaintTilingOffset;
        #endif
        
        #ifdef PAINT_MASK
			uniform sampler2D u_PaintMask;
		#endif

		#ifdef WHOLE_ALPHA
			uniform float u_alpha;
        #endif
        
        vec2 TransformUV(vec2 texcoord,vec4 tilingOffset) {
            vec2 transTexcoord=vec2(texcoord.x,texcoord.y-1.0)*tilingOffset.xy+vec2(tilingOffset.z,-tilingOffset.w);
            transTexcoord.y+=1.0;
            return transTexcoord;
        }

		void main_normal(){
			vec4 albedoTextureColor = vec4(0.0);
		
			#if defined(PAGE_BASE)&&defined(PAINT_TEXTURE)&&defined(PAINT_MASK)
				vec4 baseColor = texture2D(u_PageBase, v_Texcoord0);

				#ifdef PAINT_TILINGOFFSET
					vec2 texcoordL1 = TransformUV(v_Texcoord0, u_PaintTilingOffset);
					vec4 paintColor = texture2D(u_PaintTexture, texcoordL1);
				#else
					vec4 paintColor = texture2D(u_PaintTexture, v_Texcoord0);
				#endif

				vec4 maskColor = texture2D(u_PaintMask, v_Texcoord0);

				albedoTextureColor.rgb = baseColor.rgb * (1.0 - maskColor.rgb) + paintColor.rgb * maskColor.rgb;
				albedoTextureColor.a = baseColor.a * (1.0 - maskColor.a) + paintColor.a * maskColor.a;
			#endif

			#ifdef ALPHATEST
			if(albedoTextureColor.a <= 0.1){
				discard;
			}
			#endif

			#ifdef WHOLE_ALPHA
				//叠加全局透明度
				gl_FragColor = vec4(albedoTextureColor.rgb, albedoTextureColor.a*u_alpha);
			#else
				gl_FragColor = vec4(albedoTextureColor.rgb, albedoTextureColor.a);
			#endif
		}
	
		void main() 
		{ 
			main_normal();
		}`;
                subShader.addShaderPass(vs1, ps1, stateMap);
            }
            get pageBase() {
                return this._shaderValues.getTexture(PaintMaterial.PAGE_BASE);
            }
            set pageBase(value) {
                if (value) {
                    this._shaderValues.addDefine(PaintMaterial.SHADERDEFINE_PAGE_BASE);
                }
                else {
                    this._shaderValues.removeDefine(PaintMaterial.SHADERDEFINE_PAGE_BASE);
                }
                this._shaderValues.setTexture(PaintMaterial.PAGE_BASE, value);
            }
            get paintTexture() {
                return this._shaderValues.getTexture(PaintMaterial.PAINT_TEXTURE);
            }
            set paintTexture(value) {
                if (value) {
                    this._shaderValues.addDefine(PaintMaterial.SHADERDEFINE_PAINT_TEXTURE);
                }
                else {
                    this._shaderValues.removeDefine(PaintMaterial.SHADERDEFINE_PAINT_TEXTURE);
                }
                this._shaderValues.setTexture(PaintMaterial.PAINT_TEXTURE, value);
            }
            get paintMask() {
                return this._shaderValues.getTexture(PaintMaterial.PAINT_MASK);
            }
            set paintMask(value) {
                if (value) {
                    this._shaderValues.addDefine(PaintMaterial.SHADERDEFINE_PAINT_MASK);
                }
                else {
                    this._shaderValues.removeDefine(PaintMaterial.SHADERDEFINE_PAINT_MASK);
                }
                this._shaderValues.setTexture(PaintMaterial.PAINT_MASK, value);
            }
            get paintTilingOffset() {
                return this._shaderValues.getVector(PaintMaterial.PAINT_TILINGOFFSET);
            }
            set paintTilingOffset(value) {
                if (value) {
                    if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
                        this._shaderValues.addDefine(PaintMaterial.SHADERDEFINE_PAINT_TILINGOFFSET);
                    else
                        this._shaderValues.removeDefine(PaintMaterial.SHADERDEFINE_PAINT_TILINGOFFSET);
                }
                else {
                    this._shaderValues.removeDefine(PaintMaterial.SHADERDEFINE_PAINT_TILINGOFFSET);
                }
                this._shaderValues.setVector(PaintMaterial.PAINT_TILINGOFFSET, value);
            }
            get alpha() {
                return this._shaderValues.getNumber(PaintMaterial.WHOLE_ALPHA);
            }
            set alpha(value) {
                if (value != null) {
                    this._defineDatas.add(PaintMaterial.SHADERDEFINE_WHOLE_ALPHA);
                }
                else {
                    this._defineDatas.remove(PaintMaterial.SHADERDEFINE_WHOLE_ALPHA);
                }
                this._shaderValues.setNumber(PaintMaterial.WHOLE_ALPHA, value);
            }
            get cull() {
                return this._shaderValues.getInt(PaintMaterial.CULL);
            }
            set cull(value) {
                this._shaderValues.setInt(PaintMaterial.CULL, value);
            }
            get blend() {
                return this._shaderValues.getInt(PaintMaterial.BLEND);
            }
            set blend(value) {
                this._shaderValues.setInt(PaintMaterial.BLEND, value);
            }
            get blendSrc() {
                return this._shaderValues.getInt(PaintMaterial.BLEND_SRC);
            }
            set blendSrc(value) {
                this._shaderValues.setInt(PaintMaterial.BLEND_SRC, value);
            }
            get blendDst() {
                return this._shaderValues.getInt(PaintMaterial.BLEND_DST);
            }
            set blendDst(value) {
                this._shaderValues.setInt(PaintMaterial.BLEND_DST, value);
            }
            get depthTest() {
                return this._shaderValues.getInt(PaintMaterial.DEPTH_TEST);
            }
            set depthTest(value) {
                this._shaderValues.setInt(PaintMaterial.DEPTH_TEST, value);
            }
            get depthWrite() {
                return this._shaderValues.getBool(PaintMaterial.DEPTH_WRITE);
            }
            set depthWrite(value) {
                this._shaderValues.setBool(PaintMaterial.DEPTH_WRITE, value);
            }
            set renderMode(value) {
                switch (value) {
                    case PaintMaterial.RENDERMODE_OPAQUE:
                        this.alphaTest = false;
                        this.renderQueue = Laya.Material.RENDERQUEUE_OPAQUE;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case PaintMaterial.RENDERMODE_CUTOUT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case PaintMaterial.RENDERMODE_CUTOUT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_ALPHATEST;
                        this.alphaTest = true;
                        this.depthWrite = true;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_DISABLE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case PaintMaterial.RENDERMODE_TRANSPARENT:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case PaintMaterial.RENDERMODE_TRANSPARENT_CULL_NONE:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_NONE;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_SRC_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LESS;
                        break;
                    case PaintMaterial.RENDERMODE_TRANSPARENT_BLEND_ADD:
                        this.renderQueue = Laya.Material.RENDERQUEUE_TRANSPARENT;
                        this.alphaTest = false;
                        this.depthWrite = false;
                        this.cull = Laya.RenderState.CULL_BACK;
                        this.blend = Laya.RenderState.BLEND_ENABLE_ALL;
                        this.blendSrc = Laya.RenderState.BLENDPARAM_ONE_MINUS_DST_ALPHA;
                        this.blendDst = Laya.RenderState.BLENDPARAM_ONE;
                        this.depthTest = Laya.RenderState.DEPTHTEST_LEQUAL;
                        break;
                    default:
                        throw new Error("PaintMaterial : renderMode value error.");
                }
            }
        }
        PaintMaterial.PAGE_BASE = Laya.Shader3D.propertyNameToID("u_PageBase");
        PaintMaterial.PAINT_TEXTURE = Laya.Shader3D.propertyNameToID("u_PaintTexture");
        PaintMaterial.PAINT_TILINGOFFSET = Laya.Shader3D.propertyNameToID("u_PaintTilingOffset");
        PaintMaterial.PAINT_MASK = Laya.Shader3D.propertyNameToID("u_PaintMask");
        PaintMaterial.WHOLE_ALPHA = Laya.Shader3D.propertyNameToID("u_alpha");
        PaintMaterial.CULL = Laya.Shader3D.propertyNameToID("s_Cull");
        PaintMaterial.BLEND = Laya.Shader3D.propertyNameToID("s_Blend");
        PaintMaterial.BLEND_SRC = Laya.Shader3D.propertyNameToID("s_BlendSrc");
        PaintMaterial.BLEND_DST = Laya.Shader3D.propertyNameToID("s_BlendDst");
        PaintMaterial.DEPTH_TEST = Laya.Shader3D.propertyNameToID("s_DepthTest");
        PaintMaterial.DEPTH_WRITE = Laya.Shader3D.propertyNameToID("s_DepthWrite");
        PaintMaterial.RENDERMODE_OPAQUE = 1;
        PaintMaterial.RENDERMODE_CUTOUT = 2;
        PaintMaterial.RENDERMODE_CUTOUT_CULL_NONE = 3;
        PaintMaterial.RENDERMODE_TRANSPARENT = 4;
        PaintMaterial.RENDERMODE_TRANSPARENT_CULL_NONE = 5;
        PaintMaterial.RENDERMODE_TRANSPARENT_BLEND_ADD = 6;

        class vLoadingScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vLoadingScene";
                this.exportNodeNames = [];
                this.curProgress = 0;
                this.fakeProgress = 0;
            }
            onOpened() {
                super.onOpened();
                mgrRecord.__init();
                mgrSdk.init();
                this.buttonAgeTip.fOnClick = this.onClickButtonAgeTip.bind(this);
                this.buttonBg.fOnClick = this.onClickButtonBg.bind(this);
                this.buttonBg.__node.visible = false;
                this.labelGoon.visible = false;
                for (let i = 0; i <= 5; i++) {
                    let node = this["spriteMusicNote" + i];
                    node["_originPos"] = new Laya.Vector2(node.x, node.y);
                    node.scale(0, 0, true);
                    cc.tween(node)
                        .delay(0.2 * (i + 1)).byPos(0.2, 0, -38).byPos(0.2, 0, 38)
                        .call(() => {
                        cc.tween(node)
                            .repeatForever(cc.tween().byPos(0.2, 0, -38).byPos(0.2, 0, 38).delay(0.15 * 6))
                            .start();
                    })
                        .start();
                }
                this.spriteBgHolder.texture = new Laya.Texture(Laya.Texture2D.blackTexture);
                mgrEffect.filterColor(this.spriteBgHolder, 199, 118, 253);
                mgrSdk.getBaseChannelInfo();
                this.fillGameInfo();
                this.fillAgeTipInfo();
                mgrLayout.widget(0.5, 1, this.spriteTextBg, { x: 0.5, y: 1 });
                mgrSdk.statisOnStageStart("10013");
                this.beginLoading();
                this.registerListeners({
                    MSG_SDK_CHANNEL_INFO_RESULT: this.onMsgChannelInfoResult.bind(this),
                    MSG_SDK_BASE_CHANNEL_INFO_CHANGED: this.onMsgSdkBaseChannelInfoChanged.bind(this),
                });
                this.updateProgress();
                this.updateTimer = Timer.callLoop(0.016, () => { this.updateProgress(); }, this);
            }
            onClosed() {
                super.onClosed();
            }
            initNative(resolve) {
                Timer.callLoop(0.05, function (timer) {
                    console.log("不执行");
                    if (mgrNative.isAllowStartGame()) {
                        timer.stop();
                        console.log("执行");
                        resolve();
                    }
                });
            }
            beginLoading() {
                this.context.beginTime = Tools.time();
                let taskManager = new TaskManager((progress, total) => {
                    this.curProgress = progress / total;
                });
                let taskSamples = [];
                taskSamples = [];
                taskManager.push([(finishCallback) => {
                        this.initNative(finishCallback);
                    }]);
                taskSamples.push((finishCallback) => {
                    console.log("==>初始化自定义shader");
                    ClothMaterial.initShader();
                    HairMaterial.initShader();
                    SkinMaterial.initShader();
                    CartoonMaterial.initShader();
                    LightMapMaterial.initShader();
                    NormalMaterial.initShader();
                    PaintMaterial.initShader();
                    finishCallback();
                });
                let cfgUrls = mgrCfg.getLoadUrls();
                for (const k in cfgUrls) {
                    let url = cfgUrls[k];
                    taskSamples.push((finishcallback) => {
                        console.log(`加载配置表: ${url}`);
                        Laya.loader.load(url, new Laya.Handler(this, (obj) => {
                            if (obj) {
                                finishcallback();
                            }
                        }));
                    });
                }
                taskManager.push(taskSamples);
                taskManager.push([(finishCallback) => {
                        console.log("处理加载完毕事宜!!");
                        this.initGameData(finishCallback);
                    }]);
                taskSamples = [];
                let defaultPartModelIds = [
                    "eff_ui_xsyd",
                ];
                for (let index = 0; index < defaultPartModelIds.length; index++) {
                    const modelId = defaultPartModelIds[index];
                    taskSamples.push((finishCallback) => {
                        mgrLoader.loadModeWithModeId(modelId, () => {
                            this.add3DEffectAtFront(modelId, { x: 10000, y: 10000 }, 1);
                            Timer.callLater(0.1, () => {
                                finishCallback();
                            }, this);
                        }, this, 0);
                    });
                }
                taskManager.push(taskSamples);
                taskManager.start(() => {
                    let usedTime = Tools.time() - this.context.beginTime;
                    console.log(`加载完毕, 总共用时: ${usedTime * 1000}毫秒`);
                    mgrSdk.onLoadingComplete();
                    vLoadingScene.bInit = true;
                });
            }
            initGameData(finishCallback) {
                mgrCfg.processDb();
                this.__importAllManager();
                Manager.loadAllManagers(finishCallback);
                ScaleButton.setSoundPlayId(102);
            }
            __importAllManager() {
                let allNeedImportManager = [
                    mgrNative,
                    mgrSound,
                    mgrCfg,
                    mgrPlayer,
                    mgrDirector,
                    mgrTip,
                    mgrDebug,
                    mgrAd,
                    mgrCop,
                    mgrStage,
                    mgrOfflinePartRank,
                    mgrOfflinePvp,
                    mgrAlertRouter,
                    mgrPart,
                    mgrSign,
                    mgrAchievement,
                    mgrGuide,
                    mgrShop,
                    mgrLoader,
                    mgrChannel,
                    mgrReview,
                    mgrAdNative,
                    mgrNativeAdSdk,
                    mgrActivingBanner,
                    mgrOfflineReward,
                    mgrRole,
                    mgrBannerInt,
                    mgrBoneBinder,
                    mgrLayout,
                    mgrEffect,
                    mgrMutualSing,
                    mgrGameResVersion,
                    mgrDynamicBone,
                    mgrQuest,
                    mgrVideoRecorder,
                    mgrShare,
                    mgrSwitchOpen,
                    mgrAmaze,
                    mgrInnerCdk,
                    mgrWorldDaily,
                    mgrCard,
                    mgrCardFightSkill,
                    mgrDesign,
                    mgrPartTrial,
                    mgrAmazePen,
                ];
                for (let index = 0; index < allNeedImportManager.length; index++) {
                    const element = allNeedImportManager[index];
                    element.__init();
                }
            }
            updateProgress() {
                let factor = 0.5;
                this.fakeProgress = this.fakeProgress * (1 - factor) + this.curProgress * factor;
                for (let i = 0; i <= 5; i++) {
                    let node = this["spriteMusicNote" + i];
                    let s = this.fakeProgress >= (i / 5 - 0.1) ? 1 : 0;
                    node.scale(s, s, true);
                }
                if (this.fakeProgress >= 0.99) {
                    this.updateTimer.stop();
                    this.startGame();
                }
            }
            rollAllStar() {
                for (let i = 0; i <= 5; i++) {
                    let node = this["spriteMusicNote" + i];
                    cc.tween(node).removeAllActions();
                    cc.tween(node).toPos(0.1, node["_originPos"].x, node["_originPos"].y)
                        .call(() => {
                        cc.tween(node)
                            .repeatForever(cc.tween().byRotation(1, 360))
                            .start();
                    })
                        .start();
                }
            }
            startGame() {
                console.log("---------------startGame");
                mgrDirector.debugSavePrecompileShaderData();
                if (mgrSdk.baseChannelInfo && mgrSdk.baseChannelInfo.bStartGameByTouch) {
                    this.boxProgress.visible = false;
                    this.labelGoon.visible = true;
                    this.buttonBg.__node.visible = true;
                    cc.tween(this.labelGoon).repeatForever(cc.tween().delay(3).toAlpha(0.3, 0).toAlpha(0.3, 1)).start();
                }
                else {
                    this.goIn();
                }
            }
            goIn() {
                if (this.bStartedGame) {
                    return;
                }
                this.bStartedGame = true;
                Tools.unRegisterTouchHander(this);
                mgrPlayer.tryAdaptDouyingMaterial();
                mgrGuide.adaptGuideTrasaction();
                if (mgrSdk.getCopNumberValueByKey("b_change_adv_id_2_adevent_id") == 1) {
                    mgrAd.changeAdEventDbAdvId2AdEventId();
                }
                mgrDesign.updatePartDbByDesignedPart();
                this.boxProgress.visible = true;
                this.rollAllStar();
                if (this.labelGoon.visible) {
                    cc.tween(this.labelGoon).removeAllActions();
                    this.labelGoon.visible = false;
                }
                let path = "res/ui/loading/art_01.jpg";
                let sprite = Laya.stage.addChild(new Laya.Sprite());
                sprite.name = Const.CUSTOM_LAYA_STAGE_BASE_BG_NAME;
                sprite.size(Const.RESOLUTION_RANGE.maxWidth, Const.RESOLUTION_RANGE.maxHeight);
                sprite.pivot(Const.RESOLUTION_RANGE.maxWidth / 2, Const.RESOLUTION_RANGE.maxHeight / 2);
                sprite.pos(Laya.stage.width / 2, Laya.stage.height / 2);
                sprite.zOrder = -10000;
                Tools.loadImg(sprite, path);
                Timer.callLater(0.1, () => {
                    this.prepareBorn();
                }, this);
            }
            prepareBorn() {
                let loadShowingRoleCard = (roleId, callback) => {
                    let roleData = mgrCfg.get_from_role_db(roleId);
                    Laya.loader.load(roleData.defaultCardTextureJsonPath, new Laya.Handler(this, (obj) => {
                        let datas = Laya.loader.getRes(roleData.defaultCardTextureJsonPath);
                        let cardId = mgrCard.getMinEmptyDataCardId();
                        let textureKey = mgrCard.getRoleCardTextureKeyNameByCardId(cardId);
                        mgrRole.savePhotoData(textureKey, datas);
                        let styleId = roleData.defalutCardStyle;
                        let partIds = roleData.partIds;
                        let power = mgrCard.calculateRolePartIdsPower(roleId, partIds);
                        let hp = mgrCard.calculateRolePartIdsHp(roleId, partIds);
                        mgrCard.setPlayerCardInfo(cardId, roleId, styleId, textureKey, power, hp, partIds);
                        callback && callback();
                    }));
                };
                let goHub = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene", { fromSystemModel: SYSTEM_MODEL.loading });
                };
                let callback = (roleId) => {
                    mgrCfg.forDb_from_role_db((k, v) => {
                        if (!!v.bDefaultHave) {
                            roleId = v.id;
                        }
                    });
                    mgrPlayer.addItemAmount(roleId, 1, "出生");
                    mgrRole.changeShowingRoleId(roleId);
                    mgrRole.setBornStatus(true);
                    let roleData = mgrCfg.get_from_role_db(roleId);
                    for (let k in roleData.centerPartIds) {
                        let partId = roleData.centerPartIds[k];
                        mgrPlayer.addItemAmount(partId, 1, "初始人送");
                    }
                    mgrPart.setLastClothes(roleData.centerPartIds);
                    mgrTip.showLoadingTip("prestart_scene_load", new Laya.Vector2, 0, true);
                    mgrDirector.open2DScene("vPrestartScene");
                };
                if (!mgrRole.isBorn()) {
                    let roleId = 0;
                    mgrCfg.forDb_from_role_db((k, v) => {
                        if (!roleId && !!v.bDefaultHave) {
                            roleId = v.id;
                        }
                    });
                    roleId = roleId || 101;
                    callback(roleId);
                }
                else {
                    if (mgrGuide.isAllForceGuideFinished() && mgrCard.getAllPlayerCardInfo().length <= 0) {
                        loadShowingRoleCard(mgrRole.showingRoleId, () => {
                            goHub();
                        });
                    }
                    else {
                        if (!mgrGuide.isFinished(1700) || !mgrGuide.isFinished(1900)) {
                            mgrDirector.warpSceneWidthEffect(`vFreedomRoomScene`, {
                                stageId: 2001,
                                fromSystemModel: SYSTEM_MODEL.loading,
                            });
                        }
                        else {
                            goHub();
                        }
                    }
                }
            }
            onMsgChannelInfoResult() {
                console.log("收到初始化回调!!!");
            }
            fillGameInfo(bSdkMsg) {
                this.labelTipAuthor.text = Const.licenceInfo;
                this.labelTipAuthor.visible = true;
                if (!this.labelTipAuthor.text) {
                    this.labelTipAuthor.visible = false;
                }
                this.bgImgPath = "res/ui/loading/art_01.jpg";
                let name = !!mgrSdk.baseChannelInfo ? mgrSdk.baseChannelInfo.gameName : "珠珠装扮物语";
                this.spriteLogo.visible = name == "珠珠的秘密";
                this.spriteLogo1.visible = name == "珠珠换装衣橱";
                this.spriteLogo2.visible = name == "珠珠装扮物语";
                Tools.loadImg(this.spriteBg, this.bgImgPath);
            }
            onClickButtonAgeTip() {
                mgrDirector.openDialog(`vAgeTipDialog`);
            }
            onClickButtonBg() {
                this.goIn();
            }
            onMsgSdkBaseChannelInfoChanged() {
                this.fillAgeTipInfo();
                this.fillGameInfo(true);
            }
            fillAgeTipInfo() {
                let baseChannelInfo = mgrSdk.baseChannelInfo || null;
                this.buttonAgeTip.__node.visible = baseChannelInfo && baseChannelInfo.bShowAgeLevelInfo;
            }
        }

        class StageTouchEvent extends Laya.Script {
            constructor() {
                super(...arguments);
                this._bEnableTouchEffect = true;
                this._bEnableTouchSound = true;
                this._lastTouchTime = 0;
            }
            onStart() {
            }
            onStageMouseDown(e) {
                if ((Tools.time() - this._lastTouchTime) <= 1) {
                    return;
                }
                this._lastTouchTime = Tools.time();
                !!this._bEnableTouchEffect && vLoadingScene.bInit && mgrDirector.add3DEffectAtFront(MODEL_ID.effect.eff_ui_dianji, { x: e.stageX, y: e.stageY }, 3, 0.6);
            }
            get lastTouchedTime() {
                return this._lastTouchTime;
            }
            set lastTouchedTime(value) {
                this._lastTouchTime = value;
            }
            get enabledTouchEffect() {
                return this._bEnableTouchEffect;
            }
            set enabledTouchEffect(value) {
                this._bEnableTouchEffect = value;
            }
            set enabledTouchSound(value) {
                this._bEnableTouchSound = value;
            }
        }

        var LAYER_ZORDER;
        (function (LAYER_ZORDER) {
            LAYER_ZORDER[LAYER_ZORDER["layer2dScene"] = 1000] = "layer2dScene";
            LAYER_ZORDER[LAYER_ZORDER["layer2dDialog"] = 10000] = "layer2dDialog";
            LAYER_ZORDER[LAYER_ZORDER["layer3d"] = 20000] = "layer3d";
            LAYER_ZORDER[LAYER_ZORDER["layer2dTip"] = 30000] = "layer2dTip";
        })(LAYER_ZORDER || (LAYER_ZORDER = {}));
        class mgrDirector extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("mgrDirector.onLoad");
            }
            static initScene() {
                this.init2DLayer();
                this.init3DLayer();
            }
            static init2DLayer() {
                if (!this.Layer2D) {
                    this.Layer2D = Laya.stage.addChild(new Laya.Sprite());
                    this.Layer2D.size(0, 0);
                    this.Layer2D.pos(Laya.stage.width / 2, Laya.stage.height / 2);
                    this.Layer2D.name = "Layer2D";
                    this.Layer2D.zOrder = 1000;
                    this.stageTouchEventScript = this.Layer2D.addComponent(StageTouchEvent);
                    this.Layer2DScene = this.Layer2D.addChild(new Laya.Sprite());
                    this.Layer2DScene.size(0, 0);
                    this.Layer2DScene.pos(0, 0);
                    this.Layer2DScene.name = "Layer2DScene";
                    this.Layer2DScene.zOrder = LAYER_ZORDER.layer2dScene;
                    this.Layer2DDialog = this.Layer2D.addChild(new Laya.Sprite());
                    this.Layer2DDialog.size(0, 0);
                    this.Layer2DDialog.pos(0, 0);
                    this.Layer2DDialog.name = "Layer2DDialog";
                    this.Layer2DDialog.zOrder = LAYER_ZORDER.layer2dDialog;
                }
            }
            static get2DLayer() {
                return this.Layer2D;
            }
            static get2DSceneLayer() {
                return this.Layer2DScene;
            }
            static get2DDialogLayer() {
                return this.Layer2DDialog;
            }
            static get enabledTouchEffect() {
                if (!this.stageTouchEventScript) {
                    return;
                }
                return this.stageTouchEventScript.enabledTouchEffect;
            }
            static set enabledTouchEffect(value) {
                if (!this.stageTouchEventScript) {
                    return;
                }
                this.stageTouchEventScript.enabledTouchEffect = value;
            }
            static get stageLastTouchedTime() {
                if (!this.stageTouchEventScript) {
                    return;
                }
                return this.stageTouchEventScript.lastTouchedTime;
            }
            static set stageLastTouchedTime(value) {
                if (!this.stageTouchEventScript) {
                    return;
                }
                this.stageTouchEventScript.lastTouchedTime = value;
            }
            static getTipRoot() {
                if (!this.__tipRoot) {
                    this.__tipRoot = this.get2DLayer().addChild(new Laya.Sprite());
                    this.__tipRoot.zOrder = LAYER_ZORDER.layer2dTip;
                }
                return this.__tipRoot;
            }
            static set3DLayerAtSceneFont() { }
            static set3DLayerAtDialogFont() { }
            static set3DLayerAtBack() { }
            static init3DLayer() {
                if (!this.Layer3D) {
                    this.Layer3D = new Laya.Sprite();
                    this.Layer2D.addChild(this.Layer3D);
                    this.Layer3D.size(0, 0);
                    this.Layer3D.pos(0, 0);
                    this.Layer3D.name = "Layer3D";
                    this.Layer3D.zOrder = LAYER_ZORDER.layer3d;
                    this.Layer3DBg = new Laya.Sprite();
                    this.Layer3D.addChild(this.Layer3DBg);
                    this.Layer3DBg.size(0, 0);
                    this.Layer3DBg.pos(0, 0);
                    this.Layer3DBg.name = "Layer3DBg";
                    this.Layer3DBg.zOrder = 0;
                    this.Layer3DScene = new Laya.Scene3D();
                    this.Layer3D.addChild(this.Layer3DScene);
                    var camera = this.Layer3DScene.addChild(new Laya.Camera(0, 0.1, 100));
                    camera.transform.position = new Laya.Vector3(0, 200, 0);
                    camera.clearFlag = 2;
                    camera.orthographic = true;
                    this.Layer3DSceneCamera = camera;
                    this.Layer3DDirectionLight = this.Layer3DScene.addChild(new Laya.DirectionLight);
                    this.Layer3DDirectionLight.transform.rotationEuler = new Laya.Vector3(-15.10, -41.31, -17.27);
                    this.Layer3DDirectionLight.color = new Laya.Vector3(1, 0, 0);
                    this.Layer3DSceneRoot = this.Layer3DScene.addChild(new Laya.Sprite3D());
                    this.Layer3DSceneRoot.name = "Layer3DSceneRoot";
                }
            }
            static get3DLayer() {
                return this.Layer3D;
            }
            static get3DBgLayer() {
                return this.Layer3DBg;
            }
            static get3DRoot() {
                return this.Layer3DSceneRoot;
            }
            static get3DCamera() {
                return this.Layer3DSceneCamera;
            }
            static Create3DScene(completeCallback, modelId = null, pos = new Laya.Vector3(0, 0, 0), bClearAll = true) {
                if (bClearAll)
                    this.get3DRoot().removeChildren();
                if (!modelId) {
                    let node = new Laya.Sprite3D();
                    this.get3DRoot().addChild(node);
                    node.transform.position = pos;
                    completeCallback(node);
                }
                else {
                    mgrLoader.loadModeWithModeId(modelId, (bSuccessful) => {
                        if (bSuccessful) {
                            let res = mgrLoader.Pool.getModel(modelId);
                            this.get3DRoot().addChild(res);
                            res.transform.position = pos;
                            completeCallback(res);
                        }
                    }, this, 1);
                }
            }
            static clear3DScene() {
                let root = this.get3DRoot();
                root.destroyChildren();
                let rootbg = this.get3DBgLayer();
                rootbg.destroyChildren();
            }
            static getShowingSceneName() {
                let SceneBase = Const.require.requireModule(`SceneBase`);
                return SceneBase.showingSceneName;
            }
            static warpSceneWidthEffect(sceneName, context) {
                if (!!this.__loadingSceneName)
                    return;
                let SceneBase = Const.require.requireModule(`SceneBase`);
                if (context) {
                    if (!context.ignoreSameScene && SceneBase.showingSceneName == sceneName) {
                        return;
                    }
                }
                else {
                    if (SceneBase.showingSceneName == sceneName) {
                        return;
                    }
                }
                this.debugSavePrecompileShaderData();
                let preShowSceneName = SceneBase.showingSceneName;
                SceneBase.showingSceneName = sceneName;
                this.__loadingSceneName = sceneName;
                if (!this.warpSceneNode) {
                    let vWarpSceneNode = Const.require.requireModule(`vWarpSceneNode`);
                    this.warpSceneNode = new vWarpSceneNode({});
                    this.getTipRoot().addChild(this.warpSceneNode);
                }
                this.sendMsg("MSG_WARP_SCENE_START");
                this.bWarpScene = true;
                this.warpSceneNode.playCloseAnimation(() => {
                    let className = Const.require.requireModule(sceneName);
                    context = context || {};
                    context.fOnLoadingFinished = () => {
                        this.__loadingSceneName = null;
                        mgrMaterial.precompileShaderByViewName(sceneName, null);
                        this.warpSceneNode.playOpenAnimation();
                        mgrLoader.autoReleaseRes();
                        let adContext = context;
                        adContext.viewName = sceneName;
                        adContext.zIndex = -1;
                        this.sendMsg("MSG_WARP_SCENE_COMPLETED", adContext);
                        this.bWarpScene = false;
                    };
                    let allNeedDestroyNodes = [];
                    for (let i = this.get2DSceneLayer().numChildren - 1; i >= 0; i--) {
                        allNeedDestroyNodes.push(this.get2DSceneLayer().getChildAt(i));
                    }
                    for (let i = 0; i < allNeedDestroyNodes.length; i++) {
                        const element = allNeedDestroyNodes[i];
                        element.destroy();
                    }
                    let goNewSceneFunc = () => {
                        let view = new className(context);
                        this.get2DSceneLayer().addChild(view);
                        view.name = sceneName;
                    };
                    if (!this.DEBUG_WARP) {
                        goNewSceneFunc();
                    }
                    else {
                        try {
                            goNewSceneFunc();
                        }
                        catch (error) {
                            console.warn("----------------ERROR---------------");
                            console.warn("----------------ERROR---------------");
                            console.warn("----warpSceneWidthEffect出错-sceneName=", sceneName);
                            console.warn("----------------ERROR---------------");
                            console.warn("----------------ERROR---------------");
                            this.__loadingSceneName = null;
                            this.warpSceneNode.playOpenAnimation();
                            mgrLoader.autoReleaseRes();
                            this.bWarpScene = false;
                            if (preShowSceneName) {
                                mgrDirector.open2DScene(preShowSceneName);
                            }
                        }
                    }
                });
            }
            static warpSceneWidthEffectWhite(sceneName, context) {
                if (!!this.__loadingSceneName)
                    return;
                let SceneBase = Const.require.requireModule(`SceneBase`);
                if (SceneBase.showingSceneName == sceneName)
                    return;
                this.debugSavePrecompileShaderData();
                let preShowSceneName = SceneBase.showingSceneName;
                SceneBase.showingSceneName = sceneName;
                this.__loadingSceneName = sceneName;
                if (!this.warpSceneNodeWhite) {
                    let vWarpSceneNodeWhite = Const.require.requireModule(`vWarpSceneNodeWhite`);
                    this.warpSceneNodeWhite = new vWarpSceneNodeWhite({});
                    this.getTipRoot().addChild(this.warpSceneNodeWhite);
                }
                this.sendMsg("MSG_WARP_SCENE_START");
                this.bWarpScene = true;
                this.warpSceneNodeWhite.playCloseAnimation(() => {
                    let className = Const.require.requireModule(sceneName);
                    context = context || {};
                    context.fOnLoadingFinished = () => {
                        this.__loadingSceneName = null;
                        this.warpSceneNodeWhite.playOpenAnimation(() => {
                            this.warpSceneNodeWhite.destroy();
                            this.warpSceneNodeWhite = null;
                        });
                        cleanPreSceneFunc();
                        mgrLoader.autoReleaseRes();
                        let adContext = context;
                        adContext.viewName = sceneName;
                        adContext.zIndex = -1;
                        this.sendMsg("MSG_WARP_SCENE_COMPLETED", adContext);
                        this.bWarpScene = false;
                    };
                    let cleanPreSceneFunc = (bFlag) => {
                        let allNeedDestroyNodes = [];
                        for (let i = this.get2DSceneLayer().numChildren - 1; i >= 0; i--) {
                            let view = this.get2DSceneLayer().getChildAt(i);
                            if (!!bFlag) {
                                view["__wait_to_be_clean"] = true;
                                view.zOrder += 100;
                                continue;
                            }
                            if (!!view["__wait_to_be_clean"]) {
                                allNeedDestroyNodes.push(view);
                                delete view["__wait_to_be_clean"];
                            }
                        }
                        for (let i = 0; i < allNeedDestroyNodes.length; i++) {
                            const element = allNeedDestroyNodes[i];
                            element.destroy();
                        }
                    };
                    cleanPreSceneFunc(true);
                    let goNewSceneFunc = () => {
                        let view = new className(context);
                        this.get2DSceneLayer().addChildAt(view, 0);
                        view.name = sceneName;
                    };
                    if (!this.DEBUG_WARP) {
                        goNewSceneFunc();
                    }
                    else {
                        try {
                            goNewSceneFunc();
                        }
                        catch (error) {
                            console.warn("----------------ERROR---------------");
                            console.warn("----------------ERROR---------------");
                            console.warn("----warpSceneWidthEffectWhite出错-sceneName=", sceneName);
                            console.warn("----------------ERROR---------------");
                            console.warn("----------------ERROR---------------");
                            this.__loadingSceneName = null;
                            this.warpSceneNode.playOpenAnimation();
                            mgrLoader.autoReleaseRes();
                            this.bWarpScene = false;
                            if (preShowSceneName) {
                                mgrDirector.open2DScene(preShowSceneName);
                            }
                        }
                    }
                });
            }
            static open2DScene(sceneName, context) {
                if (!!this.__loadingSceneName)
                    return;
                let SceneBase = Const.require.requireModule(`SceneBase`);
                if (SceneBase.showingSceneName == sceneName)
                    return;
                this.debugSavePrecompileShaderData();
                let preShowSceneName = SceneBase.showingSceneName;
                SceneBase.showingSceneName = sceneName;
                this.__loadingSceneName = sceneName;
                this.sendMsg("MSG_WARP_SCENE_START");
                this.bWarpScene = true;
                let className = Const.require.requireModule(sceneName);
                context = context || {};
                mgrTip.showLoadingTip("sceneLoad");
                context.fOnLoadingFinished = () => {
                    this.__loadingSceneName = null;
                    mgrTip.hideLoadingTip("sceneLoad");
                    mgrLoader.autoReleaseRes();
                    mgrMaterial.precompileShaderByViewName(sceneName, null);
                    let adContext = context;
                    adContext.viewName = sceneName;
                    adContext.zIndex = -1;
                    this.sendMsg("MSG_WARP_SCENE_COMPLETED", adContext);
                    this.bWarpScene = false;
                };
                let allNeedDestroyNodes = [];
                for (let i = this.get2DSceneLayer().numChildren - 1; i >= 0; i--) {
                    allNeedDestroyNodes.push(this.get2DSceneLayer().getChildAt(i));
                }
                for (let i = 0; i < allNeedDestroyNodes.length; i++) {
                    const element = allNeedDestroyNodes[i];
                    element.destroy();
                }
                let goNewSceneFunc = () => {
                    let view = new className(context);
                    this.get2DSceneLayer().addChild(view);
                    view.name = sceneName;
                };
                if (!this.DEBUG_WARP) {
                    goNewSceneFunc();
                }
                else {
                    try {
                        goNewSceneFunc();
                    }
                    catch (error) {
                        console.warn("----------------ERROR---------------");
                        console.warn("----------------ERROR---------------");
                        console.warn("----open2DScene出错-sceneName=", sceneName);
                        console.warn("----------------ERROR---------------");
                        console.warn("----------------ERROR---------------");
                        this.__loadingSceneName = null;
                        mgrTip.hideLoadingTip("sceneLoad");
                        mgrLoader.autoReleaseRes();
                        this.bWarpScene = false;
                        if (preShowSceneName) {
                            mgrDirector.open2DScene(preShowSceneName);
                        }
                    }
                }
            }
            static getCur2DSceneName() {
                if (!this.get2DSceneLayer().getChildAt(0))
                    return "";
                else
                    return this.get2DSceneLayer().getChildAt(0).name;
            }
            static clear2DScene() {
                let root = this.get2DSceneLayer();
                root.destroyChildren();
            }
            static openDialog(dialogName, context, bImmediately = false) {
                let className = Const.require.requireModule(dialogName);
                if (!className) {
                    mgrTip.showMsgTip(`没有找到:${dialogName}`);
                    return;
                }
                console.log("打开", dialogName);
                context = context || {};
                mgrTip.showLoadingTip("dialogOpen");
                context.fOnLoadingFinished = () => {
                    mgrTip.hideLoadingTip("dialogOpen");
                };
                mgrMaterial.precompileShaderByViewName(dialogName, null);
                let view = new className(context);
                view.name = dialogName;
                let adContext = context;
                adContext.viewName = dialogName;
                adContext.zIndex = DialogBase.curZIndex;
                this.sendMsg("MSG_DIALOG_OPEN", adContext);
                view.openDialog(bImmediately);
                return view;
            }
            static clear2DDialog() {
                let root = this.get2DDialogLayer();
                root.destroyChildren();
            }
            static add3DEffectAtFront(modelId, pos, duration, scale = 1, callback) {
                let x = 0;
                let y = 0;
                if (pos instanceof Laya.Sprite) {
                    let _temp = pos.localToGlobal(new Laya.Point(0, 0));
                    x = _temp.x;
                    y = _temp.y;
                }
                else {
                    x = pos.x;
                    y = pos.y;
                }
                let outPos = new Laya.Vector3;
                this.Layer3DSceneCamera.convertScreenCoordToOrthographicCoord(new Laya.Vector3(x, y, 0), outPos);
                if (modelId instanceof Laya.Sprite3D) {
                    this.get3DRoot().addChild(modelId);
                    modelId.transform.position = outPos;
                    modelId.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                    callback && callback(modelId);
                    return;
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    let mode = mgrLoader.Pool.getModel(modelId);
                    this.get3DRoot().addChild(mode);
                    mode.transform.position = outPos;
                    mode.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                    duration > 0 && Timer.callLater(duration, () => {
                        mgrLoader.Pool.recoverModel(mode);
                    }, this);
                    callback && callback(mode);
                }, this, 1);
            }
            static get maxRatio() {
                return 2;
            }
            static get standardRatio() {
                return 1024 / 576;
            }
            static get ratioLerpValue() {
                let cur = Laya.stage.height / Laya.stage.width;
                cur = ul.clamp(cur, this.standardRatio, this.maxRatio);
                return (cur - this.standardRatio) / (this.maxRatio - this.standardRatio);
            }
            static get width() {
                return Laya.stage.width;
            }
            static get height() {
                return Laya.stage.height;
            }
            static adaptStageSize(forceWidth, forceHeight) {
                let minWidth = Const.RESOLUTION_RANGE.minWidth;
                let minHeight = Const.RESOLUTION_RANGE.minHeight;
                let maxWidth = Const.RESOLUTION_RANGE.maxWidth;
                let maxHeight = Const.RESOLUTION_RANGE.maxHeight;
                let designWidth = minWidth;
                let designHeight = minHeight;
                let deviceRatio = Laya.Browser.width / Laya.Browser.height;
                if (deviceRatio <= minWidth / minHeight) {
                    if (deviceRatio < minWidth / maxHeight) {
                        designWidth = minWidth;
                        designHeight = maxHeight;
                    }
                    else {
                        designWidth = minWidth;
                        designHeight = minWidth / deviceRatio;
                    }
                }
                else {
                    if (deviceRatio > maxWidth / minHeight) {
                        designWidth = maxWidth;
                        designHeight = minHeight;
                    }
                    else {
                        designHeight = minHeight;
                        designWidth = minHeight * deviceRatio;
                    }
                }
                Laya.stage.width = forceWidth || designWidth;
                Laya.stage.height = forceHeight || designHeight;
                Laya.stage.scaleMode = Laya.Stage.SCALE_SHOWALL;
                Laya.stage.screenMode = Laya.Stage.SCREEN_NONE;
                Laya.stage.alignH = Laya.Stage.ALIGN_CENTER;
                Laya.stage.alignV = Laya.Stage.ALIGN_MIDDLE;
                if (this.Layer2D) {
                    this.Layer2D.pos(Laya.stage.width / 2, Laya.stage.height / 2);
                }
                if (this.Layer3D) {
                    this.Layer3D.pos(0, 0);
                }
                this.getSafeSurplusHeight();
            }
            static getSafeSurplusHeight() {
                let resolutionRange = Const.RESOLUTION_SAFE_RANGE;
                if (this.height <= resolutionRange.maxHeight) {
                    return 0;
                }
                let deviceSize = new Laya.Size(Laya.Browser.width, Laya.Browser.height);
                let deviceRatio = deviceSize.width / deviceSize.height;
                let maxWidth = resolutionRange.maxWidth;
                let minWidth = resolutionRange.minWidth;
                let maxHeight = resolutionRange.maxHeight;
                let minHeight = resolutionRange.minHeight;
                let safeHeight = minHeight;
                if (deviceRatio <= minWidth / minHeight) {
                    if (deviceRatio < minWidth / maxHeight) {
                        safeHeight = maxHeight;
                    }
                    else {
                        safeHeight = minWidth / deviceRatio;
                    }
                }
                else {
                    if (deviceRatio > maxWidth / minHeight) {
                        safeHeight = maxWidth / deviceRatio;
                    }
                    else {
                        safeHeight = minHeight;
                    }
                }
                safeHeight = Math.floor(safeHeight);
                let retHeight = Math.max(Math.floor((this.height - safeHeight) / 2), 0);
                return retHeight;
            }
            static debugSavePrecompileShaderData() {
                if (!Laya.Shader3D.debugMode || !Const.DEBUG_SAVE_PRECOMILESHADER_FALG) {
                    return;
                }
                let viewName = mgrDirector.getShowingSceneName();
                if (!viewName) {
                    console.log("------------noviewName");
                    return;
                }
                console.log("------------viewName=", viewName);
                let oldCount = mgrMaterial.precompileShaderInfos[viewName] || [];
                let arr = [];
                for (let i = 0; i < Laya.Shader3D.debugShaderVariantCollection.variantCount; i++) {
                    let shadervariant = Laya.Shader3D.debugShaderVariantCollection.getByIndex(i);
                    let shaderName = shadervariant.shader.name;
                    let obj = {};
                    obj.shaderName = shaderName;
                    obj.defineNames = shadervariant.defineNames;
                    obj.passIndex = shadervariant.passIndex;
                    obj.subShaderIndex = shadervariant.subShaderIndex;
                    arr.push(obj);
                }
                if (arr.length <= oldCount) {
                    return;
                }
                mgrMaterial.precompileShaderInfos[viewName] = arr;
                if (!Const.GlobalRouter) {
                    mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                }
                else {
                    Const.GlobalRouter.sendMsgToServer({
                        route: "keepInFile",
                        data: {
                            filePath: `res/cfg/shader_compile.json`,
                            data: mgrMaterial.precompileShaderInfos,
                        },
                    });
                }
                Laya.Shader3D.debugShaderVariantCollection.clear();
            }
        }
        mgrDirector.bWarpScene = false;
        mgrDirector.DEBUG_WARP = false;
        mgrDirector.__loadingSceneName = null;

        class mgrMidAutumn extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化loadRecord");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("midAutumn") || {};
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {};
                mgrRecord.setData("midAutumn", record);
            }
            static isEnable() {
                let startTime = mgrSdk.getCopNumberValueByKey("mid_autumn_start_time");
                let endTime = mgrSdk.getCopNumberValueByKey("mid_autumn_end_time");
                let nowTime = Tools.time();
                if (nowTime >= startTime && nowTime <= endTime) {
                    return true;
                }
                return false;
            }
            static getSuitCollectProgress() {
                let [cur, max] = mgrPart.getSuitProgress(this.suitId);
                return [cur, max];
            }
            static getMidSuitDatas() {
                let suitData = {};
                mgrCfg.forDb_from_suit_db((k, v) => {
                    if (parseInt(k) == this.suitId) {
                        suitData = v;
                    }
                });
                return suitData;
            }
            static isMidAutumnSystem(actId) {
                switch (actId) {
                    case DailyGameType.cake:
                    case DailyGameType.clothcrossing:
                    case DailyGameType.custom_made:
                        return true;
                }
                return false;
            }
        }
        mgrMidAutumn.suitId = 1030;

        class vAdFreeTrialPartDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAdFreeTrialPartDialog";
            }
            onOpened() {
                super.onOpened();
                this.nativeBanner = mgrActivingBanner.activingAlertBanner(0, this);
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.buildUi();
                this.fillData();
            }
            onClosed() {
                super.onClosed();
                if (this.nativeBanner) {
                    this.nativeBanner.activingBannerClose();
                    this.nativeBanner = null;
                }
            }
            buildUi() {
                let adEventData = mgrCfg.get_from_ad_event_db(this.context.adEventId);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            fillData() {
                let partId = this.context.partId;
                console.warn("------------vAdFreeTrialPartDialog-----partId", partId);
                let partData = mgrCfg.get_from_item_template_db(partId);
                mgrLoader.Load2dRes(partData.icon, Laya.Loader.IMAGE, this, (res) => {
                    let width = res.width || 1;
                    let height = res.height || 1;
                    let iconW = this.imageIcon.width;
                    let iconH = this.imageIcon.height;
                    let scale = Math.max(iconW / width, iconH / height);
                    this.imageIcon.size(width, height);
                    this.imageIcon.texture = res;
                    this.imageIcon.scale(scale, scale);
                });
                this.buttonClose.__node.visible = mgrSdk.getCopNumberValueByKey("b_vAdFreeTrialPartDialog_trigger_native_banner") == 1;
                this.buttonGiveUp.__node.visible = !this.buttonClose.__node.visible;
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAdFreeTrialPartDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonGiveUp() {
                this.closeDialog();
            }
            onTouchButtonAd() {
                mgrAd.triggerAdEvent(this.context.adEventId, this.context.adTriggerParams, true);
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.context.adEventId) {
                    this.closeDialog(true);
                }
            }
        }

        class vAdFreeTrialSuccesDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAdFreeTrialSuccesDialog";
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.buildUi();
                this.fillData();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.progressbar.barName = this.progressbar.__node.name;
                this.progressbar.style = ULPROGRESSBAR_STYLE.hor;
                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAdFreeTrialPartDialog_trial);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            fillData() {
                let partId = this.context.partId;
                let partData = mgrCfg.get_from_item_template_db(partId);
                Tools.loadImg(this.imagePartIcon, partData.icon);
                this.buttonGiveUp.__node.visible = mgrSdk.getCopNumberValueByKey("b_ad_giveup_mode") == 1 ? true : false;
                this.buttonClose.__node.visible = !this.buttonGiveUp.__node.visible;
                this.buttonGetNormal.__node.visible = false;
                if (mgrSdk.getCopNumberValueByKey("b_ad_check_mode") == 1 || mgrSdk.getCopByKey("b_ad_check_mode_to_every_point").split(";")[4] == "1") {
                    this.buttonClose.__node.visible = false;
                    this.buttonGiveUp.__node.visible = false;
                    this.spriteAdCheckModeContainer.visible = true;
                    this.buttonGetNormal.__node.visible = true;
                    if (!this.adCheckModeConfig) {
                        let partId = this.context.partId;
                        let extName = "试用";
                        if (mgrPartTrial.getPartTrialCount(partId) + 1 >= mgrPartTrial.getPartUnlockNeedTrialCount()) {
                            extName = "获得";
                        }
                        let config = mgrAd.randomGetAdCheckModeConfig(extName);
                        this.labelAdCheckModelTip.text = config.text;
                        this.spriteAdCheckModeCheckFlag.visible = !!config.bDefaultChecked;
                        this.adCheckModeConfig = config;
                        this.onTouchButtonAdCheckModel();
                    }
                }
                this.refreshCount();
            }
            refreshCount() {
                let partId = this.context.partId;
                this.labelProgress.text = `${mgrPartTrial.getPartTrialCount(partId)} / ${mgrPartTrial.getPartUnlockNeedTrialCount()}`;
                this.progressbar.progress = Mathf.clamp(mgrPartTrial.getPartTrialCount(partId) / mgrPartTrial.getPartUnlockNeedTrialCount(), 0, 1);
                this.labelRestCount.text = `${mgrPartTrial.getPartUnlockNeedTrialCount() - mgrPartTrial.getPartTrialCount(partId)}`;
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonGiveUp() {
                this.closeDialog();
            }
            onTouchButtonGetNormal() {
                if (!this.adCheckModeConfig) {
                    this.onTouchButtonClose();
                    return;
                }
                if ((this.adCheckModeConfig.bCheckedTriggerAd && this.spriteAdCheckModeCheckFlag.visible) || (!this.spriteAdCheckModeCheckFlag.visible && !this.adCheckModeConfig.bCheckedTriggerAd)) {
                    this.onTouchButtonAd();
                }
                else {
                    this.onTouchButtonClose();
                }
            }
            onTouchButtonAd() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAdFreeTrialPartDialog_trial, { partId: this.context.partId }, true);
            }
            onTouchButtonAdCheckModel() {
                this.spriteAdCheckModeCheckFlag.visible = !this.spriteAdCheckModeCheckFlag.visible;
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAdFreeTrialPartDialog_trial) {
                    mgrPartTrial.addPartTrialCount(e.userData.partId);
                    this.refreshCount();
                    if (mgrPlayer.getItemAmount(e.userData.partId)) {
                        this.closeDialog(true);
                    }
                }
            }
        }

        class vAdGetMoreUnlockItemDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAdGetMoreUnlockItemDialog";
                this.roleId = null;
                this.roleData = null;
                this.amount = null;
                this.moreAmount = 1;
                this.bAd = false;
                this.fOnCloseDialog = () => { };
                this.roleId = this.context.roleId || null;
                if (this.roleId) {
                    let roleData = mgrCfg.get_from_role_db(this.roleId);
                    this.roleData = roleData;
                }
                this.amount = this.context.amount || 0;
                this.fOnCloseDialog = this.context.fOnCloseDialog || (() => { });
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
            }
            onClosed() {
                super.onClosed();
            }
            close() {
                if (this.fOnCloseDialog) {
                    this.fOnCloseDialog();
                }
                this.closeDialog();
            }
            fillData() {
                if (this.roleData) {
                    let item = mgrCfg.get_from_item_template_db(this.roleData.unlockItemId);
                    this.imageSpriteIcon.loadImage(item.icon);
                    this.labelName.text = `${item.name}`;
                }
                this.labelCount.text = `${this.amount}`;
                let bAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAdGetMoreUnlockItemDialog_more);
                this.bAd = bAd;
                if (bAd) {
                    this.buttonGetAd.__node.active = true;
                    this.labelButtonGiveUp.text = `放弃得碎片`;
                }
                else {
                    this.buttonGetAd.__node.active = false;
                    this.labelButtonGiveUp.text = `好的`;
                }
            }
            onTouchButtonTriggerNativeBanner() {
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAdGetMoreUnlockItemDialog_more, null, true);
            }
            onTouchButtonGiveUp() {
                if (!this.bAd) {
                    let itemId = this.roleData.unlockItemId;
                    let amount = this.moreAmount;
                    if (itemId && amount) {
                        mgrPlayer.addItemAmount(itemId, amount, "新年关卡通关额外碎片");
                    }
                }
                this.close();
            }
            onTouchButtonAdCheckModel() {
            }
            onTouchButtonClose() {
                this.close();
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAdGetMoreUnlockItemDialog_more) {
                    mgrCard.getNewYearStageRoleUnlockItem(this.context.stageId);
                    let roleId = this.roleId;
                    let fOnClose = this.close;
                    if (roleId) {
                        mgrDirector.openDialog("vGotNewRoleDialog", {
                            roleId, bVip: false, fOnClose: fOnClose.bind(this), bBanAd: true, labelBtnGiveUp: "确定"
                        });
                    }
                }
            }
        }

        class vAdPopMachineDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAdPopMachineDialog";
                this.exportNodeNames = [];
                this.lastDownGoldTime = 0;
                this.allGotGoldNum = 0;
                this.currDragTime = 3;
                this.curNeedDramCount = 10;
                this.dramedCount = 0;
                this.totalDramCount = 18;
                this.clickCountInTime = 0;
                this.triggerOverClickCountInTime = 0;
                this.refreshClickCountInTimeTime = 0;
                this.refreshableTime = 0;
                this.checkOverTimer = null;
            }
            onOpened() {
                super.onOpened();
                Timer.callLoop(0.5, () => {
                    if (!this || this.destroyed || this.__bClosing) {
                        return;
                    }
                    if (mgrGuide.isGuiding()) {
                        this.closeDialog(true);
                    }
                });
                this.refreshClickCountInTimeTime = mgrSdk.getCopNumberValueByKey("adPop_refresh_click_count_time") || 0;
                this.triggerOverClickCountInTime = mgrSdk.getCopNumberValueByKey("adPop_over_click_count_in_time") || 0;
                this.oldPlayingSoundId = mgrSound.playingMusicSoundId;
                mgrSound.play(16);
                mgrSound.play(506);
                this.buildUi();
                this.widget();
                this.fillData();
                this.customTimer = Timer.callLoop(0.016, this.onTimerLoop.bind(this), this);
                this.checkOverTimer = Timer.callLoop(1, this.onCheckOverPerSecond.bind(this), this);
            }
            onClosed() {
                super.onClosed();
                if (this.oldPlayingSoundId) {
                    mgrSound.play(this.oldPlayingSoundId);
                }
            }
            close() {
                mgrSwitchOpen.recordDialogOpenInfo("vAdPopMachineDialog");
                this.closeDialog(true);
            }
            getPreLoadModelIds() {
                return [];
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.buttonClose.__node);
                mgrLayout.widgetBottomMC(this.buttonPop.__node);
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onCheckOverPerSecond(timer) {
                if (this.clickCountInTime >= this.triggerOverClickCountInTime) {
                    if (this.clickCountInTime) {
                        this.checkOverTimer.stop();
                    }
                    if (this.customTimer) {
                        this.customTimer.stop();
                    }
                    this.finishDram();
                    return;
                }
                if (this.clickCountInTime > 0) {
                    let time = this.refreshableTime;
                    if (time + 1 >= this.refreshClickCountInTimeTime) {
                        this.refreshableTime = 0;
                        this.clickCountInTime = 0;
                    }
                    else {
                        this.refreshableTime = time + 1;
                    }
                }
            }
            onTimerLoop(timer) {
                if (!this.currDragStartTime) {
                    return;
                }
                let passedTime = Tools.time() - this.currDragStartTime;
                this.refreshLeftTime();
                this.progressBarCurr.progress = Mathf.clamp(this.progressBarCurr.progress - 0.005, 0, 1);
                if (this.progressBarCurr.progress < this.currFinishProgress) {
                    return;
                }
                if (!!this.bDownGold) {
                    this.downGold();
                    this.bDownGold = false;
                }
            }
            refreshLeftTime() {
                if (!this.currDragStartTime) {
                    this.labelLeftTime.alpha = 0;
                    return;
                }
                this.labelLeftTime.alpha = 1;
                let passedTime = Tools.time() - this.currDragStartTime;
                let leftTime = Math.max(0, Math.ceil(this.currDragTime - passedTime));
                this.labelLeftTime.text = `剩余时间：${leftTime}秒`;
            }
            finishDram() {
                if (!this.customTimer) {
                    return;
                }
                this.customTimer.stop();
                this.customTimer = null;
                this.allGotGoldNum = Tools.random(100, 150);
                mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, this.allGotGoldNum, "泡泡机获得");
                this.close();
                mgrTip.addGotItemTipGroupToDisplayNow([{
                        itemId: Const.ITEM_ID_DIAMONDS,
                        amount: this.allGotGoldNum,
                        amountSteps: null,
                        orderOfQueue: null,
                        customerContext: {
                            bImmediately: true,
                            fOnClose: () => {
                            }
                        },
                        bFromAd: true,
                    }]);
            }
            downGold() {
                if (!this.currDragStartTime) {
                    return;
                }
                if (this.lastDownGoldTime && (Tools.time() - this.lastDownGoldTime) < 0.2) {
                    return;
                }
                let spriteGold = this.getValidSpriteGold();
                if (!spriteGold) {
                    return;
                }
                spriteGold["_bEffecting"] = true;
                let currGoldNum = Tools.random(2, 10);
                let label = spriteGold.getChildByName("labelReward");
                if (!!label) {
                    label.text = `${currGoldNum}`;
                }
                this.lastDownGoldTime = Tools.time();
                let targetPos = spriteGold["originPos"];
                targetPos.x = spriteGold["originPos"].x > this.spriteMachine.x ? (spriteGold["originPos"].x - Tools.random(100)) : spriteGold["originPos"].x + Tools.random(100);
                targetPos.y = Tools.random(100) > 50 ? spriteGold["originPos"].y + Tools.random(100) : spriteGold["originPos"].y - Tools.random(100);
                spriteGold.scale(0, 0);
                spriteGold.pos(this.spriteMachine.x, this.spriteMachine.y);
                cc.tween(spriteGold)
                    .parallel(cc.tween().then(cc.jumpTo(0.5, targetPos.x, targetPos.y, 150, 1)), cc.tween().toScale(0.2, 1))
                    .delay(0.5)
                    .toScale(0.1, 1.3)
                    .toScale(0.1, 0)
                    .call(() => {
                    this.allGotGoldNum += currGoldNum;
                    mgrSound.play(103);
                    spriteGold["_bEffecting"] = false;
                }).start();
            }
            getValidSpriteGold() {
                for (let i = 0; i < 10; i++) {
                    let spriteGold = this["spriteGold" + (i + 1)];
                    if (!spriteGold) {
                        continue;
                    }
                    if (!spriteGold["_bEffecting"]) {
                        return spriteGold;
                    }
                }
                return null;
            }
            buildUi() {
                for (let i = 0; i < 10; i++) {
                    let spriteGold = this["spriteGold" + (i + 1)];
                    if (!spriteGold) {
                        continue;
                    }
                    spriteGold.scale(0, 0);
                    spriteGold["originPos"] = new Laya.Vector2(spriteGold.x, spriteGold.y);
                }
                this.progressBarCurr.barName = this.progressBarCurr.__node.name;
                this.progressBarCurr.style = ULPROGRESSBAR_STYLE.hor;
                this.progressBarCurr.progress = 0;
            }
            fillData() {
                this.currDragTime = Tools.random(4, 5);
                this.curNeedDramCount = Tools.random(10, 15);
                this.currFinishProgress = Tools.random(10, 20) / 100;
                this.buttonClose.__node.alpha = 0;
                cc.tween(this.buttonClose.__node).toAlpha(0.3, 1).start();
                Timer.callLater(0.5, () => {
                    this.add3DEffectAtFront("eff_ui_xsyd", this.buttonPop.__node, 0);
                }, this);
                this.refreshLeftTime();
            }
            doDrag() {
                this.bDownGold = true;
                this.removeEffectAtFront(this.buttonPop.__node);
                this.dramedCount += 1;
                this.progressBarCurr.progress = Mathf.clamp(this.progressBarCurr.progress + 0.15, 0, 0.8);
            }
            onTouchButtonClose() {
                this.close();
            }
            onTouchButtonPop() {
                this.buttonClose.__node.visible = false;
                mgrSound.play(130);
                this.clickCountInTime = Math.max(0, this.clickCountInTime + 1);
                this.doDrag();
                console.log("clickPop", this.clickCountInTime, this.triggerOverClickCountInTime);
                if (this.clickCountInTime >= this.triggerOverClickCountInTime) {
                    if (this.clickCountInTime) {
                        this.checkOverTimer.stop();
                    }
                    if (this.customTimer) {
                        this.customTimer.stop();
                    }
                    this.finishDram();
                    return;
                }
                if (this.currDragStartTime) {
                    return;
                }
                this.currDragStartTime = Tools.time();
            }
        }

        class HumanBone {
            constructor() {
                this.overloadAnimationClip();
                this.overloadAnimator();
            }
            overloadAnimationClip() {
                Laya3D[`enableNative3D`] = () => { };
                Laya3D[`_loadAnimationClip`] = (loader) => {
                    loader.on(Laya.Event.LOADED, null, function (data) {
                        loader._cache = loader._createCache;
                        var clip = Laya.AnimationClip._parse(data, loader._propertyParams, loader._constructParams);
                        Laya3D[`_endLoad`](loader, clip);
                        let startIndex = clip.url.lastIndexOf("/") + 1;
                        let endIndex = clip.url.lastIndexOf(".");
                        let name = clip.url.slice(startIndex, endIndex);
                        name = name.slice(0, name.lastIndexOf("-"));
                        if (HumanBone.allHumanBoneConfig[name]) {
                            clip[`avatar_height`] = HumanBone.allHumanBoneConfig[name].rootPos.y;
                        }
                    });
                    loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
                };
                Laya.Loader.parserMap[Laya3D.ANIMATIONCLIP] = Laya3D[`_loadAnimationClip`];
                Laya.AnimationClip.prototype[`_evaluateClipDatasRealTime`] = function (nodes, playCurTime, realTimeCurrentFrameIndexes, addtive, frontPlay, outDatas, name, humanBoneConfig, humanScaleInfo) {
                    humanBoneConfig = humanBoneConfig || { boneMap: {} };
                    humanScaleInfo = humanScaleInfo || { boneMap: {}, wholeRatio: 1 };
                    for (var i = 0, n = nodes.count; i < n; i++) {
                        var node = nodes.getNodeByIndex(i);
                        var type = node.type;
                        var nextFrameIndex;
                        var keyFrames = node._keyFrames;
                        var keyFramesCount = keyFrames.length;
                        var frameIndex = realTimeCurrentFrameIndexes[i];
                        var nodeName = node._ownerPath[node._ownerPath.length - 1];
                        if (frontPlay) {
                            if ((frameIndex !== -1) && (playCurTime < keyFrames[frameIndex].time)) {
                                frameIndex = -1;
                                realTimeCurrentFrameIndexes[i] = frameIndex;
                            }
                            nextFrameIndex = frameIndex + 1;
                            while (nextFrameIndex < keyFramesCount) {
                                if (keyFrames[nextFrameIndex].time > playCurTime)
                                    break;
                                frameIndex++;
                                nextFrameIndex++;
                                realTimeCurrentFrameIndexes[i] = frameIndex;
                            }
                        }
                        else {
                            nextFrameIndex = frameIndex + 1;
                            if ((nextFrameIndex !== keyFramesCount) && (playCurTime > keyFrames[nextFrameIndex].time)) {
                                frameIndex = keyFramesCount - 1;
                                realTimeCurrentFrameIndexes[i] = frameIndex;
                            }
                            nextFrameIndex = frameIndex + 1;
                            while (frameIndex > -1) {
                                if (keyFrames[frameIndex].time < playCurTime)
                                    break;
                                frameIndex--;
                                nextFrameIndex--;
                                realTimeCurrentFrameIndexes[i] = frameIndex;
                            }
                        }
                        var isEnd = nextFrameIndex === keyFramesCount;
                        switch (type) {
                            case 0:
                                if (frameIndex !== -1) {
                                    var frame = keyFrames[frameIndex];
                                    if (isEnd) {
                                        outDatas[i] = frame.value;
                                    }
                                    else {
                                        var nextFarme = keyFrames[nextFrameIndex];
                                        var d = nextFarme.time - frame.time;
                                        var t;
                                        if (d !== 0)
                                            t = (playCurTime - frame.time) / d;
                                        else
                                            t = 0;
                                        outDatas[i] = this[`_hermiteInterpolate`](frame, nextFarme, t, d);
                                    }
                                }
                                else {
                                    outDatas[i] = keyFrames[0].value;
                                }
                                if (addtive)
                                    outDatas[i] = outDatas[i] - keyFrames[0].value;
                                break;
                            case 1:
                            case 4:
                                var clipData = outDatas[i];
                                if (humanBoneConfig.boneMap[nodeName]) {
                                    clipData.x = humanBoneConfig.boneMap[nodeName].x;
                                    clipData.y = humanBoneConfig.boneMap[nodeName].y;
                                    clipData.z = humanBoneConfig.boneMap[nodeName].z;
                                }
                                else {
                                    if (nodeName == "Bip001" && this[`avatar_height`] && humanBoneConfig.rootPos) {
                                        let originHeight = this[`avatar_height`];
                                        this[`_evaluateFrameNodeVector3DatasRealTime`](keyFrames, frameIndex, isEnd, playCurTime, clipData, humanScaleInfo.boneMap[nodeName], "pos");
                                        let tpos = humanBoneConfig.rootPos;
                                        let factor = (tpos.y / originHeight) * humanScaleInfo.wholeRatio;
                                        clipData.x *= factor;
                                        clipData.y *= factor;
                                        clipData.z *= factor;
                                    }
                                    else {
                                        this[`_evaluateFrameNodeVector3DatasRealTime`](keyFrames, frameIndex, isEnd, playCurTime, clipData, humanScaleInfo.boneMap[nodeName], "pos");
                                    }
                                }
                                if (humanScaleInfo.boneMap[nodeName]) {
                                    if (!humanScaleInfo.boneMap[nodeName].bAddtive) {
                                        clipData.x += humanScaleInfo.boneMap[nodeName].pos.x;
                                        clipData.y += humanScaleInfo.boneMap[nodeName].pos.y;
                                        clipData.z += humanScaleInfo.boneMap[nodeName].pos.z;
                                    }
                                }
                                if (addtive) {
                                    var firstFrameValue = keyFrames[0].value;
                                    clipData.x -= firstFrameValue.x;
                                    clipData.y -= firstFrameValue.y;
                                    clipData.z -= firstFrameValue.z;
                                }
                                break;
                            case 2:
                                var clipQuat = outDatas[i];
                                this[`_evaluateFrameNodeQuaternionDatasRealTime`](keyFrames, frameIndex, isEnd, playCurTime, clipQuat, humanScaleInfo.boneMap[nodeName], "rotation");
                                if (humanScaleInfo.boneMap[nodeName]) {
                                    if (!humanScaleInfo.boneMap[nodeName].bAddtive) {
                                        var tempQuat = Laya.AnimationClip[`_tempQuaternion0`];
                                        tempQuat.x = humanScaleInfo.boneMap[nodeName].rotation.x;
                                        tempQuat.y = humanScaleInfo.boneMap[nodeName].rotation.y;
                                        tempQuat.z = humanScaleInfo.boneMap[nodeName].rotation.z;
                                        tempQuat.w = humanScaleInfo.boneMap[nodeName].rotation.w;
                                        Laya.Quaternion.multiply(clipQuat, tempQuat, clipQuat);
                                    }
                                }
                                if (addtive) {
                                    var tempQuat = Laya.AnimationClip[`_tempQuaternion0`];
                                    var firstFrameValueQua = keyFrames[0].value;
                                    Laya.Utils3D[`quaternionConjugate`](firstFrameValueQua, tempQuat);
                                    Laya.Quaternion.multiply(tempQuat, clipQuat, clipQuat);
                                }
                                break;
                            case 3:
                                clipData = outDatas[i];
                                this[`_evaluateFrameNodeVector3DatasRealTime`](keyFrames, frameIndex, isEnd, playCurTime, clipData, humanScaleInfo.boneMap[nodeName], "scale");
                                if (humanScaleInfo.boneMap[nodeName]) {
                                    if (!humanScaleInfo.boneMap[nodeName].bAddtive) {
                                        clipData.x *= humanScaleInfo.boneMap[nodeName].scale.x;
                                        clipData.y *= humanScaleInfo.boneMap[nodeName].scale.y;
                                        clipData.z *= humanScaleInfo.boneMap[nodeName].scale.z;
                                    }
                                }
                                if (addtive) {
                                    firstFrameValue = keyFrames[0].value;
                                    clipData.x /= firstFrameValue.x;
                                    clipData.y /= firstFrameValue.y;
                                    clipData.z /= firstFrameValue.z;
                                }
                                break;
                            default:
                                throw "AnimationClip:unknown node type.";
                        }
                    }
                };
            }
            overloadAnimator() {
                Laya.Animator.prototype[`_updateClipDatas`] = function (animatorState, addtive, playStateInfo, scale, name) {
                    var clip = animatorState._clip;
                    var clipDuration = clip._duration;
                    var curPlayTime = animatorState.clipStart * clipDuration + playStateInfo._normalizedPlayTime * playStateInfo._duration;
                    var currentFrameIndices = animatorState._currentFrameIndices;
                    var frontPlay = playStateInfo._elapsedTime > playStateInfo._lastElapsedTime;
                    clip._evaluateClipDatasRealTime(clip._nodes, curPlayTime, currentFrameIndices, addtive, frontPlay, animatorState._realtimeDatas, name, HumanBone.allHumanBoneConfig[this.owner.name], this[`humanScaleInfo`]);
                };
            }
        }

        class ShadowFollow extends Laya.Script {
            constructor() {
                super();
                this.__node = null;
                this.scaleMin = 0;
                this.scaleMax = 1.2;
                this._offsetXYZ = new Laya.Vector3;
            }
            get offsetXYZ() {
                return this._offsetXYZ || new Laya.Vector3;
            }
            set offsetXYZ(value) {
                this._offsetXYZ = value || new Laya.Vector3;
            }
            onAwake() {
                this.__node = this.owner;
            }
            onDisable() {
            }
            onLateUpdate() {
                if (!this.__node)
                    return;
                if (!this.__target || this.__target.destroyed)
                    return;
                let pos = this.__target.transform.position.clone();
                pos.y = 0.01;
                this.__node.transform.position = pos;
                this.__node.transform.setWorldLossyScale(new Laya.Vector3(0.8, 0.8, 0.8));
                let disTarget = this.__target.getChildByName(Const.BASE_BONE_NAME);
                if (!disTarget)
                    return;
                disTarget = disTarget.getChildByName(`${Const.BASE_BONE_NAME} Pelvis`);
                if (!disTarget)
                    return;
                disTarget = disTarget.getChildByName(`${Const.BASE_BONE_NAME} Spine`);
                if (!disTarget)
                    return;
                let distance = disTarget.transform.position.y + 0.1;
                let factor = distance / 30;
                let scale = this.scaleMin * factor + this.scaleMax * (1 - factor);
                this.__node.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                this.__node.transform.position = new Laya.Vector3(disTarget.transform.position.x + this._offsetXYZ.x, this.__target.transform.position.y + 0.01 + this._offsetXYZ.y, disTarget.transform.position.z + this._offsetXYZ.z);
            }
        }

        var Vector3 = Laya.Vector3;
        var Quaternion = Laya.Quaternion;
        var Script3D = Laya.Script3D;
        var BoneColliderPart;
        (function (BoneColliderPart) {
            BoneColliderPart[BoneColliderPart["NONE"] = 1] = "NONE";
            BoneColliderPart[BoneColliderPart["UP"] = 2] = "UP";
            BoneColliderPart[BoneColliderPart["DOWN"] = 3] = "DOWN";
        })(BoneColliderPart || (BoneColliderPart = {}));
        class Bone extends Script3D {
            constructor() {
                super(...arguments);
                this.parm1 = 0.6;
                this.radius = 0.03;
                this.part = BoneColliderPart.NONE;
                this.colliders = [];
                this.deepth = 0;
                this.boneLength = 0.1;
                this.displacementFactor = 0.3;
                this.maxDisplacement = 0.1;
                this.wind = new Laya.Vector3;
                this.gravity = new Laya.Vector3;
            }
            onAwake() {
                this.transform = this.owner.transform;
                this.originLocalRotation = this.transform.localRotation.clone();
                this.originLocalPosition = this.transform.localPosition.clone();
                this.lastWorldRotation = this.transform.rotation.clone();
                this.lastWorldPosition = this.transform.position.clone();
                this.deepth = 1;
                let cursor = this.owner;
                while (cursor.parent && cursor.getComponent(Bone)) {
                    this.deepth++;
                    cursor = cursor.parent;
                }
                let parent = this.owner.parent;
                if (parent) {
                    this.parent = parent.transform;
                    this.parentBone = this.owner.parent.getComponent(Bone);
                }
                if (this.parent) {
                    this.boneLength = Vector3.distance(this.transform.position, this.parent.position);
                }
                else {
                    this.boneLength = 0;
                }
            }
            onStart() {
                this.updateTemplateNormal = new Laya.Vector3;
            }
            _ignoreBoneFromNodeToRoot(node) {
                let boneNode = node.getComponent(Bone);
                if (boneNode) {
                    if (boneNode.bIgnoredBone) {
                        return;
                    }
                    boneNode.bIgnoredBone = true;
                }
                if (!node.parent || node == Laya.stage) {
                    return;
                }
                this._ignoreBoneFromNodeToRoot(node.parent);
            }
            UpdateBone(dt) {
                this.transform.localRotation = this.originLocalRotation.clone();
                this.transform.localPosition = this.originLocalPosition.clone();
                if (!this.owner || this.destroyed) {
                    return;
                }
                if (this.bIgnoredBone || !this.owner.parent) {
                    return;
                }
                this.owner.parent["___childBoneIdDict"] = this.owner.parent["___childBoneIdDict"] || {};
                let count = Tools.objLength(this.owner.parent["___childBoneIdDict"]);
                if (count >= 2) {
                    let numChildren = this.owner.parent.numChildren;
                    for (let index = 0; index < numChildren; index++) {
                        let nodeChild = this.owner.parent.getChildAt(index);
                        if (!nodeChild) {
                            continue;
                        }
                        this._ignoreBoneFromNodeToRoot(nodeChild);
                    }
                    return;
                }
                this.owner.parent["___childBoneIdDict"] = this.owner.parent["___childBoneIdDict"] || {};
                this.owner.parent["___childBoneIdDict"][this.owner.name] = true;
                if (!this.parentBone)
                    return;
                Quaternion.lerp(this.lastWorldRotation, this.transform.rotation, this.parm1, this.lastWorldRotation);
                this.transform.rotation = this.lastWorldRotation.clone();
                Laya.Vector3.add(this.transform.position, this.gravity, this.transform.position);
                Laya.Vector3.lerp(this.lastWorldPosition, this.transform.position, this.displacementFactor, this.lastWorldPosition);
                Laya.Vector3.subtract(this.lastWorldPosition, this.transform.position, this.updateTemplateNormal);
                if (Laya.Vector3.scalarLengthSquared(this.updateTemplateNormal) > this.maxDisplacement * this.maxDisplacement) {
                    Laya.Vector3.normalize(this.updateTemplateNormal, this.updateTemplateNormal);
                    Laya.Vector3.scale(this.updateTemplateNormal, this.maxDisplacement, this.updateTemplateNormal);
                    Laya.Vector3.add(this.transform.position, this.updateTemplateNormal, this.lastWorldPosition);
                }
                Laya.Vector3.subtract(this.lastWorldPosition, this.parent.position, this.updateTemplateNormal);
                let node = this.owner;
                let scaleX = 1;
                while (node instanceof Laya.Sprite3D) {
                    scaleX *= node.transform.localScaleX;
                    node = node.parent;
                }
                let boneLength = this.boneLength * scaleX;
                if (Laya.Vector3.scalarLengthSquared(this.updateTemplateNormal) > boneLength * boneLength) {
                    Laya.Vector3.normalize(this.updateTemplateNormal, this.updateTemplateNormal);
                    Laya.Vector3.scale(this.updateTemplateNormal, boneLength, this.updateTemplateNormal);
                    Laya.Vector3.add(this.parent.position, this.updateTemplateNormal, this.lastWorldPosition);
                }
                for (let i = 0; i < this.colliders.length; i++) {
                    const element = this.colliders[i];
                    let distanceSquared = Laya.Vector3.distanceSquared(element.transform.position, this.lastWorldPosition);
                    let collidernode = element.owner;
                    let colliderscaleX = 1;
                    while (collidernode instanceof Laya.Sprite3D) {
                        colliderscaleX *= collidernode.transform.localScaleX;
                        collidernode = collidernode.parent;
                    }
                    let factor1 = this.transform ? scaleX : 1;
                    let factor2 = colliderscaleX;
                    let radius = this.radius * factor1 + element.radius * factor2;
                    if (distanceSquared <= radius * radius) {
                        Laya.Vector3.subtract(this.lastWorldPosition, element.transform.position, this.updateTemplateNormal);
                        Laya.Vector3.normalize(this.updateTemplateNormal, this.updateTemplateNormal);
                        Laya.Vector3.scale(this.updateTemplateNormal, radius, this.updateTemplateNormal);
                        Laya.Vector3.add(element.transform.position, this.updateTemplateNormal, this.lastWorldPosition);
                    }
                }
                this.transform.position = this.lastWorldPosition;
            }
        }

        var Script3D$1 = Laya.Script3D;
        class BoneCollider extends Script3D$1 {
            constructor() {
                super(...arguments);
                this.radius = 0.1;
                this.part = BoneColliderPart.NONE;
            }
            onAwake() {
                this.transform = this.owner.transform;
            }
            onStart() {
                if (/1/.test(this.owner.name)) {
                    this.radius *= 0.5;
                }
                if (/2/.test(this.owner.name)) {
                    this.radius *= 0.8;
                }
                if (/3/.test(this.owner.name)) {
                    this.radius *= 0.7;
                }
                this.preRadius = this.radius;
            }
            SetScale(scale) {
                this.radius = this.preRadius * scale;
            }
        }

        var Script3D$2 = Laya.Script3D;
        class BoneManager extends Script3D$2 {
            constructor() {
                super(...arguments);
                this.bones = [];
                this.allColliders = [];
                this._isRefresh = false;
                this.COLLIDER_REPXS = [/PZD_/];
                this.B_SHOW_GIMOS = false;
                this.shareCollierConfig = {
                    c1s: 0.062,
                    c2s: 0.093,
                    c3s: 0.099,
                    c4s: 0.099,
                    c5s: 0.130,
                    c6s: 0.139,
                };
                this.originDynamicConfig = {};
                this.router2ModelKeyMap = {};
                this.allRouters = {};
                this.router2IgnoreRename = {};
                this._1Center = new Laya.Vector3;
                this._2Center = new Laya.Vector3;
                this._3Center = new Laya.Vector3;
            }
            onAwake() {
                let root = this.owner;
                this.AddComponentsInChildren(root, BoneCollider, this.COLLIDER_REPXS);
                this.allColliders = [];
                let colliders = this.GetComponentsInChildren(root, BoneCollider);
                this.allColliders = colliders;
            }
            onStart() {
                this.CheckBone();
                this.onStarted && this.onStarted();
            }
            addDynamicConfig(config, key, bIgnoreRename = false) {
                this.originDynamicConfig[key] = config;
                for (let i = 0; i < config.routers.length; i++) {
                    const router = config.routers[i];
                    this.allRouters[router.router] = router;
                    this.router2ModelKeyMap[router.router] = key;
                    this.router2IgnoreRename[router.router] = { bIgnore: bIgnoreRename, key: key };
                }
                this.CheckBone();
            }
            removeDynamicConfig(key) {
                let originConfig = this.originDynamicConfig[key];
                if (!originConfig)
                    return;
                for (let i = 0; i < originConfig.routers.length; i++) {
                    const element = originConfig.routers[i];
                    delete this.allRouters[element.router];
                    delete this.router2ModelKeyMap[element.router];
                }
                delete this.originDynamicConfig[key];
                this.CheckBone();
            }
            isHaveConfig(key) {
                let originConfig = this.originDynamicConfig[key];
                return !!originConfig;
            }
            CheckBone() {
                let root = this.owner;
                let newGeneratedBones = [];
                Tools.forEachMap(this.allRouters, (k, v) => {
                    let routerRoot = this.findChildByRouter(root, v.router, this.router2IgnoreRename[k].bIgnore, this.router2IgnoreRename[k].key);
                    if (routerRoot) {
                        newGeneratedBones = newGeneratedBones.concat(this.useDynamicBone(v, routerRoot));
                    }
                });
                let boneMap = {};
                for (let i = 0; i < newGeneratedBones.length; i++) {
                    const element = newGeneratedBones[i];
                    boneMap[element.id] = !!element;
                }
                if (this.bones) {
                    for (let i = 0; i < this.bones.length; i++) {
                        const bone = this.bones[i];
                        if (!boneMap[bone.id]) {
                            bone.destroy();
                        }
                    }
                }
                this.bones = newGeneratedBones;
                for (let i = 0; i < this.bones.length; i++) {
                    const bone = this.bones[i];
                    bone.colliders = this.allColliders;
                }
            }
            onLateUpdate() {
                for (let i = 0; i < this.bones.length; i++) {
                    const bone = this.bones[i];
                    if (!!bone) {
                        bone.UpdateBone(Tools.deltaTime);
                    }
                }
            }
            useDynamicBone(router, root) {
                let allChildrenConfigMap = {};
                allChildrenConfigMap[root.name] = router.config;
                for (let i = 0; i < router.children.length; i++) {
                    const childRouter = router.children[i];
                    let name = this.getRouterLastKey(childRouter.router);
                    allChildrenConfigMap[name] = router.config;
                }
                let key = this.router2ModelKeyMap[router.router];
                allChildrenConfigMap[root.parent.name] = this.originDynamicConfig[key].gBoneConfig;
                let allBones = [];
                let recurive = (root) => {
                    if (!root)
                        return;
                    let bone = root.getComponent(Bone);
                    if (!bone) {
                        bone = root.addComponent(Bone);
                    }
                    allBones.push(bone);
                    let keys = [`parm1`, `radius`, `gravity`, `displacementFactor`, `maxDisplacement`];
                    for (let i = 0; i < keys.length; i++) {
                        const key = keys[i];
                        this.useBoneParamWithParamMap(bone, root, key, allChildrenConfigMap);
                    }
                    recurive(root.getChildAt(0));
                };
                recurive(root);
                return allBones;
            }
            set forceMaxDisplacement(value) {
                for (let i = 0; i < this.bones.length; i++) {
                    const element = this.bones[i];
                    if (element.destroyed)
                        continue;
                    element.maxDisplacement = value;
                }
            }
            useBoneParamWithParamMap(bone, cursorNode, key, paramMap) {
                let name = cursorNode.name;
                let config = paramMap[name] || {};
                let value = config[key];
                if (value == null) {
                    this.useBoneParamWithParamMap(bone, cursorNode.parent, key, paramMap);
                }
                else {
                    switch (key) {
                        case "parm1":
                            bone.parm1 = value;
                            break;
                        case "radius":
                            bone.radius = value;
                            break;
                        case "displacementFactor":
                            bone.displacementFactor = value;
                            break;
                        case "maxDisplacement":
                            bone.maxDisplacement = value;
                            break;
                        case "gravity":
                            bone.gravity = new Laya.Vector3(0, -value, 0);
                            break;
                    }
                }
            }
            getRouterLastKey(router) {
                if (router[0] == "/")
                    router = router.slice(1, router.length);
                if (router[router.length - 1] == "/")
                    router = router.slice(0, router.length - 1);
                let strs = router.split("/");
                return strs[strs.length - 1];
            }
            getRouterDeepth(router) {
                if (router[0] == "/")
                    router = router.slice(1, router.length);
                if (router[router.length - 1] == "/")
                    router = router.slice(0, router.length - 1);
                let strs = router.split("/");
                return strs.length;
            }
            findChildByRouter(root, router, bIgnoreRename = false, key = "") {
                while (true) {
                    if (router[0] == "/")
                        router = router.slice(1, router.length);
                    let index = router.indexOf("/");
                    if (index >= 0) {
                        let childName = router.slice(0, index);
                        if (bIgnoreRename) {
                            childName = childName.replace(`_${key}`, "");
                        }
                        router = router.slice(index, router.length);
                        let node = root.getChildByName(childName);
                        if (node) {
                            root = node;
                        }
                        else {
                            return null;
                        }
                    }
                    else {
                        return root;
                    }
                }
            }
            GetComponentsInChildren(root, type) {
                let components = [];
                for (let i = 0; i < root.numChildren; i++) {
                    let child = root.getChildAt(i);
                    if (!!child) {
                        let comp = child.getComponent(type);
                        if (!!comp) {
                            components.push(comp);
                        }
                        let comps = this.GetComponentsInChildren(child, type);
                        for (let j = 0; j < comps.length; j++) {
                            const comp = comps[j];
                            components.push(comp);
                        }
                    }
                }
                return components;
            }
            AddComponentsInChildren(root, type, regexps, param) {
                for (let i = 0; i < root.numChildren; i++) {
                    let child = root.getChildAt(i);
                    if (!!child) {
                        let bTested = false;
                        for (let i_rep = 0; i_rep < regexps.length; i_rep++) {
                            const regexp = regexps[i_rep];
                            bTested = bTested || regexp.test(child.name);
                        }
                        if (bTested) {
                            let comp = child.addComponent(type);
                            if (param) {
                                for (const k in param) {
                                    !!param[k] && (comp[k] = param[k]);
                                }
                            }
                        }
                        this.AddComponentsInChildren(child, type, regexps, param);
                    }
                }
            }
            onUpdate() {
            }
            setColliderRidus(radius) {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const element = this.allColliders[i];
                    element && (element.radius = radius);
                }
            }
            setDisplacementFactor(factor) {
                factor = parseFloat(factor);
                for (let i = 0; i < this.bones.length; i++) {
                    const bone = this.bones[i];
                    bone.displacementFactor = factor;
                }
            }
            setMaxDisplacement(param) {
                param = parseFloat(param);
                for (let i = 0; i < this.bones.length; i++) {
                    const bone = this.bones[i];
                    bone.maxDisplacement = param;
                }
            }
            set c1s(param) {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/1/.test(collider.owner.name)) {
                    }
                }
            }
            get c1s() {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/1/.test(collider.owner.name)) {
                        return collider.radius;
                    }
                }
                return -1;
            }
            set c2s(param) {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/2/.test(collider.owner.name)) {
                    }
                }
            }
            get c2s() {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/2/.test(collider.owner.name)) {
                        return collider.radius;
                    }
                }
                return -1;
            }
            set c3s(param) {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/3/.test(collider.owner.name)) {
                    }
                }
            }
            get c3s() {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/3/.test(collider.owner.name)) {
                        return collider.radius;
                    }
                }
                return -1;
            }
            set c4s(param) {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/4/.test(collider.owner.name)) {
                    }
                }
            }
            get c4s() {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/4/.test(collider.owner.name)) {
                        return collider.radius;
                    }
                }
                return -1;
            }
            set c5s(param) {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/5/.test(collider.owner.name)) {
                    }
                }
            }
            get c5s() {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/5/.test(collider.owner.name)) {
                        return collider.radius;
                    }
                }
                return -1;
            }
            set c6s(param) {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/6/.test(collider.owner.name)) {
                    }
                }
            }
            get c6s() {
                for (let i = 0; i < this.allColliders.length; i++) {
                    const collider = this.allColliders[i];
                    if (/6/.test(collider.owner.name)) {
                        return collider.radius;
                    }
                }
                return -1;
            }
            setCurentEditorRouter(router, key) {
                this.curEditorRouter = router;
                this.curEditorKey = key;
            }
            getRoutersByCurEditorRouter() {
                if (this.curEditorRouter == "/") {
                    return this.originDynamicConfig[this.curEditorKey].routers;
                }
                else {
                    let routers = [];
                    for (let i = 0; i < this.originDynamicConfig[this.curEditorKey].routers.length; i++) {
                        const element = this.originDynamicConfig[this.curEditorKey].routers[i];
                        if (this.curEditorRouter.indexOf(element.router) >= 0) {
                            if (this.curEditorRouter == element.router) {
                                routers.push(element);
                            }
                            else {
                                let bFindChild = false;
                                let childRouter = this.curEditorRouter.replace(element.router, "");
                                for (let i = 0; i < element.children.length; i++) {
                                    const child = element.children[i];
                                    if (child.router == childRouter) {
                                        routers.push(child);
                                        bFindChild = true;
                                    }
                                }
                                if (!bFindChild) {
                                    element.children.push({
                                        router: childRouter,
                                    });
                                }
                            }
                        }
                    }
                    return routers;
                }
            }
            set parm1(p) {
                if (!p)
                    return;
                if (this.curEditorRouter == "/") {
                    this.originDynamicConfig[this.curEditorKey].gBoneConfig.parm1 = p;
                    this.CheckBone();
                }
                else {
                    let routerDatas = this.getRoutersByCurEditorRouter();
                    for (let i = 0; i < routerDatas.length; i++) {
                        const element = routerDatas[i];
                        element.config = element.config || {};
                        element.config.parm1 = p;
                    }
                    this.CheckBone();
                }
            }
            get parm1() {
                if (this.curEditorRouter == "/") {
                    return this.originDynamicConfig[this.curEditorKey].gBoneConfig.parm1;
                }
                else {
                    let boneRoot = this.findChildByRouter(this.owner, this.curEditorRouter);
                    let bone = boneRoot.getComponent(Bone);
                    return bone.parm1;
                }
            }
            set radius(p) {
                if (!p)
                    return;
                if (this.curEditorRouter == "/") {
                    this.originDynamicConfig[this.curEditorKey].gBoneConfig.radius = p;
                    this.CheckBone();
                }
                else {
                    let routerDatas = this.getRoutersByCurEditorRouter();
                    for (let i = 0; i < routerDatas.length; i++) {
                        const element = routerDatas[i];
                        element.config = element.config || {};
                        element.config.radius = p;
                    }
                    this.CheckBone();
                }
            }
            get radius() {
                if (this.curEditorRouter == "/") {
                    return this.originDynamicConfig[this.curEditorKey].gBoneConfig.radius;
                }
                else {
                    let boneRoot = this.findChildByRouter(this.owner, this.curEditorRouter);
                    let bone = boneRoot.getComponent(Bone);
                    return bone.radius;
                }
            }
            set displacementFactor(p) {
                if (!p)
                    return;
                if (this.curEditorRouter == "/") {
                    this.originDynamicConfig[this.curEditorKey].gBoneConfig.displacementFactor = p;
                    this.CheckBone();
                }
                else {
                    let routerDatas = this.getRoutersByCurEditorRouter();
                    for (let i = 0; i < routerDatas.length; i++) {
                        const element = routerDatas[i];
                        element.config = element.config || {};
                        element.config.displacementFactor = p;
                    }
                    this.CheckBone();
                }
            }
            get displacementFactor() {
                if (this.curEditorRouter == "/") {
                    return this.originDynamicConfig[this.curEditorKey].gBoneConfig.displacementFactor;
                }
                else {
                    let boneRoot = this.findChildByRouter(this.owner, this.curEditorRouter);
                    let bone = boneRoot.getComponent(Bone);
                    return bone.displacementFactor;
                }
            }
            set maxDisplacement(p) {
                if (!p)
                    return;
                if (this.curEditorRouter == "/") {
                    this.originDynamicConfig[this.curEditorKey].gBoneConfig.maxDisplacement = p;
                    this.CheckBone();
                }
                else {
                    let routerDatas = this.getRoutersByCurEditorRouter();
                    for (let i = 0; i < routerDatas.length; i++) {
                        const element = routerDatas[i];
                        element.config = element.config || {};
                        element.config.maxDisplacement = p;
                    }
                    this.CheckBone();
                }
            }
            get maxDisplacement() {
                if (this.curEditorRouter == "/") {
                    return this.originDynamicConfig[this.curEditorKey].gBoneConfig.maxDisplacement;
                }
                else {
                    let boneRoot = this.findChildByRouter(this.owner, this.curEditorRouter);
                    let bone = boneRoot.getComponent(Bone);
                    return bone.maxDisplacement;
                }
            }
            set gravity(p) {
                if (!p)
                    return;
                if (this.curEditorRouter == "/") {
                    this.originDynamicConfig[this.curEditorKey].gBoneConfig.gravity = p;
                    this.CheckBone();
                }
                else {
                    let routerDatas = this.getRoutersByCurEditorRouter();
                    for (let i = 0; i < routerDatas.length; i++) {
                        const element = routerDatas[i];
                        element.config = element.config || {};
                        element.config.gravity = p;
                    }
                    this.CheckBone();
                }
            }
            get gravity() {
                if (this.curEditorRouter == "/") {
                    return this.originDynamicConfig[this.curEditorKey].gBoneConfig.gravity;
                }
                else {
                    let boneRoot = this.findChildByRouter(this.owner, this.curEditorRouter);
                    let bone = boneRoot.getComponent(Bone);
                    return -bone.gravity.y;
                }
            }
        }

        class RoleAvatar extends Laya.Sprite3D {
            constructor(context) {
                super();
                this.unloadedPartIds = {};
                this.loadingPartIds = {};
                this.loadEndCallBacks = [];
                this.allLoadEndCallBacks = [];
                this.linkedModels = [];
                this.linkedModel2Point = {};
                this.__renderLayer__ = 0;
                this.bPresetBoneBinderSerialNumber = false;
                this.presetBoneOffsetXYZ = new Laya.Vector3;
                this._timeScale = 1;
                this.bDisableDressAnimation = true;
                this.avatarColliderName2TypeDict = {
                    ["Click_head"]: 1,
                    ["Click_l_hand"]: 2,
                    ["Click_r_hand"]: 3,
                    ["Click_cloth"]: 4,
                    ["Click_dress"]: 5,
                    ["Click_foot"]: 6,
                };
                this.avatarColliderSprite3dDict = {};
                this.roleAvatarAlpha = 1;
                this.SHOU_CHI_ANI_KEY_WORD = "_sc_idle";
                context = context || {};
                this.context = context;
                this.changeRoleId(context.roleId);
                this.bDisableDynamic = (context && !!context.bDisableDynamic) ? true : false;
                this.bDisableLoadShadow = (context && !!context.bDisableLoadShadow) ? true : false;
                if (context && !!context.boneBindSerialNumber) {
                    this.boneBinderSerialNumber = context.boneBindSerialNumber;
                    this.bPresetBoneBinderSerialNumber = true;
                    this.presetBoneOffsetXYZ = context.presetBoneOffsetXYZ;
                }
                this.parts = {};
                this.loadDefault(() => {
                    if (context && context.fBoneBindedCallback) {
                        context.fBoneBindedCallback(this.boneBinderSerialNumber);
                    }
                    Timer.callLoop(0.001, this.loadPart.bind(this), this);
                });
                this.transform.position = new Laya.Vector3(0, 0, 1000);
            }
            set renderLayer(value) {
                this.__renderLayer__ = value;
                Tools.setSprite3dLayer(this, value);
            }
            get renderLayer() {
                return this.__renderLayer__;
            }
            get bLoading() {
                return this.bLoadingNakedness || this.bLoadingPart || ul.length(this.unloadedPartIds) > 0;
            }
            getRoleId() {
                return this.context.roleId;
            }
            changeRoleId(roleId) {
                this.context.roleId = roleId || 101;
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                this.humanBoneIndex = roleData.humanBoneIndex || 0;
                let roleFaceAniConfig = mgrCfg.get("role_face_animation", this.context.roleId) || {};
                this.setIdleId(this.context.defaultBodyIdleName, roleFaceAniConfig.idle);
                let partIds = [];
                for (let k in roleData.centerPartIds) {
                    let pid = roleData.centerPartIds[k];
                    let partData = mgrCfg.get_from_part_db(pid);
                    if (partData.type == PartType.face || partData.type == PartType.hair) {
                        partIds.push(pid);
                    }
                }
                this.fillByPartIds(partIds);
            }
            outForHide() {
                this.transform.position = new Laya.Vector3(0, 0, 1000);
            }
            getBoneManager(partType) {
                if (partType != PartType.hair && partType != PartType.headDec) {
                    return this.bodyBoneManager;
                }
                else {
                    let mode = this.getNodeByType(partType);
                    if (!mode) {
                        return;
                    }
                    if (Tools.getFirstChildBone(mode)) {
                        let lboneManager = Tools.getFirstChildBone(mode).getComponent(BoneManager);
                        if (!lboneManager) {
                            lboneManager = Tools.getFirstChildBone(mode).addComponent(BoneManager);
                        }
                        return lboneManager;
                    }
                    return null;
                }
            }
            removeAllLinkModel() {
                for (let i = this.linkedModels.length - 1; i >= 0; i--) {
                    const element = this.linkedModels[i];
                    this.unlinkModel(element);
                }
                this.linkedModels = [];
                this.linkedModel2Point = {};
            }
            destroy() {
                this.preDestroyRes();
                super.destroy(false);
            }
            preDestroyRes() {
                this.removeAllLinkModel();
                for (const k in this.parts) {
                    let partInfo = this.parts[k];
                    if (!partInfo)
                        continue;
                    let nodeInfos = partInfo.nodes;
                    for (let i = 0; i < nodeInfos.length; i++) {
                        const nodeInfo = nodeInfos[i];
                        this.recoverModelSafe(nodeInfo.node);
                    }
                }
                this.parts = {};
                if (this.roleShadow) {
                    let shadowFollow = this.roleShadow.getComponent(ShadowFollow);
                    if (shadowFollow) {
                        shadowFollow.destroy();
                    }
                    this.recoverModelSafe(this.roleShadow);
                    this.roleShadow = null;
                }
                if (this.baseBodyAnimator) {
                    this.baseBodyAnimator = null;
                }
                if (this.baseBody) {
                    this.recoverModelSafe(this.baseBody);
                }
                if (!this.bPresetBoneBinderSerialNumber) {
                    mgrBoneBinder.unbindAllBone(this.boneBinderSerialNumber);
                }
                else {
                    mgrBoneBinder.removeRelateAvatar(this, this.boneBinderSerialNumber);
                }
            }
            getOffsetXYZ() {
                return this.presetBoneOffsetXYZ;
            }
            setOffsetXYZ(offsetXYZ) {
                this.presetBoneOffsetXYZ = offsetXYZ || new Laya.Vector3;
                if (this.baseBody) {
                    this.useCartonMaterial(this.baseBody, MODEL_ID.role_body);
                }
                for (const k in this.parts) {
                    let partInfo = this.parts[k];
                    if (!partInfo)
                        continue;
                    let nodeInfos = partInfo.nodes;
                    for (let i = 0; i < nodeInfos.length; i++) {
                        const nodeInfo = nodeInfos[i];
                        this.useCartonMaterial(nodeInfo.node, nodeInfo.node.name);
                    }
                }
                if (this.roleShadow) {
                    let comp = this.roleShadow.getComponent(ShadowFollow);
                    if (comp) {
                        comp.offsetXYZ = this.presetBoneOffsetXYZ;
                    }
                }
            }
            changeToMainBoneAvatar() {
                if (!this.bPresetBoneBinderSerialNumber) {
                    return;
                }
                this.bPresetBoneBinderSerialNumber = false;
                this.presetBoneOffsetXYZ = null;
                mgrBoneBinder.removeRelateAvatar(this, this.boneBinderSerialNumber);
                if (this.baseBody) {
                    mgrBoneBinder.unbindModelBone(this.baseBody);
                    this.useCartonMaterial(this.baseBody, MODEL_ID.role_body);
                }
                if (this.baseBodyAnimator) {
                    this.baseBodyAnimator.enabled = true;
                }
                this.boneBinderSerialNumber = mgrBoneBinder.addMainAvatar(this, this.baseBody);
                for (const k in this.parts) {
                    let partInfo = this.parts[k];
                    if (!partInfo)
                        continue;
                    let nodeInfos = partInfo.nodes;
                    for (let i = 0; i < nodeInfos.length; i++) {
                        const nodeInfo = nodeInfos[i];
                        this.useCartonMaterial(nodeInfo.node, nodeInfo.node.name);
                        if (this.isLinkModel(nodeInfo.node)) {
                            let linkPointName = nodeInfo.node.parent.name;
                            nodeInfo.node.removeSelf();
                            Tools.link2Node(linkPointName, this.baseBody, nodeInfo.node);
                        }
                        else {
                            mgrBoneBinder.unbindModelBone(nodeInfo.node);
                            mgrBoneBinder.relateModelBone(nodeInfo.node, this.boneBinderSerialNumber, !this.bPresetBoneBinderSerialNumber);
                        }
                    }
                }
                let comp = this.roleShadow.getComponent(ShadowFollow);
                comp.offsetXYZ = null;
                comp.__target = this.baseBody;
                this.playAnimation(this.bodyDefaultIdleName);
            }
            relateMainBoneAvatar(serialNumber, offsetXYZ) {
                if (this.bPresetBoneBinderSerialNumber) {
                    return;
                }
                mgrBoneBinder.removeRelateAvatar(this, this.boneBinderSerialNumber);
                if (this.baseBody) {
                    mgrBoneBinder.unbindModelBone(this.baseBody);
                }
                if (this.baseBodyAnimator) {
                    this.baseBodyAnimator.enabled = false;
                }
                this.bPresetBoneBinderSerialNumber = true;
                this.presetBoneOffsetXYZ = offsetXYZ || new Laya.Vector3;
                this.boneBinderSerialNumber = serialNumber;
                for (const k in this.parts) {
                    let partInfo = this.parts[k];
                    if (!partInfo)
                        continue;
                    let nodeInfos = partInfo.nodes;
                    for (let i = 0; i < nodeInfos.length; i++) {
                        const nodeInfo = nodeInfos[i];
                        this.useCartonMaterial(nodeInfo.node, nodeInfo.node.name);
                        if (this.isLinkModel(nodeInfo.node)) {
                            let linkPointName = nodeInfo.node.parent.name;
                            nodeInfo.node.removeSelf();
                            mgrBoneBinder.link2Node(linkPointName, nodeInfo.node, serialNumber);
                        }
                        else {
                            mgrBoneBinder.relateModelBone(nodeInfo.node, serialNumber, false);
                        }
                    }
                }
                this.useCartonMaterial(this.baseBody, MODEL_ID.role_body);
                this.playAnimation(this.bodyDefaultIdleName);
            }
            refreshMaterial() {
                if (this.baseBody) {
                    this.useCartonMaterial(this.baseBody, MODEL_ID.role_body);
                }
                for (const k in this.parts) {
                    let partInfo = this.parts[k];
                    if (!partInfo)
                        continue;
                    let nodeInfos = partInfo.nodes;
                    for (let i = 0; i < nodeInfos.length; i++) {
                        const nodeInfo = nodeInfos[i];
                        this.useCartonMaterial(nodeInfo.node, nodeInfo.node.name);
                    }
                }
            }
            loadDefault(finishCallback) {
                this.bLoadingNakedness = true;
                let preModelIds = [MODEL_ID.role_body];
                if (!this.bDisableLoadShadow) {
                    preModelIds.push(MODEL_ID.role_shadow);
                }
                let taskSamples = [];
                for (let index = 0; index < preModelIds.length; index++) {
                    const modelId = preModelIds[index];
                    taskSamples.push((endCallback) => {
                        mgrLoader.loadModeWithModeId(modelId, () => {
                            endCallback();
                        }, this, 1);
                    });
                }
                let taskManager = new TaskManager();
                taskManager.push(taskSamples);
                let loadEndCallback = () => {
                    for (let i = 0; i < preModelIds.length; i++) {
                        const modelId = preModelIds[i];
                        let mode = mgrLoader.Pool.getModel(modelId);
                        mode.active = true;
                        if (modelId == MODEL_ID.role_body) {
                            for (let colliderName in this.avatarColliderName2TypeDict) {
                                let sprite3d = Tools.findNode(colliderName, mode);
                                let meshRenderer = Tools.getMeshRender(sprite3d);
                                if (meshRenderer) {
                                    meshRenderer.enable = false;
                                }
                                this.avatarColliderSprite3dDict[colliderName] = sprite3d;
                            }
                            let animator = mode.getComponent(Laya.Animator);
                            animator.enabled = !this.bPresetBoneBinderSerialNumber;
                            this.baseBody = mode;
                            this.baseBodyAnimator = animator;
                            this.baseBodyAnimator.speed = this._timeScale;
                            this.addChild(mode);
                            this.useCartonMaterial(mode, MODEL_ID.role_body);
                            this.humanBoneIndex = this._usingHumanBoneIndex;
                            if (Tools.getFirstChildBone(mode)) {
                                this.bodyBoneManager = Tools.getFirstChildBone(mode).getComponent(BoneManager);
                                if (!this.bodyBoneManager) {
                                    this.bodyBoneManager = Tools.getFirstChildBone(mode).addComponent(BoneManager);
                                }
                            }
                            if (this.bPresetBoneBinderSerialNumber) {
                                mgrBoneBinder.addRelateAvatar(this, this.boneBinderSerialNumber);
                                mgrBoneBinder.relateModelBone(mode, this.boneBinderSerialNumber, !this.bPresetBoneBinderSerialNumber);
                            }
                            else {
                                if (this.boneBinderSerialNumber) {
                                    mgrBoneBinder.unbindAllBone(this.boneBinderSerialNumber);
                                    this.boneBinderSerialNumber = 0;
                                }
                                this.boneBinderSerialNumber = mgrBoneBinder.addMainAvatar(this, this.baseBody);
                            }
                            if (this.roleShadow) {
                                let shadowTarget = this.baseBody;
                                if (this.bPresetBoneBinderSerialNumber) {
                                    let mainAvatar = mgrBoneBinder.getMainAvatar(this.boneBinderSerialNumber);
                                    if (mainAvatar && mainAvatar.baseBody) {
                                        shadowTarget = mainAvatar.baseBody;
                                    }
                                }
                                if (shadowTarget) {
                                    let comp = this.roleShadow.addComponent(ShadowFollow);
                                    comp.offsetXYZ = this.presetBoneOffsetXYZ;
                                    comp.__target = shadowTarget;
                                }
                            }
                        }
                        else if (modelId == MODEL_ID.role_shadow) {
                            this.roleShadow = mode;
                            this.roleShadow.transform.position = new Laya.Vector3(0, 0.01);
                            this.addChild(mode);
                            let shadowTarget = this.baseBody;
                            if (this.bPresetBoneBinderSerialNumber) {
                                let mainAvatar = mgrBoneBinder.getMainAvatar(this.boneBinderSerialNumber);
                                if (mainAvatar && mainAvatar.baseBody) {
                                    shadowTarget = mainAvatar.baseBody;
                                }
                            }
                            if (shadowTarget) {
                                let comp = this.roleShadow.addComponent(ShadowFollow);
                                comp.offsetXYZ = this.presetBoneOffsetXYZ;
                                comp.__target = shadowTarget;
                            }
                        }
                        let animator = mode.getComponent(Laya.Animator);
                        if (!!animator) {
                            animator.enabled = true;
                        }
                    }
                    let defaultPartIds = [];
                    mgrCfg.forDb_from_part_type_db((k, v) => {
                        if (v.id != PartType.face && v.id != PartType.hair && v.defaultPartId && !this.unloadedPartIds[v.id]) {
                            defaultPartIds.push(v.defaultPartId);
                        }
                    });
                    if (!!this.context.roleId) {
                        let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                        for (let k in roleData.centerPartIds) {
                            let pid = roleData.centerPartIds[k];
                            let partData = mgrCfg.get_from_part_db(pid);
                            if (partData.type == PartType.face || partData.type == PartType.hair) {
                                defaultPartIds.push(pid);
                            }
                        }
                    }
                    this.fillByPartIds(defaultPartIds);
                    this.bLoadingNakedness = false;
                };
                taskManager.start(() => {
                    loadEndCallback();
                    finishCallback();
                });
            }
            clearPartSafely() {
                let partIds = [];
                for (const k in this.parts) {
                    let element = this.parts[k];
                    if (element) {
                        let partData = mgrCfg.get_from_part_db(element.partId);
                        if (partData.type == PartType.face ||
                            partData.type == PartType.hair ||
                            partData.type == PartType.cloth ||
                            partData.type == PartType.shoe) {
                            continue;
                        }
                        if (this.unloadedPartIds[partData.type]) {
                            partIds.push(this.unloadedPartIds[partData.type]);
                        }
                        else {
                            partIds.push(element.partId);
                        }
                    }
                }
                for (let k in partIds) {
                    this.removePart(partIds[k]);
                }
            }
            fillByPartIds(partIds, bClearSafely) {
                if (bClearSafely) {
                    this.clearPartSafely();
                }
                for (let i = 0; i < partIds.length; i++) {
                    const partId = partIds[i];
                    let partData = mgrCfg.get_from_part_db(partId);
                    if (!partData) {
                        console.log("---部件不存在---partId=", partId);
                        continue;
                    }
                    this.unloadedPartIds[partData.type] = partId;
                }
            }
            removePart(partId) {
                let partData = mgrCfg.get_from_part_db(partId);
                let oldPartInfo = this.parts[partData.type];
                if (oldPartInfo) {
                    console.log(`移除部件: ${oldPartInfo.partId}`);
                    for (let index = 0; index < oldPartInfo.nodes.length; index++) {
                        const element = oldPartInfo.nodes[index];
                        this.recoverModelSafe(element.node);
                    }
                    this.parts[partData.type] = null;
                }
            }
            registerLoadEndCallback(callback) {
                this.loadEndCallBacks.push(callback);
                return this;
            }
            registerAllLoadEndCallback(callback) {
                this.allLoadEndCallBacks.push(callback);
                return this;
            }
            loadPart() {
                let mustRequiredPartTypes = [];
                let allPartTypes = [];
                mgrCfg.forDb_from_part_type_db((k, v) => {
                    allPartTypes.push(v.id);
                    if (v.bRequired)
                        mustRequiredPartTypes.push(v.id);
                });
                let allNeedFinishedCount = 0;
                let allFinishedCount = 0;
                for (let i = 0; i < mustRequiredPartTypes.length; i++) {
                    const partType = mustRequiredPartTypes[i];
                    if (!this.loadingPartIds[partType] && !this.unloadedPartIds[partType]) {
                        allNeedFinishedCount++;
                    }
                }
                if (allNeedFinishedCount == mustRequiredPartTypes.length) {
                    for (let index = 0; index < this.loadEndCallBacks.length; index++) {
                        const callback = this.loadEndCallBacks[index];
                        Timer.callLater(0.02, () => {
                            callback && callback();
                        }, this);
                    }
                    this.loadEndCallBacks = [];
                }
                for (let i = 0; i < allPartTypes.length; i++) {
                    const partType = allPartTypes[i];
                    if (!this.loadingPartIds[partType] && !this.unloadedPartIds[partType]) {
                        allFinishedCount++;
                    }
                }
                if (allFinishedCount >= allPartTypes.length) {
                    for (let index = 0; index < this.allLoadEndCallBacks.length; index++) {
                        const callback = this.allLoadEndCallBacks[index];
                        Timer.callLater(0.02, () => {
                            callback && callback();
                        }, this);
                    }
                    this.allLoadEndCallBacks = [];
                }
                if (this.bLoadingPart)
                    return;
                if (ul.length(this.unloadedPartIds) <= 0) {
                    return;
                }
                this.loadingPartIds = this.unloadedPartIds;
                this.unloadedPartIds = {};
                this.bLoadingPart = true;
                let mustRequiredPartIds = [];
                let otherPartIds = [];
                for (const k in this.loadingPartIds) {
                    let partId = this.loadingPartIds[k];
                    if (!partId)
                        continue;
                    let partData = mgrCfg.get_from_part_db(partId);
                    if (mustRequiredPartTypes.indexOf(partData.type) >= 0) {
                        mustRequiredPartIds.push(partId);
                    }
                    else {
                        otherPartIds.push(partId);
                    }
                }
                let tManager = new TaskManager();
                let tSamples = [];
                tSamples.push((finishCallback) => {
                    let finishedCount = 0;
                    for (let i = 0; i < mustRequiredPartIds.length; i++) {
                        let partId = mustRequiredPartIds[i];
                        let partData = mgrCfg.get_from_part_db(partId);
                        let tsManager = new TaskManager();
                        let tsSamples = [];
                        const modelId = partData.modelId;
                        tsSamples.push((fc) => {
                            mgrLoader.loadModeWithModeId(modelId, () => {
                                mgrLoader.markPartResLoaded(partId);
                                fc();
                            }, this, 1);
                        });
                        tsManager.push(tsSamples);
                        tsManager.start(() => {
                            if (!this.unloadedPartIds[partData.type]) {
                                this.replaceLoadedPart(partId);
                            }
                            finishedCount++;
                            if (finishedCount == mustRequiredPartIds.length) {
                                finishCallback();
                            }
                        });
                    }
                    if (mustRequiredPartIds.length == 0) {
                        finishCallback();
                    }
                });
                tManager.push(tSamples);
                tSamples = [];
                tSamples.push((finishCallback) => {
                    let finishedCount = 0;
                    for (let i = 0; i < otherPartIds.length; i++) {
                        let partId = otherPartIds[i];
                        let partData = mgrCfg.get_from_part_db(partId);
                        let tsManager = new TaskManager();
                        let tsSamples = [];
                        tsSamples.push((fc) => {
                            mgrLoader.loadModeWithModeId(partData.modelId, () => {
                                mgrLoader.markPartResLoaded(partId);
                                fc();
                            }, this, 1);
                        });
                        tsManager.push(tsSamples);
                        tsManager.start(() => {
                            if (!this.unloadedPartIds[partData.type]) {
                                this.replaceLoadedPart(partId);
                            }
                            finishedCount++;
                            if (finishedCount == otherPartIds.length) {
                                finishCallback();
                            }
                        });
                    }
                    if (otherPartIds.length == 0) {
                        finishCallback();
                    }
                });
                tManager.push(tSamples);
                tSamples = [];
                tManager.start(() => {
                    this.loadingPartIds = {};
                    this.bLoadingPart = false;
                });
            }
            replaceLoadedPart(partId) {
                let partData = mgrCfg.get_from_part_db(partId);
                this.loadingPartIds[partData.type] = null;
                let oldPartInfo = this.parts[partData.type];
                if (oldPartInfo) {
                    for (let index = 0; index < oldPartInfo.nodes.length; index++) {
                        const element = oldPartInfo.nodes[index];
                        this.recoverModelSafe(element.node);
                    }
                    this.parts[partData.type] = null;
                }
                this.parts[partData.type] = {
                    partId: partId,
                    nodes: []
                };
                const modelId = partData.modelId;
                let mode = mgrLoader.Pool.getModel(modelId);
                Tools.setSprite3dLayer(mode, this.renderLayer);
                let animator = mode.getComponent(Laya.Animator);
                if (!animator) {
                    animator = mode.addComponent(Laya.Animator);
                }
                this.useCartonMaterial(mode, modelId, partData.modelMaterialNo, mgrDesign.isDesignPart(partData.id));
                mgrDesign.tryAdaptDesignPartModelMaterial(mode, partData.id, this.context.bDesignPartForceUseTextureColor);
                let partTypeData = mgrCfg.get_from_part_type_db(partData.type);
                if (partTypeData.linkPoint || partData.assignLinkPoint) {
                    this.linkModel(mode, partData.assignLinkPoint || partTypeData.linkPoint);
                    if (partData.offsetY) {
                        mode.transform.localPosition = new Laya.Vector3(0, partData.offsetY || 0, 0);
                        let scale = 1 + (partData.offsetScaleModel || 0);
                        mode.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                    }
                    if (!partData.bEffectPart) {
                        if (!this.bDisableDynamic) {
                            let dyConfig = mgrDynamicBone.getDynamicConfig(modelId);
                            if (dyConfig && Tools.getFirstChildBone(mode)) {
                                let lboneManager = Tools.getFirstChildBone(mode).getComponent(BoneManager);
                                if (!lboneManager) {
                                    lboneManager = Tools.getFirstChildBone(mode).addComponent(BoneManager);
                                }
                                lboneManager.addDynamicConfig(dyConfig, modelId);
                            }
                        }
                        else {
                            if (Tools.getFirstChildBone(mode)) {
                                let lboneManager = Tools.getFirstChildBone(mode).getComponent(BoneManager);
                                if (lboneManager) {
                                    lboneManager.removeDynamicConfig(mode.name);
                                }
                            }
                        }
                    }
                }
                else {
                    this.addChild(mode);
                    if (!partData.bEffectPart) {
                        mgrBoneBinder.relateModelBone(mode, this.boneBinderSerialNumber, !this.bPresetBoneBinderSerialNumber);
                        if (!this.bDisableDynamic) {
                            let dyConfig = mgrDynamicBone.getDynamicConfig(modelId);
                            if (dyConfig && this.bodyBoneManager)
                                this.bodyBoneManager.addDynamicConfig(dyConfig, modelId);
                        }
                        else {
                            this.bodyBoneManager && this.bodyBoneManager.isHaveConfig(mode.name) && this.bodyBoneManager.removeDynamicConfig(mode.name);
                        }
                    }
                }
                animator.enabled = true;
                if (!this.bDisableDressAnimation) {
                    partData.assignAnimation && this.playAnimation(partData.assignAnimation);
                }
                this.parts[partData.type].nodes.push({
                    node: mode,
                    animator: animator,
                });
                if (partData.type == PartType.face) {
                    this._adaptFaceTimeScale();
                }
                else if (partData.type == PartType.handHold) {
                    if (!this.isIdling()) {
                        this.hideShouChi();
                    }
                }
            }
            setDisableDressAnimationStatus(value) {
                this.bDisableDressAnimation = value;
            }
            setDisableRelateFaceBodyAni(value) {
                this.bDisableRelateFaceBodyAni = value;
            }
            setDisableAnimationWaitLoadPart(value) {
                this.context.bDisableAnimationWaitLoadPart = value;
            }
            setIdleId(bodyIdle, faceIdle, bPlayNow) {
                this.bodyDefaultIdleName = bodyIdle || this.bodyDefaultIdleName || ANIMATION_ID.idle;
                this.faceDefaultIdleName = faceIdle || this.faceDefaultIdleName || ANIMATION_ID.face.idle;
                if (bPlayNow) {
                    this.playDefaultIdleAnimation();
                }
            }
            playDefaultIdleAnimation() {
                this.playAnimation(this.bodyDefaultIdleName);
                this.playFaceAnimation(this.faceDefaultIdleName);
            }
            playToFaceNormalizedTime(shortAniName, faceNormalizedTime) {
                this.registerLoadEndCallback(() => {
                    let faceNode = this.getNodeByType(PartType.face);
                    if (faceNode && faceNode.getComponent(Laya.Animator)) {
                        let realAniId = this.getFaceRealAniIdByShortAniId(shortAniName);
                        if (realAniId) {
                            let animatorState = faceNode.getComponent(Laya.Animator).getControllerLayer(0).getAnimatorState(realAniId);
                            if (!!animatorState) {
                                faceNode.getComponent(Laya.Animator).play(realAniId, 0, faceNormalizedTime);
                            }
                            else {
                                console.warn("-------[ERROR]--playToFaceNormalizedTime---动画不存在");
                            }
                        }
                    }
                });
            }
            getFaceRealAniIdByShortAniId(shortAniName) {
                if (!shortAniName || shortAniName == "" || !this.context.roleId) {
                    return null;
                }
                let roleFaceAniConfig = mgrCfg.get("role_face_animation", this.context.roleId);
                if (!roleFaceAniConfig) {
                    return null;
                }
                return roleFaceAniConfig[shortAniName];
            }
            getRelateFaceAnimationByRoleBodyAnimationId(bodyAnimatinoId) {
                if (!this.context.roleId || !bodyAnimatinoId || this.bDisableRelateFaceBodyAni) {
                    return [];
                }
                let tmpArr = [];
                let roleFaceAniConfig = mgrCfg.get("role_face_animation", this.context.roleId);
                let faceConfig = mgrCfg.get("role_face_body_animation_relation_db", bodyAnimatinoId);
                if (faceConfig && roleFaceAniConfig) {
                    let timeToAid = {};
                    for (let k in faceConfig) {
                        if (k == "id") {
                            continue;
                        }
                        let aid = roleFaceAniConfig[k];
                        let time = faceConfig[k];
                        if (!aid || aid == "" || !time || time < 0) {
                            continue;
                        }
                        timeToAid[time] = aid;
                    }
                    for (let time in timeToAid) {
                        tmpArr.push({ aid: timeToAid[time], time: parseFloat(time) });
                    }
                    tmpArr = Tools.sortArrayByField(tmpArr, "time");
                }
                return tmpArr;
            }
            preinitAnimationArr(animationArr, initCompletedCallback, animator) {
                animator = animator || this.baseBodyAnimator;
                if (!animator) {
                    return false;
                }
                let index = 0;
                let onAnimationInitedFunc = null;
                let initAnimtaionFunc = null;
                onAnimationInitedFunc = () => {
                    if (index == (animationArr.length - 1)) {
                        if (initCompletedCallback) {
                            initCompletedCallback();
                        }
                    }
                    else {
                        index++;
                        initAnimtaionFunc();
                    }
                };
                initAnimtaionFunc = () => {
                    let animationId = animationArr[index];
                    let animationData = mgrCfg.get_from_animation_db(animationId);
                    let animatorState = animator.getControllerLayer(0).getAnimatorState(animationData.id);
                    if (!animatorState) {
                        Laya.AnimationClip.load(animationData.path, new Laya.Handler(this, (clip) => {
                            if (!animator || animator.destroyed || !animator.getControllerLayer(0)) {
                                return;
                            }
                            let __temp = animator.getControllerLayer(0).getAnimatorState(animationData.id);
                            if (__temp) {
                                onAnimationInitedFunc();
                                return;
                            }
                            animatorState = new Laya.AnimatorState();
                            animatorState.clip = clip;
                            animatorState.clipStart = 0;
                            animatorState.clipEnd = 1;
                            animatorState.name = animationData.id;
                            animator.getControllerLayer(0).addState(animatorState);
                            onAnimationInitedFunc();
                        }));
                    }
                    else {
                        onAnimationInitedFunc();
                    }
                };
                initAnimtaionFunc();
            }
            _playAnimatorAnimation(bFace, animationIdArr, mixFactor = 0.1, loadEndCallback, playEndCallback, isLooping, bDisableAllExitToIdle) {
                let animator;
                if (bFace) {
                    if (!this.parts[PartType.face] || !this.parts[PartType.face].nodes || !this.parts[PartType.face].nodes[0]) {
                        return;
                    }
                    animator = this.parts[PartType.face].nodes[0].animator;
                }
                else {
                    animator = this.baseBodyAnimator;
                }
                if (!animator || animator.destroyed || !animator.getControllerLayer(0)) {
                    return;
                }
                if (!(animationIdArr instanceof Array)) {
                    animationIdArr = [animationIdArr];
                }
                isLooping = isLooping || false;
                let animationId = animationIdArr[0];
                let animationData = mgrCfg.get_from_animation_db(animationId);
                if (!animationData) {
                    loadEndCallback && loadEndCallback(0);
                    playEndCallback && playEndCallback();
                    return;
                }
                if (bFace) {
                    this.playingFaceAnimationId = animationId;
                }
                else {
                    this.playingBodyAnimationId = animationId;
                    if (animationId.indexOf(this.SHOU_CHI_ANI_KEY_WORD) < 0) {
                        this.hideShouChi();
                    }
                    else {
                        this.showShouChi();
                    }
                }
                let execPlay = () => {
                    let tryAddCustomScript = (scriptAnimationIdArr, scriptPlayEndCallback) => {
                        let clip = animatorState.clip;
                        clip["_originIslooping"] = clip["_originIslooping"] || clip.islooping;
                        clip.islooping = scriptAnimationIdArr.length > 1 ? false : isLooping;
                        let script = animatorState.getScript(RoleAvatarAnimatorStateScript);
                        if (!script) {
                            script = animatorState.addScript(RoleAvatarAnimatorStateScript);
                        }
                        script.animationIdArr = scriptAnimationIdArr;
                        script.startPlayTime = Tools.time();
                        script.relationFaceAnimationArr = null;
                        if (!bFace && this.context.roleId) {
                            script.relationFaceAnimationArr = this.getRelateFaceAnimationByRoleBodyAnimationId(animationId);
                        }
                        script.fOnExitFunc = (aniIdArr) => {
                            aniIdArr.shift();
                            let playState = animator.getControllerLayer(0).getCurrentPlayState();
                            if (!playState || playState.animatorState.name != animatorState.name) {
                                return;
                            }
                            if (aniIdArr.length > 0) {
                                this._playAnimatorAnimation(bFace, aniIdArr, mixFactor, null, scriptPlayEndCallback, isLooping, bDisableAllExitToIdle);
                                return;
                            }
                            let idleName = !!bFace ? this.faceDefaultIdleName : this.bodyDefaultIdleName;
                            if (!bDisableAllExitToIdle) {
                                let __temp = animator.getControllerLayer(0).getAnimatorState(idleName);
                                if (!!__temp) {
                                    animator.play(idleName, 0, 0);
                                }
                                else {
                                    this._playAnimatorAnimation(bFace, idleName, undefined, undefined, undefined, true);
                                }
                            }
                            scriptPlayEndCallback && scriptPlayEndCallback();
                        };
                        script.fOnStartFunc = (aniIdArr) => {
                        };
                        script.fOnUpdateFunc = (aniIdArr) => {
                            if (!!bFace) {
                                return;
                            }
                            let relationFaceAnimationArr = script.relationFaceAnimationArr;
                            if (relationFaceAnimationArr && relationFaceAnimationArr.length > 0) {
                                let passedTime = Tools.time() - script.startPlayTime;
                                for (let i = 0; i < relationFaceAnimationArr.length; i++) {
                                    let data = relationFaceAnimationArr[i];
                                    if (passedTime >= data.time) {
                                        relationFaceAnimationArr.shift();
                                        this.playFaceAnimation(data.aid);
                                        break;
                                    }
                                }
                            }
                        };
                    };
                    let doLoadedPlay = () => {
                        tryAddCustomScript(animationIdArr, playEndCallback);
                        if (!mixFactor || mixFactor == 0) {
                            animator.play(animationId, 0, 0);
                        }
                        else {
                            animator.crossFade(animationId, mixFactor, 0);
                        }
                    };
                    let animatorState = animator.getControllerLayer(0).getAnimatorState(animationId);
                    if (!animatorState) {
                        Laya.AnimationClip.load(animationData.path, new Laya.Handler(this, (clip) => {
                            if (!animator || animator.destroyed || !animator.getControllerLayer(0)) {
                                return;
                            }
                            let __temp = animator.getControllerLayer(0).getAnimatorState(animationId);
                            if (__temp)
                                return;
                            animatorState = new Laya.AnimatorState();
                            animatorState.clip = clip;
                            animatorState.clipStart = 0;
                            animatorState.clipEnd = 1;
                            animatorState.name = animationId;
                            animator.getControllerLayer(0).addState(animatorState);
                            doLoadedPlay();
                            loadEndCallback && loadEndCallback(clip.duration() / this.timeScale);
                        }));
                    }
                    else {
                        doLoadedPlay();
                        let clip = animatorState.clip;
                        loadEndCallback && loadEndCallback(clip.duration() / this.timeScale);
                    }
                };
                if (!this.context.bDisableAnimationWaitLoadPart) {
                    this.registerLoadEndCallback(() => {
                        execPlay();
                    });
                }
                else {
                    execPlay();
                }
            }
            getCurrentPlayStateNormalizedTime() {
                if (!this.baseBodyAnimator || this.baseBodyAnimator.destroyed || !this.baseBodyAnimator.getControllerLayer(0)) {
                    return 0;
                }
                let playState = this.baseBodyAnimator.getControllerLayer(0).getCurrentPlayState();
                return playState.normalizedTime;
            }
            getCurrentPlayAnimatorStateName() {
                if (!this.baseBodyAnimator || this.baseBodyAnimator.destroyed || !this.baseBodyAnimator.getControllerLayer(0)) {
                    return null;
                }
                let playState = this.baseBodyAnimator.getControllerLayer(0).getCurrentPlayState();
                return playState.animatorState.name;
            }
            changeCurrentPlayAnimatorClipLoop(bLoop) {
                if (!this.baseBodyAnimator || this.baseBodyAnimator.destroyed || !this.baseBodyAnimator.getControllerLayer(0)) {
                    return null;
                }
                let playState = this.baseBodyAnimator.getControllerLayer(0).getCurrentPlayState();
                playState.animatorState.clip.islooping = bLoop;
                return true;
            }
            cleanCurrentPlayAnimationScriptData() {
                if (!this.baseBodyAnimator || this.baseBodyAnimator.destroyed || !this.baseBodyAnimator.getControllerLayer(0)) {
                    return;
                }
                let playState = this.baseBodyAnimator.getControllerLayer(0).getCurrentPlayState();
                if (!playState) {
                    return;
                }
                let script = playState.animatorState.getScript(RoleAvatarAnimatorStateScript);
                if (script) {
                    script.animationIdArr = [];
                    script.relationFaceAnimationArr = [];
                    script.fOnExitFunc = (aniIdArr) => { };
                    script.fOnStartFunc = (aniIdArr) => { };
                    script.fOnUpdateFunc = (aniIdArr) => { };
                }
                return;
            }
            isIdling() {
                let playingName = this.playingBodyAnimationId;
                if (!playingName || !this.bodyDefaultIdleName || playingName != this.bodyDefaultIdleName) {
                    return false;
                }
                return true;
            }
            playFaceAnimation(animationIdArr, mixFactor = 0.1, loadEndCallback, playEndCallback, isLooping, bDisableAllExitToIdle) {
                if (!(animationIdArr instanceof Array)) {
                    animationIdArr = [animationIdArr];
                }
                else if (animationIdArr.length == 0) {
                    return;
                }
                this._playAnimatorAnimation(true, ul.clone(animationIdArr), mixFactor, loadEndCallback, playEndCallback, isLooping, bDisableAllExitToIdle);
            }
            playRoleFaceAnimation(roleFaceMovFieldArr, mixFactor = 0.1, loadEndCallback, playEndCallback, isLooping, bDisableAllExitToIdle) {
                if (!this.context.roleId) {
                    return;
                }
                if (!(roleFaceMovFieldArr instanceof Array)) {
                    roleFaceMovFieldArr = [roleFaceMovFieldArr];
                }
                else if (roleFaceMovFieldArr.length == 0) {
                    return;
                }
                let animationIdArr = [];
                let roleFaceAniConfig = mgrCfg.get("role_face_animation", this.context.roleId);
                if (roleFaceAniConfig) {
                    for (let i = 0; i < roleFaceMovFieldArr.length; i++) {
                        animationIdArr.push(roleFaceAniConfig[roleFaceMovFieldArr[i]]);
                    }
                }
                if (animationIdArr.length == 0) {
                    if (loadEndCallback) {
                        loadEndCallback(0);
                    }
                    if (playEndCallback) {
                        playEndCallback();
                    }
                    return;
                }
                this.playFaceAnimation(animationIdArr, mixFactor, loadEndCallback, playEndCallback, isLooping, bDisableAllExitToIdle);
            }
            playAnimation(animationIdArr, mixFactor = 0.1, loadEndCallback, playEndCallback, isLooping, bDisableAllExitToIdle) {
                if (this.bPresetBoneBinderSerialNumber) {
                    return;
                }
                if (!(animationIdArr instanceof Array)) {
                    animationIdArr = [animationIdArr];
                }
                else if (animationIdArr.length == 0) {
                    return;
                }
                this._playAnimatorAnimation(false, ul.clone(animationIdArr), mixFactor, loadEndCallback, playEndCallback, isLooping, bDisableAllExitToIdle);
            }
            isCurAnimationId(animationId) {
                if (this.destroyed)
                    return;
                if (!this.baseBodyAnimator)
                    return;
                if (!this.baseBodyAnimator || this.baseBodyAnimator.destroyed || !this.baseBodyAnimator.getControllerLayer(0)) {
                    return;
                }
                return this.baseBodyAnimator.getControllerLayer(0).getCurrentPlayState().animatorState.name == animationId;
            }
            useCartonMaterial(model, modelId, modelMaterialNo, bForPlayerCustom) {
                let materials = mgrMaterial.setCustomMaterial(model, modelId, modelMaterialNo, !!bForPlayerCustom);
            }
            reload() {
                let oldPartIds = this.getPartIds();
                this.preDestroyRes();
                this.loadDefault(() => { });
                this.fillByPartIds(oldPartIds);
            }
            clear() {
                if (this.bLoadingPart)
                    return;
                let defaultPartIds = [];
                mgrCfg.forDb_from_part_type_db((k, v) => {
                    if (v.defaultPartId) {
                        defaultPartIds.push(v.defaultPartId);
                    }
                });
                let willDeleteKeys = [];
                for (const k in this.parts) {
                    let element = this.parts[k];
                    if (!element)
                        continue;
                    if (defaultPartIds.indexOf(element.partId) >= 0) {
                        continue;
                    }
                    let nodes = element.nodes;
                    for (let index = 0; index < nodes.length; index++) {
                        const node = nodes[index];
                        this.recoverModelSafe(node.node);
                    }
                    willDeleteKeys.push(k);
                }
                for (let i = 0; i < willDeleteKeys.length; i++) {
                    const key = willDeleteKeys[i];
                    this.parts[key] = null;
                }
                this.fillByPartIds(defaultPartIds);
                this.loadPart();
            }
            getPartIds(bAll = false) {
                let partIdDict = {};
                for (const k in this.parts) {
                    let element = this.parts[k];
                    if (element) {
                        let partData = mgrCfg.get_from_part_db(element.partId);
                        if (this.unloadedPartIds[partData.type]) {
                            partIdDict[this.unloadedPartIds[partData.type]] = true;
                        }
                        else {
                            partIdDict[element.partId] = true;
                        }
                    }
                }
                if (this.unloadedPartIds) {
                    for (let type in this.unloadedPartIds) {
                        partIdDict[this.unloadedPartIds[type]] = true;
                    }
                }
                let partIds = [];
                for (let tmpPartId in partIdDict) {
                    partIds.push(parseInt(tmpPartId));
                }
                return partIds;
            }
            linkMode2UpperArmLeft(model) {
                this.linkModel(model, "Guadian_UpperArm_L");
            }
            linkMode2UpperArmRight(model) {
                this.linkModel(model, "Guadian_UpperArm_R");
            }
            linkMode2Bip01(model) {
                this.linkModel(model, Const.BASE_BONE_NAME);
            }
            linkMode2Bip01Spine(model) {
                this.linkModel(model, `${Const.BASE_BONE_NAME} Spine`);
            }
            linkMode2GuaDianFoot(model) {
                this.linkModel(model, "Guadian_foot");
            }
            linkMode2EffectCloth(model) {
                this.linkModel(model, "Effect_cloth");
            }
            linkMode2EffectDress(model) {
                this.linkModel(model, "Effect_dress");
            }
            linkMode2EffectFoot(model) {
                this.linkModel(model, "Effect_foot");
            }
            linkMode2EffectSock(model) {
                this.linkModel(model, "Effect_sock");
            }
            linkMode2EffectHead(model) {
                this.linkModel(model, "Effect_head");
            }
            linkMode2EffectNeck(model) {
                this.linkModel(model, "Effect_neck");
            }
            linkMode2EffectEar(model) {
                this.linkModel(model, "Effect_ear");
            }
            linkMode2FashionShoeLeftFoot(model) {
                this.linkModel(model, "Guadian_fashion_shoe_left");
            }
            linkMode2FashionShoeRightFoot(model) {
                this.linkModel(model, "Guadian_fashion_shoe_right");
            }
            linkMode2BaseBody(model) {
                this.linkModel(model, this.baseBody.name);
            }
            linkModel(model, linkPointName) {
                if (!model || model.destroyed)
                    return;
                if (this.linkedModels.indexOf(model) >= 0 && this.linkedModel2Point[model.id] == linkPointName) {
                    this.unlinkModel(model);
                }
                this.linkedModels.push(model);
                this.linkedModel2Point[model.id] = linkPointName;
                if (this.bPresetBoneBinderSerialNumber) {
                    mgrBoneBinder.link2Node(linkPointName, model, this.boneBinderSerialNumber);
                }
                else {
                    Tools.link2Node(linkPointName, this.baseBody, model);
                }
            }
            unlinkModel(model, bDisableRecover) {
                if (!model)
                    return;
                let index = this.linkedModels.indexOf(model);
                if (index == -1)
                    return;
                this.linkedModels.splice(index, 1);
                if (!bDisableRecover) {
                    mgrLoader.Pool.recoverModel(model);
                }
                return true;
            }
            isLinkModel(model) {
                if (!model)
                    return false;
                let index = this.linkedModels.indexOf(model);
                if (index == -1)
                    return false;
                return true;
            }
            recoverModelSafe(model) {
                this.bodyBoneManager && this.bodyBoneManager.isHaveConfig(model.name) && this.bodyBoneManager.removeDynamicConfig(model.name);
                if (Tools.getFirstChildBone(model)) {
                    let lboneManager = Tools.getFirstChildBone(model).getComponent(BoneManager);
                    if (lboneManager) {
                        lboneManager.removeDynamicConfig(model.name);
                    }
                }
                if (!this.unlinkModel(model)) {
                    if (mgrLoader.Pool.recoverModel(model)) {
                        mgrBoneBinder.unbindModelBone(model);
                    }
                }
            }
            hideShouChi() {
                if (!this.parts || !this.parts[PartType.handHold] || !this.parts[PartType.handHold].nodes) {
                    return;
                }
                let nodes = this.parts[PartType.handHold].nodes;
                if (!nodes) {
                    return;
                }
                for (let i = 0; i < nodes.length; i++) {
                    const nodeInfo = nodes[i];
                    nodeInfo.node.active = false;
                }
            }
            showShouChi() {
                if (!this.parts || !this.parts[PartType.handHold] || !this.parts[PartType.handHold].nodes) {
                    return;
                }
                let nodes = this.parts[PartType.handHold].nodes;
                if (!nodes) {
                    return;
                }
                for (let i = 0; i < nodes.length; i++) {
                    const nodeInfo = nodes[i];
                    nodeInfo.node.active = true;
                }
            }
            hideShadow() {
                if (!this.roleShadow || this.roleShadow.destroyed) {
                    return;
                }
                this.roleShadow.active = false;
            }
            showShadow() {
                if (!this.roleShadow || this.roleShadow.destroyed) {
                    return;
                }
                this.roleShadow.active = true;
            }
            pause() {
                this.timeScale = 0;
            }
            resume() {
                this.timeScale = 1;
            }
            set timeScale(value) {
                this._timeScale = value;
                if (this.baseBodyAnimator) {
                    this.baseBodyAnimator.speed = this._timeScale;
                }
                this._adaptFaceTimeScale();
            }
            get timeScale() {
                return this._timeScale;
            }
            _adaptFaceTimeScale() {
                if (!this.context.bDisableFaceTimeScale) {
                    let faceNode = this.getNodeByType(PartType.face);
                    if (faceNode && faceNode.getComponent(Laya.Animator)) {
                        faceNode.getComponent(Laya.Animator).speed = this._timeScale;
                    }
                }
            }
            set randomDiscardFactor(value) {
            }
            getNodeByType(type) {
                if (!this.parts) {
                    return;
                }
                let info = this.parts[type];
                if (!info || !info.nodes || !info.nodes[0]) {
                    return;
                }
                return info.nodes[0].node;
            }
            getPartIdByType(type, bContainDefault = false) {
                let partIds = this.getPartIds();
                for (let k in partIds) {
                    let partData = mgrCfg.get_from_part_db(partIds[k]);
                    if (partData.type == type) {
                        let typeData = mgrCfg.get("part_type_db", type);
                        if (typeData.defaultPartId && partData.id == typeData.defaultPartId) {
                            if (bContainDefault) {
                                return partData.id;
                            }
                            continue;
                        }
                        return partData.id;
                    }
                }
                return 0;
            }
            set humanBoneIndex(index) {
                this._usingHumanBoneIndex = index;
                if (!this.baseBodyAnimator || !HumanBone.allHumanBoneScaleInfo || !HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME]) {
                    return;
                }
                this.baseBodyAnimator[`humanScaleInfo`] = HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][index];
            }
            get humanBoneIndex() {
                return this._usingHumanBoneIndex || 0;
            }
            tryShowLuckEffect() {
                let bLuckyed = false;
                let partIds = this.getPartIds();
                for (let k in partIds) {
                    let partId = partIds[k];
                    if (mgrPart.isDailyLuckyPart(partId)) {
                        bLuckyed = true;
                        break;
                    }
                }
                if (bLuckyed) {
                    this.showLuckEffect();
                }
                else {
                    this.hideLuckEffect();
                }
            }
            showLuckEffect() {
                if (!this.luckEffectModel) {
                    let effModel = mgrLoader.Pool.getModel(Const.ROLE_LUCKY_FULL_EFFECT_NAME);
                    effModel.transform.setWorldLossyScale(new Laya.Vector3(1.2, 1.2, 1.2));
                    this.addChild(effModel);
                    this.luckEffectModel = effModel;
                }
                this.luckEffectModel.active = true;
            }
            hideLuckEffect() {
                if (!this.luckEffectModel) {
                    return;
                }
                this.luckEffectModel.active = false;
            }
        }
        class RoleAvatarAnimatorStateScript extends Laya.AnimatorStateScript {
            constructor() {
                super();
                this._animationIdArr = [];
            }
            get animationIdArr() {
                return this._animationIdArr;
            }
            set animationIdArr(value) {
                this._animationIdArr = value || [];
            }
            onStateEnter() {
                if (this.fOnStartFunc) {
                    this.fOnStartFunc(this._animationIdArr);
                }
            }
            onStateUpdate() {
                if (this.fOnUpdateFunc) {
                    this.fOnUpdateFunc(this._animationIdArr);
                }
            }
            onStateExit() {
                if (this.fOnExitFunc) {
                    this.fOnExitFunc(this._animationIdArr);
                }
            }
        }

        const CAMERA_PRARAM_END = {
            fov: 30,
            position: new Laya.Vector3(0, 1.73, 4.25),
            rotation: new Laya.Vector3(-14),
            lerpValue: 0.1,
        };
        class vAdSuitDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAdSuitDialog";
                this.exportNodeNames = [];
                this.VIDEO_WARP_LOTTERY_SUIT_PART = "video_vHubScene_warp";
                this.spriteItemBgs = [];
            }
            onOpened() {
                super.onOpened();
                Timer.callLoop(0.5, () => {
                    if (!this || this.destroyed || this.__bClosing) {
                        return;
                    }
                    if (mgrGuide.isGuiding()) {
                        this.closeDialog(true);
                    }
                }, this);
                this.fillData();
                this.refreshUiByCop();
                this.widget();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.playOutUi();
                Timer.callLater(0.3, () => {
                    this.playInUi();
                }, this);
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGame);
            }
            playOutUi() {
            }
            playInUi() {
            }
            onClosed() {
                super.onClosed();
            }
            onAnimationFinished() {
            }
            fillData() {
                this.spriteLight.zOrder = -100;
                let adEventData = mgrCfg.get_from_ad_event_db(this.VIDEO_WARP_LOTTERY_SUIT_PART);
                if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                    mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                }
                this.spriteItemBgs = [
                    this.spriteItemBg1,
                    this.spriteItemBg2,
                    this.spriteItemBg3,
                    this.spriteItemBg4,
                    this.spriteItemBg5,
                    this.spriteItemBg6,
                    this.spriteItemBg7,
                    this.spriteItemBg8,
                ];
                let data = mgrCfg.get("ad_suit_config_db", 1);
                let suitIds = data.suitIds || [];
                let useSuitId = null;
                for (let i = 0; i < suitIds.length; i++) {
                    if (!mgrPart.isSuitCollectionCompleted(suitIds[i])) {
                        useSuitId = suitIds[i];
                    }
                }
                useSuitId = useSuitId || suitIds[0];
                let suitData = mgrCfg.get("suit_db", useSuitId);
                this.suitData = suitData;
                this.labelSuitName.text = `看视频获得：${suitData.name}套装`;
                this.avatar = new RoleAvatar({ roleId: suitData.roleId });
                this.add3DEffectAtBack(this.avatar, 0);
                this.avatar.setIdleId(suitData.showAnimationId || ANIMATION_ID.idle, suitData.showFaceAnimationId || ANIMATION_ID.face.idle);
                this.avatar.fillByPartIds(suitData.partIds);
                this.avatar.registerLoadEndCallback(() => {
                    this.avatar.playAnimation(suitData.showAnimationId || ANIMATION_ID.idle, 0, () => {
                        this.avatar.transform.rotationEuler = new Laya.Vector3(0, 0, 0);
                        this.avatar.transform.position = new Laya.Vector3;
                    }, null, true, true);
                    this.avatar.playRoleFaceAnimation(suitData.showFaceAnimationId || ANIMATION_ID.face.idle, 0, null, null, true, true);
                });
                let cf = this.cameraBack.getComponent(CameraFollow);
                cf.lookMode = E_CAMERA_MODE.fixMode;
                cf.fov = CAMERA_PRARAM_END.fov;
                cf.position = CAMERA_PRARAM_END.position;
                cf.endRotation = CAMERA_PRARAM_END.rotation;
                cf.lerpValue = 1;
                cf.onLateUpdate();
                cf.lerpValue = CAMERA_PRARAM_END.lerpValue;
                let validBgArr = [];
                for (let i = 0; i < 8; i++) {
                    let partId = this.suitData.partIds[i];
                    this.spriteItemBgs[i].visible = i < suitData.partIds.length ? true : false;
                    if (i < suitData.partIds.length) {
                        Tools.loadImg(this.spriteItemBgs[i].getChildByName("spriteIcon"), mgrPlayer.getIcon(partId));
                    }
                    if (this.spriteItemBgs[i].visible) {
                        validBgArr.push(this.spriteItemBgs[i]);
                    }
                }
                this.validBgArr = validBgArr;
                this.refreshOwnFlag();
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
            }
            refreshUiByCop() {
                this.buttonGiveUp.__node.visible = true;
                this.buttonClose.__node.visible = true;
            }
            refreshOwnFlag() {
                if (!this.suitData) {
                    return;
                }
                for (let i = 0; i < 8; i++) {
                    let partId = this.suitData.partIds[i];
                    let spriteOwnFlag = this.spriteItemBgs[i].getChildByName("spriteHad");
                    spriteOwnFlag.visible = (partId && mgrPlayer.getItemAmount(partId) > 0) ? true : false;
                }
            }
            doLotteryEffect(callback) {
                let soundTimer = Timer.callLoop(0.1, () => {
                    mgrSound.play(116);
                }, this);
                let count = Tools.random(10, 15);
                let ranCount = 0;
                Timer.callLoop(0.1, (timer) => {
                    if (ranCount >= count) {
                        soundTimer.stop();
                        timer.stop();
                        if (callback) {
                            callback();
                        }
                    }
                    ranCount++;
                    let index = Tools.random(0, this.validBgArr.length - 1);
                    this.validBgArr.forEach((v, i) => {
                        if (i == index) {
                            Tools.loadImg(v, "res/ui/room_zz/sprite_part_bg_select.png");
                        }
                        else {
                            Tools.loadImg(v, "res/ui/room_zz/sprite_part_bg.png");
                        }
                    });
                }, this);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.VIDEO_WARP_LOTTERY_SUIT_PART) {
                    this.buttonGiveUp.__node.visible = false;
                    this.buttonAd.__node.visible = false;
                    this.doLotteryEffect(() => {
                        this.refreshOwnFlag();
                        let bGotPart = false;
                        for (let k in this.suitData.partIds) {
                            let partId = this.suitData.partIds[k];
                            if (mgrPlayer.getItemAmount(partId) <= 0) {
                                bGotPart = true;
                                mgrPlayer.addItemAmount(partId, 1, "广告抽取套装");
                                mgrTip.addGotItemTip(partId, 1, null, {
                                    fOnClose: () => {
                                        if (this.context.fOnAdResult) {
                                            this.context.fOnAdResult(true);
                                        }
                                        this.closeDialog();
                                    }
                                });
                                break;
                            }
                        }
                        if (!bGotPart) {
                            if (this.context.fOnAdResult) {
                                this.context.fOnAdResult(true);
                            }
                            this.closeDialog();
                        }
                    });
                }
            }
            onTouchButtonClose() {
                this.onTouchButtonGiveUp();
            }
            onTouchButtonGiveUp() {
                let doClose = () => {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(false);
                    }
                    this.closeDialog();
                };
                doClose();
            }
            onTouchButtonAd() {
                mgrAd.triggerAdEvent(this.VIDEO_WARP_LOTTERY_SUIT_PART, null, true);
            }
        }

        class vAdTurntableDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAdTurntableDialog";
                this.suitId = 0;
                this.items = [];
                this.ITEM_NUM = 10;
                this.itemArr = [];
                this.INDEX_TO_ITEM = {
                    1: 1,
                    3: 2,
                    5: 3,
                    7: 4,
                    9: 5,
                    2: 6,
                    4: 7,
                    6: 8,
                    8: 9,
                    10: 10,
                };
                this.bTurning = false;
                this.costNum = 10;
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.buildUi();
                this.refreshButtons();
                this.fillData();
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                let lotteryData = mgrCfg.get_from_pvp_offline_lottery_db(1);
                this.costNum = lotteryData.costNum;
                let suitIdArr = lotteryData.suitIdArr;
                if (suitIdArr && suitIdArr.length > 0) {
                    for (let i = 0; i < suitIdArr.length; i++) {
                        let partIds = mgrCfg.get_from_suit_db(suitIdArr[i]).partIds;
                        let bOwned = true;
                        for (let j = 0; j < partIds.length; j++) {
                            if (mgrPlayer.getItemAmount(partIds[j]) <= 0) {
                                bOwned = false;
                            }
                        }
                        if (!bOwned) {
                            this.suitId = suitIdArr[i];
                            break;
                        }
                    }
                }
                if (this.suitId) {
                    let partIds = mgrCfg.get_from_suit_db(this.suitId).partIds;
                    partIds.forEach(v => {
                        this.items.push({ itemId: v, amount: 1 });
                    });
                    while (this.items.length < this.ITEM_NUM) {
                        this.items.push({ itemId: 1, amount: Tools.random(lotteryData.diamondRange[0], lotteryData.diamondRange[1]) });
                    }
                }
                else {
                    let scatterPartIdArr = lotteryData.scatterPartIdArr;
                    let resetPartIds = [];
                    scatterPartIdArr.forEach(v => {
                        if (mgrPlayer.getItemAmount(v) <= 0) {
                            resetPartIds.push(v);
                        }
                    });
                    resetPartIds.forEach(v => {
                        this.items.push({ itemId: v, amount: 1 });
                    });
                    if (this.items.length > this.ITEM_NUM) {
                        this.items = this.items.splice(0, this.ITEM_NUM);
                    }
                    else if (this.items.length < this.ITEM_NUM) {
                        while (this.items.length < this.ITEM_NUM) {
                            this.items.push({ itemId: 1, amount: Tools.random(lotteryData.diamondRange[0], lotteryData.diamondRange[1]) });
                        }
                    }
                }
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (this.buttonBuy.__node.visible && mgrSdk.getCopNumberValueByKey("b_vAdTurntableDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                    if (mgrSdk.getCopNumberValueByKey("b_vAdTurntableDialog_trigger_native_banner") == 1) {
                        this.buttonCancel.__node.visible = false;
                        this.boxBtns.x = 330;
                    }
                }, this);
            }
            widget() {
                mgrLayout.widgetBottomMC(this.boxBtns);
                mgrLayout.widgetBottomMC(this.buttonTriggerNativeBanner.__node);
            }
            refreshButtons() {
                this.buttonCancel.__node.visible = true;
                this.buttonClose.__node.visible = true;
                this.buttonBuy.__node.visible = false;
                this.buttonAd.__node.visible = false;
                this.buttonTriggerNativeBanner.__node.visible = false;
                if (mgrPlayer.getItemAmount(Const.ITEM_ID_TURNTABLE_COUNT) > 0) {
                    this.buttonBuy.__node.visible = true;
                }
                else {
                    this.buttonAd.__node.visible = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAdTurntableDialog_free);
                    if (mgrPlayer.getItemAmount(Const.ITEM_ID_TURNTABLE_COUNT) <= 0) {
                        let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAdTurntableDialog_free);
                        if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                            mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                        }
                    }
                }
                if (mgrPlayer.getItemAmount(Const.ITEM_ID_TURNTABLE_COUNT) <= 0 && !mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAdTurntableDialog_free)) {
                    this.closeDialog();
                }
            }
            fillData() {
                this.itemArr = [
                    this.spriteItem1,
                    this.spriteItem3,
                    this.spriteItem5,
                    this.spriteItem7,
                    this.spriteItem9,
                    this.spriteItem2,
                    this.spriteItem4,
                    this.spriteItem6,
                    this.spriteItem8,
                    this.spriteItem10,
                ];
                for (let i = 0; i < this.ITEM_NUM; i++) {
                    let icon = mgrPlayer.getIcon(this.items[i].itemId);
                    icon && Tools.loadImg(this.itemArr[i], icon);
                    let labelAmout = this.itemArr[i].getChildByName("labelAmout");
                    labelAmout.text = `x${this.items[i].amount}`;
                    labelAmout.visible = mgrPlayer.getItemAmount(this.items[i].itemId) <= 0;
                    let spriteHad = this.itemArr[i].getChildByName("spriteHad");
                    spriteHad.visible = mgrPlayer.getItemAmount(this.items[i].itemId) > 0;
                    if (this.items[i].itemId == Const.ITEM_ID_DIAMONDS) {
                        labelAmout.visible = true;
                        spriteHad.visible = false;
                    }
                }
            }
            refreshHad() {
                for (let i = 0; i < this.ITEM_NUM; i++) {
                    if (this.items[i].itemId != Const.ITEM_ID_DIAMONDS) {
                        let labelAmout = this.itemArr[i].getChildByName("labelAmout");
                        labelAmout.visible = mgrPlayer.getItemAmount(this.items[i].itemId) <= 0;
                        let spriteHad = this.itemArr[i].getChildByName("spriteHad");
                        spriteHad.visible = mgrPlayer.getItemAmount(this.items[i].itemId) > 0;
                    }
                }
            }
            doTurn(bAd) {
                if (!bAd) {
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, -this.costNum, "转盘钻石消耗");
                    mgrPlayer.addItemAmount(Const.ITEM_ID_TURNTABLE_COUNT, -1, "转盘次数消耗");
                }
                this.bTurning = true;
                let unitAngle = 360 / 10;
                let randomUnitNum = Tools.randomGotOneArrayData([30, 40]);
                let filterRepeatIndexArr = [];
                for (let key in this.INDEX_TO_ITEM) {
                    let itemData = this.items[this.INDEX_TO_ITEM[key] - 1];
                    if (itemData.itemId == Const.ITEM_ID_DIAMONDS) {
                        filterRepeatIndexArr.push(parseInt(key));
                    }
                    else {
                        if (mgrPlayer.getItemAmount(itemData.itemId) <= 0) {
                            filterRepeatIndexArr.push(parseInt(key));
                        }
                    }
                }
                randomUnitNum += Tools.randomGotOneArrayData(filterRepeatIndexArr) - 1;
                let itemIndex = this.INDEX_TO_ITEM[(randomUnitNum % 10) + 1];
                let allAngle = unitAngle * randomUnitNum;
                let curAngle = 0;
                let originSpeed = 1200;
                let finalSpeed = 100;
                let soundTimer = Timer.callLoop(0.1, () => {
                    mgrSound.play(116);
                }, this);
                Timer.callLoop(0.016, (timer) => {
                    let speed = originSpeed;
                    speed = (allAngle - curAngle) / allAngle * originSpeed;
                    speed = Math.max(speed, finalSpeed);
                    curAngle += speed * 0.016;
                    curAngle = Math.min(allAngle, curAngle);
                    this.spritePointer.rotation = curAngle % 360;
                    if (curAngle == allAngle) {
                        soundTimer.stop();
                        this.bTurning = false;
                        mgrPlayer.addItemAmount(this.items[itemIndex - 1].itemId, this.items[itemIndex - 1].amount, "转盘抽奖");
                        mgrTip.addGotItemTip(this.items[itemIndex - 1].itemId, this.items[itemIndex - 1].amount);
                        timer.stop();
                        this.refreshHad();
                        this.refreshButtons();
                    }
                }, this);
            }
            onTouchButtonCancel() {
                this.onTouchButtonClose();
            }
            onTouchButtonAd() {
                if (!this.bTurning) {
                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAdTurntableDialog_free, null, true);
                }
            }
            onTouchButtonBuy() {
                if (!this.bTurning) {
                    if (mgrPlayer.getItemAmount(Const.ITEM_ID_DIAMONDS) < this.costNum) {
                        mgrTip.showMsgTip("货币不足！");
                        return;
                    }
                    this.doTurn(false);
                }
            }
            onTouchButtonClose() {
                if (this.bTurning) {
                    mgrTip.showMsgTip("别着急啊");
                    return;
                }
                this.closeDialog();
            }
            onTouchButtonRatioTip() {
                mgrTip.alertPrompt1("概率公示", "转盘中的10个物品的获得概率均为10%", "确定");
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAdTurntableDialog_free) {
                    this.doTurn(true);
                }
            }
        }

        class vAdvancedSettingDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAdvancedSettingDialog";
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            buildUi() {
                let config = [];
                try {
                    let copConfig = mgrCop.get("s_client_advancced_setting_config");
                    let data = JSON.parse(copConfig);
                    for (let i = 0; i < data.length; i++) {
                        const v = data[i];
                        config.push({ text: v[0], url: v[1] });
                    }
                }
                catch (error) {
                    console.log("解析cop数据出错，跳过");
                }
                for (let i = 0; i < 6; i++) {
                    let button = this["button" + (i + 1)];
                    let label = this["label" + (i + 1)];
                    let data = config[i];
                    if (data) {
                        button.__node.visible = true;
                        label.text = data.text;
                        while (label.width > 280) {
                            label.fontSize--;
                        }
                        button.__node["_url"] = data.url;
                    }
                    else {
                        button.__node.visible = false;
                    }
                }
            }
            onTouchButton(button) {
                let url = button["_url"];
                console.log("onClick", url);
                if (url == "CLEAR_RECORD") {
                }
                else {
                    mgrSdk.ulWebView(url);
                }
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButton1() {
                this.onTouchButton(this.button1);
            }
            onTouchButton2() {
                this.onTouchButton(this.button2);
            }
            onTouchButton3() {
                this.onTouchButton(this.button3);
            }
            onTouchButton4() {
                this.onTouchButton(this.button4);
            }
            onTouchButton5() {
                this.onTouchButton(this.button5);
            }
            onTouchButton6() {
                this.onTouchButton(this.button6);
            }
        }

        class vAgeTipDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAgeTipDialog";
            }
            onOpened() {
                super.onOpened();
                let baseChannelInfo = mgrSdk.baseChannelInfo || null;
                if (baseChannelInfo && baseChannelInfo.ageLevelInfo) {
                    this.labelContent.text = `${baseChannelInfo.ageLevelInfo}`;
                }
                this.button1.fOnClick = this.onTouchButton1.bind(this);
                this.buttonClose.fOnClick = this.onTouchButtonClose.bind(this);
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButton1() {
                this.closeDialog();
            }
        }

        class vTopBar extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vTopBar";
                this.exportNodeNames = [];
                this.anchorX = 0;
                this.anchorY = 0;
                this.width = 300;
                this.height = 32;
            }
            onOpened() {
                this.widget();
                this.fadeIn();
                this.buildUI();
                this.fillData();
                this.registerListeners({
                    MSG_ITEM_AMOUNT_CHANGED: this.onMsgItemAmountChanged.bind(this),
                    MSG_ENERGY_FLY_END: this.onMsgEnergyFlyEnd.bind(this),
                    MSG_Diamond_FLY_END: this.onMsgDiamondFlyEnd.bind(this),
                });
                if (!!this.context.bDisableDiamond) {
                    this.hideDiamond();
                }
                if (!!this.context.bDisableEnergy) {
                    this.hideEnergy();
                }
                this.spriteAddDiamond.visible = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vHubScene_free_diamon);
                this.spriteAddEnergy.visible = false;
            }
            onClosed() {
            }
            widget() {
            }
            fadeIn() { }
            buildUI() {
                Tools.loadImg(this.imageDiamondIcon, mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS).icon);
            }
            fillData() {
                this.labelDiamondCount.text = `${mgrPlayer.getItemAmount(Const.ITEM_ID_DIAMONDS)}`;
                this.labelEnergyCount.text = `${mgrPlayer.getItemAmount(Const.ITEM_ID_ENERGY)}/${mgrPlayer.getItemAmount(Const.ITEM_ID_ENERGY_MAX)}`;
                this.refreshTime();
                Timer.callLoop(1, this.refreshTime.bind(this), this);
            }
            refreshTime() {
                if (!this.labelEnergyRecoverTime) {
                    return;
                }
                let recoverRemainTime = mgrPlayer.getRecoverRemainTime(Const.ITEM_ID_ENERGY);
                if (recoverRemainTime) {
                    let minute = Math.floor(recoverRemainTime / 60);
                    let second = recoverRemainTime % 60;
                    this.labelEnergyRecoverTime.visible = true;
                    this.labelEnergyRecoverTime.text = ul.format("%d:%02d", minute, second);
                }
                else {
                    this.labelEnergyRecoverTime.visible = false;
                }
            }
            onMsgItemAmountChanged(data) {
                this.fillData();
            }
            onMsgEnergyFlyEnd() {
                CustomTween.to(this.imageEnergyIcon, { scaleX: 1.1, scaleY: 1.1 }, 100).to({ scaleX: 1, scaleY: 1 }, 100).start(1);
            }
            onMsgDiamondFlyEnd() {
                CustomTween.to(this.imageDiamondIcon, { scaleX: 1.1, scaleY: 1.1 }, 100).to({ scaleX: 1, scaleY: 1 }, 100).start(1);
            }
            onTouchButtonDiamond() {
                if (mgrGuide.isGuiding())
                    return;
                if (this.lastClickTime && (Tools.time() - this.lastClickTime) < 1) {
                    return;
                }
                this.lastClickTime = Tools.time();
                if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vHubScene_free_diamon)) {
                    mgrDirector.openDialog(`vLuckDiamondDialog`);
                }
            }
            onTouchButtonEnergy() {
                if (mgrGuide.isGuiding())
                    return;
                if (!this.spriteAddEnergy.visible)
                    return;
                if (this.lastClickTime && (Tools.time() - this.lastClickTime) < 1) {
                    return;
                }
                this.lastClickTime = Tools.time();
                if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vHubScene_free_energy)) {
                    mgrDirector.openDialog(`vLuckEnergyDialog`);
                }
            }
            hideDiamond() {
                this.imageDiamond.visible = false;
            }
            showDiamond() {
                this.imageDiamond.visible = true;
            }
            hideEnergy() {
                this.imageEnergy.visible = false;
            }
        }

        class vAmuseCakePreviewDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCakePreviewDialog";
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.initUi();
                this.widget();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            buildUi() {
                this.topBar = new vTopBar({ bDisableDiamond: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseCakePreviewDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            initUi() {
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let stageId = this.context.stageId || 1;
                console.warn("----stageId=", stageId);
                this.stageData = mgrCfg.get_from_cake_stage_db(stageId);
                this.labelStagePreview.text = this.stageData.stageDesc || "";
                this.labelRoleName.text = roleData.name;
                Tools.loadImg(this.spriteRoleIcon, roleData.halfBodyIcon);
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                this.labelItemAmount1.text = `+${this.stageData.bestRewardRmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.cake);
                let itemData = mgrCfg.get_from_item_template_db(rewardPartId);
                if (!!itemData && itemData.type) {
                    let itemTypeData = mgrCfg.get_from_item_type_db(itemData.type);
                    Tools.loadImg(this.spriteItemIcon2, itemTypeData.iconTcutShot);
                    this.labelItemAmount2.text = `+${this.stageData.bestRewardColorPoint}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonStart() {
                let count = 1;
                let bRet = mgrShop.tryConsumeItem(Const.ITEM_ID_ENERGY, count, "蛋糕烘焙");
                if (bRet) {
                    mgrTip.addGotItemTip(Const.ITEM_ID_ENERGY, -count);
                    mgrWorldDaily.cleanGameTempParms(DailyGameType.cake);
                    mgrWorldDaily.addPlayedGameStageId(DailyGameType.cake, this.context.stageId);
                    mgrDirector.warpSceneWidthEffect("vAmuseCakeMakeScene", this.context);
                    if (this.context.fOnStart) {
                        this.context.fOnStart();
                    }
                    this.closeDialog();
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vAmuseCakePreviewVipDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCakePreviewVipDialog";
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.buildUi();
                this.initUi();
            }
            onAnimationFinished() {
            }
            buildUi() {
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseCakePreviewVipDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            initUi() {
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let stageId = this.context.stageId || 1;
                console.warn("----stageId=", stageId);
                this.stageData = mgrCfg.get_from_cake_stage_db(stageId);
                this.labelStagePreview.text = this.stageData.stageDesc || "";
                this.labelRoleName.text = roleData.name;
                Tools.loadImg(this.spriteRoleIcon, roleData.halfBodyIcon);
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                this.labelItemAmount1.text = `+${this.stageData.bestRewardRmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.cake);
                let partData = mgrCfg.get_from_item_template_db(rewardPartId);
                if (!!partData && partData.type) {
                    let partTypeData = mgrCfg.get_from_item_type_db(partData.type);
                    Tools.loadImg(this.spriteItemIcon3, partTypeData.iconTcutShot);
                    this.labelItemAmount3.text = `+${this.stageData.bestRewardColorPoint}`;
                }
                else {
                    this.spriteItem3.visible = false;
                }
                let vipPartId = mgrWorldDaily.getUnownedVipPart(DailyGameType.cake);
                let partDataVip = mgrCfg.get_from_item_template_db(vipPartId);
                this.vipPartId = vipPartId;
                if (!!partDataVip && partDataVip.type) {
                    Tools.loadImg(this.spriteItemIcon2, partDataVip.icon);
                    let typeData = mgrCfg.get_from_item_type_db(partDataVip.type);
                    this.labelItemAmount2.text = `+${typeData.name}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
                if (mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.cake)) {
                    this.buttonGetNormal.__node.visible = false;
                    this.spriteAdFlag.visible = false;
                }
            }
            onClosed() {
                super.onClosed();
            }
            onAdded() {
                mgrWorldDaily.cleanGameTempParms(DailyGameType.cake);
                mgrWorldDaily.addPlayedGameStageId(DailyGameType.cake, this.context.stageId);
                this.context.bVip = true;
                mgrDirector.warpSceneWidthEffect("vAmuseCakeMakeScene", this.context);
                if (this.context.fOnStart) {
                    this.context.fOnStart();
                }
                this.closeDialog();
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonAdAreaScreen() {
            }
            onTouchButtonGetNormal() {
                if (!!this.context.fOnGiveUp) {
                    this.context.fOnGiveUp();
                }
                this.closeDialog();
            }
            onTouchButtonGetAd() {
                if (mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.cake)) {
                    this.onAdded();
                }
                else {
                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakePreviewVipDialog_vip, null, true);
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseCakePreviewVipDialog_vip) {
                    this.onAdded();
                }
            }
        }

        class vAmuseCakeResultDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCakeResultDialog";
                this.PER_CLICK_COLORPOINT = 50;
                this.MAX_CLICK_COUNT = 5;
                this.perClick2ColorPointDict = {};
                this.sizeTcutBg = [1, 1];
                this.sizeTcutFill = [1, 1];
                this.iconTcutBg = "";
                this.iconTcutFill = "";
                this.unlockColorPoint = 99999;
                this.filledCount = 0;
                this.dailyGameType = this.context.dailyGameType || DailyGameType.cake;
                if (!!this.context.rewardPartId) {
                    let tcutImgData = null;
                    let partData = null;
                    let partId = this.context.rewardPartId;
                    partData = mgrCfg.get_from_item_template_db(partId);
                    this.unlockColorPoint = partData.unlockColorPoint || 0;
                    if (!!partData && partData.type) {
                        tcutImgData = mgrCfg.get_from_item_type_db(partData.type);
                        if (!tcutImgData) {
                            tcutImgData = mgrCfg.get_from_world_daily_quest_config(this.dailyGameType);
                        }
                    }
                    if (!!tcutImgData) {
                        this.sizeTcutBg = tcutImgData.sizeTcutBg;
                        this.sizeTcutFill = tcutImgData.sizeTcutFill;
                        this.iconTcutBg = tcutImgData.iconTcutBg;
                        this.iconTcutFill = tcutImgData.iconTcutFill;
                    }
                }
                let leftColorPoint = this.context.oldColorPoint + this.context.currGotColorPoint;
                let perClickColorPoint = this.PER_CLICK_COLORPOINT;
                if (perClickColorPoint < leftColorPoint && Math.ceil(leftColorPoint / perClickColorPoint) > this.MAX_CLICK_COUNT) {
                    perClickColorPoint = Math.ceil(leftColorPoint / this.MAX_CLICK_COUNT);
                }
                for (let i = 0; i < this.MAX_CLICK_COUNT; i++) {
                    if (!leftColorPoint) {
                        break;
                    }
                    if (leftColorPoint >= perClickColorPoint) {
                        this.perClick2ColorPointDict[i] = perClickColorPoint;
                        leftColorPoint -= perClickColorPoint;
                    }
                    else {
                        this.perClick2ColorPointDict[i] = leftColorPoint;
                        leftColorPoint = 0;
                    }
                }
            }
            getPreLoadModelIds() {
                return [
                    "117_ui_loop_trailparticle_pink",
                    "116_ui_once_bao_02"
                ];
            }
            getPreLoadImagePaths() {
                let arr = [];
                if (!!this.iconTcutBg) {
                    arr.push(this.iconTcutBg);
                }
                if (!!this.iconTcutFill) {
                    arr.push(this.iconTcutFill);
                }
                return arr;
            }
            onOpened() {
                super.onOpened();
                this.nativeBanner = mgrActivingBanner.activingAlertBanner(5, this);
                this.buildUi();
                this.initUi();
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseCakeResultDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onAnimationFinished() {
                if (!this.context.rewardPartId) {
                    return;
                }
                let totalGotValue = this.context.currGotColorPoint || 0;
                let gotColorValueDict = {};
                let perValue = Math.ceil(totalGotValue / 7);
                for (let i = 1; i <= 7; i++) {
                    let useValue = perValue;
                    if (useValue * i > totalGotValue) {
                        useValue = totalGotValue - useValue * (i - 1);
                    }
                    gotColorValueDict[i] = useValue;
                }
                let holderSprite = this.spriteShine;
                for (let i = 1; i <= 7; i++) {
                    let sprite = this["spriteColor" + i];
                    let effModel = mgrLoader.Pool.getModel("117_ui_loop_trailparticle_pink");
                    this.add3DEffectAtFront(effModel, sprite, 2);
                    sprite['__tmpEffModel'] = effModel;
                    cc.tween(sprite)
                        .delay(0.1 * i)
                        .toPos(0.2, holderSprite.x, holderSprite.y)
                        .call(() => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        sprite.alpha = 0;
                        mgrLoader.Pool.recoverModel(sprite['__tmpEffModel']);
                        this.add3DEffectAtFront("116_ui_once_bao_02", this.spriteShine, 1);
                    })
                        .start();
                }
                mgrSound.play(611);
                let oldOwnedColorPoint = mgrPart.getPartColorOwnPoint(this.context.rewardPartId);
                let allPoint = mgrPlayer.getItemAmount(this.context.colorItemId);
                mgrPart.addPartColorOwnPoint(this.context.rewardPartId, allPoint);
                mgrPlayer.addItemAmount(this.context.colorItemId, -allPoint, "填充时减掉颜色值");
                let currOwnedColorPoint = mgrPart.getPartColorOwnPoint(this.context.rewardPartId);
                let startProgress = ul.clamp(oldOwnedColorPoint / (this.unlockColorPoint || 1), 0, 1);
                let targetProgress = ul.clamp(currOwnedColorPoint / (this.unlockColorPoint || 1), 0, 1);
                let labelProgress = Math.floor(targetProgress * 100);
                this.progressBarCurr.progress = startProgress;
                Timer.callLater(0.3, () => {
                    this.progressBarCurr.progressTweenTo(0.6, targetProgress, startProgress, 0, () => {
                        this.labelProgress.text = `${labelProgress}%`;
                        let bArrived = mgrPart.isPartOwnColorPointEnough(this.context.rewardPartId);
                        if (bArrived) {
                            mgrPlayer.addItemAmount(this.context.rewardPartId, 1, "颜色填充界面填满后获得");
                            let oldCloseFunc = this.context.fOnClose;
                            this.context.fOnClose = () => {
                                mgrTip.addGotItemTip(this.context.rewardPartId, 1, null, {
                                    fOnClose: () => {
                                        oldCloseFunc && oldCloseFunc();
                                    }
                                });
                            };
                            this.labelBack.text = "收下";
                        }
                        else {
                            this.labelBack.text = "确认";
                        }
                        this.startGuide();
                    }, (value) => {
                        this.labelProgress.text = `${Math.floor(value * 100)}%`;
                    });
                }, this);
            }
            buildUi() {
                this.spriteLuckyTitle.visible = false;
                this.spriteWaitNext.visible = false;
                if (!this.context.rewardPartId) {
                    this.spriteProgressBg.visible = false;
                    this.labelProgress.visible = false;
                    this.spriteWillGotWord.visible = false;
                    this.spriteWaitNext.visible = true;
                    return;
                }
                else {
                    let spriteCurr = this.progressBarCurr.__node;
                    this.spriteProgressBg.size(this.sizeTcutBg[0], this.sizeTcutBg[1]);
                    spriteCurr.size(this.sizeTcutFill[0], this.sizeTcutFill[1]);
                    Tools.loadImg(this.spriteProgressBg, this.iconTcutBg);
                    Tools.loadImg(spriteCurr, this.iconTcutFill, false, () => {
                        this.spriteProgressBg.x = (this.spriteProgressBg.parent.width - this.sizeTcutBg[0]) / 2;
                        let currX = (this.sizeTcutBg[0] - this.sizeTcutFill[0]) / 2;
                        let currY = (this.sizeTcutBg[1] - this.sizeTcutFill[1]) / 2;
                        spriteCurr.pos(currX, currY);
                        this.progressBarCurr.barName = this.progressBarCurr.owner.name;
                        this.progressBarCurr.style = ULPROGRESSBAR_STYLE.ver;
                        this.progressBarCurr.progress = mgrPart.getPartColorOwnPoint(this.context.rewardPartId) / (this.unlockColorPoint || 1);
                        this.labelProgress.text = `${Math.floor(this.progressBarCurr.progress * 100)}%`;
                    });
                }
            }
            initUi() {
                mgrEffect.rotateForever(this.spriteShine);
            }
            startGuide() {
                mgrGuide.registerGuideNode("vAmuseCakeResultDialog.buttonBack", this.buttonBack.__node);
                if (mgrGuide.isFinished(803) && !mgrGuide.isFinished(340)) {
                    mgrGuide.startGuide(340);
                }
                else if (!mgrGuide.isFinished(330)) {
                    mgrGuide.startGuide(330);
                }
            }
            onClosed() {
                super.onClosed();
                if (this.nativeBanner) {
                    this.nativeBanner.activingBannerClose();
                    this.nativeBanner = null;
                }
            }
            onTouchButtonBack() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeResultDialog.buttonBack.click` });
                this.closeDialog();
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        var List = Laya.List;
        var Handler = Laya.Handler;
        class ReuseList extends Laya.Box {
            constructor(repeatX, repeatY, maxRepeat) {
                super();
                this.index = 0;
                this.pos(0, 0);
                this.bLoop = false;
                this.repeatX = repeatX;
                this.repeatY = repeatY;
                this.maxRepeat = maxRepeat;
                this.list = new List();
                this.list.elasticEnabled = false;
                this.addChild(this.list);
            }
            setItemClass(itemClass) {
                this.list.itemRender = itemClass;
                this.setup();
            }
            setup() {
                this.x = 0;
                this.y = 0;
                this.list.x = 0;
                this.list.y = 0;
                this.list.selectEnable = true;
                this.list.selectHandler = new Handler(this, this.onSelect);
                this.list.renderHandler = new Handler(this, this.updateItem);
            }
            setDatas(datas) {
                let oldScroll = this.scrollValue;
                this.datas = datas;
                if ((this.repeatX != 0 && this.repeatY != 0) || (this.repeatX == 0 && this.repeatY == 0))
                    return;
                let colNumber = this.repeatX || this.repeatY;
                let rowNumber = Math.ceil(this.datas.length / colNumber);
                this.maxIndex = rowNumber - this.maxRepeat;
                if (this.repeatX) {
                    this.list.repeatX = colNumber;
                    this.list.repeatY = rowNumber > this.maxRepeat ? this.maxRepeat : rowNumber;
                    console.log("repeatX, repeatY:", this.list.repeatX, this.list.repeatY);
                }
                else {
                    this.list.repeatX = rowNumber > this.maxRepeat ? this.maxRepeat : rowNumber;
                    this.list.repeatY = colNumber;
                    console.log("repeatX, repeatY:", this.list.repeatX, this.list.repeatY);
                }
                this.list.array = datas;
                this.list.height = this.height;
                this.list.width = this.width;
                this.setScroll(oldScroll);
            }
            getDatas() {
                return this.datas;
            }
            updateItem(cell, index) {
                cell.fillByData(cell.dataSource);
            }
            onSelect(index) {
                let cell = this.list.getCell(index);
                cell.onSelect(this.datas[index]);
            }
            scrollTo(index) {
                this.index = index;
                this.list.scrollTo(index);
            }
            tweenTo(index, time = 300) {
                this.index = index;
                this.list.tweenTo(index, time);
            }
            setHorizontalMoveEnable(b) {
                this.list.hScrollBarSkin = b ? "" : null;
            }
            setVerticalMoveEnable(b) {
                this.list.vScrollBarSkin = b ? "" : null;
            }
            tweenToNext(time = 300) {
                this.index++;
                if (this.bLoop) {
                    this.index = this.index > this.maxIndex ? 0 : this.index;
                }
                else {
                    this.index = this.index > this.maxIndex ? this.maxIndex : this.index;
                }
                this.list.tweenTo(this.index, time);
            }
            tweenToLast(time = 300) {
                this.index--;
                if (this.bLoop) {
                    this.index = this.index < 0 ? this.maxIndex : this.index;
                }
                else {
                    this.index = this.index < 0 ? 0 : this.index;
                }
                this.list.tweenTo(this.index, time);
            }
            setTouchEnable(b) {
                this.list.scrollBar.touchScrollEnable = b;
                this.list.scrollBar.mouseWheelEnable = b;
            }
            refresh() {
                this.list.refresh();
            }
            setSpaceX(value) {
                this.list.spaceX = value;
            }
            setSpaceY(value) {
                this.list.spaceY = value;
            }
            setLoop(b) {
                this.bLoop = b;
            }
            getAllCells() {
                return this.list.cells;
            }
            get minScrollValue() {
                return this.list.scrollBar.min;
            }
            get maxScrollValue() {
                return this.list.scrollBar.max;
            }
            setScroll(value) {
                if (!this.list.scrollBar)
                    return;
                this.list.scrollBar.value = value;
            }
            get scrollValue() {
                if (!this.list.scrollBar)
                    return 0;
                return this.list.scrollBar.value;
            }
        }

        class vAmuseCardAlbumSelectItem extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vAmuseCardAlbumSelectItem";
                this.exportNodeNames = [];
                this.size(145, 236);
                this.anchorY = 0;
                this.anchorX = 0;
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelShowingPower);
                this.data && this.fillByData(this.data);
            }
            onClosed() {
                super.onClosed();
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                if ((this.data.fIsSelected && !!this.data.fIsSelected(this.data.cardId))) {
                    this.spriteSelect.visible = true;
                    this.spriteSelect.alpha = 1;
                    cc.tween(this.spriteSelect, true)
                        .repeatForever(cc.tween()
                        .toAlpha(0.5, 0, cc.Ease.linear)
                        .delay(0.3)
                        .toAlpha(0.5, 1, cc.Ease.linear)
                        .delay(0.3))
                        .start();
                }
                else {
                    cc.clearTween(this.spriteSelect);
                    this.spriteSelect.visible = false;
                }
                let bUnlocked = mgrPlayer.getItemAmount(this.data.cardId) <= 0 ? false : true;
                let cardData = mgrCard.getPlayerCardInfo(this.data.cardId);
                this.spriteEmptyContainer.visible = (!bUnlocked || !cardData) ? true : false;
                this.spriteAdd.visible = (!!bUnlocked && !cardData) ? true : false;
                this.spriteAdFlag.visible = (!bUnlocked && !!this.data.bCanAd) ? true : false;
                this.spriteCoinLock.visible = (!bUnlocked && !this.data.bCanAd) ? true : false;
                if (!!bUnlocked && !!cardData) {
                    let roleData = mgrCfg.get_from_role_db(this.data.roleId);
                    let styleData = mgrCfg.get_from_amuse_card_style_db(this.data.styleId);
                    let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                    this.spriteShowingPhoto.texture = new Laya.Texture(this.data.textureCard);
                    Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureSmallBack);
                    Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureSmallFront);
                    Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                    this.labelShowingPower.text = `${this.data.power}`;
                    for (let i = 0; i < 5; i++) {
                        let spriteStar = this.spriteStarContainer.getChildAt(i);
                        let level = mgrCard.calculateCardLevelStarByPower(this.data.power);
                        spriteStar.visible = level > i;
                    }
                    this.labelRoleName.text = `${roleData.name}`;
                }
            }
            onTouchButtonContent() {
                if (!!this.data && this.data.fOnClick) {
                    this.data.fOnClick(this.data.cardId, this.data.bCanAd);
                }
            }
        }

        class vAmuseCardAlbumDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardAlbumDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.buildUi();
                this.fillData();
                this.widget();
                this.uiActionIn();
            }
            onClosed() {
                super.onClosed();
            }
            getPreLoadImagePaths() {
                let arr = [];
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (mgrPlayer.getItemAmount(v.id) <= 0) {
                        return;
                    }
                    arr.push(v.defaultCardTexture);
                });
                return [];
            }
            buildUi() {
                this.reuseList = new ReuseList(3, 0, 4);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vAmuseCardAlbumSelectItem);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(5);
                this.reuseList.setSpaceY(10);
                this.reuseList.alpha = 0;
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            uiActionIn() {
                if (mgrSdk.getCopNumberValueByKey("b_disable_ui_enter_effect") == 1) {
                    this.reuseList.alpha = 1;
                    return;
                }
                Timer.callLater(0.5, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    this.reuseList.alpha = 1;
                    let cells = this.reuseList.getAllCells();
                    for (let i = 0; i < cells.length; i++) {
                        let cell = cells[i];
                        cell.scale(0, 0, true);
                        cc.tween(cell).delay(i * 0.1).toScale(0.15, 1, cc.Ease.backOut).start();
                    }
                }, this);
            }
            fillData() {
                let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment);
                if (bCanAd) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment);
                    adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                }
                let arr = [];
                mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                    let cardInfo = mgrCard.getPlayerCardInfo(v.id) || {};
                    let texture = null;
                    let tex2dSaved = mgrRole.getPhotoTexture2D(cardInfo.cardTextureKeyName);
                    if (!!tex2dSaved) {
                        texture = new Laya.Texture(tex2dSaved);
                    }
                    else {
                    }
                    arr.push({
                        cardId: v.id,
                        roleId: cardInfo.roleId,
                        styleId: cardInfo.styleId,
                        textureCard: texture,
                        power: cardInfo.power || 0,
                        hp: cardInfo.hp,
                        partIds: cardInfo.partIds,
                        fOnClick: this.onClickItem.bind(this),
                        fIsSelected: this.isSelectedCard.bind(this),
                        bCanAd: bCanAd
                    });
                });
                this.cardArr = arr;
                this.reuseList.setDatas(arr);
                if (mgrPlayer.getItemAmount(arr[0].cardId) >= 0) {
                    this.onClickItem(arr[0].cardId, false);
                }
            }
            onClickItem(cardId, bAd) {
                if (mgrPlayer.getItemAmount(cardId) <= 0) {
                    if (bAd) {
                        mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment, { cardId }, true);
                    }
                    else {
                        let coinAmount = Const.UNLOCK_ALBUM_CARD_COST;
                        let coinTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                        mgrTip.alertPrompt2("提示", `是否花费${coinAmount}${coinTemplate.name}【解锁卡槽】？`, "取消", "确定", null, () => {
                            if (mgrShop.tryConsumeItem(Const.ITEM_ID_DIAMONDS, coinAmount, "解锁卡册位置")) {
                                mgrPlayer.addItemAmount(cardId, 1, "解锁卡册位置");
                                this.onClickItem(cardId, false);
                            }
                        });
                    }
                    return;
                }
                this.currSelectCardId = cardId;
                this.reuseList.refresh();
            }
            isSelectedCard(cardId) {
                return this.currSelectCardId == cardId ? true : false;
            }
            onTouchButtonMake() {
                if (!this.currSelectCardId) {
                    return;
                }
                if (mgrPlayer.getItemAmount(this.currSelectCardId) <= 0) {
                    mgrTip.showMsgTip("该位置还没有解锁的呢");
                    return;
                }
                let emptyCardId = mgrCard.getMinEmptyDataCardId();
                if (this.currSelectCardId > emptyCardId) {
                    this.currSelectCardId = emptyCardId;
                }
                let cardInfo = mgrCard.getPlayerCardInfo(this.currSelectCardId);
                let callback2 = () => {
                    mgrDirector.warpSceneWidthEffect(`vFreedomRoomScene`, {
                        stageId: 2002,
                        cardId: this.currSelectCardId,
                        roleId: !!cardInfo ? cardInfo.roleId : null,
                        backSceneName: "vAmuseCardStartScene",
                        nextDialogName: "vAmuseCardAlbumDialog",
                        partIds: !!cardInfo ? cardInfo.partIds : null,
                    });
                    this.closeDialog();
                };
                if (!!cardInfo) {
                    let callback1 = () => {
                        mgrDirector.warpSceneWidthEffect(`vAmuseCardPhotoMakeScene`, {
                            fromViewDesc: "卡册直接制卡",
                            backSceneName: `vHubScene`,
                            nextDialogName: "vAmuseCardAlbumDialog",
                            bRemakeCardResult: true,
                            roleId: cardInfo.roleId,
                            cardId: this.currSelectCardId,
                            partIds: cardInfo.partIds
                        });
                        this.closeDialog();
                    };
                    let showCardInfo = null;
                    for (let k in this.cardArr) {
                        let data = this.cardArr[k];
                        if (data.cardId == this.currSelectCardId) {
                            showCardInfo = data;
                            break;
                        }
                    }
                    mgrDirector.openDialog("vAmuseCardChooseChangeDialog", { data: showCardInfo, fOnClick1: callback1.bind(this), fOnClick2: callback2.bind(this) });
                }
                else {
                    callback2();
                }
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment) {
                    let cardId = e.userData.cardId;
                    mgrPlayer.addItemAmount(cardId, 1, "解锁卡册位置");
                    this.onClickItem(cardId, false);
                    this.reuseList.refresh();
                }
            }
        }

        class vAmuseCardChooseChangeDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardChooseChangeDialog";
            }
            onOpened() {
                super.onOpened();
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                this.buildUi();
            }
            buildUi() {
                let data = this.context.data;
                this.data = data;
                let styleData = mgrCfg.get_from_amuse_card_style_db(this.data.styleId);
                let roleData = mgrCfg.get_from_role_db(this.data.roleId);
                let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                this.spriteShowingPhoto.texture = new Laya.Texture(this.data.textureCard);
                Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureBack);
                Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureFront);
                Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                this.labelShowingPower.text = `${this.data.power}`;
                for (let i = 0; i < 5; i++) {
                    let spriteStar = this.spriteStarContainer.getChildAt(i);
                    let level = mgrCard.calculateCardLevelStarByPower(this.data.power);
                    spriteStar.visible = level > i;
                }
                this.labelRoleName.text = `${roleData.name}`;
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseCardChooseChangeDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonJump() {
                if (this.context.fOnClick1) {
                    this.context.fOnClick1();
                }
                this.closeDialog();
            }
            onTouchButtonChange() {
                if (this.context.fOnClick2) {
                    this.context.fOnClick2();
                }
                this.closeDialog();
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vAmuseCardDoubleNpcAlbumItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vAmuseCardDoubleNpcAlbumItem";
                this.size(145, 236);
                this.anchorY = 0;
                this.anchorX = 0;
            }
            onOpened() {
                super.onOpened();
                this.spriteEmptyContainer.visible = false;
                this.data && this.fillByData(this.data);
            }
            onClosed() {
                super.onClosed();
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.spriteMask.visible = mgrPlayer.getItemAmount(data.cardId) <= 0;
                let styleData = mgrCfg.get_from_amuse_card_style_db(this.data.cardStyleId);
                let roleData = mgrCfg.get_from_amuse_double_npc_card_role_pic_db(this.data.npcPicId);
                let tagData = mgrCfg.get_from_part_tag_db(this.data.roleTagId);
                Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                Tools.loadImg(this.spriteShowingPhoto, roleData.smallTextuer);
                Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureSmallBack);
                Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureSmallFront);
                this.labelRoleName.text = this.data.name;
                this.labelShowingPower.text = this.data.fightPower;
                for (let i = 0; i < 5; i++) {
                    let spriteStar = this.spriteStarContainer.getChildAt(i);
                    let level = mgrCard.calculateCardLevelStarByPower(this.data.fightPower);
                    spriteStar.visible = level > i;
                }
            }
            onTouchButtonContent() {
            }
        }

        const DEBUG$2 = false;
        class mgrDoubleNpcCard extends Manager {
            static onLoad() {
                super.onLoad();
                console.log("初始化loadRecord");
                this.loadRecord();
            }
            static loadRecord() {
                super.loadRecord();
                let record = mgrRecord.getData("mgrDoubleNpcCard") || {};
                this.saveRecord();
            }
            static saveRecord() {
                super.saveRecord();
                let record = {};
                mgrRecord.setData("mgrDoubleNpcCard", record);
            }
            static getStarCard(starNum) {
                let cardData = [];
                mgrCfg.forDb_from_amuse_double_card_npc_db((k, v) => {
                    let star = mgrCard.calculateCardLevelStarByPower(v.fightPower);
                    if (star == starNum) {
                        cardData.push(v);
                    }
                });
                return cardData;
            }
            static getCurrencyData() {
                let currencyArr = [];
                let configData = mgrCfg.get_from_double_card_extract_rule_db(2);
                for (let i = configData.param1; i <= configData.param2; i++) {
                    currencyArr.push({
                        itemId: Const.ITEM_ID_GOLD,
                        amount: i
                    });
                }
                return currencyArr;
            }
            static getLowStarCard() {
                let totalData = this.getStarCard(Tools.random(2, 3));
                let cardData = Tools.randomGotOneArrayData(totalData);
                let currencyData = this.getCurrencyData();
                currencyData = Tools.randomGotArrayDatas(currencyData, currencyData.length);
                for (let i = 0; i < currencyData.length; i++) {
                    const data = currencyData[i];
                    this.cardArr.push(data);
                }
                this.cardArr.push(cardData);
                this.cardArr = Tools.randomGotArrayDatas(this.cardArr, this.cardArr.length);
                for (let i = 0; i < this.cardArr.length; i++) {
                    let item = this.cardArr[i];
                    item["id"] = i + 1;
                }
                return this.cardArr;
            }
            static getHighStarCard() {
                let cardExtractRuleData = mgrCfg.get_from_double_card_extract_rule_db(2);
                let coinNums = [50, 150];
                if (cardExtractRuleData && cardExtractRuleData.param1) {
                    coinNums[0] = cardExtractRuleData.param1;
                }
                if (cardExtractRuleData && cardExtractRuleData.param2) {
                    coinNums[1] = cardExtractRuleData.param2;
                }
                let coinNumMin = Math.min(coinNums[0], coinNums[1]);
                let coinNumMax = Math.max(coinNums[0], coinNums[1]);
                this.cardArr = [];
                for (let i = 0; i < 5; ++i) {
                    let itemId = 1;
                    let count = Mathf.random(coinNumMin, coinNumMax);
                    if (Mathf.random(0, 100) >= 50) {
                        itemId = 5;
                        count = 1;
                    }
                    this.cardArr.push({
                        itemId: itemId,
                        amount: count,
                        id: i + 1,
                    });
                }
                let ratiodb = mgrCfg.get_from_double_card_lottery_ratio_db(1);
                let curRatio = Mathf.random(0, 100);
                let count = 0;
                let star = 2;
                for (let i = 0; i < ratiodb.ratio.length; ++i) {
                    count += ratiodb.ratio[i];
                    if (curRatio <= count) {
                        star = ratiodb.star[i];
                        break;
                    }
                }
                let totalData = this.getStarCard(star);
                let cardData = Tools.randomGotOneArrayData(totalData);
                this.cardArr.push(cardData);
                this.cardArr = Tools.randomGotArrayDatas(this.cardArr, this.cardArr.length);
                for (let i = 0; i < this.cardArr.length; i++) {
                    let item = this.cardArr[i];
                    item["id"] = i + 1;
                }
                return this.cardArr;
            }
            static getCardArr() {
                return this.cardArr;
            }
            static resetCardArr() {
                this.cardArr = [];
            }
            static getOwnedDoubleNpcCard() {
                let ownedCardData = [];
                mgrCfg.forDb_from_amuse_double_card_npc_db((k, v) => {
                    if (mgrPlayer.getItemAmount(v.cardId) > 0) {
                        ownedCardData.push(v);
                    }
                });
                return ownedCardData;
            }
            static getDoubleNpcCard() {
                let ownedCardData = [];
                mgrCfg.forDb_from_amuse_double_card_npc_db((k, v) => {
                    if (mgrPlayer.getItemAmount(v.cardId) == 0) {
                        ownedCardData.push(v);
                    }
                });
                return ownedCardData;
            }
            static changeFreeCount(count) {
                this.freeCount += count;
            }
            static getCardDataByCardId(cardId) {
                let cardData;
                mgrCfg.forDb_from_amuse_double_card_npc_db((k, v) => {
                    if (v.cardId == cardId) {
                        cardData = v;
                    }
                });
                return cardData;
            }
            static getRemainFreeCount() {
                return this.freeCount;
            }
            static resetFreeCount() {
                this.freeCount = 3;
            }
        }
        mgrDoubleNpcCard.freeCount = 3;
        mgrDoubleNpcCard.extractedCount = 0;
        mgrDoubleNpcCard.cardArr = [];

        class vAmuseCardDoubleNpcAlbumDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardDoubleNpcAlbumDialog";
                this.cardArr = [];
                this.collectSkillId = 1;
                this.spriteSkillMap = {};
                this.progressSkillCollect = null;
                this.progressBar = null;
                this.progressBarToTalLength = null;
                this.progressCardTotalCount = 0;
                this.skillUnlockNeedCardCount = {};
                this.sortedSkillIdArr = [];
            }
            onOpened() {
                super.onOpened();
                let cardArr1 = mgrDoubleNpcCard.getOwnedDoubleNpcCard();
                cardArr1.sort((A, B) => {
                    return A.fightPower - B.fightPower;
                });
                let cardArr2 = mgrDoubleNpcCard.getDoubleNpcCard();
                cardArr2.sort((A, B) => {
                    return A.fightPower - B.fightPower;
                });
                this.cardArr = cardArr1;
                for (let i = 0; i < cardArr2.length; ++i) {
                    this.cardArr.push(cardArr2[i]);
                }
                this.buildUi();
                this.fillData();
                this.fillProgress();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseList = new ReuseList(3, 0, 4);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vAmuseCardDoubleNpcAlbumItem);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(10);
                this.reuseList.setSpaceY(10);
                this.progressSkillCollect = this.boxSkill.getChildByName("progressSkillCollect");
                this.progressBar = this.progressSkillCollect.getChildByName("bar");
                this.progressBarToTalLength = this.progressBar.width;
                this.fillNeedCardCountMap();
                let skillIdArr = this.sortedSkillIdArr;
                let perCount = Math.ceil(this.progressCardTotalCount / skillIdArr.length);
                if (skillIdArr && skillIdArr.length > 0) {
                    let skillCount = skillIdArr.length;
                    let progressWidth = this.progressSkillCollect.width;
                    let progressPos = [this.progressSkillCollect.x, this.progressSkillCollect.y];
                    let intervalX = progressWidth / skillCount;
                    for (let i = 0; i < skillIdArr.length; i++) {
                        let skillId = skillIdArr[i];
                        if (!skillId) {
                            continue;
                        }
                        let skillData = mgrCardFightSkill.getSkillTemplateData(skillId);
                        let skillCollectionData = mgrCfg.get_from_amuse_card_skil_collection_db(skillId);
                        let descLabel = `${skillCollectionData.needCardCount}张`;
                        if (!skillData) {
                            continue;
                        }
                        let count = i + 1;
                        this.skillUnlockNeedCardCount[skillData.id] = Mathf.clamp(perCount * count, 0, this.progressCardTotalCount);
                        Laya.loader.load(skillData.icon, Laya.Handler.create(this, () => {
                            let skill = new Laya.Sprite();
                            skill.loadImage(skillData.icon);
                            this.boxSkill.addChild(skill);
                            this.spriteSkillMap[skillData.id] = skill;
                            skill.pos(progressPos[0] + (count * intervalX) - (skill.width / 2), progressPos[1] - skill.height / 2);
                            skill["_skillId"] = skillData.id;
                            skill.on("click", this, this.onClickSkillItem.bind(this));
                            this.add3DEffectAtFront(skillCollectionData.iconEff, skill, 0, 1, (model) => {
                                let bCanUnlock = this.isSkillCanUnlock(skillId);
                                if (bCanUnlock) {
                                    mgrTip.showBadgeWithNumber(skill, 1, new Laya.Point(8, 8));
                                }
                            });
                        }));
                        let label = new Laya.Label();
                        label.stroke = 2;
                        label.strokeColor = "#ffffff";
                        label.color = "#4d62ff";
                        label.fontSize = 20;
                        label.text = `${descLabel}`;
                        this.boxSkill.addChild(label);
                        label.pos(progressPos[0] + (count * intervalX) - (label.width / 2), (progressPos[1] + label.height) + 16);
                    }
                }
            }
            fillData() {
                this.reuseList.setDatas(this.cardArr);
            }
            fillProgress() {
                let cardOwnedArr = mgrDoubleNpcCard.getOwnedDoubleNpcCard();
                let progress = cardOwnedArr.length / this.progressCardTotalCount;
                this.renderProgressBar(progress, this.progressBar, this.progressBarToTalLength);
            }
            tryUnlockSkill(skillId) {
                let skillTemplateData = mgrCardFightSkill.getSkillTemplateData(skillId);
                if (!skillTemplateData) {
                    return;
                }
                let curSkillInfo = mgrCardFightSkill.getCurTeamSkillInfo();
                if (curSkillInfo && (curSkillInfo.id == skillId)) {
                    return;
                }
                if (curSkillInfo) {
                    let curSkillCollectionData = mgrCfg.get_from_amuse_card_skil_collection_db(curSkillInfo.id);
                    let skillCollectionData = mgrCfg.get_from_amuse_card_skil_collection_db(skillId);
                    if (curSkillCollectionData.needCardCount > skillCollectionData.needCardCount) {
                        return false;
                    }
                }
                let cardOwnedArr = mgrDoubleNpcCard.getOwnedDoubleNpcCard();
                let OwnedCardCount = cardOwnedArr.length;
                let needCardCount = this.skillUnlockNeedCardCount[skillId];
                if (!needCardCount && needCardCount != 0) {
                    return;
                }
                if (OwnedCardCount < needCardCount) {
                    return;
                }
                mgrCardFightSkill.unlockSkillAsTeamSkill(skillId);
                mgrTip.showMsgTip(`已解锁技能【${skillTemplateData.name}】！`);
                let sprite = this.spriteSkillMap[skillId];
                if (sprite) {
                    mgrTip.showBadgeWithNumber(sprite, -1);
                }
                let collectionData = mgrCfg.get_from_amuse_card_skil_collection_db(skillId);
                if (collectionData) {
                    mgrSdk.statisCommonEvent(collectionData.statisId);
                }
            }
            isSkillCanUnlock(skillId) {
                let skillTemplateData = mgrCardFightSkill.getSkillTemplateData(skillId);
                if (!skillTemplateData) {
                    return false;
                }
                let curSkillInfo = mgrCardFightSkill.getCurTeamSkillInfo();
                if (curSkillInfo && (curSkillInfo.id == skillId)) {
                    return false;
                }
                if (curSkillInfo) {
                    let curSkillCollectionData = mgrCfg.get_from_amuse_card_skil_collection_db(curSkillInfo.id);
                    let skillCollectionData = mgrCfg.get_from_amuse_card_skil_collection_db(skillId);
                    if (curSkillCollectionData.needCardCount > skillCollectionData.needCardCount) {
                        return false;
                    }
                }
                let cardOwnedArr = mgrDoubleNpcCard.getOwnedDoubleNpcCard();
                let OwnedCardCount = cardOwnedArr.length;
                let needCardCount = this.skillUnlockNeedCardCount[skillId];
                if (!needCardCount && needCardCount != 0) {
                    return false;
                }
                if (OwnedCardCount < needCardCount) {
                    return false;
                }
                return true;
            }
            renderProgressBar(progress, bar, totalLength) {
                if (!progress && progress != 0) {
                    return;
                }
                progress = Mathf.clamp(progress, 0, 1);
                let width = totalLength * progress;
                bar.size(width, bar.height);
            }
            fillNeedCardCountMap() {
                let skillCollectionDb = mgrCfg.getDb("amuse_card_skil_collection_db");
                if (!skillCollectionDb) {
                    return;
                }
                let maxCount = 0;
                let sortedArr = [];
                let idSortedArr = [];
                for (let key in skillCollectionDb) {
                    let data = skillCollectionDb[key];
                    if (data) {
                        this.skillUnlockNeedCardCount[data.id] = data.needCardCount;
                        if (maxCount < data.needCardCount) {
                            maxCount = data.needCardCount;
                        }
                        sortedArr.push(data);
                    }
                }
                sortedArr = Tools.sortArrayByField(sortedArr, "sort");
                for (let i = 0; i < sortedArr.length; i++) {
                    let skillCollectionData = sortedArr[i];
                    idSortedArr.push(skillCollectionData.id);
                }
                this.sortedSkillIdArr = idSortedArr;
                this.progressCardTotalCount = maxCount;
            }
            onClickSkillItem(e) {
                let skillId = e.target["_skillId"];
                let skillData = mgrCardFightSkill.getSkillTemplateData(skillId);
                if (!skillData) {
                    return;
                }
                mgrTip.alertPrompt1("提示", `${skillData.desc}`, "确定", () => { });
                this.tryUnlockSkill(skillData.id);
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
        }

        class vAmuseCardExtractItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vAmuseCardExtractItem";
                this.bStatic = false;
                this.size(160, 267);
                this.anchorY = 0;
                this.anchorX = 0;
            }
            onOpened() {
                super.onOpened();
                if (!this.model) {
                    this.add3DEffectAtFront("117_ui_loop_cardback", this.spriteEffect, 0, 1, (model) => {
                        this.model = model;
                    });
                }
                this.data && this.fillByData(this.data);
                if (this.data) {
                    let fAutoOpen = this.data.fAutoOpen;
                    if (fAutoOpen) {
                        fAutoOpen(this);
                    }
                }
            }
            onClosed() {
                super.onClosed();
            }
            fillByData(data) {
                console.log("vAmuseCardExtractItem.fillByData.data=========", data);
                this.data = data;
                if (!this.bResLoaded)
                    return;
                if (this.data.bAd && !this.data.bExtracted) {
                    if (!this.bStatic) {
                        mgrAd.staticsAdShow(AD_EVENT_ID.VIDEO.video_vAmuseCardExtractDialog_ad_extract);
                        this.bStatic = true;
                    }
                    this.spriteAdFlag.visible = true;
                    this.spriteMask.visible = true;
                }
                else {
                    this.spriteAdFlag.visible = false;
                    this.spriteMask.visible = false;
                }
                if (this.data.bAd || this.data.bExtracted) {
                    this.spriteBackContainer.visible = false;
                }
                else {
                    this.spriteBackContainer.visible = true;
                }
                if (!!this.data.cardId) {
                    let styleData = mgrCfg.get_from_amuse_card_style_db(this.data.cardStyleId);
                    let roleData = mgrCfg.get_from_amuse_double_npc_card_role_pic_db(this.data.npcPicId);
                    let tagData = mgrCfg.get_from_part_tag_db(this.data.roleTagId);
                    Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                    Tools.loadImg(this.spriteShowingPhoto, roleData.smallTextuer);
                    Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureSmallBack);
                    Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureSmallFront);
                    this.labelRoleName.text = this.data.name;
                    this.labelShowingPower.text = this.data.fightPower;
                    for (let i = 0; i < 5; i++) {
                        let spriteStar = this.spriteStarContainer.getChildAt(i);
                        let level = mgrCard.calculateCardLevelStarByPower(this.data.fightPower);
                        spriteStar.visible = level > i;
                    }
                    this.boxShowingPhotoContainer.visible = true;
                    this.spriteItem.visible = false;
                }
                else {
                    this.boxShowingPhotoContainer.visible = false;
                    this.spriteItem.visible = true;
                    this.labelCount.text = `X${this.data.amount}`;
                    Tools.loadImg(this.imageSpriteIcon, mgrPlayer.getIcon(this.data.itemId), true, () => {
                    });
                }
            }
            doOpen(delayTime) {
                Timer.callLater(delayTime, () => {
                    if (!this || !this.data || !this.data.fOnOpened) {
                        return;
                    }
                    cc.tween(this.buttonContent.__node)
                        .to(0.3, { scaleX: 0 })
                        .call(() => {
                        this.add3DEffectAtFront("117_ui_once_cardturn", this.spriteEffect, 0, 1, (model) => {
                        });
                        this.spriteBackContainer.visible = false;
                    })
                        .to(0.3, { scaleX: -1 })
                        .call(() => {
                        this.data.fOnOpened(this.data);
                        this.buttonContent.__node.scaleX = 1;
                    })
                        .start();
                });
            }
            onTouchButtonContent() {
                return;
            }
        }

        class vAmuseCardExtractDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardExtractDialog";
                this.cardArr = [];
                this.bCanClick = true;
                this.rewardAlertQueue = [];
                this.bGotNewDoubleRoleDialogCover = false;
                this.bStartedTip = false;
                this.bTipRewardDelayTimeOver = false;
                this.count = 0;
            }
            onOpened() {
                super.onOpened();
                this.cardArr = mgrDoubleNpcCard.getHighStarCard();
                this.buildUi();
                this.fillData();
                Timer.callLoop(0.2, () => {
                    if (!this.bTipRewardDelayTimeOver) {
                        return;
                    }
                    if (!this.rewardAlertQueue || !this.rewardAlertQueue.length) {
                        return;
                    }
                    let bCanAlert = this.isCanAlertReward();
                    if (!bCanAlert) {
                        return;
                    }
                    let fRewardAlert = this.rewardAlertQueue.shift();
                    if (fRewardAlert) {
                        fRewardAlert();
                    }
                }, this);
            }
            onClosed() {
                super.onClosed();
                mgrDoubleNpcCard.resetCardArr();
                mgrDoubleNpcCard.resetFreeCount();
            }
            buildUi() {
                this.reuseList = new ReuseList(3, 0, 4);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vAmuseCardExtractItem);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(25);
                this.reuseList.setSpaceY(25);
            }
            fillData() {
                let baseDelayTime = 0.5;
                let durTime = 0.16;
                let tipRewardDelayTime = baseDelayTime + ((this.cardArr.length - 1) * durTime) + 1.8;
                Timer.callLater(tipRewardDelayTime, () => {
                    if (!this) {
                        return;
                    }
                    this.bTipRewardDelayTimeOver = true;
                });
                for (let i = 0; i < this.cardArr.length; i++) {
                    let delayTime = baseDelayTime + i * durTime;
                    let cardData = this.cardArr[i];
                    let autoOpen = (item) => {
                        if (!item) {
                            return;
                        }
                        item.doOpen(delayTime);
                    };
                    cardData["bExtracted"] = false;
                    cardData["bAd"] = false;
                    cardData["fOnOpened"] = this.onOpenedItem.bind(this);
                    cardData["fAutoOpen"] = autoOpen;
                }
                this.reuseList.setDatas(this.cardArr);
                console.log("vAmuseCardExtractDialog.fillData.this.cardArr=======", this.cardArr);
            }
            isCanAlertReward() {
                let bGotItemDialogAlerted = mgrTip.isAllGotItemTipDisplayed();
                if (!bGotItemDialogAlerted) {
                    return false;
                }
                let bGotNewDoubleRoleDialogClosed = !this.bGotNewDoubleRoleDialogCover;
                if (!bGotNewDoubleRoleDialogClosed) {
                    return false;
                }
                return true;
            }
            refreshCardAdArr() {
                let remainCount = mgrDoubleNpcCard.getRemainFreeCount();
                if (remainCount == 0) {
                    for (let i = 0; i < this.cardArr.length; i++) {
                        let cardData = this.cardArr[i];
                        if (!cardData["bExtracted"]) {
                            cardData["bAd"] = true;
                        }
                    }
                }
            }
            changeCardState(cardId, id) {
                let itemId = 0;
                for (let i = 0; i < this.cardArr.length; i++) {
                    let cardData = this.cardArr[i];
                    if (!!cardId && cardId == cardData.cardId) {
                        cardData["bExtracted"] = true;
                        itemId = cardId;
                        break;
                    }
                    if (!!id && id == cardData.id) {
                        cardData["bExtracted"] = true;
                        itemId = id;
                        break;
                    }
                }
                return itemId;
            }
            getReward(cardData) {
                if (!!cardData.cardId) {
                    if (mgrPlayer.getItemAmount(cardData.cardId) > 0) {
                        let itemDb = mgrCfg.get_from_item_template_db(cardData.cardId);
                        let count = itemDb.sellItemAmount;
                        let itemId = itemDb.sellItemId;
                        mgrTip.showMsgTip(`卡牌已拥有,自动兑换为:魔力币X${count}`);
                        mgrPlayer.addItemAmount(itemId, count, "抽卡奖励");
                    }
                    else {
                        mgrPlayer.addItemAmount(cardData.cardId, 1, "抽卡奖励");
                    }
                    this.rewardAlertQueue.unshift(() => {
                        if (this) {
                            this.bGotNewDoubleRoleDialogCover = true;
                        }
                        mgrDirector.openDialog("vGotNewDoubleRoleDialog", {
                            cardId: cardData.cardId, fOnClose: () => {
                                if (this) {
                                    this.bGotNewDoubleRoleDialogCover = false;
                                }
                            }
                        });
                    });
                }
                else {
                    mgrPlayer.addItemAmount(cardData.itemId, cardData.amount, "抽卡奖励");
                    this.rewardAlertQueue.push(() => {
                        mgrTip.addGotItemTip(cardData.itemId, cardData.amount);
                    });
                }
                this.bStartedTip = true;
            }
            onTouchButtonBack() {
                if (!this.bStartedTip || this.rewardAlertQueue.length > 0) {
                    return;
                }
                this.closeDialog();
            }
            onTouchButtonGetNormal() {
                if (!this.bStartedTip || this.rewardAlertQueue.length > 0) {
                    return;
                }
                this.closeDialog();
            }
            onOpenedItem(cardData) {
                let cardId = null;
                if (cardData.cardId) {
                    cardId = cardData.cardId;
                }
                let id = cardData.id;
                console.log("vAmuseCardExtractDialog.onClickItem...id...bAd...", cardId, id);
                for (let i = 0; i < this.cardArr.length; i++) {
                    let cardData = this.cardArr[i];
                    if (cardData["bExtracted"] && !!cardId && cardId == cardData.cardId) {
                        console.log("已经翻过这张牌了..双人卡...");
                        return;
                    }
                    if (cardData["bExtracted"] && !!id && id == cardData.id) {
                        console.log("已经翻过这张牌了..货币...");
                        return;
                    }
                }
                this.count++;
                this.changeCardState(cardId, id);
                this.getReward(cardData);
                this.reuseList.refresh();
                console.log("vAmuseCardExtractDialog.onClickItem..this.cardArr..", this.cardArr);
            }
        }

        class vAmuseCardFightSelectItem extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vAmuseCardFightSelectItem";
                this.exportNodeNames = [];
                this.size(130, 252);
                this.anchorY = 0;
                this.anchorX = 0;
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelShowingPower);
                this.labelShowingPower.scale(0.4, 0.4, true);
                this.data && this.fillByData(this.data);
            }
            onClosed() {
                super.onClosed();
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                if (this.data.bDoubleNpc) {
                    let styleData = mgrCfg.get_from_amuse_card_style_db(this.data.cardStyleId);
                    let roleData = mgrCfg.get_from_amuse_double_npc_card_role_pic_db(this.data.npcPicId);
                    let tagData = mgrCfg.get_from_part_tag_db(this.data.roleTagId);
                    this.spriteShowingPhoto.visible = false;
                    this.spriteShowingPhoto2.visible = true;
                    Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                    Tools.loadImg(this.spriteShowingPhoto2, roleData.smallTextuer);
                    Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureSmallBack);
                    Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureSmallFront);
                    this.labelRoleName.text = this.data.name;
                    this.labelShowingPower.text = this.data.fightPower;
                    for (let i = 0; i < 5; i++) {
                        let spriteStar = this.spriteStarContainer.getChildAt(i);
                        let level = mgrCard.calculateCardLevelStarByPower(this.data.power);
                        spriteStar.visible = level > i;
                    }
                    this.labelRoleName.text = `${this.data.name}`;
                    this.spriteTry.visible = false;
                }
                else {
                    this.spriteShowingPhoto.visible = true;
                    this.spriteShowingPhoto2.visible = false;
                    let styleData = mgrCfg.get_from_amuse_card_style_db(this.data.styleId);
                    let roleData = mgrCfg.get_from_role_db(this.data.roleId);
                    let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                    this.spriteShowingPhoto.texture = new Laya.Texture(this.data.textureCard);
                    if (!this.data.bCanTry) {
                        this.spriteTry.visible = false;
                    }
                    else {
                        this.spriteTry.visible = true;
                    }
                    if (mgrCard.isShowTrying(this.data.cardId)) {
                        this.spriteTry.visible = false;
                    }
                    this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                    Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureBack);
                    Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureFront);
                    Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                    this.labelShowingPower.text = `${this.data.power}`;
                    for (let i = 0; i < 5; i++) {
                        let spriteStar = this.spriteStarContainer.getChildAt(i);
                        let level = mgrCard.calculateCardLevelStarByPower(this.data.power);
                        spriteStar.visible = level > i;
                    }
                    this.labelRoleName.text = `${roleData.name}`;
                }
            }
            onTouchButtonContent() {
                if (!!this.data && this.data.fOnClick) {
                    this.data.fOnClick(this.data.cardId);
                }
            }
        }

        class vAmuseCardFightSelectDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardFightSelectDialog";
                this.exportNodeNames = [];
                this.curSelectCard = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.fillData();
                this.widget();
                this.uiActionIn();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseList = new ReuseList(3, 0, 4);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vAmuseCardFightSelectItem);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(20);
                this.reuseList.setSpaceY(18);
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            uiActionIn() {
                let cells = this.reuseList.getAllCells();
                for (let i = 0; i < cells.length; i++) {
                    let cell = cells[i];
                    cell.scale(0, 0, true);
                    cc.tween(cell).delay(i * 0.1).toScale(0.15, 1, cc.Ease.backOut).start();
                }
            }
            fillData() {
                let tryArr = mgrCfg.getDbArr("amuse_card_npc_db", (data) => {
                    return !!data.bCanTrial && data.id != 521;
                });
                let arr = [];
                let allCards = mgrCard.getAllPlayerCardInfo();
                for (let k in allCards) {
                    let cardInfo = allCards[k];
                    if (mgrCard.isCardInTempFightCardStandbying(cardInfo.cardId)) {
                        continue;
                    }
                    let texture = null;
                    let tex2dSaved = mgrRole.getPhotoTexture2D(cardInfo.cardTextureKeyName);
                    if (!!tex2dSaved) {
                        texture = new Laya.Texture(tex2dSaved);
                    }
                    else {
                    }
                    arr.push({
                        cardId: cardInfo.cardId,
                        roleId: cardInfo.roleId,
                        styleId: cardInfo.styleId,
                        textureCard: texture,
                        power: cardInfo.power || 0,
                        hp: cardInfo.hp,
                        partIds: cardInfo.partIds,
                        fOnClick: this.onClickItem.bind(this),
                        bTrying: mgrCard.isBTrying(cardInfo.cardId),
                    });
                }
                let preloadPlayerCardImgArr = [];
                for (let index = 0; index < tryArr.length; index++) {
                    const npcData = tryArr[index];
                    preloadPlayerCardImgArr.push(npcData.imgCardTexture);
                }
                mgrLoader.batchLoadResources(null, null, preloadPlayerCardImgArr, () => {
                    for (let index = 0; index < tryArr.length; index++) {
                        const npcData = tryArr[index];
                        let textureCard = mgrLoader.get2dRes(npcData.imgCardTexture);
                        if (mgrCard.isShowTrying(npcData.id)) {
                            continue;
                        }
                        arr.unshift({
                            cardId: npcData.id,
                            roleId: npcData.roleId,
                            styleId: npcData.cardStyle,
                            textureCard: textureCard,
                            power: npcData.fightPower || 0,
                            hp: npcData.hp,
                            partIds: [],
                            fOnClick: this.onClickItem.bind(this),
                            bCanTry: true,
                            bTrying: mgrCard.isBTrying(npcData.id),
                        });
                    }
                    let totalArr = [];
                    let ownedArr = [];
                    for (let index = 0; index < arr.length; index++) {
                        const data = arr[index];
                        if (data.bCanTry) {
                            totalArr.push(data);
                        }
                        else {
                            ownedArr.push(data);
                        }
                    }
                    for (let index = 0; index < ownedArr.length; index++) {
                        if (index >= 3) {
                            break;
                        }
                        const data = ownedArr[index];
                        totalArr.push(data);
                    }
                    totalArr = Tools.shuffle(totalArr);
                    for (let index = 0; index < 3; index++) {
                        ownedArr.shift();
                    }
                    if (ownedArr.length > 0) {
                        for (let index = 0; index < ownedArr.length; index++) {
                            const element = ownedArr[index];
                            totalArr.push(element);
                        }
                    }
                    this.ownedCardArr = totalArr;
                    let doubleNpcCards = mgrDoubleNpcCard.getOwnedDoubleNpcCard();
                    for (let i = 0; i < doubleNpcCards.length; i++) {
                        let bSelect = false;
                        const card = doubleNpcCards[i];
                        for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                            let cardDataInfo = mgrCard.getTempFightCardPosInfoByPosIndex(i);
                            if (cardDataInfo && card.cardId == cardDataInfo.cardId) {
                                bSelect = true;
                                break;
                            }
                        }
                        if (bSelect) {
                            continue;
                        }
                        card["fOnClick"] = this.onClickItem.bind(this);
                        this.ownedCardArr.push(card);
                    }
                    this.reuseList.setDatas(this.ownedCardArr);
                });
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseCardFightSelectDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onClickItem(cardId) {
                let data = null;
                for (let k in this.ownedCardArr) {
                    let roleData = this.ownedCardArr[k];
                    if (roleData.cardId == cardId) {
                        data = roleData;
                        break;
                    }
                }
                if (data.bCanTry && !mgrCard.isShowTrying(cardId)) {
                    mgrAd.triggerAdEvent("video_vAmuseCardFightScene_trial", { cardId: cardId }, true);
                    return;
                }
                this.doClickItem(data, cardId);
            }
            doClickItem(data, cardId) {
                mgrCard.pushSelectCard(this.context.posIndex, cardId);
                let callback = () => {
                    mgrCard.setTempFightCardDataByPosIndex(this.context.posIndex, data);
                    if (this.context.fOnChanged) {
                        this.context.fOnChanged(cardId);
                    }
                    this.closeDialog(true);
                };
                this.spriteBgContainer.visible = false;
                let clickCell = null;
                let cells = this.reuseList.getAllCells();
                for (let i = 0; i < cells.length; i++) {
                    let cell = cells[i];
                    if (!cell || !cell["data"] || !cell["data"].cardId) {
                        continue;
                    }
                    cell.alpha = cell["data"].cardId == cardId ? 1 : 0;
                    if (cell.visible) {
                        clickCell = cell;
                    }
                    cell["buttonContent"].fOnClick = () => { };
                }
                if (!clickCell) {
                    callback();
                    return;
                }
                this.reuseList.setTouchEnable(false);
                let originPosList = new Laya.Vector2(this.boxList.x, this.boxList.y);
                let worldPosClickedCell = clickCell.localToGlobal(new Laya.Point(clickCell.pivotX + clickCell.width / 2, clickCell.pivotY + clickCell.height / 2));
                let pivotInList = this.boxList.globalToLocal(worldPosClickedCell);
                this.boxList.pivot(pivotInList.x, pivotInList.y);
                this.boxList.pos(originPosList.x + pivotInList.x, originPosList.y + pivotInList.y);
                let targetPos = this.boxList.parent.globalToLocal(this.context.worldPos);
                let targetPosCenter = this.boxList.parent.globalToLocal(new Laya.Point(mgrDirector.width / 2, mgrDirector.height / 2));
                cc.tween(this.boxList)
                    .delay(0.2)
                    .parallel(cc.tween().toPos(0.3, targetPosCenter.x, targetPosCenter.y), cc.tween().toScale(0.3, 1.3))
                    .delay(0.3)
                    .parallel(cc.tween().then(cc.jumpTo(0.3, targetPos.x, targetPos.y, 100, 1)), cc.tween().toScale(0.3, 0.76))
                    .call(() => {
                    callback();
                })
                    .start();
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonCardCollect() {
                mgrDirector.openDialog("vAmuseCardAlbumDialog");
                this.closeDialog(true);
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == "video_vAmuseCardFightScene_trial") {
                    let cardId = e.userData.cardId;
                    let data = null;
                    for (let k in this.ownedCardArr) {
                        let roleData = this.ownedCardArr[k];
                        if (roleData.cardId == cardId) {
                            data = roleData;
                            this.ownedCardArr[k].bTrying = true;
                            break;
                        }
                    }
                    mgrCard.setTrying(cardId, data);
                    this.doClickItem(data, cardId);
                }
            }
        }

        class vAmuseCardModeDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardModeDialog";
            }
            onOpened() {
                super.onOpened();
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonMakeCard() {
                mgrDirector.openDialog("vAmuseCardAlbumDialog");
                this.closeDialog();
            }
            onTouchButtonExtractCard() {
                mgrDirector.openDialog("vAmuseCardPreviewExtractDialog");
                this.closeDialog();
            }
        }

        class vAmuseCardPreviewExtractDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardPreviewExtractDialog";
                this.costNum = 200;
            }
            getPreLoadModelIds() {
                return ["117_ui_loop_card_anim"];
            }
            onOpened() {
                this.add3DEffectAtFront("117_ui_loop_card_anim", this.spriteShine, 0, 1, (model) => {
                });
                super.onOpened();
                let cardExtractRuleData = mgrCfg.get_from_double_card_extract_rule_db(1);
                if (cardExtractRuleData && cardExtractRuleData.param1) {
                    this.costNum = cardExtractRuleData.param1;
                }
                this.labelStart.text = `${this.costNum}抽卡`;
                if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardExtractDialog_rare_extract)) {
                    mgrAd.staticsAdShow(AD_EVENT_ID.VIDEO.video_vAmuseCardExtractDialog_rare_extract);
                    this.buttonAdStart.__node.visible = true;
                }
                else {
                    this.buttonAdStart.__node.visible = false;
                }
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.topBar = new vTopBar({ bDisableGold: true, bDisableEnergy: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            onTouchButtonStart() {
                if (mgrPlayer.getItemAmount(1) < this.costNum) {
                    mgrTip.showMsgTip("魔力币不足~");
                }
                else {
                    mgrPlayer.addItemAmount(1, -this.costNum, "");
                    mgrDirector.openDialog("vAmuseCardExtractDialog", { bAd: false });
                }
            }
            onTouchButtonAdStart() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardExtractDialog_rare_extract, null, true);
            }
            onTouchButtonCardCollect() {
                mgrDirector.openDialog("vAmuseCardDoubleNpcAlbumDialog");
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonRatio() {
                mgrTip.alertPrompt1("概率公示", "每次抽卡，双人卡牌的概率为16%，体力和星光币的概率均为42%。", "确定");
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseCardExtractDialog_rare_extract) {
                    mgrDirector.openDialog("vAmuseCardExtractDialog", { bAd: true });
                }
            }
        }

        class vAmuseCardTipDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardTipDialog";
            }
            onOpened() {
                super.onOpened();
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                    this.spriteRole.visible = false;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                this.buildUi();
                this.fillData();
                this.startGuide();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
            }
            fillData() {
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                Tools.loadImg(this.spriteRole, roleData.bodyIcon);
                Tools.loadImg(this.spriteRoleTag1, tagData.icon);
                Tools.loadImg(this.spriteRoleTag2, tagData.icon);
                this.labelOldCardPower.text = `${this.context.oldPower || 0}`;
                this.labelCurCardPower.text = `${this.context.currPower || 0}`;
                this.labelRoleName.text = `${roleData.name}`;
                this.spriteStageScoreUpFlag.visible = this.context.oldPower <= this.context.currPower ? true : false;
                this.spriteStageScoreDownFlag.visible = !this.spriteStageScoreUpFlag.visible;
                this.spritePop.visible = this.context.oldPower <= this.context.currPower ? true : false;
            }
            startGuide() {
                mgrGuide.registerGuideNode("vAmuseCardTipDialog.buttonOk", this.buttonOk.__node);
                if (!mgrGuide.isFinished(350)) {
                    mgrGuide.startGuide(350);
                }
            }
            onTouchButtonGiveUp() {
                if (this.context.fGiveUp) {
                    this.context.fGiveUp();
                }
                this.closeDialog();
            }
            onTouchButtonOk() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCardTipDialog.clickButtonOk` });
                if (this.context.fReplace) {
                    this.context.fReplace();
                }
                this.closeDialog();
            }
        }

        class vAmuseCardTrialDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardTrialDialog";
            }
            onOpened() {
                super.onOpened();
                this.nativeBanner = mgrActivingBanner.activingAlertBanner(4, this);
                mgrLoader.loadFont("card_power", this.labelShowingPower);
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
                this.buttonCloseNativeBanner.__node.visible = mgrSdk.getCopNumberValueByKey("b_vAmuseCardTrialDialog_trigger_native_banner") == 1 ? true : false;
                this.buttonClose.__node.visible = !this.buttonCloseNativeBanner.__node.visible;
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseCardTrialDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onClosed() {
                super.onClosed();
                if (this.nativeBanner) {
                    this.nativeBanner.activingBannerClose();
                    this.nativeBanner = null;
                }
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                let npcData = mgrCfg.get_from_amuse_card_npc_db(this.context.npcId);
                let styleData = mgrCfg.get_from_amuse_card_style_db(npcData.cardStyle || 1);
                Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureFront);
                Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureBack);
                Tools.loadAdImg(this.imageShowingPhoto, npcData.imgCardTextureBig);
                let tagData = mgrCfg.get_from_part_tag_db(npcData.roleTagId);
                Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                this.labelShowingPower.text = `${npcData.fightPower}`;
                let star = mgrCard.calculateCardLevelStarByPower(npcData.fightPower);
                let numChildren = this.spriteStarContainer.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let sprite = this.spriteStarContainer.getChildAt(i);
                    sprite.visible = star - 1 >= i ? true : false;
                }
                cc.tween(this.spriteShine).repeatForever(cc.tween().byRotation(6, 360)).start();
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                let adEventData = mgrCfg.get_from_ad_event_db(this.context.adEventId);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.context.adEventId) {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(true);
                    }
                    this.closeDialog(true);
                }
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonClose() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(this.context.adEventId, null, true);
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonCloseNativeBanner() {
                this.onTouchButtonClose();
            }
        }

        class vAmuseCardWorldDailyStartDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseCardWorldDailyStartDialog";
                this.preInitData();
            }
            getPreLoadModelIds() {
                return [];
            }
            getPreLoadAnimationIds() {
                return [];
            }
            getPreLoadImagePaths() {
                let arr = [];
                let npcIdArr = this.stageData.npcIdArr || [];
                for (let k in npcIdArr) {
                    let npcId = npcIdArr[k];
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    if (!npcData.imgBody) {
                        continue;
                    }
                    arr.push(npcData.imgBody);
                    break;
                }
                return arr;
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelTotalPower);
                this.buildUi();
                this.fillData();
                this.widget();
                if (!this.context.bRemakeCardResult) {
                    this.playMovie(() => { this.startGuide(); });
                }
                else if (this.context.nextDialogName) {
                    mgrDirector.openDialog(this.context.nextDialogName);
                }
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                mgrEffect.shineNode(this.buttonStart.__node);
            }
            preInitData() {
                this.stageData = mgrCfg.get_from_amaze_card_stage_db(this.context.stageId);
                let power = 0;
                let npcIdArr = this.stageData.npcIdArr || [];
                for (let k in npcIdArr) {
                    let npcId = npcIdArr[k];
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    if (!npcData) {
                        continue;
                    }
                    power += npcData.fightPower;
                }
                this.npcTotalPower = power;
            }
            fillData() {
                let npcId1 = this.stageData.npcIdArr[0];
                let npcData1 = mgrCfg.get_from_amuse_card_npc_db(npcId1);
                Tools.loadImg(this.spriteRoleBody, npcData1.imgBody);
                Tools.loadImg(this.spriteRoleShadow, npcData1.imgShadowBody);
                Tools.loadImg(this.spriteRoleName, npcData1.imgName);
                let tagTemplate = mgrCfg.get_from_part_tag_db(npcData1.roleTagId);
                Tools.loadImg(this.spriteRoleTagIcon, tagTemplate.icon);
                this.labelTotalPower.text = `${this.npcTotalPower}`;
                this.labelStageLv.text = `${this.stageData.level}`;
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                let rmbAmount = Tools.random(5, 10);
                this.labelItemAmount1.text = `+${rmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.card);
                let partData = mgrCfg.get_from_part_db(rewardPartId);
                if (!!partData && partData.type) {
                    let partTypeData = mgrCfg.get_from_part_type_db(partData.type);
                    Tools.loadImg(this.spriteItemIcon2, partTypeData.iconTcutShot);
                    this.labelItemAmount2.text = `+${this.stageData.successRewardColorPoint}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
            }
            playMovie(callback) {
                let finishCallback = () => {
                    callback && callback();
                };
                if (this.stageData.storyId != 0) {
                    mgrDirector.openDialog("vStoryDialog", {
                        storyId: this.stageData.storyId,
                        bShowSkip: true,
                        skipCallback: finishCallback,
                        finishCallback: finishCallback,
                    });
                }
                else {
                    finishCallback();
                }
            }
            activeAvatarOut(callback) {
            }
            startGuide() {
                mgrGuide.registerGuideNode(`vAmuseCardWorldDailyStartDialog.buttonStart`, this.buttonStart.__node);
                if (!mgrGuide.isFinished(801)) {
                    mgrGuide.startGuide(801);
                }
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonStart() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCardWorldDailyStartDialog.clickButtonStart` });
                let backSceneName = this.context.bFromCard ? "vAmuseCardStartScene" : "vWorldDailyQuestMainScene";
                mgrDirector.warpSceneWidthEffect(`vAmuseCardTeamSetScene`, {
                    stageId: this.stageData.id,
                    backSceneName: backSceneName,
                    bFromCard: this.context.bFromCard,
                    bSpecial: true
                });
                this.closeDialog();
            }
        }

        class vAmuseClothCrossingCardSaveDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseClothCrossingCardSaveDialog";
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelShowingPower);
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let styleData = mgrCfg.get_from_amuse_card_style_db(this.context.styleId);
                Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureFront);
                Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureBack);
                this.imageShowingPhoto.texture = new Laya.Texture(this.context.tex2d);
                let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                this.labelShowingPower.text = `${this.context.power}`;
                this.labelName.text = roleData.name;
                let star = mgrCard.calculateCardLevelStarByPower(this.context.power);
                let numChildren = this.spriteStarContainer.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let sprite = this.spriteStarContainer.getChildAt(i);
                    sprite.visible = star - 1 >= i ? true : false;
                }
                cc.tween(this.spriteShine).repeatForever(cc.tween().byRotation(6, 360)).start();
                this.spriteAdFlag.visible = false;
                this.bNeedAd = false;
                let emptyCardId = mgrCard.getMinEmptyDataCardId();
                if (!emptyCardId) {
                    let lockedCardId = mgrCard.getMinLockedCardId();
                    if (!!lockedCardId) {
                        this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                        let adEventData = mgrCfg.get_from_ad_event_db(this.context.adEventId);
                        adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                        this.context.cardId = lockedCardId;
                        this.bNeedAd = true;
                    }
                    else {
                        let arr = [];
                        mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                            arr.push(v.id);
                        });
                        this.context.cardId = Tools.randomGotOneArrayData(arr);
                    }
                }
                else {
                    this.context.cardId = emptyCardId;
                }
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseClothCrossingCardSaveDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.context.adEventId) {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(true, this.context.cardId);
                    }
                    this.closeDialog(true);
                }
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonClose() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
            onTouchButtonGetAd() {
                if (!!this.bNeedAd) {
                    mgrAd.triggerAdEvent(this.context.adEventId, null, true);
                }
                else {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(true, this.context.cardId);
                    }
                    this.closeDialog(true);
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vAmuseClothCrossingPreviewDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseClothCrossingPreviewDialog";
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.initUi();
                this.widget();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            buildUi() {
                this.topBar = new vTopBar({ bDisableDiamond: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseClothCrossingPreviewDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            initUi() {
                let stageId = this.context.stageId || 1;
                this.stageData = mgrCfg.get_from_amaze_cloth_crossing_stage_db(stageId);
                this.labelStagePreview.text = this.stageData.stageDesc || "";
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                this.labelItemAmount1.text = `+${this.stageData.bestRewardRmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.parkour);
                let itemData = mgrCfg.get_from_item_template_db(rewardPartId);
                if (!!itemData && itemData.type) {
                    let itemTypeData = mgrCfg.get_from_item_type_db(itemData.type);
                    Tools.loadImg(this.spriteItemIcon2, itemTypeData.iconTcutShot);
                    this.labelItemAmount2.text = `+${this.stageData.bestRewardColorPoint}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
                let playerRoleId = mgrRole.showingRoleId;
                let playerRoleData = mgrCfg.get_from_role_db(playerRoleId);
                let enemyRoleData = this.getRoleExceptShowingRole(playerRoleData.id);
                Tools.loadImg(this.spriteLeftHeadIcon, enemyRoleData.headIcon);
                Tools.loadImg(this.spriteRightHeadIcon, playerRoleData.headIcon);
                this.labelLeftName.text = enemyRoleData.name;
                this.labelRightName.text = playerRoleData.name;
                this.context.enemyRoleId = enemyRoleData.id;
            }
            getRoleExceptShowingRole(muteRoleId) {
                let arr = [];
                let roleDataShowing = mgrCfg.get_from_role_db(muteRoleId);
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (!!muteRoleId && v.id == muteRoleId) {
                        return;
                    }
                    if (!v.rootRoleId || v.rootRoleId != roleDataShowing.rootRoleId) {
                        arr.push(v);
                    }
                });
                return Tools.randomGotOneArrayData(arr);
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonStart() {
                let count = 1;
                let bRet = mgrShop.tryConsumeItem(Const.ITEM_ID_ENERGY, count, "女神挑战赛");
                if (bRet) {
                    mgrTip.addGotItemTip(Const.ITEM_ID_ENERGY, -count);
                    mgrWorldDaily.cleanGameTempParms(DailyGameType.clothcrossing);
                    mgrWorldDaily.addPlayedGameStageId(DailyGameType.clothcrossing, this.context.stageId);
                    mgrDirector.warpSceneWidthEffect("vAmuseClothCrossingScene", this.context);
                    if (this.context.fOnStart) {
                        this.context.fOnStart();
                    }
                    this.closeDialog();
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
        }

        class vAmuseParkourPreviewDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmuseParkourPreviewDialog";
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.initUi();
                this.widget();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            buildUi() {
                this.topBar = new vTopBar({ bDisableDiamond: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseParkourPreviewDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            initUi() {
                this.stageData = mgrCfg.get_from_amaze_parkour_stage_db(this.context.stageId);
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                this.labelItemAmount1.text = `+${this.stageData.bestRewardRmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.parkour);
                let itemData = mgrCfg.get_from_item_template_db(rewardPartId);
                if (!!itemData && itemData.type) {
                    let itemTypeData = mgrCfg.get_from_item_type_db(itemData.type);
                    Tools.loadImg(this.spriteItemIcon2, itemTypeData.iconTcutShot);
                    this.labelItemAmount2.text = `+${this.stageData.bestRewardColorPoint}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonStart() {
                let stageId = this.context.stageId;
                let count = 1;
                let bRet = mgrShop.tryConsumeItem(Const.ITEM_ID_ENERGY, count, "颜色跑酷");
                if (bRet) {
                    mgrTip.addGotItemTip(Const.ITEM_ID_ENERGY, -count);
                }
                else {
                    return;
                }
                mgrWorldDaily.cleanGameTempParms(DailyGameType.parkour);
                mgrWorldDaily.addPlayedGameStageId(DailyGameType.parkour, this.context.stageId);
                mgrDirector.warpSceneWidthEffect("vAmuseParkourScene", { stageId });
                this.closeDialog(true);
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vAmusePenChooseListItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vAmusePenChooseListItem";
                this.size(190, 227);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let roleId = this.data.id;
                let roleData = mgrCfg.get_from_role_db(roleId);
                let halfBodyIcon = roleData.halfBodyIcon;
                Tools.loadImg(this.spriteRole, halfBodyIcon);
                let adedCount = mgrAmazePen.getPenRoleAdTrialedCount(roleId);
                this.labelGetAd.text = `${adedCount}/${this.data.unlockAdTrialCount}解锁`;
                if (mgrAmazePen.isUnlockedRole(roleId)) {
                    this.spriteHad.visible = true;
                    this.boxAd.visible = false;
                }
                else {
                    this.spriteHad.visible = false;
                    this.boxAd.visible = !!this.data.bAdValid;
                }
                if (this.data.fIsSelected && this.data.fIsSelected(this.data.id)) {
                    this.spriteActive.visible = true;
                }
                else {
                    this.spriteActive.visible = false;
                }
            }
            onTouchButtonBg() {
                if (mgrAmazePen.isUnlockedRole(this.data.id)) {
                    if (this.data.fOnClick) {
                        this.data.fOnClick(this.data.id, false);
                    }
                }
                else {
                    if (this.boxAd.visible) {
                        this.data.fOnClick(this.data.id, true);
                    }
                    else {
                        mgrTip.showMsgTip("还未获得角色哦！");
                    }
                }
            }
        }

        class vAmusePenChooseDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmusePenChooseDialog";
                this.avatarPresetPosition = new Laya.Vector3;
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.buildUi();
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                let bAdValid = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmusePenChooseDialog_trial);
                let arr = mgrCfg.getDbArr("amaze_pen_select_role_db");
                let bAdStatis = false;
                arr.forEach((v, i) => {
                    v["fOnClick"] = this.onClickRoleItem.bind(this);
                    v["fIsSelected"] = this.isSelected.bind(this);
                    if (v.bFirstShowRole && mgrPlayer.getItemAmount(v.id) <= 0 && bAdValid) {
                        bAdStatis = true;
                        v["adIndex"] = 1;
                    }
                    v["bAdValid"] = bAdValid;
                });
                if (bAdStatis) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAmusePenChooseDialog_trial);
                    adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                }
                this.reuseList = new ReuseList(3, 0, 3);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vAmusePenChooseListItem);
                if (arr.length > 6) {
                    this.reuseList.setVerticalMoveEnable(true);
                }
                else {
                    this.reuseList.setVerticalMoveEnable(false);
                    this.reuseList.setTouchEnable(false);
                }
                this.reuseList.setSpaceX(0);
                this.reuseList.setSpaceY(5);
                this.reuseList.setDatas(arr);
            }
            onAnimationFinished() {
                if (this.context.roleId) {
                    this.refreshSelectRole(this.context.roleId);
                }
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    this.lastTouchBgPos = e.pos;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            refreshSelectRole(roleId) {
                this.selectedRoleId = roleId;
                let roleData = mgrCfg.get_from_role_db(roleId);
                let partIds = roleData.partIds;
                if (!this.avatar) {
                    this.avatar = new RoleAvatar({ roleId });
                    this.add3DEffectAtBack(this.avatar, 0);
                    let cf = this.cameraBack.getComponent(CameraFollow);
                    cf.lookMode = E_CAMERA_MODE.fixMode;
                    cf.fov = 44;
                    cf.offset = new Laya.Vector3(0, 0.85);
                    cf.position = new Laya.Vector3(0, 0.94, 3.55);
                    cf.endRotation = new Laya.Vector3(-6.34);
                    cf.lerpValue = 1;
                    cf.onLateUpdate();
                    this.avatar.fillByPartIds(partIds, true);
                    this.avatar.registerLoadEndCallback(() => {
                        if (this.destroyed) {
                            return;
                        }
                        this.avatar.transform.rotationEuler = new Laya.Vector3(0, 0, 0);
                        this.avatar.transform.position = this.avatarPresetPosition;
                        if (!this.boxContainerMC["_registerTouched"]) {
                            Tools.registerTouchHander(this.boxContainerMC, this.onTouchSpriteBg.bind(this));
                            this.boxContainerMC["_registerTouched"] = true;
                        }
                    });
                    this.spriteBg.zOrder = -100;
                }
                else {
                    this.avatar.fillByPartIds(partIds, true);
                }
                this.labelRoleName.text = roleData.name;
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onClickRoleItem(roleId, bAd = false) {
                if (mgrAmazePen.isUnlockedRole(roleId)) {
                    this.refreshSelectRole(roleId);
                }
                else {
                    if (bAd) {
                        mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmusePenChooseDialog_trial, { roleId }, true);
                    }
                }
            }
            isSelected(id) {
                return (id && this.selectedRoleId && this.selectedRoleId == id) ? true : false;
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonSummit() {
                this.closeDialog();
                this.context.fOnConfirm && this.context.fOnConfirm(this.selectedRoleId);
            }
            onMsgAdEventSuccessd(e) {
                let userData = e.userData;
                let roleId = userData.roleId;
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmusePenChooseDialog_trial) {
                    mgrAmazePen.addPenRoleAdTrialedCount(roleId, 1);
                    let rolePenData = mgrCfg.get_from_amaze_pen_select_role_db(roleId);
                    if (mgrAmazePen.getPenRoleAdTrialedCount(roleId) >= rolePenData.unlockAdTrialCount) {
                        mgrAmazePen.unlockRole(roleId);
                    }
                    this.reuseList.refresh();
                    this.onClickRoleItem(roleId);
                }
            }
        }

        class vAmusePenPreviewDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmusePenPreviewDialog";
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.initUi();
            }
            onAnimationFinished() {
            }
            buildUi() {
            }
            initUi() {
                this.stageData = mgrCfg.get_from_amaze_pen_stage_db(this.context.stageId);
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                this.labelItemAmount1.text = `+${this.stageData.bestRewardRmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.parkour);
                let partData = mgrCfg.get_from_part_db(rewardPartId);
                if (!!partData && partData.type) {
                    let partTypeData = mgrCfg.get_from_part_type_db(partData.type);
                    Tools.loadImg(this.spriteItemIcon2, partTypeData.iconTcutShot);
                    this.labelItemAmount2.text = `+${this.stageData.bestRewardColorPoint}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonStart() {
                let callback = () => {
                    mgrWorldDaily.cleanGameTempParms(DailyGameType.pen);
                    mgrWorldDaily.addPlayedGameStageId(DailyGameType.pen, this.context.stageId);
                    this.context.rewardSurprisePartId = mgrWorldDaily.getUnownedVipPart(DailyGameType.pen);
                    mgrDirector.warpSceneWidthEffect("vAmuseFashionPenScene", this.context);
                };
                let arr = [];
                mgrCfg.forDb_from_amaze_pen_select_role_db((k, v) => {
                    if (v.id != this.context.roleId && mgrPlayer.getItemAmount(v.id) <= 0) {
                        arr.push(v.id);
                    }
                });
                let trialRoleId = Tools.randomGotOneArrayData(arr);
                mgrDirector.openDialog("vAmusePenRoleTrialDialog", {
                    adEventId: AD_EVENT_ID.VIDEO.video_vAmusePenRoleTrialDialog_trial,
                    roleId: trialRoleId,
                    fOnAdResult: (bAded) => {
                        if (bAded) {
                            this.context.roleId = trialRoleId;
                            callback();
                        }
                        else {
                            callback();
                        }
                    }
                });
                this.closeDialog();
            }
            onTouchButtonRoleStyle() {
                mgrDirector.openDialog("vAmusePenChooseDialog", {
                    roleId: this.context.roleId,
                    fOnConfirm: (roleId) => {
                    }
                });
            }
        }

        class vAmusePenRevivalDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmusePenRevivalDialog";
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                this.buttonGetAd.__node.visible = true;
                this.buttonCheckAdModeClose.__node.visible = false;
                this.spriteAdCheckModeContainer.visible = false;
                this.buttonClose.__node.visible = true;
                if (mgrSdk.getCopNumberValueByKey("b_ad_check_mode") == 1) {
                    this.buttonCheckAdModeClose.__node.visible = true;
                    this.spriteAdCheckModeContainer.visible = true;
                    this.buttonClose.__node.visible = false;
                    if (!this.adCheckModeConfig) {
                        let config = mgrAd.randomGetAdCheckModeConfig("强势复活");
                        this.labelAdCheckModelTip.text = config.text;
                        this.spriteAdCheckModeCheckFlag.visible = !!config.bDefaultChecked;
                        this.adCheckModeConfig = config;
                    }
                }
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                let adEventData = mgrCfg.get_from_ad_event_db(this.context.adEventId);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.context.adEventId) {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(true);
                    }
                    this.closeDialog(true);
                }
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonCheckAdModeClose() {
                if ((this.adCheckModeConfig.bCheckedTriggerAd && this.spriteAdCheckModeCheckFlag.visible) || (!this.spriteAdCheckModeCheckFlag.visible && !this.adCheckModeConfig.bCheckedTriggerAd)) {
                    this.onTouchButtonGetAd();
                }
                else {
                    this.onTouchButtonClose();
                }
            }
            onTouchButtonClose() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(this.context.adEventId, null, true);
            }
            onTouchButtonAdCheckModel() {
                this.spriteAdCheckModeCheckFlag.visible = !this.spriteAdCheckModeCheckFlag.visible;
            }
        }

        class vAmusePenRoleTrialDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmusePenRoleTrialDialog";
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
                this.buttonCloseNativeBanner.__node.visible = mgrSdk.getCopNumberValueByKey("b_vAmusePenRoleTrialDialog_trigger_native_banner") == 1 ? true : false;
                this.buttonClose.__node.visible = !this.buttonCloseNativeBanner.__node.visible;
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmusePenRoleTrialDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onClosed() {
                super.onClosed();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                Tools.loadImg(this.spriteBodyIcon, this.context.previewImg);
                this.buttonGetAd.__node.visible = true;
                this.buttonClose.__node.visible = true;
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                let adEventData = mgrCfg.get_from_ad_event_db(this.context.adEventId);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.context.adEventId) {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(true);
                    }
                    this.closeDialog(true);
                }
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonClose() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(this.context.adEventId, null, true);
            }
            onTouchButtonCloseNativeBanner() {
                this.onTouchButtonClose();
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vAmusePenSuperDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmusePenSuperDialog";
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                this.buttonGetAd.__node.visible = true;
                this.buttonClose.__node.visible = true;
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                let adEventData = mgrCfg.get_from_ad_event_db(this.context.adEventId);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                this.buttonTriggerNativeBanner.__node.visible = false;
                this.buttonClose2.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmusePenSuperDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                    if (mgrSdk.getCopNumberValueByKey("b_vAmusePenSuperDialog_trigger_native_banner") == 1) {
                        this.buttonClose2.__node.visible = true;
                        this.buttonClose.__node.visible = false;
                        this.spriteBtns.x = 380;
                    }
                }, this);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.context.adEventId) {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(true);
                    }
                    this.closeDialog(true);
                }
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonClose() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(this.context.adEventId, null, true);
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonClose2() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
        }

        class vAmusePenSuperDialog1 extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vAmusePenSuperDialog1";
                this.enemyIconUrl = ["res/pvp_npc/boss_andi.png", "res/pvp_npc/boss_beila.png", "res/pvp_npc/boss_sijia.png", "res/pvp_npc/boss_boyisong.png"];
            }
            onOpened() {
                super.onOpened();
                let roleId = 101;
                let roleEvent = mgrCfg.getDb("role_event_db");
                let allRoleId = [];
                for (let i = 0; i < roleEvent.length; ++i) {
                    if (roleEvent[i].roleId != roleId) {
                        allRoleId.push(roleEvent[i].roleId);
                    }
                }
                let curId = allRoleId[Mathf.random(0, allRoleId.length - 1)];
                if (curId == 10000) {
                    this.spriteRoleIcon.loadImage(this.enemyIconUrl[Mathf.random(0, this.enemyIconUrl.length - 1)]);
                }
                else {
                    let db = mgrCfg.get_from_role_db(curId);
                    this.spriteRoleIcon.loadImage(db.bodyIcon);
                }
                let eventId = 1;
                for (let i = 0; i < roleEvent.length; ++i) {
                    if (roleEvent[i].roleId == curId) {
                        eventId = roleEvent[i].eventIds[Mathf.random(0, roleEvent[i].eventIds.length - 1)];
                    }
                }
                let eventDb = mgrCfg.get_from_event_db(eventId);
                this.labelDesc.text = eventDb.desc;
                this.labelClose.text = eventDb.btn1;
                this.labelGetAd.text = eventDb.btn2;
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                let mask = new Laya.Sprite();
                mask.graphics.drawRect(40, 0, 323, 452, "#ff0000");
                mask.pos(0, 0);
                this.spriteRoleIcon.mask = mask;
                this.buttonGetAd.__node.visible = true;
                this.buttonClose.__node.visible = true;
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                let adEventData = mgrCfg.get_from_ad_event_db(this.context.adEventId);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                this.buttonTriggerNativeBanner.__node.visible = false;
                this.buttonClose2.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmusePenSuperDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                    if (mgrSdk.getCopNumberValueByKey("b_vAmusePenSuperDialog_trigger_native_banner") == 1) {
                        this.buttonClose2.__node.visible = true;
                        this.buttonClose.__node.visible = false;
                        this.spriteBtns.x = 380;
                    }
                }, this);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.context.adEventId) {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(true);
                    }
                    this.closeDialog(true);
                }
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonClose() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(this.context.adEventId, null, true);
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonClose2() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
        }

        class vCardNewYearPreviewItem extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vCardNewYearPreviewItem";
                this.size(294, 170);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelFightPower);
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let npcId = data.previewNpcId;
                let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                Tools.loadImg(this.spriteNpc, npcData.imgCardTexture);
                this.labelFightPower.text = npcData.fightPower.toString();
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                Tools.loadImg(this.spriteItemIcon2, "res/ui/amuse_card_start/color.png");
                this.labelItemAmount2.text = `+${data.successRewardColorPoint}`;
                if (mgrCard.getStageProgress() + 1 > data.id) {
                    this.buttonBg.__node.visible = false;
                    this.spriteSuccess.visible = true;
                }
                else {
                    this.buttonBg.__node.visible = true;
                    this.spriteSuccess.visible = false;
                }
                let curStageId = mgrCard.getNewYearStageProgress();
                let stageId = data.id;
                if (curStageId >= stageId) {
                    this.labelGo.text = `再次挑战`;
                }
                else {
                    this.labelGo.text = `挑战`;
                }
            }
            onTouchButtonBg() {
                if (this.data.fOnClick) {
                    this.data.fOnClick();
                }
            }
        }

        class vCdkDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vCdkDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buttonCdkey.fOnClick = () => {
                    if (this.input.text) {
                        mgrInnerCdk.receiveInnerCdk(this.input.text.trim());
                    }
                    else {
                        mgrTip.showMsgTip("请输入兑换码");
                    }
                };
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onAnimationFinished() {
            }
        }

        class vCollectWorldColorDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vCollectWorldColorDialog";
                this.showingColorPoint = 0;
                this.showingColorPoint = this.context.oldColorPoint || 0;
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.initUi();
            }
            getPreLoadModelIds() {
                return [
                    "118_e_once_ribbon_01",
                    "83_ui_loop_upparticle_01"
                ];
            }
            onAnimationFinished() {
                let totalGotValue = this.context.currGotColorPoint || 0;
                let gotColorValueDict = {};
                let perValue = Math.floor(totalGotValue * 2 / 3 / 7);
                for (let i = 1; i <= 7; i++) {
                    gotColorValueDict[i] = perValue;
                }
                totalGotValue -= perValue * 7;
                while (totalGotValue > 0) {
                    let index = Tools.random(6) + 1;
                    let cur = Tools.random(totalGotValue);
                    gotColorValueDict[index] += cur;
                    totalGotValue -= cur;
                }
                for (let i = 1; i <= 7; i++) {
                    let value = gotColorValueDict[i];
                    let holderSprite = this["spriteColorHolder" + i + "Step1"];
                    let sprite = this["spriteColor" + i + "Step1"];
                    cc.tween(sprite)
                        .delay(Tools.random() * 0.3)
                        .then(cc.jumpTo(0.5, sprite["_originPos"].x, sprite["_originPos"].y, 100, 1))
                        .delay(0.2)
                        .toPos(0.2, holderSprite.x, holderSprite.y)
                        .call(() => {
                        sprite.alpha = 0;
                        this.showingColorPoint += value;
                        this.refreshColorPointStep1();
                        if (i == 1 || i == 5) {
                            this.add3DEffectAtFront("118_e_once_ribbon_01", holderSprite, 0.5);
                        }
                    })
                        .start();
                }
                Timer.callLater(2, () => {
                    cc.tween(this.spritePaletteStep1).parallel(cc.tween().toPos(0.15, 288, 863), cc.tween().toScale(0.15, 0.6))
                        .call(() => {
                        this.closeDialog(true);
                    })
                        .start();
                }, this);
            }
            buildUi() {
                this.spriteLuckyTitleStep1.visible = false;
            }
            initUi() {
                for (let i = 1; i <= 7; i++) {
                    let sprite = this["spriteColor" + i + "Step1"];
                    sprite["_originPos"] = new Laya.Vector2(sprite.x, sprite.y);
                    sprite.x = Tools.random(100) > 50 ? sprite.x + mgrDirector.width : sprite.x - mgrDirector.width;
                }
                this.refreshColorPointStep1();
            }
            refreshColorPointStep1() {
                this.labelColorPointStep1.text = `${this.showingColorPoint}`;
            }
            onClosed() {
                super.onClosed();
            }
        }

        class vCustomMadeClothesPreviewDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vCustomMadeClothesPreviewDialog";
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vCustomMadeClothesPreviewDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
                this.topBar = new vTopBar({ bDisableDiamond: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                let stageData = mgrCfg.get_from_custom_made_clothes_stage_db(this.context.stageId);
                this.labelContent.text = stageData.stageDesc;
                let roleData = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                this.labelHello.text = `亲爱的${roleData.name}：`;
                this.inputNode.visible = false;
                let customerRoleData = mgrCfg.get_from_role_db(this.context.roleId);
                if (customerRoleData.headIcon) {
                    Tools.loadImg(this.spriteHeadIcon, customerRoleData.halfBodyIcon);
                }
                this.labelCustomerName.text = customerRoleData.name;
                if (mgrDebug.bShowDevButton) {
                    // this.inputNode.visible = true;
                }
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                this.labelItemAmount1.text = `+${stageData.bestRewardRmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.custom_made);
                let itemData = mgrCfg.get_from_item_template_db(rewardPartId);
                if (!!itemData && itemData.type) {
                    let itemTypeData = mgrCfg.get_from_item_type_db(itemData.type);
                    Tools.loadImg(this.spriteItemIcon2, itemTypeData.iconTcutShot);
                    this.labelItemAmount2.text = `+${stageData.bestRewardColorPoint}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.buttonClose.__node);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            onTouchButtonAcceptOrder() {
                let stageId = this.context.stageId;
                if (this.input.text) {
                    stageId = parseInt(this.input.text);
                }
                let count = 1;
                let bRet = mgrShop.tryConsumeItem(Const.ITEM_ID_ENERGY, count, "定制衣服");
                if (bRet) {
                    mgrTip.addGotItemTip(Const.ITEM_ID_ENERGY, -count);
                }
                else {
                    return;
                }
                mgrWorldDaily.cleanGameTempParms(DailyGameType.custom_made);
                mgrWorldDaily.addPlayedGameStageId(DailyGameType.custom_made, stageId);
                mgrDirector.warpSceneWidthEffect("vCustomMadeClothesScene", { stageId, roleId: this.context.roleId, ignoreSameScene: this.context.ignoreSameScene });
                if (this.context.fOnStart) {
                    this.context.fOnStart();
                }
                this.closeDialog();
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vCustomMadeClothesPreviewVipDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vCustomMadeClothesPreviewVipDialog";
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.initUi();
                this.buildUi();
            }
            buildUi() {
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vCustomMadeClothesPreviewVipDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            initUi() {
                let roleData = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                let stageId = this.context.stageId || 1;
                console.warn("----stageId=", stageId);
                this.stageData = mgrCfg.get_from_custom_made_clothes_stage_db(stageId);
                this.labelHello.text = `亲爱的${roleData.name || ""}`;
                this.labelContent.text = `${this.stageData.stageDesc || ""}`;
                Tools.loadImg(this.spriteRoleIcon, roleData.halfBodyIcon);
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                this.labelItemAmount1.text = `+${this.stageData.bestRewardRmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.custom_made);
                let partData = mgrCfg.get_from_item_template_db(rewardPartId);
                if (!!partData && partData.type) {
                    let partTypeData = mgrCfg.get_from_item_type_db(partData.type);
                    Tools.loadImg(this.spriteItemIcon2, partTypeData.iconTcutShot);
                    this.labelItemAmount2.text = `+${this.stageData.bestRewardColorPoint}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
                let vipPartId = mgrWorldDaily.getUnownedVipPart(DailyGameType.custom_made);
                let partDataVip = mgrCfg.get_from_item_template_db(vipPartId);
                this.vipPartId = vipPartId;
                if (!!partDataVip && partDataVip.type) {
                    Tools.loadImg(this.spriteItemIcon3, partDataVip.icon);
                    let typeData = mgrCfg.get_from_item_type_db(partDataVip.type);
                    this.labelItemAmount3.text = `+${typeData.name}`;
                }
                else {
                    this.spriteItem3.visible = false;
                }
                let customerRoleData = mgrCfg.get_from_role_db(this.context.roleId);
                this.labelCustomerName.text = customerRoleData.name;
                if (mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.custom_made)) {
                    this.buttonGetNormal.__node.visible = false;
                    this.spriteAdFlag.visible = false;
                }
            }
            onClosed() {
                super.onClosed();
            }
            onAdded() {
                mgrWorldDaily.cleanGameTempParms(DailyGameType.custom_made);
                mgrWorldDaily.addPlayedGameStageId(DailyGameType.custom_made, this.context.stageId);
                mgrDirector.warpSceneWidthEffect("vCustomMadeClothesScene", { rewardSurprisePartId: this.vipPartId, stageId: this.context.stageId, roleId: this.context.roleId, bVip: true, ignoreSameScene: this.context.ignoreSameScene });
                if (this.context.fOnStart) {
                    this.context.fOnStart();
                }
                this.closeDialog();
            }
            onTouchButtonAdAreaScreen() {
            }
            onTouchButtonGetNormal() {
                if (!!this.context.fOnGiveUp) {
                    this.context.fOnGiveUp();
                }
                this.closeDialog();
            }
            onTouchButtonGetAd() {
                if (mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.custom_made)) {
                    this.onAdded();
                }
                else {
                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesPreviewVipDialog_vip, null, true);
                }
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vCustomMadeClothesPreviewVipDialog_vip) {
                    this.onAdded();
                }
            }
        }

        class vDebugDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vDebugDialog";
                this.exportNodeNames = [];
                this.prevX = 0;
                this.prevY = 0;
            }
            onOpened() {
                super.onOpened();
                this.boxLock.visible = true;
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                this.buttonModelPreview.fOnClick = () => {
                };
                this.buttonResetRecord.fOnClick = () => {
                    mgrRecord.resetRecord();
                };
                this.buttonPwdConfrim.fOnClick = () => {
                    let input = this.boxLock.getChildByName("inputPwd");
                    let dt = new Date();
                    if (input.text == `ul_${ul.format("%02d", dt.getHours())}`) {
                        this.boxLock.visible = false;
                    }
                };
                this.buttonTest.fOnClick = () => {
                    mgrDirector.openDialog(`vTestDialog`);
                };
                let cops = mgrCop.getCops();
                let str = `渠道名：${mgrChannel._channelName}\n`;
                str += `sdcardPath: ${Const.sdcardPath}\n`;
                str += `packageVersion: ${Const.packageVersion}\n`;
                str += `copChannelId: ${Const.copChannelId}\n`;
                str += `ulsdkVersion: ${Const.ulsdkVersion}\n`;
                str += `cdkChannelId: ${Const.cdkChannelId}\n`;
                str += "\n";
                str += `_cardType: ${mgrChannel._cardType}\n`;
                str += `_isThirdExit: ${mgrChannel._isThirdExit}\n`;
                str += `_isAbout: ${mgrChannel._isAbout}\n`;
                str += `_isMoreGame: ${mgrChannel._isMoreGame}\n`;
                str += `_isULMoreGame: ${mgrChannel._isULMoreGame}\n`;
                str += `_isShowUrlAdIcon: ${mgrChannel._isShowUrlAdIcon}\n`;
                str += `_isPayEnabled: ${mgrChannel._isPayEnabled}\n`;
                str += `_isShareEnabled: ${mgrChannel._isShareEnabled}\n`;
                str += `_isUseSdkRank: ${mgrChannel._isUseSdkRank}\n`;
                str += `_isSupportRecordShare: ${mgrChannel._isSupportRecordShare}\n`;
                str += `_isSupportClipboardData: ${mgrChannel._isSupportClipboardData}\n`;
                str += `_isSupportInstallShortcut: ${mgrChannel._isSupportInstallShortcut}\n`;
                str += `_isSupportFindMinigames: ${mgrChannel._isSupportFindMinigames}\n`;
                str += `_isSupportRecommendationBtn: ${mgrChannel._isSupportRecommendationBtn}\n`;
                str += `interPushConfig Length: ${mgrChannel.interPushConfig.length}\n`;
                str += "\n";
                Tools.forEachMap(cops, (key, value) => {
                    str += `\n${key}：${value}`;
                    console.log(`\n${key}：${value}`);
                });
                this.labelCop.text = str;
                this.labelCop.on(Laya.Event.MOUSE_DOWN, this, this.startScrollText);
            }
            onClosed() {
                super.onClosed();
            }
            startScrollText(e) {
                this.prevX = this.labelCop.mouseX;
                this.prevY = this.labelCop.mouseY;
                Laya.stage.on(Laya.Event.MOUSE_MOVE, this, this.scrollText);
                Laya.stage.on(Laya.Event.MOUSE_UP, this, this.finishScrollText);
            }
            finishScrollText(e) {
                Laya.stage.off(Laya.Event.MOUSE_MOVE, this, this.scrollText);
                Laya.stage.off(Laya.Event.MOUSE_UP, this, this.finishScrollText);
            }
            scrollText(e) {
                var nowX = this.labelCop.mouseX;
                var nowY = this.labelCop.mouseY;
                this.labelCop.textField.scrollX += this.prevX - nowX;
                this.labelCop.textField.scrollY += this.prevY - nowY;
                this.prevX = nowX;
                this.prevY = nowY;
            }
        }

        class vDesktopIconDilaog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vDesktopIconDilaog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                this.labelCountReward.text = `${mgrChannel.getInstallShortCutRewardCount()}`;
                Tools.loadImg(this.imageIconReward, mgrPlayer.getIcon(1));
                this.add3DEffectAtFront("eff_ui_wg_loop", this.imageIconReward);
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonShare() {
                mgrSdk.installShortcut();
                this.closeDialog();
            }
        }

        class vDouyinDesktop extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vDouyinDesktop";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                let spriteIcons = [this.spriteIcon1];
                for (let i = 0; i < spriteIcons.length; i++) {
                    const spriteIcon = spriteIcons[i];
                    spriteIcon.alpha = 0;
                }
                if (mgrChannel.findmeImageUrl) {
                    for (let i = 0; i < spriteIcons.length; i++) {
                        const spriteIcon = spriteIcons[i];
                        spriteIcon.loadImage(mgrChannel.findmeImageUrl);
                        spriteIcon.alpha = 1;
                    }
                }
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                this.buttonClose.fOnClick = this.onTouchButttonClose.bind(this);
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onTouchButttonClose() {
                this.closeDialog();
            }
        }

        class vDouyinFollow extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vDouyinFollow";
                this.items = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.registerListeners({
                    "FOLLOW_OFFICIAL_ACCOUNT_SUC": this.onMsgFollowOfficialAccountSuc.bind(this),
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            buildUi() {
                let rewardsDb = mgrCfg.getDb("follow_rewards_db");
                console.log("查看rewardsDb", rewardsDb);
                for (let key in rewardsDb) {
                    let rewardData = rewardsDb[key];
                    let item = { itemId: rewardData.id, count: rewardData.count };
                    this.items.push(item);
                }
                this.fillData();
            }
            fillData() {
                if (mgrSdk.followState == 2) {
                    if (mgrPlayer.getItemAmount(99) <= 0) {
                        this.labelButtonFollow.text = "关注领取";
                    }
                    else {
                        this.labelButtonFollow.text = "关注领取";
                    }
                }
                else {
                    if (mgrPlayer.getItemAmount(99) > 0) {
                        this.labelButtonFollow.text = "已领取";
                    }
                    else {
                        this.labelButtonFollow.text = "关注领取";
                    }
                }
            }
            getRewards() {
                mgrPlayer.addItemAmount(99, 1, "关注抖音账号领奖次数");
                console.log("查看items", this.items);
                for (let i = 0; i < this.items.length; i++) {
                    let item = this.items[i];
                    if (item.itemId && item.count) {
                        mgrPlayer.addItemAmount(item.itemId, item.count, "关注抖音账号领奖");
                        mgrTip.addGotItemTip(item.itemId, item.count);
                    }
                }
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonFollow() {
                mgrSdk.followOfficialAccount();
            }
            onTouchButtonFollow2() {
                mgrSdk.followOfficialAccount();
            }
            onMsgFollowOfficialAccountSuc(e) {
                console.log("onMsgFollowOfficialAccountSuc=====", e);
                this.fillData();
                if (mgrSdk.followState == 1 && mgrPlayer.getItemAmount(99) <= 0) {
                    console.log("查看followState", mgrSdk.followState, mgrPlayer.getItemAmount(99));
                    this.getRewards();
                }
                this.closeDialog();
            }
        }

        class vDouyinSmallGame extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vDouyinSmallGame";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                let spriteIcons = [this.spriteIcon1];
                for (let i = 0; i < spriteIcons.length; i++) {
                    const spriteIcon = spriteIcons[i];
                    spriteIcon.alpha = 0;
                }
                if (mgrChannel.findmeImageUrl) {
                    for (let i = 0; i < spriteIcons.length; i++) {
                        const spriteIcon = spriteIcons[i];
                        spriteIcon.loadImage(mgrChannel.findmeImageUrl);
                        spriteIcon.alpha = 1;
                    }
                }
                this.buttonClose.fOnClick = this.onTouchButttonClose.bind(this);
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onTouchButttonClose() {
                this.closeDialog();
            }
        }

        class vEditorColorDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vEditorColorDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buttonClose.fOnClick = () => {
                    this.closeDialog(true);
                };
                this.__fillSideColor();
                this.mainColor = this.__getSideColorByPos(0, 0);
                this.curColor = this.mainColor;
                this.__fillMainColor();
                this.__fillCurColor();
                this.registerTouch();
            }
            onClosed() {
                super.onClosed();
            }
            isShowShadow() {
                return false;
            }
            registerTouch() {
                Tools.registerTouchHander(this.spriteSide, (e) => {
                    if (!e.isClick)
                        return;
                    let localPoint = this.spriteSide.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                    this.mainColor = this.__getSideColorByPos(localPoint.x, localPoint.y);
                    this.__fillMainColor();
                });
                let bDown = false;
                Tools.registerTouchHander(this.spriteMainHandle, (e) => {
                    if (e.isBegin)
                        bDown = true;
                    if (e.isEnd)
                        bDown = false;
                    if (!bDown)
                        return;
                    let localPoint = this.spriteMain.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                    this.curColor = this.__getMainColorByPos(localPoint.x, localPoint.y);
                    this.curColor.r = ul.clamp(this.curColor.r, 0, 255);
                    this.curColor.g = ul.clamp(this.curColor.g, 0, 255);
                    this.curColor.b = ul.clamp(this.curColor.b, 0, 255);
                    this.__fillCurColor();
                    this.context.colorChange && this.context.colorChange(this.curColor);
                });
            }
            __fillSideColor() {
                this.spriteSide.graphics.clear(true);
                for (let x = 0; x <= this.spriteSide.width; x++) {
                    for (let y = 0; y <= this.spriteSide.height; y++) {
                        let color = this.__getSideColorByPos(x, y);
                        let hexColor = `#${this.__toHex(color.r)}${this.__toHex(color.g)}${this.__toHex(color.b)}`;
                        this.spriteSide.graphics.drawRect(x, y, 1, 1, hexColor);
                    }
                }
            }
            __fillMainColor() {
                this.spriteMain.graphics.clear(true);
                for (let x = 0; x <= this.spriteMain.width; x++) {
                    for (let y = 0; y <= this.spriteMain.height; y++) {
                        let color = this.__getMainColorByPos(x, y);
                        let hexColor = `#${this.__toHex(color.r)}${this.__toHex(color.g)}${this.__toHex(color.b)}`;
                        this.spriteMain.graphics.drawRect(x, y, 1, 1, hexColor);
                    }
                }
            }
            __fillCurColor() {
                let hexColor = this.__colorToHex(this.curColor);
                this.labelColor.text = hexColor;
                this.labelRGB.text = `${this.curColor.r}:${this.curColor.g}:${this.curColor.b}`;
                this.spriteColor.graphics.clear(true);
                this.spriteColor.graphics.drawPie(this.spriteColor.width / 2, this.spriteColor.height / 2, 15, 0, 360, hexColor);
            }
            __getSideColorByPos(x, y) {
                let height = this.spriteSide.height;
                if (y < 0 || y > height)
                    return new Laya.Color(0, 0, 0, 0);
                let rArray = [255, 255, 0, 0, 0, 255, 255];
                let gArray = [0, 255, 255, 255, 0, 0, 0];
                let bArray = [0, 0, 0, 255, 255, 255, 0];
                let persent = y / height;
                for (let i = 1; i <= 6; i++) {
                    if (persent <= i / 6) {
                        let localPersent = (persent - (i - 1) / 6) / (1 / 6);
                        return new Laya.Color(Math.floor(rArray[i - 1] * (1 - localPersent) + rArray[i] * localPersent), Math.floor(gArray[i - 1] * (1 - localPersent) + gArray[i] * localPersent), Math.floor(bArray[i - 1] * (1 - localPersent) + bArray[i] * localPersent));
                    }
                }
            }
            __getMainColorByPos(x, y) {
                let width = this.spriteMain.width;
                let height = this.spriteMain.height;
                let xPersent = x / width;
                let yPersent = y / height;
                let r = 255 * (1 - xPersent) + this.mainColor.r * xPersent;
                let g = 255 * (1 - xPersent) + this.mainColor.g * xPersent;
                let b = 255 * (1 - xPersent) + this.mainColor.b * xPersent;
                r = r * (1 - yPersent) + 0 * yPersent;
                g = g * (1 - yPersent) + 0 * yPersent;
                b = b * (1 - yPersent) + 0 * yPersent;
                r = Math.floor(r);
                g = Math.floor(g);
                b = Math.floor(b);
                return new Laya.Color(r, g, b);
            }
            __colorToHex(color) {
                let hexColor = `#${this.__toHex(color.r)}${this.__toHex(color.g)}${this.__toHex(color.b)}`;
                return hexColor;
            }
            __toHex(n) {
                let f = 0;
                while (n >= 16) {
                    f++;
                    n = n - 16;
                }
                let b = n;
                let m = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
                return m[f] + m[b];
            }
        }

        class vEditorMaterialImgSelectDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vEditorMaterialImgSelectDialog";
                this.arr = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.fillData();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.context.mType = this.context.mType || 0;
                let arr = [];
                let dbArr = mgrCfg.getDbArr("material_img_db");
                for (let k in dbArr) {
                    let data = dbArr[k];
                    if (this.context.mType != data.mType) {
                        continue;
                    }
                    arr.push({
                        id: data.id,
                        fOnClick: this.onClickItem.bind(this)
                    });
                }
                this.arr = arr;
                this.reuseList = new ReuseList(2, 0, 6);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vMaterialImgItem);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(0);
                this.reuseList.setSpaceY(0);
            }
            fillData() {
                this.reuseList.setDatas(this.arr);
            }
            onClickItem(id) {
                if (this.context.fOnClick) {
                    this.context.fOnClick(id);
                }
                this.closeDialog();
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonClean() {
                mgrTip.alertPrompt2("清除", "是否【清除】对应【shader中】选择的图片？", "不清除", "清除", null, () => {
                    if (this.context.fOnClean) {
                        this.context.fOnClean();
                    }
                    this.closeDialog();
                });
            }
        }
        class vMaterialImgItem extends ReuseListItem {
            constructor() {
                super();
                let width = 250;
                let height = 250;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.sprite = new Laya.Sprite();
                this.sprite.size(width, height);
                this.addChild(this.sprite);
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.label.stroke = 2;
                this.label.strokeColor = `#ff0000`;
                this.addChild(this.label);
                this.button = this.sprite.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = this.data.id || "unknown";
                let template = mgrCfg.get_from_material_img_db(this.data.id);
                Tools.loadImg(this.sprite, template.materialImg);
            }
        }

        class vEditorUiTipInfoDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vEditorUiTipInfoDialog";
                this.exportNodeNames = [];
                this.openedViewCount = 0;
                this.triggeredVideoCount = 0;
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_WARP_SCENE_COMPLETED: this.onMsgWarpSceneCompleted.bind(this),
                    MSG_DIALOG_OPEN: this.onMsgDialogOpen.bind(this),
                    MSG_VIDEO_AD_EVENT_START: this.onMsgVideoAdEventStart.bind(this)
                });
                this.widget();
                this.exportNodeNames = [];
                this.__dialogRoot.y -= (Laya.stage.height / 2 + 1280 / 2 - this.imageContainer.height);
                this.__dialogRoot.zOrder = 10000;
                this.inputNode.visible = false;
                this.buttonCdkey.__node.visible = false;
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onAnimationFinished() {
            }
            onMsgWarpSceneCompleted(e) {
                this.openedViewCount++;
                let arr = [];
                let str = this.labelViewName.text;
                if (!!this.labelViewName.text) {
                    arr = this.labelViewName.text.split("\n");
                    if (arr.length > 3) {
                        str = "";
                        for (let i = arr.length - 3 - 1; i < arr.length; i++) {
                            str += arr[i];
                            if (i != (arr.length - 1)) {
                                str += "\n";
                            }
                        }
                    }
                }
                this.labelViewName.text = `最近打开界面\n${str}\n${this.openedViewCount}-${e.viewName || "Unknow"}\n`;
                this.showCurrViewPointContent(e.viewName);
            }
            onMsgDialogOpen(e) {
                this.openedViewCount++;
                this.labelViewName.text = `${this.labelViewName.text}\n${this.openedViewCount}-${e.viewName || "Unknow"}\n`;
                this.showCurrViewPointContent(e.viewName);
            }
            showCurrViewPointContent(viewName) {
                let pointIdStr = "当前界面打点\n";
                pointIdStr += "video\n";
                mgrCfg.forDb_from_ad_event_db((k, v) => {
                    if (v.id.startsWith("video_") && v.id.indexOf(viewName) >= 0) {
                        pointIdStr += `${v.pointEventId}\n`;
                    }
                });
                pointIdStr += "\nint\n";
                mgrCfg.forDb_from_ad_event_db((k, v) => {
                    if (v.id.startsWith("int_") && v.id.indexOf(viewName) >= 0) {
                        pointIdStr += `${v.pointEventId}\n`;
                    }
                });
                pointIdStr += "\nbanner\n";
                mgrCfg.forDb_from_ad_event_db((k, v) => {
                    if (v.id.startsWith("banner_") && v.id.indexOf(viewName) >= 0) {
                        pointIdStr += `${v.pointEventId}\n`;
                    }
                });
                pointIdStr += "\nbutton\n";
                let baseSceneName = mgrDirector.getCur2DSceneName();
                mgrCfg.forDb_from_ui_button_click_point_event_db((k, v) => {
                    for (let tmp in v) {
                        let tmpBtnDataArr = v[tmp];
                        for (let bt in tmpBtnDataArr) {
                            let oneData = tmpBtnDataArr[bt];
                            if (oneData.viewName != viewName) {
                                return;
                            }
                            if (oneData.viewName == viewName && (!oneData.parentViewName || (!!baseSceneName && oneData.parentViewName == baseSceneName))) {
                                pointIdStr += `${oneData.selfPointEventId}\n`;
                            }
                        }
                    }
                });
                let copStr = mgrCop.get("video_share_cds");
                if (copStr.indexOf(viewName) >= 0) {
                    pointIdStr += `\nshare:Yes\n`;
                }
                else {
                    pointIdStr += `\nshare:No\n`;
                }
                copStr = mgrCop.get("show_trigger_native_banner_switch");
                if (copStr.indexOf(viewName) >= 0) {
                    pointIdStr += `\nclickBannerBtn:Yes\n`;
                }
                else {
                    pointIdStr += `\nclickBannerBtn:No\n`;
                }
                this.labelCurrViewPoints.text = pointIdStr || "Unknow";
            }
            onMsgVideoAdEventStart(e) {
                if (!e || !e.adEventId) {
                    return;
                }
                let adEventId = e.adEventId;
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                this.triggeredVideoCount++;
                let arr = [];
                let str = this.labelTriggerVideoAd.text;
                if (!!this.labelTriggerVideoAd.text) {
                    arr = this.labelTriggerVideoAd.text.split("\n");
                    if (arr.length > 3) {
                        str = "";
                        for (let i = arr.length - 3 - 1; i < arr.length; i++) {
                            str += arr[i];
                            if (i != (arr.length - 1)) {
                                str += "\n";
                            }
                        }
                    }
                }
                this.labelTriggerVideoAd.text = `最近触发视频\n${str}\n${this.triggeredVideoCount}-${adEventData.pointEventId || "Unknow"}\n`;
                this.showCurrViewPointContent(e.viewName);
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonCdkey() {
            }
        }

        class vFindMeDialogBaidu extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vFindMeDialogBaidu";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
        }

        class vFindMeDialogDouyin extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vFindMeDialogDouyin";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                let spriteIcons = [this.spriteIcon1];
                for (let i = 0; i < spriteIcons.length; i++) {
                    const spriteIcon = spriteIcons[i];
                    spriteIcon.alpha = 0;
                }
                if (mgrChannel.findmeImageUrl) {
                    for (let i = 0; i < spriteIcons.length; i++) {
                        const spriteIcon = spriteIcons[i];
                        spriteIcon.loadImage(mgrChannel.findmeImageUrl);
                        spriteIcon.alpha = 1;
                    }
                }
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
        }

        class vFindMeDialogToutiao extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vFindMeDialogToutiao";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                let spriteIcons = [this.spriteIcon1, this.spriteIcon2];
                for (let i = 0; i < spriteIcons.length; i++) {
                    const spriteIcon = spriteIcons[i];
                    spriteIcon.alpha = 0;
                }
                if (mgrChannel.findmeImageUrl) {
                    for (let i = 0; i < spriteIcons.length; i++) {
                        const spriteIcon = spriteIcons[i];
                        spriteIcon.loadImage(mgrChannel.findmeImageUrl);
                        spriteIcon.alpha = 1;
                    }
                }
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
        }

        class vFindMeDialogWeixin extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vFindMeDialogWeixin";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                let spriteIcons = [this.spriteIcon1, this.spriteIcon2, this.spriteIcon3, this.spriteIcon4];
                for (let i = 0; i < spriteIcons.length; i++) {
                    const spriteIcon = spriteIcons[i];
                    spriteIcon.alpha = 0;
                }
                if (mgrChannel.findmeImageUrl) {
                    for (let i = 0; i < spriteIcons.length; i++) {
                        const spriteIcon = spriteIcons[i];
                        spriteIcon.loadImage(mgrChannel.findmeImageUrl);
                        spriteIcon.alpha = 1;
                    }
                }
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
        }

        class vFreedomRoomPreviewTalkItem extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vFreedomRoomPreviewTalkItem";
                this.exportNodeNames = [];
                this.size(388, 80);
                this.anchorY = 0;
                this.anchorX = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
            }
            onClosed() {
                super.onClosed();
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.spriteLeftContainer.visible = !data.bSelf;
                this.spriteRightContainer.visible = !this.spriteLeftContainer.visible;
                if (!!data.bSelf) {
                    Tools.loadImg(this.spriteRightHeadIcon, data.icon);
                    this.labelRightWord.text = `${data.text}`;
                }
                else {
                    Tools.loadImg(this.spriteLeftHeadIcon, data.icon);
                    this.labelLeftWord.text = `${data.text}`;
                }
            }
        }

        class vFreedomRoomPreviewDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vFreedomRoomPreviewDialog";
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.initUi();
                this.widget();
                this.uiActionIn(() => {
                });
                this.startGuide();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            buildUi() {
                this.topBar = new vTopBar({ bDisableDiamond: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vFreedomRoomPreviewDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
                this.reuseList = new ReuseList(1, 0, 6);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vFreedomRoomPreviewTalkItem);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(40);
                this.reuseList.setSpaceY(0);
            }
            initUi() {
                let stageData = mgrCfg.get_from_stage_db(this.context.stageId);
                let storyId = stageData.storyId;
                let storyDatas = mgrCfg.get_from_story_db(storyId);
                if (!!storyDatas) {
                    let enemyName = "";
                    let arr = [];
                    let showRoleData = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                    let targetRoleData = mgrCfg.get_from_role_db(this.context.targetRoleId);
                    for (let i = 0; i < storyDatas.length; i++) {
                        let data = storyDatas[i];
                        if (!data.bSelf && !enemyName) {
                            enemyName = data.name;
                        }
                        arr.push({ name: data.bSelf ? showRoleData.name : targetRoleData.name, icon: data.bSelf ? showRoleData.headIcon : targetRoleData.headIcon, text: data.text, bSelf: data.bSelf });
                    }
                    this.labelEnemyName.text = enemyName;
                    this.reuseList.setDatas(arr);
                    this.reuseList.tweenTo(arr.length - 1, 1);
                }
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                this.labelItemAmount1.text = `+${stageData.bestRewardRmbAmount}`;
                let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.cloth);
                let itemData = mgrCfg.get_from_item_template_db(rewardPartId);
                if (!!itemData && itemData.type) {
                    let itemTypeData = mgrCfg.get_from_item_type_db(itemData.type);
                    Tools.loadImg(this.spriteItemIcon2, itemTypeData.iconTcutShot);
                    this.labelItemAmount2.text = `+${stageData.bestRewardColorPoint}`;
                }
                else {
                    this.spriteItem2.visible = false;
                }
            }
            uiActionIn(callback) {
                if (mgrSdk.getCopNumberValueByKey("b_disable_ui_enter_effect") == 1) {
                    callback && callback();
                    return;
                }
                mgrEffect.playComebackAction([this.spritePhoneContainer], 0, -mgrDirector.height, 0, 1, callback);
            }
            startGuide() {
                mgrGuide.registerGuideNode(`vFreedomRoomPreviewDialog.buttonStart`, this.buttonStart.__node);
                if (!mgrGuide.isFinished(201)) {
                    mgrGuide.startGuide(201);
                }
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonBack() {
                this.closeDialog(true);
            }
            onTouchButtonStart() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vFreedomRoomPreviewDialog.clickButtonStart` });
                mgrStage.beginStage(this.context.stageId, false, () => {
                    mgrWorldDaily.cleanGameTempParms(DailyGameType.cloth);
                    mgrWorldDaily.addPlayedGameStageId(DailyGameType.cloth, this.context.stageId);
                    this.closeDialog(true);
                });
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vFullScreenMoreGameItem extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vFullScreenMoreGameItem";
                this.exportNodeNames = [];
                this.size(150, 180);
                this.anchorY = 0;
                this.anchorX = 0;
            }
            onOpened() {
                super.onOpened();
                this.buttonGet = this.imageIcon.addComponent(ScaleButton);
                this.buttonGet.fOnClick = this.onButtonGetClick.bind(this);
                this.data && this.fillByData(this.data);
            }
            onClosed() {
                super.onClosed();
            }
            onButtonGetClick() {
                let userData = {
                    jumpGameIndex: this.data.index || this.data.gameId,
                };
                let jsonStr = JSON.stringify(userData);
                this.data.fOnClickItem(this.data.index, "list", jsonStr);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                Tools.loadImg(this.imageIcon, data.url);
            }
        }

        class vFullScreenMoreGame extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vFullScreenMoreGame";
                this.exportNodeNames = [];
                this.JUMP_TYPE = "list";
            }
            onOpened() {
                super.onOpened();
                this.buttonClose.__node.visible = false;
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                    MSG_SDK_JUMP_OTHER_GAME_RESULT: this.onMsgJumpOtherGameResult.bind(this),
                });
                mgrSdk.openJump(Const.gameIndex, this.JUMP_TYPE);
                let guideHhand = new Laya.Image;
                this.guideHhand = guideHhand;
                guideHhand.size(1, 1);
                guideHhand.anchorX = 0.5;
                guideHhand.anchorY = 0.5;
                this.spriteFinger.addChild(guideHhand);
                let xsydSprite3d = mgrLoader.Pool.getModel("eff_ui_xsyd");
                this.add3DEffectAtFront(xsydSprite3d, guideHhand, 0);
                xsydSprite3d.transform.rotationEuler = new Laya.Vector3(0, 0, 0);
                let copTime = mgrSdk.getCopNumberValueByKey("full_screen_more_game_close_btn_delay_time") || 0;
                Timer.callLater(copTime, () => {
                    this.buttonClose.__node.visible = true;
                }, this);
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
            }
            onMsgOpenJumpResult(e) {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (e.type == this.JUMP_TYPE) {
                    let datas = e.jumpInfo;
                    for (let index = 0; index < datas.length; index++) {
                        const element = datas[index];
                        element.fOnClickItem = this.onClickItem.bind(this);
                    }
                    this.fillData(datas);
                    this.autoClick();
                }
            }
            onMsgJumpOtherGameResult(e) {
                if (e.bSuccessful) {
                    this.closeDialog();
                }
            }
            autoClick() {
                if (this.datas && mgrSdk.getCopNumberValueByKey("b_auto_jump_other_game_full_screen_more_game") == 1) {
                    mgrSdk.jumpOtherGame(this.datas[Tools.random(0, this.datas.length - 1)].index, "list", null);
                }
            }
            fillData(datas) {
                if (this.datas)
                    return;
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(3, 0, 10);
                    this.reuseList.size(this.boxList.width, this.boxList.height);
                    this.boxList.addChild(this.reuseList);
                    this.reuseList.setItemClass(vFullScreenMoreGameItem);
                    this.reuseList.setVerticalMoveEnable(true);
                    this.reuseList.setSpaceX(5);
                    this.reuseList.setSpaceY(5);
                }
                this.reuseList.setDatas(datas);
                this.datas = datas;
                Timer.callLoop(0.016, () => {
                    if (this.guideHhand.visible && this.reuseList && this.reuseList.scrollValue > 0) {
                        this.guideHhand.visible = false;
                    }
                }, this);
            }
            onClickItem(index, param1, param2) {
                this.spriteFinger.visible = false;
                mgrSdk.jumpOtherGame(index, param1, param2);
            }
            onTouchButtonStart() {
                this.onClickItem(this.datas[Tools.random(0, this.datas.length - 1)].index, "list", null);
            }
            onTouchButtonClose() {
                mgrDirector.openDialog("vFullScreenMoreGame2");
                this.closeDialog();
            }
        }

        class vFullScreenMoreGameItem2 extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vFullScreenMoreGameItem2";
                this.exportNodeNames = [];
                this.size(172.5, 207);
                this.anchorY = 0;
                this.anchorX = 0;
            }
            onOpened() {
                super.onOpened();
                this.buttonGet = this.imageIcon.addComponent(ScaleButton);
                this.buttonGet.fOnClick = this.onButtonGetClick.bind(this);
                this.data && this.fillByData(this.data);
            }
            onClosed() {
                super.onClosed();
            }
            onButtonGetClick() {
                let userData = {
                    jumpGameIndex: this.data.index || this.data.gameId,
                };
                let jsonStr = JSON.stringify(userData);
                this.data.fOnClickItem(this.data.index, "list", jsonStr);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                Tools.loadImg(this.imageIcon, data.url);
            }
        }

        class vFullScreenMoreGame2 extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vFullScreenMoreGame2";
                this.exportNodeNames = [];
                this.JUMP_TYPE = "list";
            }
            onOpened() {
                super.onOpened();
                this.buttonClose.__node.visible = false;
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                    MSG_SDK_JUMP_OTHER_GAME_RESULT: this.onMsgJumpOtherGameResult.bind(this),
                });
                mgrSdk.openJump(Const.gameIndex, this.JUMP_TYPE);
                let guideHhand = new Laya.Image;
                this.guideHhand = guideHhand;
                guideHhand.size(1, 1);
                guideHhand.anchorX = 0.5;
                guideHhand.anchorY = 0.5;
                this.addChild(guideHhand);
                this.add3DEffectAtFront(`eff_ui_xsyd_hand`, guideHhand, 0);
                let localPosStart = { x: this.spriteFinger.x, y: this.spriteFinger.y };
                let localPosEnd = { x: this.spriteFinger2.x, y: this.spriteFinger2.y };
                guideHhand.pos(localPosStart.x, localPosStart.y);
                CustomTween.to(guideHhand, { x: localPosEnd.x, y: localPosEnd.y }, 1000)
                    .callback(() => {
                    guideHhand.pos(localPosStart.x, localPosStart.y);
                })
                    .start(0);
                let copTime = mgrSdk.getCopNumberValueByKey("full_screen_more_game_close_btn_delay_time") || 0;
                Timer.callLater(copTime, () => {
                    this.buttonClose.__node.visible = true;
                }, this);
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
            }
            onMsgOpenJumpResult(e) {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (e.type == this.JUMP_TYPE) {
                    let datas = e.jumpInfo;
                    for (let index = 0; index < datas.length; index++) {
                        const element = datas[index];
                        element.fOnClickItem = this.onClickItem.bind(this);
                    }
                    this.fillData(datas);
                    this.autoClick();
                }
            }
            onMsgJumpOtherGameResult(e) {
                if (e.bSuccessful) {
                    this.closeDialog();
                }
            }
            autoClick() {
                if (this.datas && mgrSdk.getCopNumberValueByKey("b_auto_jump_other_game_full_screen_more_game2") == 1) {
                    mgrSdk.jumpOtherGame(this.datas[Tools.random(0, this.datas.length - 1)].index, "list", null);
                }
            }
            fillData(datas) {
                if (this.datas)
                    return;
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(2, 0, 15);
                    this.reuseList.size(this.boxList.width, this.boxList.height);
                    this.boxList.addChild(this.reuseList);
                    this.reuseList.setItemClass(vFullScreenMoreGameItem2);
                    this.reuseList.setVerticalMoveEnable(true);
                    this.reuseList.setSpaceX(25);
                    this.reuseList.setSpaceY(5);
                }
                this.reuseList.setDatas(datas);
                this.datas = datas;
                Timer.callLoop(0.016, () => {
                    if (this.guideHhand.visible && this.reuseList && this.reuseList.scrollValue > 0) {
                        this.guideHhand.visible = false;
                    }
                }, this);
            }
            onClickItem(index, param1, param2) {
                this.guideHhand.visible = false;
                mgrSdk.jumpOtherGame(index, param1, param2);
            }
            onTouchButtonStart() {
                this.onClickItem(this.datas[Tools.random(0, this.datas.length - 1)].index, "list", null);
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
        }

        class ULSkeleton extends Laya.Sprite {
            constructor(path, loadedCallback, frameRate = 30) {
                super();
                this._playingBackRate = 1;
                this.path = path;
                this.loadedCallback = loadedCallback;
                let templet = ULSkeleton.allTemplets[path];
                let bLoading = !!ULSkeleton.loadingTemplets[path];
                if (templet && !bLoading) {
                    this.templet = templet;
                    this.parseComplete();
                    return;
                }
                else {
                    if (!templet) {
                        templet = new Laya.Templet();
                        templet.rate = frameRate;
                        templet.on(Laya.Event.COMPLETE, this, this.parseComplete);
                        templet.on(Laya.Event.ERROR, this, this.onError);
                        templet.loadAni(path);
                        this.templet = templet;
                    }
                    else {
                        templet.on(Laya.Event.COMPLETE, this, this.parseComplete);
                        templet.on(Laya.Event.ERROR, this, this.onError);
                        this.templet = templet;
                    }
                }
            }
            onError() {
                console.log("骨骼动画初始化 parse error");
            }
            parseComplete() {
                console.log("骨骼动画初始化 成功!!!");
                let skeleton;
                skeleton = this.templet.buildArmature(2);
                this.templet.lock = true;
                skeleton.showSkinByName("normal");
                this.addChild(skeleton);
                this.bLoaded = true;
                this.skeleton = skeleton;
                ULSkeleton.allTemplets[this.path] = this.templet;
                if (this.playingAnimationName)
                    this.playAnimation(this.playingAnimationName, this.bPlayingLoop, this.playEndCallback, this.firstPlayEndCallbackParams);
                if (this._playingBackRate)
                    this.timeScale = this._playingBackRate;
                this.loadedCallback && this.loadedCallback();
            }
            getBoneLocalPosByName(name) {
                if (!this.skeleton) {
                    return new Laya.Vector2;
                }
                let boneArr = this.skeleton["_boneList"];
                if (!boneArr || boneArr.length <= 0) {
                    return new Laya.Vector2;
                }
                for (let k in boneArr) {
                    let bone = boneArr[k];
                    if (bone.name == name) {
                        return new Laya.Vector2(bone.resultMatrix.tx, bone.resultMatrix.ty);
                    }
                }
                return new Laya.Vector2;
            }
            playAnimation(name, loop = true, firstPlayEndCallback, firstPlayEndCallbackParams) {
                this.bPlayingLoop = loop;
                this.playingAnimationName = name;
                this.playEndCallback = firstPlayEndCallback;
                this.firstPlayEndCallbackParams = firstPlayEndCallbackParams;
                if (!this.bLoaded)
                    return;
                this.skeleton.play(this.playingAnimationName, loop);
                if (this.playCallbackTimer) {
                    this.playCallbackTimer.stop();
                    this.playCallbackTimer = null;
                }
                if (this.playEndCallback) {
                    this.playCallbackTimer = Timer.callLater(Math.max(0, this.skeleton.player.playDuration / 1000 - 0.02), () => {
                        if (this.destroyed) {
                            return;
                        }
                        let params = Tools.deepCopy(this.firstPlayEndCallbackParams);
                        let temp = this.playEndCallback;
                        this.playEndCallback = null;
                        this.firstPlayEndCallbackParams = null;
                        temp && temp(params);
                    }, this);
                }
            }
            set timeScale(value) {
                this._playingBackRate = value;
                if (!this.bLoaded)
                    return;
                this.skeleton.playbackRate(this._playingBackRate);
            }
            get timeScale() {
                return this._playingBackRate;
            }
            static create(spineId, loadedCallback, frameRate = 30) {
                let spineData = mgrCfg.get_from_spine_db(spineId);
                if (!spineData)
                    return null;
                return new ULSkeleton(spineData.path, loadedCallback, frameRate);
            }
            static getRealNameByMovName(spineId, movName) {
                let spineData = mgrCfg.get_from_spine_db(spineId);
                if (!spineData)
                    return null;
                return spineData[movName];
            }
        }
        ULSkeleton.allTemplets = {};
        ULSkeleton.loadingTemplets = {};

        class vGiftOpenDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vGiftOpenDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                CustomTween.rotateForever(this.spriteLight, 10000);
                mgrSound.play(104);
            }
            onClosed() {
                super.onClosed();
            }
            fillData() {
                let spine = ULSkeleton.create("ui_lihe");
                this.boxAnchor.addChild(spine);
                spine.x = this.boxAnchor.width / 2;
                spine.y = this.boxAnchor.height / 2;
                spine.playAnimation("idle1");
                let endPos = this.boxAnchor.localToGlobal(new Laya.Point(spine.x, spine.y));
                spine.scale(0.1, 0.1);
                let wPos = this.context.wPos || new Laya.Point(Laya.stage.width / 2, Laya.stage.height / 2);
                let localPos = this.boxAnchor.globalToLocal(wPos);
                spine.pos(localPos.x, localPos.y);
                CustomTween.jumpTo(spine, endPos, 1, 500, () => {
                    Tools.registerTouchHander(this.boxAnchor, (e) => {
                        if (!e.isClick)
                            return;
                        Tools.unRegisterTouchHander(this.boxAnchor);
                        spine.playAnimation("idle2", false, () => {
                            this.context.fOnOpen && this.context.fOnOpen();
                            CustomTween.delayTime(this, 500).to({ alpha: 0 }, 500)
                                .callback(() => {
                                this.closeDialog();
                            })
                                .start(1);
                        });
                    });
                });
            }
        }

        class vGotItemDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vGotItemDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.nativeBanner = mgrActivingBanner.activingAlertBanner(2, this);
                if (mgrMidAutumn.isEnable()) {
                    Tools.loadImg(this.spriteTitle, "res/ui/got_item_zz/sprite_title_mid_autumn.png");
                }
                this.buttonExchange.__node.visible = false;
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.widget();
                this.fadeIn(this.onFadeInFinished.bind(this));
                let oldCloseFunc = this.context.fOnClose;
                this.context.fOnClose = () => {
                    if (mgrSwitchOpen.checkOpenDialog("vAdPopMachineDialog")) {
                        mgrDirector.openDialog("vAdPopMachineDialog", {
                            fOnClose: () => {
                                if (oldCloseFunc) {
                                    oldCloseFunc();
                                }
                            }
                        });
                    }
                    else {
                        if (oldCloseFunc) {
                            oldCloseFunc();
                        }
                    }
                };
            }
            onClosed() {
                super.onClosed();
                if (this.nativeBanner) {
                    this.nativeBanner.activingBannerClose();
                    this.nativeBanner = null;
                }
            }
            widget() {
            }
            onFadeInFinished() {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (this.spriteAdButtonContainer.visible) {
                    cc.tween(this.spriteAdButtonContainer).toAlpha(0.03, 1).start();
                    if (mgrGuide.isAllForceGuideFinished() && this.buttonGetAd.__node.visible && mgrSdk.getCopNumberValueByKey("guide_ad_button_second") > 0) {
                        this.add3DEffectAtFront("eff_ui_xsyd", this.buttonGetAd.__node, mgrSdk.getCopNumberValueByKey("guide_ad_button_second") || 0);
                    }
                }
                if (this.buttonClose.__node.visible) {
                    cc.tween(this.buttonClose.__node).toScale(0.5, 1).start();
                }
                this.tryShowSomeDialog();
            }
            tryShowSomeDialog() {
            }
            fillData() {
                let itemId = this.context.itemId;
                let itemData = mgrCfg.get_from_item_template_db(itemId);
                Tools.loadImg(this.imageSpriteIcon, mgrPlayer.getIcon(itemId), true, () => {
                    let deltaScale = 176 / this.imageSpriteIcon.height;
                    this.imageSpriteIcon.scale(deltaScale, deltaScale);
                });
                let amount = this.context.amount;
                console.log("------------------vGotItemDialog amount=", amount);
                this.labelCount.text = `*${mgrPlayer.getItemAmountStr(Math.floor(amount))}`;
                this.labelName.text = itemData.name;
                let bExtrnalAdReward = false;
                if (mgrGuide.isAllForceGuideFinished() && !this.context.bGuideEffect && !this.context.bFromAd && this.context.orderOfQueue == 0 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward)) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                    mgrAd.markFinished(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward);
                    bExtrnalAdReward = true;
                    this.adRewardAmount = mgrPlayer.gotAdGotExternalAmount();
                }
                this.adaptAdMode(bExtrnalAdReward);
                if (bExtrnalAdReward) {
                    console.log("------------------vGotItemDialog this.adRewardAmount=", this.adRewardAmount);
                    this.labelRewardAmount.text = `${mgrPlayer.getItemAmountStr(this.adRewardAmount)}`;
                    this.buttonGetAd.__node.visible = true;
                    this.labelButtonGetNormal.text = "直接领取";
                }
                else {
                    this.buttonClose.__node.scale(0, 0);
                }
                if (this.context.bTriple) {
                    this.labelGetAd.text = "三倍领取";
                    this.labelRewardAmount.text = `*${mgrPlayer.getItemAmountStr(Math.floor(amount * 3))}`;
                    this.adRewardAmount = Math.floor(amount * 3);
                }
                if (!mgrGuide.isAllForceGuideFinished() || this.context.bGuideEffect) {
                    this.add3DEffectAtFront("eff_ui_xsyd", this.buttonGetNormal.__node, 0);
                }
                this.spriteExtraFlag.visible = false;
                if (this.context.bExtra) {
                    this.spriteExtraFlag.visible = true;
                }
                if (itemId == Const.ITEM_ID_MOON_CAKE && mgrMidAutumn.isEnable()) {
                    this.buttonExchange.__node.visible = true;
                    this.buttonGetAd.__node.visible = false;
                }
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vGotItemDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            adaptAdMode(bAd) {
                this.spriteAdButtonContainer.alpha = 0;
                this.buttonClose.__node.visible = false;
                this.labelButtonGetNormal.text = "确定";
                this.buttonGetNormal.__node.visible = true;
                this.buttonGetAd.__node.visible = false;
                this.spriteAdCheckModeContainer.visible = false;
                this.buttonAdAreaContent.__node.visible = false;
                this.buttonAdAreaScreen.__node.visible = false;
                if (!bAd) {
                    return;
                }
                this.buttonAdCheckModel.bTween = false;
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                if (mgrSdk.getCopNumberValueByKey("b_ad_check_mode") == 1 && (Tools.time() - mgrCop.lastAdCheckModelValidTime) >= mgrSdk.getCopNumberValueByKey("ad_check_mode_gap_second")) {
                    mgrCop.lastAdCheckModelValidTime = Tools.time();
                    this.buttonClose.__node.visible = false;
                    this.spriteAdCheckModeContainer.visible = true;
                    if (!this.adCheckModeConfig) {
                        let config = mgrAd.randomGetAdCheckModeConfig("额外领取");
                        this.labelAdCheckModelTip.text = config.text;
                        this.spriteAdCheckModeCheckFlag.visible = !!config.bDefaultChecked;
                        this.adCheckModeConfig = config;
                    }
                }
                this.buttonClose.__node.visible = !this.buttonGetNormal.__node.visible ? true : false;
                let b_extra_mistake = mgrSdk.getCopNumberValueByKey("b_extra_mistake") == 1 ? true : false;
                if (b_extra_mistake) {
                    this.buttonClose.__node.visible = true;
                    this.buttonGetNormal.__node.visible = false;
                    this.spriteAdBg.loadImage("res/ui/common/b2_pink.png");
                    this.labelGetAd.strokeColor = "#ff85a7";
                }
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward) {
                    this.bCostSuccess = true;
                    this.buttonGetAd.__node.visible = false;
                    this.buttonGetNormal.__node.visible = true;
                    this.spriteAdCheckModeContainer.visible = false;
                    this.labelButtonGetNormal.text = "确定";
                }
            }
            fadeOut() {
                cc.tween(this.spriteIconBg, true)
                    .toScale(0.05, 0)
                    .call(() => {
                    if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                        return;
                    }
                    cc.tween(this.spriteBg, true)
                        .toScale(0.05, 0)
                        .call(() => {
                        if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                            return;
                        }
                        this.closeDialog(true);
                    })
                        .start();
                })
                    .start();
            }
            fadeIn(callback) {
                this.onFindStartPosition(this.context.wPos, callback);
            }
            onFindStartPosition(wPos, callback) {
                let originPos = new Laya.Point(this.spriteBg.x, this.spriteBg.y);
                if (wPos) {
                    let startPos = this.spriteBg.parent.globalToLocal(wPos);
                    this.spriteBg.pos(startPos.x, startPos.y);
                }
                else {
                    this.spriteBg.pos(originPos.x + 50, originPos.y - 200);
                }
                this.spriteBg.scale(0, 0, true);
                let offsetSpriteTitleY = 500;
                this.spriteTitle.y -= offsetSpriteTitleY;
                cc.tween(this.spriteTitle)
                    .byPos(0.02, 0, offsetSpriteTitleY)
                    .start();
                cc.tween(this.spriteBg).parallel(cc.tween().then(cc.jumpTo(0.05, originPos.x, originPos.y, 100, 1)), cc.tween().toScale(0.05, 1)).call(() => {
                    if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                        return;
                    }
                    mgrSound.play(103);
                    callback && callback();
                }).start();
            }
            onTouchButtonClose() {
                this.fadeOut();
            }
            onTouchButtonGetAd() {
                let rewards = [
                    [Const.ITEM_ID_DIAMONDS, this.adRewardAmount, this.adRewardAmount],
                ];
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward, { rewards: rewards }, true);
            }
            onTouchButtonAdCheckModel() {
                this.spriteAdCheckModeCheckFlag.visible = !this.spriteAdCheckModeCheckFlag.visible;
            }
            onTouchButtonGetNormal() {
                if (!this.adCheckModeConfig || this.bCostSuccess) {
                    this.onTouchButtonClose();
                    return;
                }
                if ((this.adCheckModeConfig.bCheckedTriggerAd && this.spriteAdCheckModeCheckFlag.visible) || (!this.spriteAdCheckModeCheckFlag.visible && !this.adCheckModeConfig.bCheckedTriggerAd)) {
                    this.onTouchButtonGetAd();
                }
                else {
                    this.onTouchButtonClose();
                }
            }
            onTouchButtonNoThanks() {
                this.onTouchButtonClose();
            }
            onTouchButtonAdAreaContent() {
                if (this.bCostSuccess) {
                    this.onTouchButtonClose();
                }
                else {
                    this.onTouchButtonGetAd();
                }
            }
            onTouchButtonAdAreaScreen() {
                if (this.bCostSuccess) {
                    this.onTouchButtonClose();
                }
                else {
                    this.onTouchButtonGetAd();
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonExchange() {
                mgrDirector.openDialog("vMidAutumnActivityDialog");
            }
        }

        class vGotNewDoubleRoleDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vGotNewDoubleRoleDialog";
            }
            onOpened() {
                this.bullidUi();
                super.onOpened();
            }
            bullidUi() {
                let cardId = this.context.cardId;
                if (!cardId) {
                    return;
                }
                let cardData = mgrDoubleNpcCard.getCardDataByCardId(cardId);
                let styleData = mgrCfg.get_from_amuse_card_style_db(cardData.cardStyleId);
                let roleData = mgrCfg.get_from_amuse_double_npc_card_role_pic_db(cardData.npcPicId);
                let tagData = mgrCfg.get_from_part_tag_db(cardData.roleTagId);
                Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                Tools.loadImg(this.spriteShowingPhoto, roleData.texture);
                Tools.loadImg(this.spriteShowingPhotoBg, styleData.textureBack);
                Tools.loadImg(this.spriteShowingPhotoMask, styleData.textureFront);
                this.labelRoleName.text = cardData.name;
                this.labelShowingPower.text = cardData.fightPower.toString();
                for (let i = 0; i < 5; i++) {
                    let spriteStar = this.spriteStarContainer.getChildAt(i);
                    let level = mgrCard.calculateCardLevelStarByPower(cardData.fightPower);
                    spriteStar.visible = level > i;
                }
                this.boxShowingPhotoContainer.visible = true;
            }
            onClosed() {
                super.onClosed();
                let fOnClose = this.context.fOnClose;
                if (fOnClose) {
                    fOnClose();
                }
            }
            onTouchButtonReceive() {
                this.closeDialog();
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
        }

        class vGotNewRoleDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vGotNewRoleDialog";
                this.bAd = true;
                this.img = null;
                if (this.context.bBanAd) {
                    this.bAd = false;
                }
            }
            getPreLoadModelIds() {
                let preloadModelIdArr = [
                    "116_ui_once_bao_08",
                ];
                return preloadModelIdArr;
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.buildUi();
                this.widget();
                this.playUiOut();
                this.playUiIn();
                Timer.callLoop(0.016, () => {
                    if (mgrSdk.getCopNumberValueByKey("b_vGotNewRoleDialog_trigger_native_banner") != 1 || !mgrBannerInt.isNativeBannerShowing()) {
                        this.buttonTriggerNativeBanner0.__node.visible = false;
                        this.buttonTriggerNativeBanner.__node.visible = false;
                    }
                }, this);
            }
            onClosed() {
                super.onClosed();
                mgrTip.hideLoadingTip("vGotNewRoleDialog_genCard");
            }
            buildUi() {
                mgrLoader.loadFont("card_power", this.labelShowingPower);
                this.boxShowingPhotoContainer.visible = false;
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let curFragmentNum = mgrPlayer.getItemAmount(roleData.unlockItemId);
                this.spriteRoleGray.addChild(this.spriteRoleMask);
                this.spriteRoleMask.y += curFragmentNum / roleData.unlockItemAmount * this.spriteRoleMask.height;
                this.spriteRoleMask.removeSelf();
                this.labelRoleName.text = roleData.name;
                Tools.loadImg(this.spriteRole, roleData.bodyIcon);
                Tools.loadImg(this.spriteRoleGray, roleData.bodyIconGray);
                this.spriteRoleGray.mask = this.spriteRoleMask;
                Tools.loadImg(this.spriteFragment, mgrPlayer.getIcon(roleData.unlockItemId));
                Tools.loadImg(this.spriteFragment1, mgrPlayer.getIcon(roleData.unlockItemId));
                this.refreshUi();
                if (this.context.labelBtnGiveUp && this.context.labelBtnGiveUp != "") {
                    let label = this.buttonGiveUp.__node.getChildByName("label");
                    if (label) {
                        label.text = `${this.context.labelBtnGiveUp}`;
                    }
                }
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
            }
            playUiOut() {
                this.boxBeforeGet.visible = false;
                this.buttonBack.__node.visible = false;
                this.buttonGiveUp.__node.visible = false;
                this.buttonAd.__node.visible = false;
            }
            playUiIn() {
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let curFragmentNum = mgrPlayer.getItemAmount(roleData.unlockItemId);
                let needFragmentNum = roleData.unlockItemAmount;
                if (mgrPlayer.getItemAmount(this.context.roleId) <= 0 && curFragmentNum >= needFragmentNum) {
                }
                else {
                    mgrEffect.playComebackAction([this.boxBeforeGet], 0, -500, 0.5, 0.3);
                    this.img = new Laya.Image(mgrPlayer.getIcon(roleData.unlockItemId));
                    this.img.size(100, 100);
                    this.img.anchorX = 0.5;
                    this.img.anchorY = 0.5;
                    this.img.alpha = 0;
                }
                let parent = this.boxEffect;
                parent.addChild(this.img);
                let buttons = [this.buttonBack.__node, this.buttonGiveUp.__node, this.buttonAd.__node];
                buttons.forEach(v => {
                    v.scale(0, 0, true);
                });
                this.spriteTitle.alpha = 0;
                cc.tween(this.spriteTitle).toAlpha(0.1, 1).start();
                let callback = () => {
                    let titleNodes = [this.labelRoleProgress, this.spriteFragment];
                    for (let i = 0; i < titleNodes.length; i++) {
                        let cell = titleNodes[i];
                        cc.tween(cell)
                            .to(0.05, { scaleX: 1.1, scaleY: 1.1 })
                            .to(0.05, { scaleX: 1, scaleY: 1 })
                            .call(() => {
                            this.refreshUi(true);
                            mgrGuide.registerGuideNode(`vGotNewRoleDialog.buttonReceive`, this.buttonReceive.__node);
                            if (!mgrGuide.isFinished(400)) {
                                mgrGuide.startGuide(400);
                            }
                            if (i == titleNodes.length - 1) {
                                for (let j = 0; j < buttons.length; j++) {
                                    let cell = buttons[j];
                                    cell.scale(0, 0, true);
                                    cc.tween(cell)
                                        .toScale(0.05, 1, cc.Ease.backOut)
                                        .start();
                                }
                            }
                        })
                            .start();
                    }
                };
                if (this.context.bVip) {
                    this.gotFragment(callback);
                }
                else {
                    callback();
                }
            }
            gotFragment(callback) {
                this.boxButtons.visible = false;
                this.buttonBack.__node.visible = false;
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                mgrPlayer.addItemAmount(roleData.unlockItemId, 1, "获得角色碎片");
                if (!this.img) {
                    this.img = new Laya.Image(mgrPlayer.getIcon(roleData.unlockItemId));
                    this.img.size(100, 100);
                    this.img.anchorX = 0.5;
                    this.img.anchorY = 0.5;
                    let parent = this.boxEffect;
                    parent.addChild(this.img);
                }
                let endNode;
                endNode = this.boxBeforeShowing;
                this.add3DEffectAtFront(MODEL_ID.effect.eff_ui_jiesuan_tuowei, this.img);
                let wPos = this.boxEffect.localToGlobal(new Laya.Point(this.boxEffect.width / 2, this.boxEffect.height / 2));
                let parent = this.img.parent;
                let pos = parent.globalToLocal(wPos, true);
                this.img.pos(pos.x, pos.y);
                this.img.zOrder = 1000;
                this.img.alpha = 1;
                let deltaX = Math.random() > 0.5 ? Tools.random(200, 500) : Tools.random(-200, -500);
                let pos2 = new Laya.Vector2(pos.x + deltaX, pos.y);
                let endWPos = endNode.localToGlobal(new Laya.Point(endNode.width / 2, endNode.height / 2));
                endWPos = parent.globalToLocal(endWPos);
                mgrSound.play(117);
                CustomTween.bezierCurveMotion(pos, pos2, endWPos, this.img, 500)
                    .callback(() => {
                    this.add3DEffectAtFront('116_ui_once_bao_08', this.boxBeforeShowing);
                    this.spriteRoleGray.addChild(this.spriteRoleMask);
                    this.spriteRoleMask.removeSelf();
                    cc.tween(this.spriteRoleMask)
                        .toPos(0.1, 191, this.spriteRoleMask.height / roleData.unlockItemAmount * mgrPlayer.getItemAmount(roleData.unlockItemId))
                        .call(() => {
                        if (callback) {
                            callback();
                        }
                    })
                        .start();
                    this.img.destroy();
                    this.img = null;
                })
                    .start(1);
            }
            refreshUi(bDisableStaticsAd) {
                this.boxButtons.visible = true;
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let curFragmentNum = mgrPlayer.getItemAmount(roleData.unlockItemId);
                this.labelRoleProgress.text = `${curFragmentNum}/${roleData.unlockItemAmount}`;
                let needAmount = Math.max(0, roleData.unlockItemAmount - curFragmentNum);
                this.labelGotNumAgain.text = `${needAmount}`;
                this.spriteGotTip.visible = needAmount > 0 ? true : false;
                this.boxBeforeGet.visible = curFragmentNum < roleData.unlockItemAmount;
                this.boxGet.visible = curFragmentNum >= roleData.unlockItemAmount;
                this.buttonReceive.__node.visible = this.boxGet.visible;
                this.buttonTriggerNativeBanner0.__node.visible = mgrSdk.getCopNumberValueByKey("b_vGotNewRoleDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing();
                this.buttonTriggerNativeBanner.__node.visible = (this.buttonReceive.__node.visible && mgrSdk.getCopNumberValueByKey("b_vGotNewRoleDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                this.buttonAd.__node.visible = this.bAd && (curFragmentNum < roleData.unlockItemAmount) && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotNewRoleDialog_fragment);
                this.buttonGiveUp.__node.visible = !this.buttonTriggerNativeBanner0.__node.visible && (curFragmentNum < roleData.unlockItemAmount) && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotNewRoleDialog_fragment);
                this.buttonBack.__node.visible = (!this.buttonReceive.__node.visible && mgrGuide.isAllForceGuideFinished()) ? true : false;
                if (!bDisableStaticsAd) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vGotNewRoleDialog_fragment);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
            }
            showPhotoContainer() {
                this.boxBeforeShowing.visible = false;
                this.boxShowingPhotoContainer.visible = true;
                this.spriteShowingPhotoTitle.visible = false;
                this.buttonOk.__node.visible = false;
                this.spriteShine.visible = false;
                this.spriteShowingPhotoNewFlag.scale(0, 0, true);
                this.boxShowingPhotoContainer.scale(0, 0, true);
                cc.tween(this.boxShowingPhotoContainer)
                    .toScale(0.15, 1)
                    .call(() => {
                    this.spriteShine.visible = true;
                    cc.tween(this.spriteShine).repeatForever(cc.tween().byRotation(6, 360)).start();
                })
                    .delay(0.1)
                    .call(() => {
                    mgrEffect.playComebackAction([this.spriteShowingPhotoTitle], 0, -500, 0, 0.7);
                    mgrEffect.playComebackAction([this.buttonOk.__node], 0, 800, 0, 0.9);
                })
                    .start();
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                mgrSdk.statisCommonEvent(roleData.unlockStatisPointId);
                mgrPlayer.addItemAmount(this.context.roleId, 1, "获得角色");
                for (let k in roleData.centerPartIds) {
                    mgrPlayer.addItemAmount(roleData.centerPartIds[k], 1, "获得角色时得其部件");
                }
                let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                let defaultCardTexture = roleData.defaultCardTextureBig;
                let defalutCardStyle = roleData.defalutCardStyle;
                let textureBack = mgrCfg.get_from_amuse_card_style_db(defalutCardStyle).textureBack;
                let textureFront = mgrCfg.get_from_amuse_card_style_db(defalutCardStyle).textureFront;
                Tools.loadImg(this.spriteShowingPhotoBg, textureBack);
                Tools.loadImg(this.imageShowingPhoto, defaultCardTexture);
                Tools.loadImg(this.spriteShowingPhotoMask, textureFront);
                let power = mgrCard.calculateRoleTagPartIdsPower(roleData.roleTagId, roleData.centerPartIds);
                this.labelShowingPower.text = `${power}`;
                let star = mgrCard.calculateCardLevelStarByPower(power);
                let numChildren = this.spriteStarContainer.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let sprite = this.spriteStarContainer.getChildAt(i);
                    sprite.visible = star - 1 >= i ? true : false;
                }
                this.labelRoleName2.text = roleData.name;
                mgrGuide.registerGuideNode(`vGotNewRoleDialog.buttonOk`, this.buttonOk.__node);
                if (!mgrGuide.isFinished(401)) {
                    mgrGuide.startGuide(401);
                }
            }
            doSaveCard() {
                this.buttonOk.__node.visible = false;
                let roleId = this.context.roleId;
                let roleData = mgrCfg.get_from_role_db(roleId);
                mgrTip.showLoadingTip("vGotNewRoleDialog_genCard");
                Laya.loader.load(roleData.defaultCardTextureJsonPath, new Laya.Handler(this, (obj) => {
                    mgrTip.hideLoadingTip("vGotNewRoleDialog_genCard");
                    let datas = Laya.loader.getRes(roleData.defaultCardTextureJsonPath);
                    let cardId = this.context.cardId;
                    let textureKey = mgrCard.getRoleCardTextureKeyNameByCardId(cardId);
                    mgrRole.savePhotoData(textureKey, datas);
                    let styleId = roleData.defalutCardStyle;
                    let partIds = roleData.partIds;
                    let power = mgrCard.calculateRolePartIdsPower(roleId, partIds);
                    let hp = mgrCard.calculateRolePartIdsHp(roleId, partIds);
                    mgrCard.setPlayerCardInfo(cardId, roleId, styleId, textureKey, power, hp, partIds);
                    this.closeDialog(true);
                }));
            }
            onTouchButtonBack() {
                this.closeDialog(true);
            }
            onTouchButtonReceive() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vGotNewRoleDialog.clickButtonReceive` });
                this.showPhotoContainer();
            }
            onTouchButtonAd() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotNewRoleDialog_fragment, null, true);
            }
            onTouchButtonGiveUp() {
                this.closeDialog(true);
            }
            onTouchButtonOk() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vGotNewRoleDialog.clickButtonOk` });
                let emptyCardId = mgrCard.getMinEmptyDataCardId();
                if (!emptyCardId) {
                    let lockedCardId = mgrCard.getMinLockedCardId();
                    if (!!lockedCardId) {
                        let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment);
                        if (!!bCanAd) {
                            mgrTip.alertPrompt2("提示", "已没有更多的卡槽，是否解锁新的卡槽？", "不了", "好的", null, () => {
                                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment);
                                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment, { cardId: lockedCardId }, true);
                            });
                        }
                        else {
                            let coinAmount = Const.UNLOCK_ALBUM_CARD_COST;
                            let coinTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                            mgrTip.alertPrompt2("提示", `是否花费${coinAmount}${coinTemplate.name}【解锁卡槽】？`, "取消", "确定", null, () => {
                                if (mgrShop.tryConsumeItem(Const.ITEM_ID_DIAMONDS, coinAmount, "解锁卡册位置")) {
                                    mgrPlayer.addItemAmount(lockedCardId, 1, "解锁卡册位置");
                                    this.context.cardId = lockedCardId;
                                    this.doSaveCard();
                                }
                            });
                        }
                    }
                    else {
                        let arr = [];
                        mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                            arr.push(v.id);
                        });
                        this.context.cardId = Tools.randomGotOneArrayData(arr);
                        this.doSaveCard();
                    }
                }
                else {
                    this.context.cardId = emptyCardId;
                    this.doSaveCard();
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonTriggerNativeBanner0() {
                this.onTouchButtonTriggerNativeBanner();
            }
            onMsgAdEventSuccessd(e) {
                let userData = e.userData || {};
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vGotNewRoleDialog_fragment) {
                    this.gotFragment(this.refreshUi.bind(this));
                }
                else if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment) {
                    mgrPlayer.addItemAmount(userData.cardId, 1, "解锁卡册位置");
                    this.context.cardId = userData.cardId;
                    this.doSaveCard();
                }
            }
            openDialog(bImmediately = false) {
                super.openDialog(true);
            }
        }

        class vStarLevelItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vStarLevelItem";
                this.exportNodeNames = [];
                this.starLevel = -1;
            }
            onOpened() {
                this.name = "vStarLevelItem";
                if (this.starLevel != -1) {
                    this.fillByData(this.starLevel);
                }
            }
            onClosed() {
            }
            fillByData(starLevel) {
                this.starLevel = starLevel;
                if (!this.bResLoaded) {
                    return;
                }
                let nodeWidth = 33;
                let startX = 166 / 2 - starLevel * nodeWidth / 2 + nodeWidth / 2;
                for (let index = 0; index < 5; index++) {
                    let node = this.boxStars.getChildAt(index);
                    if (index < starLevel) {
                        node.visible = true;
                        node.pos(startX + nodeWidth * index, 15, true);
                    }
                    else {
                        node.visible = false;
                    }
                }
            }
        }

        class vGotPartDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vGotPartDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.nativeBanner = mgrActivingBanner.activingAlertBanner(3, this);
                if (mgrMidAutumn.isEnable()) {
                    Tools.loadImg(this.spriteTitle, "res/ui/got_item_zz/sprite_title_mid_autumn.png");
                }
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.widget();
                this.fadeIn(this.onFadeInFinished.bind(this));
                Timer.callLoop(0.016, () => {
                }, this);
                let oldCloseFunc = this.context.fOnClose;
                this.context.fOnClose = () => {
                    if (mgrSwitchOpen.checkOpenDialog("vAdPopMachineDialog")) {
                        mgrDirector.openDialog("vAdPopMachineDialog", {
                            fOnClose: () => {
                                if (oldCloseFunc) {
                                    oldCloseFunc();
                                }
                            }
                        });
                    }
                    else {
                        if (oldCloseFunc) {
                            oldCloseFunc();
                        }
                    }
                };
            }
            onClosed() {
                super.onClosed();
                if (this.nativeBanner) {
                    this.nativeBanner.activingBannerClose();
                    this.nativeBanner = null;
                }
            }
            widget() {
            }
            onFadeInFinished() {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (this.spriteAdButtonContainer.visible) {
                    cc.tween(this.spriteAdButtonContainer).toAlpha(0.03, 1).start();
                    if (mgrGuide.isAllForceGuideFinished() && !this.context.bGuideEffect && this.buttonGetAd.__node.visible && mgrSdk.getCopNumberValueByKey("guide_ad_button_second") > 0) {
                        this.add3DEffectAtFront("eff_ui_xsyd", this.buttonGetAd.__node, mgrSdk.getCopNumberValueByKey("guide_ad_button_second") || 0);
                    }
                }
                if (this.buttonClose.__node.visible) {
                    cc.tween(this.buttonClose.__node).toScale(0.5, 1).start();
                }
                this.tryShowSomeDialog();
            }
            tryShowSomeDialog() {
            }
            fillData() {
                let itemId = this.context.itemId;
                let itemData = mgrCfg.get_from_item_template_db(itemId);
                let partData = mgrCfg.get_from_part_db(itemId);
                Tools.loadImg(this.imageSpriteIcon, mgrPlayer.getIcon(itemId), true, () => {
                    let deltaScale = 176 / this.imageSpriteIcon.height;
                    this.imageSpriteIcon.scale(deltaScale, deltaScale);
                });
                this.labelName.text = itemData.name;
                console.log("查看level", partData.level);
                if (!this.starLevelNode) {
                    this.starLevelNode = new vStarLevelItem({});
                    this.starLevelNode.pos(this.spriteStarLevel.width / 2, this.spriteStarLevel.height / 2);
                    this.spriteStarLevel.addChild(this.starLevelNode);
                    this.starLevelNode.scale(0.7, 0.7, true);
                }
                this.starLevelNode.fillByData(partData.level);
                this.spriteStarLevel.visible = false;
                let repeatCount = mgrPlayer.getRepeatSellCount(this.context.itemId);
                this.boxOwnedContainer.visible = repeatCount > 0;
                if (repeatCount > 0) {
                    this.bAutoRecharged = true;
                    let itemData = mgrCfg.get_from_item_template_db(this.context.itemId);
                    let itemRechargeData = mgrCfg.get_from_item_template_db(itemData.sellItemId);
                    Tools.loadImg(this.spriteRechargedUnit, itemRechargeData.icon);
                    this.labelRechargedCount.text = `${mgrPlayer.getItemAmountStr(Math.floor(repeatCount))}`;
                }
                let bExtrnalAdReward = false;
                if (mgrGuide.isAllForceGuideFinished() && !this.context.bGuideEffect && !this.context.bFromAd && this.context.orderOfQueue == 0 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward)) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                    mgrAd.markFinished(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward);
                    bExtrnalAdReward = true;
                    this.adRewardAmount = mgrPlayer.gotAdGotExternalAmount();
                }
                this.adaptAdMode(bExtrnalAdReward);
                if (bExtrnalAdReward) {
                    this.labelRewardAmount.text = `${mgrPlayer.getItemAmountStr(this.adRewardAmount)}`;
                    this.buttonGetAd.__node.visible = true;
                    this.labelButtonGetNormal.text = "直接领取";
                }
                else {
                    this.buttonClose.__node.scale(0, 0);
                }
                if (!mgrGuide.isAllForceGuideFinished() || this.context.bGuideEffect) {
                    this.add3DEffectAtFront("eff_ui_xsyd", this.buttonGetNormal.__node, 0);
                }
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vGotPartDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            adaptAdMode(bAd) {
                this.spriteAdButtonContainer.alpha = 0;
                this.buttonClose.__node.visible = false;
                this.labelButtonGetNormal.text = "确定";
                this.buttonGetNormal.__node.visible = true;
                this.buttonGetAd.__node.visible = false;
                this.spriteAdCheckModeContainer.visible = false;
                this.buttonAdAreaContent.__node.visible = false;
                this.buttonAdAreaScreen.__node.visible = false;
                if (!bAd) {
                    return;
                }
                this.buttonAdCheckModel.bTween = false;
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                if (mgrSdk.getCopNumberValueByKey("b_ad_check_mode") == 1 && (Tools.time() - mgrCop.lastAdCheckModelValidTime) >= mgrSdk.getCopNumberValueByKey("ad_check_mode_gap_second")) {
                    mgrCop.lastAdCheckModelValidTime = Tools.time();
                    this.buttonClose.__node.visible = false;
                    this.spriteAdCheckModeContainer.visible = true;
                    if (!this.adCheckModeConfig) {
                        let config = mgrAd.randomGetAdCheckModeConfig("额外领取");
                        this.labelAdCheckModelTip.text = config.text;
                        this.spriteAdCheckModeCheckFlag.visible = !!config.bDefaultChecked;
                        this.adCheckModeConfig = config;
                    }
                }
                this.buttonClose.__node.visible = !this.buttonGetNormal.__node.visible ? true : false;
                let b_extra_mistake = mgrSdk.getCopNumberValueByKey("b_extra_mistake") == 1 ? true : false;
                if (b_extra_mistake) {
                    this.buttonClose.__node.visible = true;
                    this.buttonGetNormal.__node.visible = false;
                    this.spriteAdBg.loadImage("res/ui/common/b2_pink.png");
                    this.labelGetAd.strokeColor = "#ff85a7";
                }
            }
            fadeOut() {
                if (this.bAutoRecharged) {
                    let itemData = mgrCfg.get_from_item_template_db(this.context.itemId);
                    mgrTip.showGotItemEffect(itemData.sellItemId, itemData.sellItemAmount, this.imageSpriteIcon.localToGlobal(new Laya.Point(this.imageSpriteIcon.width / 2, this.imageSpriteIcon.height / 2)));
                    this.closeDialog();
                    return;
                }
                cc.tween(this.spriteIconBg, true)
                    .toScale(0.05, 0)
                    .call(() => {
                    if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                        return;
                    }
                    cc.tween(this.spriteBg, true)
                        .toScale(0.05, 0)
                        .call(() => {
                        if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                            return;
                        }
                        mgrTip.showGotItemEffect(this.context.itemId, this.context.amount, this.imageSpriteIcon.localToGlobal(new Laya.Point(this.imageSpriteIcon.width / 2, this.imageSpriteIcon.height / 2)));
                        this.closeDialog(true);
                    })
                        .start();
                })
                    .start();
            }
            fadeIn(callback) {
                this.onFindStartPosition(this.context.wPos, callback);
            }
            onFindStartPosition(wPos, callback) {
                let originPos = new Laya.Point(this.spriteBg.x, this.spriteBg.y);
                if (wPos) {
                    let startPos = this.spriteBg.parent.globalToLocal(wPos);
                    this.spriteBg.pos(startPos.x, startPos.y);
                }
                else {
                    this.spriteBg.pos(originPos.x + 50, originPos.y - 200);
                }
                this.spriteBg.scale(0, 0, true);
                let offsetSpriteTitleY = 500;
                this.spriteTitle.y -= offsetSpriteTitleY;
                cc.tween(this.spriteTitle)
                    .byPos(0.02, 0, offsetSpriteTitleY)
                    .call(() => {
                })
                    .start();
                cc.tween(this.spriteBg).parallel(cc.tween().then(cc.jumpTo(0.05, originPos.x, originPos.y, 100, 1)), cc.tween().toScale(0.05, 1)).call(() => {
                    if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                        return;
                    }
                    mgrSound.play(103);
                    callback && callback();
                }).start();
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward) {
                    this.bCostSuccess = true;
                    this.buttonGetAd.__node.visible = false;
                    this.buttonGetNormal.__node.visible = true;
                    this.spriteAdCheckModeContainer.visible = false;
                    this.labelButtonGetNormal.text = "确定";
                }
            }
            onTouchButtonClose() {
                this.fadeOut();
            }
            onTouchButtonGetAd() {
                let rewards = [
                    [Const.ITEM_ID_DIAMONDS, this.adRewardAmount, this.adRewardAmount],
                ];
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotItemDialog_extrnal_reward, { rewards: rewards }, true);
            }
            onTouchButtonAdCheckModel() {
                this.spriteAdCheckModeCheckFlag.visible = !this.spriteAdCheckModeCheckFlag.visible;
            }
            onTouchButtonGetNormal() {
                if (!this.adCheckModeConfig || this.bCostSuccess) {
                    this.onTouchButtonClose();
                    return;
                }
                if ((this.adCheckModeConfig.bCheckedTriggerAd && this.spriteAdCheckModeCheckFlag.visible) || (!this.spriteAdCheckModeCheckFlag.visible && !this.adCheckModeConfig.bCheckedTriggerAd)) {
                    this.onTouchButtonGetAd();
                }
                else {
                    this.onTouchButtonClose();
                }
            }
            onTouchButtonNoThanks() {
                this.onTouchButtonClose();
            }
            onTouchButtonAdAreaContent() {
                if (this.bCostSuccess) {
                    this.onTouchButtonClose();
                }
                else {
                    this.onTouchButtonGetAd();
                }
            }
            onTouchButtonAdAreaScreen() {
                if (this.bCostSuccess) {
                    this.onTouchButtonClose();
                }
                else {
                    this.onTouchButtonGetAd();
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vHotActivityListItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vHotActivityListItem";
                this.size(520, 200);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            onTouchButtonGo() {
                if (!this.data) {
                    return;
                }
                if (this.data.fOnClick) {
                    this.data.fOnClick(this.data.id);
                }
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let configData = null;
                let configDataArr = mgrCfg.get("hot_activity_db", this.data.id);
                for (let i = configDataArr.length - 1; i >= 0; i--) {
                    let tmpData = configDataArr[i];
                    if (!mgrGameResVersion.isValidGameResVersion(tmpData.gameResVersion)) {
                        continue;
                    }
                    configData = tmpData;
                    break;
                }
                if (!configData) {
                    return;
                }
                Tools.loadImg(this.spriteIcon, configData.icon);
            }
        }

        class vHotActivityDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vHotActivityDialog";
            }
            onOpened() {
                super.onOpened();
                this.widget();
                this.fillData();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                let configArr = [];
                let db = mgrCfg.getDb("hot_activity_db");
                for (let k in db) {
                    let configDataArr = db[k];
                    for (let i = configDataArr.length - 1; i >= 0; i--) {
                        let tmpData = configDataArr[i];
                        if (!mgrGameResVersion.isValidGameResVersion(tmpData.gameResVersion)) {
                            continue;
                        }
                        if (mgrSdk.getCopNumberValueByKey(tmpData.copFromRouteRatio) != 1) {
                            continue;
                        }
                        tmpData.order = mgrSdk.getCopNumberValueByKey(tmpData.copFromOrderRatio) || 0;
                        configArr.push(tmpData);
                        break;
                    }
                }
                configArr = Tools.sortArrayByField(configArr, ["-order", "-gameResVersion"]);
                let dataArr = [];
                for (let k in configArr) {
                    let tmpData = configArr[k];
                    dataArr.push({
                        id: tmpData.id,
                        fOnClick: this.onClickActityItem.bind(this)
                    });
                }
                let listParent = this.boxListLong;
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(1, 0, 5);
                    this.reuseList.size(listParent.width, listParent.height);
                    listParent.addChild(this.reuseList);
                    this.reuseList.setItemClass(vHotActivityListItem);
                    this.reuseList.setVerticalMoveEnable(true);
                    this.reuseList.setSpaceX(10);
                    this.reuseList.setSpaceY(15);
                }
                this.reuseList.setDatas(dataArr);
            }
            onClickActityItem(id) {
                let configDataArr = mgrCfg.get("hot_activity_db", id);
                for (let i = configDataArr.length - 1; i >= 0; i--) {
                    let configData = configDataArr[i];
                    if (!mgrGameResVersion.isValidGameResVersion(configData.gameResVersion)) {
                        continue;
                    }
                    mgrShop.goWidthRouterId(configData.router);
                    break;
                }
                this.closeDialog();
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
        }

        class vIntitleDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vIntitleDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                this.buttonClose.__node.visible = false;
                this.labelName.text = mgrPlayer.calcRandomName();
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onTouchButtonRandom() {
                this.labelName.text = mgrPlayer.calcRandomName();
            }
            onTouchButtonSure() {
                mgrPlayer.setName(this.labelName.text);
                this.closeDialog();
            }
        }

        class vIosInvateReview extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vIosInvateReview";
                this.items = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.fillData();
                this.registerListeners({});
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            buildUi() {
                let rewardsDb = mgrCfg.getDb("follow_rewards_db");
                console.log("查看rewardsDb", rewardsDb);
                for (let key in rewardsDb) {
                    let rewardData = rewardsDb[key];
                    let item = { itemId: rewardData.id, count: rewardData.count };
                    this.items.push(item);
                }
                this.fillData();
            }
            fillData() {
                this.buttonComment.__node.visible = true;
                this.buttonReward.__node.visible = false;
            }
            doComment() {
                Timer.callLater(5, () => {
                    this.buttonComment.__node.visible = false;
                    this.buttonReward.__node.visible = true;
                    this.labelReward.text = mgrPlayer.getItemAmount(99) <= 0 ? "领取奖励" : "已领取";
                }, this);
            }
            getRewards() {
                mgrPlayer.addItemAmount(99, 1, "关注抖音账号领奖次数");
                console.log("查看items", this.items);
                for (let i = 0; i < this.items.length; i++) {
                    let item = this.items[i];
                    if (item.itemId && item.count) {
                        mgrPlayer.addItemAmount(item.itemId, item.count, "关注抖音账号领奖");
                        mgrTip.addGotItemTip(item.itemId, item.count);
                    }
                }
                this.labelReward.text = mgrPlayer.getItemAmount(99) <= 0 ? "领取奖励" : "已领取";
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonComment() {
                mgrReview.recordReview();
                this.doComment();
            }
            onTouchButtonReward() {
                if (mgrPlayer.getItemAmount(99) <= 0) {
                    this.getRewards();
                }
            }
        }

        class vItemGotEffectDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vItemGotEffectDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                let texture2d = Laya.Texture2D.blackTexture;
                texture2d.width = 768;
                texture2d.height = 1280;
                let texture = new Laya.Texture(texture2d, undefined, 768, 1280);
                this.spriteBg.graphics.drawTexture(texture);
                this.imageDiamond.alpha = 0;
                this.imageEnergy.alpha = 0;
                this.buildUI();
                this.widget();
                this.fillData();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                this.nodeResource.alpha = 0;
                mgrLayout.widget(0.5, Laya.stage.height, this.spriteBottom, { x: 0.5, y: 1 });
                mgrLayout.widgetLeftTopMC(this.boxLeftTop);
            }
            buildUI() {
            }
            fillData() {
                this.labelDiamondCount.text = `${mgrPlayer.getItemAmount(Const.ITEM_ID_DIAMONDS)}`;
                this.labelEnergyCount.text = `${mgrPlayer.getItemAmount(Const.ITEM_ID_ENERGY)}`;
            }
            fadeIn() {
                this.showTop();
                this.fadeInTween && this.fadeInTween.clear();
                this.visible = true;
                this.fadeInTween = CustomTween.to(this.nodeResource, { alpha: 1 }, 400)
                    .delayTime(500)
                    .to({ alpha: 0 }, 400)
                    .callback(() => {
                    this.clearFrontScene();
                    this.boxEffect.destroyChildren();
                    this.visible = false;
                })
                    .start(1);
            }
            playAction(itemId, amount, wPos) {
                let needShowItemIds = [Const.ITEM_ID_GOLD, Const.ITEM_ID_DIAMONDS];
                if (needShowItemIds.indexOf(itemId) == -1)
                    return;
                this.fadeIn();
                let count = amount;
                if (count > 7)
                    count = 7;
                if (itemId == Const.ITEM_ID_GOLD) {
                    mgrSound.play(109);
                }
                else if (itemId == Const.ITEM_ID_DIAMONDS) {
                    mgrSound.play(109);
                }
                for (let i = 1; i <= count; i++) {
                    let img = new Laya.Image(mgrCfg.get_from_item_template_db(itemId).icon);
                    img.size(30, 30);
                    img.anchorX = 0.5;
                    img.anchorY = 0.5;
                    let parent = this.boxEffect;
                    parent.addChild(img);
                    let endNode;
                    if (itemId == Const.ITEM_ID_GOLD) {
                        endNode = this.imageEnergy;
                        this.add3DEffectAtFront(MODEL_ID.effect.eff_ui_jinbi_loop, img);
                    }
                    else if (itemId == Const.ITEM_ID_DIAMONDS) {
                        endNode = this.imageDiamond;
                        this.add3DEffectAtFront(MODEL_ID.effect.eff_ui_zuanshi_loop, img);
                    }
                    let pos = parent.globalToLocal(wPos, true);
                    img.pos(pos.x, pos.y);
                    img.zOrder = 1000;
                    let pos2 = new Laya.Vector2(pos.x + Tools.random(-500, 500), pos.y);
                    let endWPos = endNode.localToGlobal(new Laya.Point(endNode.width / 2, endNode.height / 2));
                    endWPos = parent.globalToLocal(endWPos);
                    CustomTween.bezierCurveMotion(pos, pos2, endWPos, img, 500)
                        .delayTime(50)
                        .callback(() => {
                        img.destroy();
                    })
                        .start(1);
                }
                if (itemId == Const.ITEM_ID_GOLD) {
                    let node = this.imageEnergy;
                    let oldCount = parseInt(this.labelEnergyCount.text);
                    let newCount = mgrPlayer.getItemAmount(Const.ITEM_ID_GOLD);
                    CustomTween.to(node, { alpha: 1 }, 800)
                        .actionFloat(oldCount, newCount, 300, (value) => {
                        this.labelEnergyCount.text = `${Math.floor(value)}`;
                    })
                        .to({ alpha: 0 }, 300)
                        .start(1);
                }
                else if (itemId == Const.ITEM_ID_DIAMONDS) {
                    let node = this.imageDiamond;
                    let oldCount = parseInt(this.labelDiamondCount.text);
                    let newCount = mgrPlayer.getItemAmount(Const.ITEM_ID_DIAMONDS);
                    CustomTween.to(node, { alpha: 1 }, 800)
                        .actionFloat(oldCount, newCount, 300, (value) => {
                        this.labelDiamondCount.text = `${Math.floor(value)}`;
                    })
                        .to({ alpha: 0 }, 300)
                        .start(1);
                }
            }
        }

        class vLuckDiamondDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vLuckDiamondDialog";
                this.exportNodeNames = [];
                this.DIAMOND_AD_REWARD_AMOUNT = 200;
            }
            onOpened() {
                super.onOpened();
                this.nativeBanner = mgrActivingBanner.activingAlertBanner(1, this);
                this.labelLeftAdCount.visible = false;
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
                if (this.spriteAdFlag.visible) {
                    this.add3DEffectAtFront("eff_ui_jinbi_star_loop", this.spriteEffect2);
                }
                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vHubScene_free_diamon);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            onClosed() {
                super.onClosed();
                if (this.nativeBanner) {
                    this.nativeBanner.activingBannerClose();
                    this.nativeBanner = null;
                }
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
            }
            fillData() {
                this.labelRewardAmountAd.text = mgrPlayer.getItemAmountStr(Math.floor(this.DIAMOND_AD_REWARD_AMOUNT));
                let count = mgrAd.getAdEventRemainCount(AD_EVENT_ID.VIDEO.video_vHubScene_free_diamon);
                this.labelLeftAdCount.text = `今日剩余次数:${count}`;
                if (mgrGuide.isAllForceGuideFinished() && this.buttonGetAd.__node.visible && mgrSdk.getCopNumberValueByKey("guide_ad_button_second") > 0) {
                    this.add3DEffectAtFront("eff_ui_xsyd", this.buttonGetAd.__node, mgrSdk.getCopNumberValueByKey("guide_ad_button_second") || 0);
                }
                this.adaptAdMode(true);
                this.buttonClose2.__node.visible = false;
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vLuckDiamondDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                    if (mgrSdk.getCopNumberValueByKey("b_vLuckDiamondDialog_trigger_native_banner") == 1) {
                        this.buttonNoNormal.__node.visible = false;
                        this.buttonClose2.__node.visible = true;
                        this.spriteBtns.x = 380;
                    }
                }, this);
            }
            adaptAdMode(bAd) {
                this.buttonClose.__node.visible = true;
                this.buttonAdAreaContent.__node.visible = false;
                this.buttonAdAreaScreen.__node.visible = false;
                if (!bAd) {
                    return;
                }
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                this.buttonNoNormal.__node.visible = true;
                this.buttonNoNormal.__node.x -= 100;
                this.buttonGetAd.__node.x += 100;
                this.buttonClose.__node.visible = !this.buttonNoNormal.__node.visible ? true : false;
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vHubScene_free_diamon) {
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, this.DIAMOND_AD_REWARD_AMOUNT, "免费钻石");
                    mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, this.DIAMOND_AD_REWARD_AMOUNT);
                    this.closeDialog();
                }
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vHubScene_free_diamon, null, true);
            }
            onTouchButtonNoNormal() {
                this.onTouchButtonClose();
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonClose2() {
                this.onTouchButtonClose();
            }
        }

        class vLuckEnergyDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vLuckEnergyDialog";
                this.ENERGY_AD_REWARD_AMOUNT = 5;
            }
            onOpened() {
                super.onOpened();
                this.labelLeftAdCount.visible = false;
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
                if (this.spriteAdFlag.visible) {
                    this.add3DEffectAtFront("eff_ui_jinbi_star_loop", this.spriteEffect2);
                }
                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vHubScene_free_energy);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
            }
            fillData() {
                this.labelRewardAmountAd.text = mgrPlayer.getItemAmountStr(Math.floor(this.ENERGY_AD_REWARD_AMOUNT));
                let count = mgrAd.getAdEventRemainCount(AD_EVENT_ID.VIDEO.video_vHubScene_free_energy);
                this.labelLeftAdCount.text = `今日剩余次数:${count}`;
                if (mgrGuide.isAllForceGuideFinished() && this.buttonGetAd.__node.visible && mgrSdk.getCopNumberValueByKey("guide_ad_button_second") > 0) {
                    this.add3DEffectAtFront("eff_ui_xsyd", this.buttonGetAd.__node, mgrSdk.getCopNumberValueByKey("guide_ad_button_second") || 0);
                }
                this.adaptAdMode(true);
                this.buttonTriggerNativeBanner.__node.visible = false;
                this.buttonClose2.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vLuckEnergyDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                    if (mgrSdk.getCopNumberValueByKey("b_vLuckEnergyDialog_trigger_native_banner") == 1) {
                        this.buttonClose2.__node.visible = true;
                        this.buttonNoNormal.__node.visible = false;
                        this.spriteBtns.x = 380;
                    }
                }, this);
            }
            adaptAdMode(bAd) {
                this.buttonClose.__node.visible = true;
                this.buttonAdAreaContent.__node.visible = false;
                this.buttonAdAreaScreen.__node.visible = false;
                if (!bAd) {
                    return;
                }
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                this.buttonNoNormal.__node.visible = true;
                this.buttonNoNormal.__node.x -= 100;
                this.buttonGetAd.__node.x += 100;
                this.buttonClose.__node.visible = !this.buttonNoNormal.__node.visible ? true : false;
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vHubScene_free_energy) {
                    mgrPlayer.addItemAmount(Const.ITEM_ID_ENERGY, this.ENERGY_AD_REWARD_AMOUNT, "免费体力");
                    mgrTip.addGotItemTip(Const.ITEM_ID_ENERGY, this.ENERGY_AD_REWARD_AMOUNT);
                    this.closeDialog();
                }
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vHubScene_free_energy, null, true);
            }
            onTouchButtonNoNormal() {
                this.onTouchButtonClose();
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonClose2() {
                this.onTouchButtonClose();
            }
        }

        class vMallItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vMallItem";
                this.exportNodeNames = [];
                this.size(466, 146);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.buttonBg.fOnClick = () => {
                    this.data && this.data.fOnClickBuy && this.data.fOnClickBuy(this.data.shopId);
                };
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let shopData = mgrCfg.get_from_shop_template_db(this.data.shopId);
                let itemId = shopData.items[0][0];
                let amount = shopData.items[0][1];
                if (itemId == Const.ITEM_ID_GOLD || itemId == Const.ITEM_ID_DIAMONDS) {
                    amount = Math.floor(amount);
                }
                Tools.loadImg(this.spriteRewardIcon, mgrPlayer.getIcon(itemId));
                Tools.loadImg(this.imageDescIcon, shopData.sprIcon);
                this.labelRewardAmount.text = `${amount}`;
                this.labelBuy.text = `${shopData.price}元`;
                if (cc.tween(this.spriteEffect).getNumberOfRunningActions() <= 0) {
                    cc.tween(this.spriteEffect).repeatForever(cc.tween().byRotation(6, 360)).start();
                }
            }
        }

        class vMallDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vMallDialog";
                this.exportNodeNames = [];
                this.COIN_TYPE = 151;
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.fillData();
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            buildUi() {
                this.mallReuseList = new ReuseList(1, 0, 6);
                this.mallReuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.mallReuseList);
                this.mallReuseList.setItemClass(vMallItem);
                this.mallReuseList.setVerticalMoveEnable(true);
            }
            fillData() {
                let datas = mgrShop.getAllShopItemListByCategory([this.COIN_TYPE], true);
                let arr = [];
                for (let k in datas) {
                    let data = datas[k];
                    arr.push({
                        shopId: data.id,
                        fOnClickBuy: this.onClickItem.bind(this),
                    });
                }
                this.mallReuseList.setDatas(arr);
            }
            onClickItem(shopId) {
                let shopData = mgrCfg.get_from_shop_template_db(shopId);
                if (!shopData) {
                    return;
                }
                mgrShop.requestBuy(shopId, "商城");
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
        }

        class vMidAutumnActItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vMidAutumnActItem";
                this.exportNodeNames = [];
                this.size(115, 170);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                Tools.loadImg(this.imageIcon, this.data.icon);
            }
            onTouchButtonBg() {
                if (this.data.fOnClick) {
                    this.data.fOnClick(this.data.actId);
                }
            }
        }

        class vMidAutumnPart extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vMidAutumnPart";
                this.exportNodeNames = [];
                this.size(90, 96);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.partId && this.fillByData(this.partId);
                this.registerListeners({
                    MSG_ROOM_PART_REFRESH: this.onMsgRoomPartRefresh.bind(this),
                });
            }
            onClosed() {
            }
            onMsgRoomPartRefresh() {
                this.partId && this.fillByData(this.partId);
            }
            fillByData(partId) {
                this.partId = partId;
                if (!this.bResLoaded)
                    return;
                let shopData = mgrCfg.get_from_shop_template_db(this.partId);
                let partData = mgrCfg.get_from_part_db(this.partId);
                Tools.loadImg(this.imageIcon, partData.icon);
                if (mgrPlayer.getItemAmount(this.partId) > 0) {
                    this.spriteOwned.visible = true;
                }
                else {
                    this.spriteOwned.visible = false;
                }
                this.spriteCoin.visible = (mgrPlayer.getItemAmount(this.partId) <= 0 && !!shopData && shopData.price > 0) ? true : false;
                if (!!shopData) {
                    this.labelPrice.text = `${shopData.price}`;
                }
            }
            onTouchButtonBg() {
                if (mgrPlayer.getItemAmount(this.partId) > 0) {
                    return;
                }
                mgrShop.requestBuy(this.partId, "中秋兑换");
            }
        }

        class vMidAutumnActivityDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vMidAutumnActivityDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.fillData();
                this.widget();
                this.uiActionIn();
                this.registerListeners({
                    MSG_ITEM_AMOUNT_CHANGED: this.onMsgItemAmountChanged.bind(this),
                });
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseList = new ReuseList(2, 0, 10);
                this.reuseList.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseList);
                this.reuseList.setItemClass(vMidAutumnPart);
                this.reuseList.setSpaceX(20);
                this.reuseList.setSpaceY(10);
                this.reuseList.alpha = 0;
                this.reuseActList = new ReuseList(0, 1, 3);
                this.reuseActList.size(this.boxActivityList.width, this.boxActivityList.height);
                this.boxActivityList.addChild(this.reuseActList);
                this.reuseActList.setItemClass(vMidAutumnActItem);
                this.reuseActList.setSpaceX(25);
                this.reuseActList.setSpaceY(0);
                this.progressBar.barName = this.progressBar.__node.name;
                this.progressBar.style = ULPROGRESSBAR_STYLE.hor;
            }
            widget() {
            }
            uiActionIn() {
                if (mgrSdk.getCopNumberValueByKey("b_disable_ui_enter_effect") == 1) {
                    this.reuseList.alpha = 1;
                    return;
                }
                Timer.callLater(0.5, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    this.reuseList.alpha = 1;
                    let cells = this.reuseList.getAllCells();
                    for (let i = 0; i < cells.length; i++) {
                        let cell = cells[i];
                        cell.scale(0, 0, true);
                        cc.tween(cell).delay(i * 0.1).toScale(0.15, 1, cc.Ease.backOut).start();
                    }
                }, this);
            }
            fillData() {
                let suitData = mgrMidAutumn.getMidSuitDatas() || {};
                let partIds = suitData.partIds;
                this.labelName.text = suitData.name;
                this.labelMoonCakeCount.text = "" + mgrPlayer.getItemAmount(Const.ITEM_ID_MOON_CAKE);
                this.reuseList.setDatas(partIds);
                let actListData = [
                    { id: 1, actId: DailyGameType.cake, name: "蛋糕烘焙", icon: "res/ui/mid_autumn/sprite_icon_cake.png", fOnClick: this.onClickActItem.bind(this) },
                    { id: 2, actId: DailyGameType.clothcrossing, name: "女神向前冲", icon: "res/ui/mid_autumn/sprite_icon_cross.png", fOnClick: this.onClickActItem.bind(this) },
                    { id: 3, actId: DailyGameType.custom_made, name: "定制衣服", icon: "res/ui/mid_autumn/sprite_icon_design.png", fOnClick: this.onClickActItem.bind(this) }
                ];
                this.reuseActList.setDatas(actListData);
                let [cur, max] = mgrMidAutumn.getSuitCollectProgress();
                this.labelProgress.text = cur + "/" + max;
                this.progressBar.progress = cur / max;
            }
            getRoleExceptShowingRole(gameType, muteRoleId) {
                let roleId = mgrWorldDaily.getGameTempParms(gameType);
                if (!!roleId && roleId != muteRoleId && roleId != mgrRole.showingRoleId) {
                    return mgrCfg.get_from_role_db(roleId);
                }
                let arr = [];
                let roleDataShowing = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (!!muteRoleId && v.id == muteRoleId) {
                        return;
                    }
                    if (!v.rootRoleId || v.rootRoleId != roleDataShowing.rootRoleId) {
                        arr.push(v);
                    }
                });
                return Tools.randomGotOneArrayData(arr);
            }
            onClickActItem(actId) {
                let worldDay = mgrWorldDaily.getWorldDay();
                switch (actId) {
                    case DailyGameType.cake: {
                        let config = mgrCfg.get_from_cake_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.cake, config.maxStageId);
                        let stageData = mgrCfg.get_from_cake_stage_db(stageId);
                        let commonCustomerFunc = () => {
                            let roleData = this.getRoleExceptShowingRole(DailyGameType.cake, stageData.cakeHumanMuteRoleId);
                            mgrWorldDaily.setGameTempParms(DailyGameType.cake, roleData.id);
                            mgrDirector.openDialog("vAmuseCakePreviewDialog", { stageId: stageId, roleId: roleData.id, bVip: false, fOnStart: () => { this.closeDialog(); mgrDirector.clear2DDialog(); }, ignoreSameScene: true });
                        };
                        if (stageData.id > 3 && Tools.random(100) < 50 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakePreviewVipDialog_vip)) {
                            mgrWorldDaily.addVipShowCountByGameType(DailyGameType.cake);
                            if (!mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.cake)) {
                                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAmuseCakePreviewVipDialog_vip);
                                if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                                    mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                                }
                            }
                            mgrWorldDaily.cleanGameTempParms(DailyGameType.cake);
                            let roleData = this.getRoleExceptShowingRole(DailyGameType.cake, stageData.cakeHumanMuteRoleId);
                            mgrDirector.openDialog("vAmuseCakePreviewVipDialog", { stageId: stageId, roleId: roleData.id, bVip: true, fOnGiveUp: commonCustomerFunc, fOnStart: () => { this.closeDialog(); mgrDirector.clear2DDialog(); }, ignoreSameScene: true });
                        }
                        else {
                            commonCustomerFunc();
                        }
                        break;
                    }
                    case DailyGameType.clothcrossing: {
                        let config = mgrCfg.get_from_cloth_crossing_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.clothcrossing, config.maxStageId);
                        mgrDirector.openDialog("vAmuseClothCrossingPreviewDialog", { stageId: stageId, fOnStart: () => { this.closeDialog(); mgrDirector.clear2DDialog(); }, ignoreSameScene: true });
                        break;
                    }
                    case DailyGameType.custom_made: {
                        let config = mgrCfg.get_from_custom_made_cloth_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.custom_made, config.maxStageId);
                        let commonCustomerFunc = () => {
                            let roleData = this.getRoleExceptShowingRole(DailyGameType.custom_made);
                            mgrWorldDaily.setGameTempParms(DailyGameType.custom_made, roleData.id);
                            mgrDirector.openDialog("vCustomMadeClothesPreviewDialog", { stageId: stageId, roleId: roleData.id, bVip: false, fOnStart: () => { this.closeDialog(); mgrDirector.clear2DDialog(); }, ignoreSameScene: true });
                        };
                        if (stageId > 3 && Tools.random(100) < 50 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesPreviewVipDialog_vip)) {
                            mgrWorldDaily.addVipShowCountByGameType(DailyGameType.custom_made);
                            if (!mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.custom_made)) {
                                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesPreviewVipDialog_vip);
                                if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                                    mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                                }
                            }
                            mgrWorldDaily.cleanGameTempParms(DailyGameType.custom_made);
                            let roleData = this.getRoleExceptShowingRole(DailyGameType.custom_made);
                            mgrDirector.openDialog("vCustomMadeClothesPreviewVipDialog", { stageId: stageId, roleId: roleData.id, bVip: true, fOnGiveUp: commonCustomerFunc, fOnStart: () => { this.closeDialog(); mgrDirector.clear2DDialog(); }, ignoreSameScene: true });
                        }
                        else {
                            commonCustomerFunc();
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onMsgItemAmountChanged(e) {
                this.fillData();
            }
        }

        class vMoreGameDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vMoreGameDialog";
                this.exportNodeNames = [];
                this.JUMP_TYPE = "list";
            }
            onOpened() {
                super.onOpened();
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                mgrSdk.openJump(Const.gameIndex, this.JUMP_TYPE);
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            buildUi(datas) {
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(3, 0, 10);
                    this.reuseList.size(this.boxList.width, this.boxList.height);
                    this.boxList.addChild(this.reuseList);
                    this.reuseList.setItemClass(vMoreGameItem);
                    this.reuseList.setVerticalMoveEnable(true);
                    this.reuseList.setSpaceX(30);
                    this.reuseList.setSpaceY(20);
                }
                this.reuseList.setDatas(datas);
            }
            onMsgOpenJumpResult(e) {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (e.type == this.JUMP_TYPE) {
                    let datas = e.jumpInfo;
                    this.buildUi(datas);
                }
            }
        }
        class vMoreGameItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 160;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.image = new Laya.Image;
                this.image.size(width, height);
                this.image.anchorX = 0.5;
                this.image.anchorY = 0.5;
                this.image.x = width / 2;
                this.image.y = height / 2;
                this.addChild(this.image);
                this.button = this.image.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                mgrSdk.jumpOtherGame(this.data.index, "list");
            }
            fillByData(data) {
                Tools.loadImg(this.image, data.url);
                this.data = data;
            }
        }

        class vMoreGameFriendHotPlayDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vMoreGameFriendHotPlayDialog";
                this.exportNodeNames = [];
                this.JUMP_TYPE = "single";
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                });
                mgrSdk.openJump(Const.gameIndex, this.JUMP_TYPE);
                Timer.callLoop(0.5, () => {
                    if (mgrGuide.isGuiding()) {
                        this.closeDialog();
                    }
                }, this);
            }
            onClosed() {
                super.onClosed();
            }
            fillData(datas) {
                this.datas = datas;
                Tools.loadImg(this.imageIcon, datas[0].url);
            }
            onMsgOpenJumpResult(e) {
                if (this.destroyed || !this.imageIcon || this.imageIcon.destroyed) {
                    return;
                }
                if (e.type == this.JUMP_TYPE) {
                    let datas = e.jumpInfo;
                    this.fillData(datas);
                }
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonGo() {
                if (!this.datas)
                    return;
                mgrSdk.jumpOtherGame(this.datas[0].index, this.JUMP_TYPE);
            }
        }

        class vNativeDialogSmall extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vNativeDialogSmall";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.adEventId = this.context.adEventId;
                this.userData = this.context.userData;
                this.fillData();
                this.registerListeners({
                    MSG_NATIVE_AD_SDK_CLICK_SUCCESS: this.onMsgNativeAdSdkClickSuccess.bind(this),
                });
            }
            onClosed() {
                super.onClosed();
                mgrAdNative.onNativeAdViewClenup(this.context.adEventId, true, true);
            }
            fillData() {
                let nativeData = mgrAdNative.getNativeDataByAdEventId(this.adEventId);
                if (!nativeData) {
                    mgrTip.showMsgTip("发生了不可预知的错误, 这个不应该弹出的!!!");
                }
                else {
                    this.labelName.text = nativeData.title;
                    this.labelDesc.text = nativeData.desc;
                    this.labelTarget.text = nativeData.targetTitle;
                    Tools.loadAdImg(this.imageIcon, nativeData.url);
                }
                let rangeMode = mgrSdk.getCopNumberValueByKey(`native_insert_mode`);
                this.buttonContent.__node.visible = rangeMode == 2;
                this.buttonFullScreen.__node.visible = rangeMode == 3;
                if (mgrSdk.getCopNumberValueByKey(`native_insert_scale_close_count`) == 1) {
                    this.buttonClose.__node.size(50, 50);
                    this.spriteCloseBg.size(50, 50);
                    mgrLayout.widget(0.5, 0.5, this.spriteCloseBg, { x: 0.5, y: 0.5 }, this.buttonClose.__node);
                }
                else if (mgrSdk.getCopNumberValueByKey(`native_insert_scale_close_count`) == 2) {
                    this.buttonClose.__node.size(80, 80);
                    this.spriteCloseBg.size(80, 80);
                    mgrLayout.widget(0.5, 0.5, this.spriteCloseBg, { x: 0.5, y: 0.5 }, this.buttonClose.__node);
                }
                else if (mgrSdk.getCopNumberValueByKey(`native_insert_scale_close_count`) == 3) {
                    this.buttonClose.__node.size(50, 50);
                    this.spriteCloseBg.size(80, 80);
                    mgrLayout.widget(0.5, 0.5, this.spriteCloseBg, { x: 0.5, y: 0.5 }, this.buttonClose.__node);
                }
                else {
                    if (mgrAd.todayNativeInsertScaleCount < mgrSdk.getCopNumberValueByKey(`native_insert_scale_close_count`)) {
                        mgrAd.todayNativeInsertScaleIntervalCount++;
                        if (mgrAd.todayNativeInsertScaleIntervalCount >= mgrSdk.getCopNumberValueByKey(`native_insert_scale_close_interval`)) {
                            mgrAd.todayNativeInsertScaleIntervalCount = 0;
                            mgrAd.todayNativeInsertScaleCount++;
                            this.buttonClose.__node.size(50, 50);
                            mgrLayout.widget(0.5, 0.5, this.spriteCloseBg, { x: 0.5, y: 0.5 }, this.buttonClose.__node);
                        }
                        else {
                            this.buttonClose.__node.size(30, 30);
                            mgrLayout.widget(0.5, 0.5, this.spriteCloseBg, { x: 0.5, y: 0.5 }, this.buttonClose.__node);
                        }
                        mgrAd.saveRecord();
                    }
                }
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonDownLoad() {
                mgrAdNative.clickNative(this.adEventId);
            }
            onTouchButtonContent() {
                mgrAdNative.clickNative(this.adEventId);
            }
            onTouchButtonFullScreen() {
                mgrAdNative.clickNative(this.adEventId);
            }
            onMsgNativeAdSdkClickSuccess() {
                mgrTip.showMsgTip("谢谢!");
                this.closeDialog();
            }
        }

        class vNewYearPreviewDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vNewYearPreviewDialog";
                this.suitId = null;
                this.sortedPartIdArr = [];
            }
            onOpened() {
                super.onOpened();
                this.initData();
                this.widget();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonGo() {
                mgrDirector.warpSceneWidthEffect(`vAmuseCardStartNewYearStageScene`, {
                    backSceneName: `vHubScene`,
                    fOnClose: () => {
                        mgrDirector.openDialog(`vNewYearPreviewDialog`);
                    }
                });
                this.closeDialog();
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            widget() {
                mgrLayout.widgetLeftMC(this.boxLeftMC);
                mgrLayout.widgetRightMC(this.boxRightMC);
                mgrLayout.widgetTopMC(this.boxTopMC);
                mgrLayout.widgetBottomMC(this.boxBottomMC);
            }
            initData() {
                let rewardConfig = mgrCfg.get_from_amuse_card_new_year_reward_config_db(1);
                let stageMappingData = mgrCfg.get_from_amuse_card_new_year_reward_config_db(2);
                let suitId = rewardConfig.suitId;
                let sortArr = [];
                let stagePartMapping = stageMappingData.stagePartMapping;
                let partIds = [];
                for (let i = 0; i < stagePartMapping.length; i++) {
                    let data = stagePartMapping[i];
                    sortArr.push({
                        stageId: data[0],
                        partId: data[1],
                    });
                }
                sortArr = Tools.sortArrayByField(sortArr, "stageId");
                for (let i = 0; i < sortArr.length; i++) {
                    let data = sortArr[i];
                    partIds.push(data.partId);
                }
                this.sortedPartIdArr = partIds;
                this.suitId = suitId;
            }
            buildUi() {
                for (let i = 1; i <= 6; i++) {
                    let node = this[`spritePart${i}`];
                    let imageIcon = node.getChildByName("imagePart");
                    let cover = node.getChildByName("ownCover");
                    let index = i - 1;
                    let partId = this.sortedPartIdArr[index];
                    let partData = mgrCfg.get_from_part_db(partId);
                    let bOwned = mgrPlayer.getItemAmount(partId) > 0;
                    imageIcon.loadImage(partData.icon);
                    cover.visible = bOwned;
                    if (bOwned) {
                    }
                }
                let newYearRoleId = mgrCard.getNewYearStageRewardConfig().roleId;
                let roleData = mgrCfg.get_from_role_db(newYearRoleId);
                let itemId = roleData.unlockItemId;
                let ownCount = mgrPlayer.getItemAmount(itemId);
                let totalCount = roleData.unlockItemAmount;
                Mathf.clamp(ownCount, 0, totalCount);
                let progress = ownCount / totalCount;
                this.labelProgress.text = `${ownCount}/${totalCount}`;
                this.progressBar.barName = this.progressBar.owner.name;
                let startProgress = 0.0001;
                let targetProgress = progress;
                this.progressBar.progress = 0;
                this.labelProgress.scale(0, 0, true);
                this.spriteProgressContainer.scale(0, 0, true);
                this.progressBar.progressTweenTo(0.05, targetProgress, startProgress, 0.6, () => {
                    cc.tween(this.spriteProgressContainer)
                        .toScale(0.05, 2)
                        .call(() => {
                        this.labelProgress.scale(1, 1, true);
                    })
                        .toScale(0.05, 1)
                        .call(() => {
                        this.add3DEffectAtFront("117_ui_once_flash_03", this.labelProgress, 1);
                    }).start();
                });
                let suitData = mgrCfg.get_from_suit_db(this.suitId);
                this.labelSuitName.text = `${suitData.name}`;
            }
        }

        class vOfflineDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vOfflineDialog";
                this.exportNodeNames = [];
                vOfflineDialog.offlineDialog = this;
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.buttonAd.fOnClick = () => {
                    mgrAd.triggerAdEvent("video_double_offline", null, true);
                };
                this.boxAdGet.visible = mgrAd.preCheckCanTriggerAdEvent("video_double_offline");
                if (this.boxAdGet.visible) {
                    this.add3DEffectAtFront(MODEL_ID.effect.eff_ui_qiandao_lh, this.boxAdGet);
                    let adEventData = mgrCfg.get_from_ad_event_db("video_double_offline");
                    adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    this.fillAdMode();
                }
                else {
                    let image = new Laya.Image;
                    image.size(200, 200);
                    this.boxAdGet.parent.addChild(image);
                }
                this.buttonget.fOnClick = () => {
                    if (this.__bClosing)
                        return;
                    let [offPassTime, offReward] = mgrOfflineReward.getOfflineReward();
                    mgrPlayer.addItemAmount(Const.ITEM_ID_GOLD, offReward, "");
                    mgrTip.addGotItemTip(Const.ITEM_ID_GOLD, offReward);
                    this.closeDialog();
                    mgrOfflineReward.markOfflineRewardGeted();
                };
                this.checkBoxAd.changeCallback = this.fillAdMode.bind(this);
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                CustomTween.roke(this.spriteTitle);
                CustomTween.rotateForever(this.spriteLightNormal, 8000);
            }
            onClosed() {
                super.onClosed();
                vOfflineDialog.offlineDialog = null;
            }
            fillData() {
                let [offPassTime, offReward] = mgrOfflineReward.getOfflineReward();
                let count = Math.ceil(offReward);
                this.labelRewardCountNoraml.text = `${mgrPlayer.getItemAmountStr(count)}`;
                this.labelRewardCountAd.text = `+${mgrPlayer.getItemAmountStr(count * 2)}`;
                this.labelTime.text = `${Tools.formatTime(offPassTime, "%H小时%M分%S秒")}`;
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == "video_double_offline") {
                    let [offPassTime, offReward] = mgrOfflineReward.getOfflineReward();
                    offReward *= 3;
                    mgrPlayer.addItemAmount(Const.ITEM_ID_GOLD, offReward, "");
                    mgrTip.addGotItemTip(Const.ITEM_ID_GOLD, offReward, undefined, {
                        bFromAd: true,
                    });
                    this.closeDialog();
                    mgrOfflineReward.markOfflineRewardGeted();
                }
            }
            fillAdMode() {
                if (mgrSdk.getCopNumberValueByKey(`video_ad_mode`) == 0) {
                    this.boxGet.visible = true;
                    this.labelAdModeTip.visible = false;
                }
                else {
                    if (this.checkBoxAd.bCheck) {
                        this.labelAdModeTip.visible = true;
                        this.boxGet.visible = false;
                    }
                    else {
                        this.boxGet.visible = true;
                        this.labelAdModeTip.visible = true;
                    }
                }
            }
        }

        class vPartDetailDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vPartDetailDialog";
                this.exportNodeNames = [];
                this.dailyGameType = 0;
            }
            onOpened() {
                super.onOpened();
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                console.log("-----this.context.itemId=", this.context.itemId);
                this.fillData();
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onAnimationFinished() {
            }
            fillData() {
                let partId = this.context.itemId;
                this.boxDesc.visible = mgrPlayer.getItemAmount(partId) <= 0;
                let partData = mgrCfg.get_from_part_db(partId);
                let routerData = mgrWorldDaily.getDailyQuestDataByPartId(partId);
                this.labelPartName.text = partData.name;
                Tools.loadImg(this.spritePart, partData.icon);
                if (routerData) {
                    this.labelRouterName.text = `日程-${routerData.routerDesc}`;
                    this.dailyGameType = routerData.id;
                    if (!mgrMidAutumn.isEnable() && routerData.id == DailyGameType.mid_autumn) {
                        this.labelRouterName.text = "去自由换装看看吧";
                        this.labelLeft.visible = false;
                        this.labelSecond.visible = false;
                        this.dailyGameType = 0;
                    }
                    else if (routerData.id == DailyGameType.new_year) {
                        this.labelRouterName.text = `去新年活动看看吧`;
                        this.labelLeft.visible = false;
                        this.labelSecond.visible = false;
                        this.dailyGameType = DailyGameType.new_year;
                    }
                }
                else {
                    this.labelRouterName.text = "去自由换装看看吧";
                    this.labelLeft.visible = false;
                    this.labelSecond.visible = false;
                }
                if (mgrPlayer.getItemAmount(this.context.itemId) > 0) {
                    this.labelToGet.text = "确定";
                }
                this.buttonClose.__node.visible = mgrPlayer.getItemAmount(this.context.itemId) <= 0;
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vPartDetailDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonToGet() {
                if (mgrPlayer.getItemAmount(this.context.itemId) > 0 || this.context.ignoreRouter) {
                    this.closeDialog();
                }
                else {
                    switch (this.dailyGameType) {
                        case DailyGameType.cake:
                        case DailyGameType.cloth:
                        case DailyGameType.custom_made:
                        case DailyGameType.parkour:
                        case DailyGameType.clothcrossing:
                            mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene", { dailyGameType: this.dailyGameType, bFromItemRouter: true });
                            break;
                        case DailyGameType.card:
                            mgrDirector.warpSceneWidthEffect(`vAmuseCardStartScene`, {
                                backSceneName: `vHubScene`
                            });
                            break;
                        case DailyGameType.mid_autumn:
                            mgrDirector.openDialog("vMidAutumnActivityDialog");
                            break;
                        case DailyGameType.new_year:
                            mgrDirector.warpSceneWidthEffect(`vHubScene`);
                            mgrDirector.openDialog("vNewYearPreviewDialog");
                            break;
                        default:
                            mgrDirector.warpSceneWidthEffect(`vFreedomRoomScene`, {
                                stageId: 2001,
                                backSceneName: `vHubScene`,
                            });
                            break;
                    }
                    this.sendMsg("MSG_CLOSE_SUIT_SHOWING");
                    this.closeDialog();
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vPromptDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vPromptDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                let title = this.context.title;
                let content = this.context.content;
                let btnTexts = this.context.btnTexts;
                let callbacks = this.context.callbacks;
                let bShowAd = this.context.bShowAd;
                this.labelTitle.text = title || this.labelTitle.text;
                this.label1.text = btnTexts[0] || "取消";
                this.label2.text = btnTexts[1] || "确定";
                this.labelContent.text = content;
                this.spriteAdFlag.visible = bShowAd;
                !btnTexts[0] && (this.button1.__node.visible = false);
                this.button1.fOnClick = () => {
                    if (callbacks && callbacks[0] instanceof Function) {
                        if (callbacks[0]()) {
                            return;
                        }
                    }
                    this.closeDialog();
                };
                !btnTexts[1] && (this.button2.__node.visible = false);
                this.button2.fOnClick = () => {
                    if (callbacks && callbacks[1] instanceof Function) {
                        if (callbacks[1]()) {
                            return;
                        }
                    }
                    this.closeDialog();
                };
                this.buttonClose.fOnClick = () => {
                    if (callbacks && callbacks[0] instanceof Function) {
                        if (callbacks[0]()) {
                            return;
                        }
                    }
                    this.closeDialog();
                };
                this.buttonClose.__node.visible = !!this.context.bShowClose;
                if (mgrSdk.getCopNumberValueByKey("b_vPromptDialog_trigger_native_banner") == 1 && this.button1.__node.visible && this.button2.__node.visible) {
                    this.buttonClose.__node.visible = true;
                    this.button1.__node.visible = false;
                }
                this.widget();
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vPromptDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
            }
            onAnimationFinished() {
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
        }

        class vRewardMoreGameItem extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vRewardMoreGameItem";
                this.exportNodeNames = [];
                this.size(150, 180);
                this.anchorY = 0;
                this.anchorX = 0;
            }
            onOpened() {
                super.onOpened();
                this.buttonGet = this.imageIcon.addComponent(ScaleButton);
                this.buttonGet.fOnClick = this.onButtonGetClick.bind(this);
                this.data && this.fillByData(this.data);
            }
            onClosed() {
                super.onClosed();
            }
            onButtonGetClick() {
                let userData = {
                    jumpGameIndex: this.data.index || this.data.gameId,
                };
                let jsonStr = JSON.stringify(userData);
                this.data.fOnClickItem(this.data.index, "reward", jsonStr);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                Tools.loadImg(this.imageIcon, data.url);
                this.spriteGeted.visible = !!data.bReceived;
                let rewards = data.rewards;
                if (rewards.length && rewards.length >= 1) {
                    this.labelRewardAmount.text = `*${rewards[0][1]}`;
                }
                else {
                    console.error("fillByData no rewards:", rewards);
                    this.spriteReward.visible = false;
                }
            }
        }

        class vRewardMoreGame extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vRewardMoreGame";
                this.exportNodeNames = [];
                this.JUMP_TYPE = "reward";
            }
            onOpened() {
                super.onOpened();
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                    MSG_SDK_JUMP_OTHER_GAME_RESULT: this.onMsgJumpOtherGameResult.bind(this),
                });
                mgrSdk.openJump(Const.gameIndex, this.JUMP_TYPE);
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onMsgOpenJumpResult(e) {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (e.type == this.JUMP_TYPE) {
                    let datas = e.jumpInfo;
                    this.datas;
                    for (let index = 0; index < datas.length; index++) {
                        const element = datas[index];
                        element.fOnClickItem = this.onClickItem.bind(this);
                    }
                    this.fillData(datas);
                    this.autoClick();
                }
            }
            onMsgJumpOtherGameResult(e) {
                if (e.bSuccessful) {
                    this.closeDialog();
                }
            }
            autoClick() {
                if (this.datas && mgrSdk.getCopNumberValueByKey("b_auto_jump_other_game_reward_more_game") == 1) {
                    mgrSdk.jumpOtherGame(this.datas[Tools.random(0, this.datas.length - 1)].index, this.JUMP_TYPE, null);
                }
            }
            fillData(datas) {
                if (this.datas)
                    return;
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(3, 0, 10);
                    this.reuseList.size(this.boxList.width, this.boxList.height);
                    this.boxList.addChild(this.reuseList);
                    this.reuseList.setItemClass(vRewardMoreGameItem);
                    this.reuseList.setVerticalMoveEnable(true);
                    this.reuseList.setSpaceX(5);
                    this.reuseList.setSpaceY(5);
                }
                this.reuseList.setDatas(datas);
                this.datas = datas;
            }
            onClickItem(index, param1, param2) {
                mgrSdk.jumpOtherGame(index, param1, param2);
            }
        }

        class UVPickerByMesh {
            static pick(ray, meshSprite3d, bCullingBack = false, bCalculateUv = false) {
                let result = {
                    bHit: false,
                    point: null,
                    uv: null,
                    idx: -1
                };
                if (!meshSprite3d || !meshSprite3d.meshFilter) {
                    return result;
                }
                this.ray.origin = ray.origin.clone();
                this.ray.direction = ray.direction.clone();
                ray = this.ray;
                let mesh = meshSprite3d.meshFilter.sharedMesh;
                let matrix = meshSprite3d.transform.worldMatrix;
                let inverseMatrix = new Laya.Matrix4x4;
                matrix.invert(inverseMatrix);
                Laya.Vector3.transformCoordinate(ray.origin, inverseMatrix, ray.origin);
                Laya.Vector3.TransformNormal(ray.direction, inverseMatrix, ray.direction);
                let poss = [];
                mesh.getPositions(poss);
                let uvs = [];
                mesh.getUVs(uvs);
                let normals = [];
                mesh.getNormals(normals);
                let indices = mesh.getIndices();
                for (let i = 0; i < indices.length / 3; i++) {
                    let p1idx = indices[i * 3 + 0];
                    let p2idx = indices[i * 3 + 1];
                    let p3idx = indices[i * 3 + 2];
                    let PA = poss[p1idx];
                    let PB = poss[p2idx];
                    let PC = poss[p3idx];
                    Laya.Vector3.subtract(PA, PB, this.tempVec31);
                    Laya.Vector3.subtract(PA, PC, this.tempVec32);
                    Laya.Vector3.cross(this.tempVec32, this.tempVec31, this.planeNormal);
                    if (bCullingBack && Laya.Vector3.dot(ray.direction, this.planeNormal) > 0)
                        continue;
                    let A = this.planeNormal.x;
                    let B = this.planeNormal.y;
                    let C = this.planeNormal.z;
                    let xp = PA.x;
                    let yp = PA.y;
                    let zp = PA.z;
                    let xl = ray.origin.x;
                    let yl = ray.origin.y;
                    let zl = ray.origin.z;
                    let m = ray.direction.x;
                    let n = ray.direction.y;
                    let p = ray.direction.z;
                    let t = (A * xp - A * xl + B * yp - B * yl + C * zp - C * zl) / (A * m + B * n + C * p);
                    let x = xl + m * t;
                    let y = yl + n * t;
                    let z = zl + p * t;
                    this.crossPointDir.x = x - ray.origin.x;
                    this.crossPointDir.y = y - ray.origin.y;
                    this.crossPointDir.z = z - ray.origin.z;
                    if (Laya.Vector3.dot(ray.direction, this.crossPointDir) <= 0)
                        continue;
                    this.crossPoint.x = x;
                    this.crossPoint.y = y;
                    this.crossPoint.z = z;
                    let P = this.crossPoint;
                    this.soluteWeightByPos123(PA, PB, PC, P, this.tempVec31);
                    let u = this.tempVec31.x;
                    let v = this.tempVec31.y;
                    let w = this.tempVec31.z;
                    if (u == Infinity || v == Infinity || w == Infinity)
                        continue;
                    if (isNaN(u) || isNaN(v) || isNaN(w))
                        continue;
                    if (u < 0 || v < 0 || w < 0)
                        continue;
                    result.bHit = true;
                    Laya.Vector3.transformCoordinate(P, meshSprite3d.transform.worldMatrix, this.outPoint);
                    result.point = this.outPoint;
                    let uvA = uvs[p1idx];
                    let uvB = uvs[p2idx];
                    let uvC = uvs[p3idx];
                    result.uv = this.soluteUVByWeight(u, v, w, uvA, uvB, uvC);
                    result["idx"] = i;
                    break;
                }
                return result;
            }
            static soluteWeightByPos123_ex(orig, dir, v0, v1, v2, rec) {
                let t = 0;
                let u = 0;
                let v = 0;
                let E1 = this.TEMP_VEC3S[0];
                Laya.Vector3.subtract(v1, v0, E1);
                let E2 = this.TEMP_VEC3S[1];
                Laya.Vector3.subtract(v2, v0, E2);
                let P = this.TEMP_VEC3S[2];
                Laya.Vector3.cross(dir, E2, P);
                let det = Laya.Vector3.dot(E1, P);
                let T = this.TEMP_VEC3S[3];
                if (det > 0) {
                    Laya.Vector3.subtract(orig, v0, T);
                }
                else {
                    Laya.Vector3.subtract(v0, orig, T);
                    det = -det;
                }
                if (det <= 0)
                    return false;
                u = Laya.Vector3.dot(T, P);
                if (u < 0 || u > det)
                    return false;
                let Q = this.TEMP_VEC3S[4];
                Laya.Vector3.cross(T, E1, Q);
                v = Laya.Vector3.dot(dir, Q);
                if (v < 0 || u + v > det)
                    return false;
                t = Laya.Vector3.dot(E2, Q);
                if (rec) {
                    let fInvDet = 1 / det;
                    t *= fInvDet;
                    u *= fInvDet;
                    v *= fInvDet;
                    rec.t = t;
                    let pos = dir.clone();
                    Laya.Vector3.scale(pos, t, pos);
                    Laya.Vector3.add(orig, pos, pos);
                    rec.p = pos;
                }
                return true;
            }
            static soluteWeightByPos123(p1, p2, p3, p, out) {
                this.solute3eleEquation(p1.x, p2.x, p3.x, p.x, p1.y, p2.y, p3.y, p.y, p1.z, p2.z, p3.z, p.z, out);
            }
            static soluteUVByWeight(u, v, w, uv1, uv2, uv3) {
                let uv = new Laya.Vector2(uv1.x * u + uv2.x * v + uv3.x * w, uv1.y * u + uv2.y * v + uv3.y * w);
                return uv;
            }
            static solute3eleEquation(a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34, out) {
                if (a31 == 0 &&
                    a32 == 0 &&
                    a33 == 0) {
                    a31 = 1;
                    a32 = 1;
                    a33 = 1;
                    a34 = 1;
                }
                let d = this.solute3rdOrderDeterminant(a11, a12, a13, a21, a22, a23, a31, a32, a33);
                let dx = this.solute3rdOrderDeterminant(a14, a12, a13, a24, a22, a23, a34, a32, a33);
                let dy = this.solute3rdOrderDeterminant(a11, a14, a13, a21, a24, a23, a31, a34, a33);
                let dz = this.solute3rdOrderDeterminant(a11, a12, a14, a21, a22, a24, a31, a32, a34);
                out.x = dx / d;
                out.y = dy / d;
                out.z = dz / d;
            }
            static solute3rdOrderDeterminant(a1, b1, c1, a2, b2, c2, a3, b3, c3) {
                return a1 * b2 * c3 + a2 * b3 * c1 + a3 * b1 * c2 - a3 * b2 * c1 - a2 * b1 * c3 - a1 * b3 * c2;
            }
            static isSameSide(PA, PB, PC, P) {
                let AP = new Laya.Vector3(P.x - PA.x, P.y - PA.y, P.z - PA.z);
                let BP = new Laya.Vector3(P.x - PB.x, P.y - PB.y, P.z - PB.z);
                let AC = new Laya.Vector3(PC.x - PA.x, PC.y - PA.y, PC.z - PA.z);
                let BC = new Laya.Vector3(PC.x - PB.x, PC.y - PB.y, PC.z - PB.z);
                let crossABP = new Laya.Vector3;
                Laya.Vector3.cross(AP, BP, crossABP);
                let crossABC = new Laya.Vector3;
                Laya.Vector3.cross(AC, BC, crossABC);
                if (Laya.Vector3.dot(crossABC, crossABP) <= 0)
                    return false;
                return true;
            }
        }
        UVPickerByMesh.planeNormal = new Laya.Vector3;
        UVPickerByMesh.crossPointDir = new Laya.Vector3;
        UVPickerByMesh.crossPoint = new Laya.Vector3;
        UVPickerByMesh.outPoint = new Laya.Vector3;
        UVPickerByMesh.tempVec41 = new Laya.Vector4;
        UVPickerByMesh.tempVec42 = new Laya.Vector4;
        UVPickerByMesh.tempVec43 = new Laya.Vector4;
        UVPickerByMesh.tempVec31 = new Laya.Vector3;
        UVPickerByMesh.tempVec32 = new Laya.Vector3;
        UVPickerByMesh.tempVec33 = new Laya.Vector3;
        UVPickerByMesh.tempVec34 = new Laya.Vector3;
        UVPickerByMesh.ray = new Laya.Ray(new Laya.Vector3, new Laya.Vector3);
        UVPickerByMesh.TEMP_VEC3S = [
            new Laya.Vector3(),
            new Laya.Vector3(),
            new Laya.Vector3(),
            new Laya.Vector3(),
            new Laya.Vector3(),
        ];

        class vDesignCollectCell extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vDesignCollectCell";
                this.exportNodeNames = [];
                this.size(90, 96);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                this.registerListeners({
                    MSG_ROOM_PART_REFRESH: this.onMsgRoomPartRefresh.bind(this),
                });
            }
            onClosed() {
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag2"];
            }
            onMsgRoomPartRefresh() {
                this.data && this.fillByData(this.data);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let designData = mgrDesign.getDesignPartDataByPartId(this.data.partId);
                this.imageIcon.alpha = !!designData ? 1 : 0;
                if (!!designData) {
                    let tex2dSaved = mgrRole.getPhotoTexture2D(mgrDesign.getDesignPartIconKey(this.data.partId));
                    if (!!tex2dSaved) {
                        let texture = new Laya.Texture(tex2dSaved);
                        this.imageIcon.graphics.drawImage(texture, 0, 0, this.imageIcon.width, this.imageIcon.height);
                    }
                }
                this.spriteLockFlag.visible = !mgrDesign.isUnlockedPartCell(this.data.partId);
                if (this.spriteLockFlag.visible) {
                    this.context.fStaticsShow && this.context.fStaticsShow();
                }
                this.spriteLockBg.visible = this.spriteLockFlag.visible;
                this.spriteSelect.visible = !!this.context.bShowSelectFlag && this.context.fIsSelect && this.context.fIsSelect(this.data.partId);
            }
            onTouchButtonBg() {
                if (this.data && this.data.fOnClick) {
                    this.data.fOnClick(this.data.partId);
                }
            }
        }

        class vRoomPart extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vRoomPart";
                this.exportNodeNames = [];
                this.size(90, 96);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                this.registerListeners({
                    MSG_ROOM_PART_REFRESH: this.onMsgRoomPartRefresh.bind(this),
                });
                Tools.registerTouchHander(this.spriteEaseTrigger, (e) => {
                    if (e.isBegin) {
                        this.onTouchButtonBg();
                    }
                });
            }
            onClosed() {
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag2"];
            }
            onMsgRoomPartRefresh() {
                this.data && this.fillByData(this.data);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let shopData = mgrCfg.get_from_shop_template_db(this.data.partId);
                let partData = mgrCfg.get_from_part_db(this.data.partId);
                if (!mgrDesign.isDesignPart(this.data.partId)) {
                    Tools.loadImg(this.imageIcon, partData.icon);
                }
                else {
                    let tex2dSaved = mgrRole.getPhotoTexture2D(mgrDesign.getDesignPartIconKey(this.data.partId));
                    if (!!tex2dSaved) {
                        let texture = new Laya.Texture(tex2dSaved);
                        this.imageIcon.graphics.drawImage(texture, 0, 0, this.imageIcon.width, this.imageIcon.height);
                    }
                }
                this.spriteDressed.visible = this.data.fIsDressing && this.data.fIsDressing(this.data.partId) ? true : false;
                this.spriteSelect.visible = this.data.fIsSelected && this.data.fIsSelected(this.data.partId) ? true : false;
                this.spriteLucky.visible = this.data.fIsLuckyPart && this.data.fIsLuckyPart(this.data.partId) ? true : false;
                let bRecommend = !this.spriteLucky.visible && this.data.fIsRecommend && this.data.fIsRecommend(this.data.partId) ? true : false;
                this.spriteRecommend.visible = bRecommend;
                let bShowTrialText = mgrSdk.getCopNumberValueByKey("b_hide_trail_text") == 0 ? true : false;
                this.imageTrial.visible = !!bShowTrialText;
                this.imageTrialNoText.visible = !this.imageTrial.visible;
                this.spriteCoin.visible = (mgrPlayer.getItemAmount(this.data.partId) <= 0 && !!shopData && shopData.price > 0) ? true : false;
                if (!!shopData) {
                    this.labelPrice.text = `${shopData.price}`;
                    let priceItemId = shopData.priceUnit;
                    let itemData = mgrCfg.get_from_item_template_db(priceItemId);
                    Tools.loadImg(this.spritePriceImg, itemData.icon);
                }
                let bTrying = this.data.fIsTry && this.data.fIsTry(this.data.partId) ? true : false;
                this.spriteCoinTrial.visible = false;
                this.spriteTrialContainer.visible = false;
                this.spriteEaseTrigger.visible = false;
                if (!this.spriteCoin.visible && mgrPlayer.getItemAmount(this.data.partId) <= 0 && !bTrying) {
                    this.spriteTrialContainer.visible = !!this.data.bAd;
                    if (this.spriteTrialContainer.visible) {
                    }
                    else {
                        this.spriteCoinTrial.visible = true;
                    }
                    let b_trail_easy_trigger = mgrSdk.getCopNumberValueByKey("b_trail_easy_trigger") == 1 ? true : false;
                    this.spriteEaseTrigger.visible = !!b_trail_easy_trigger;
                }
                mgrGuide.registerGuideNode(`vRoomPart.part${this.data.partId}`, this.spriteGuide);
            }
            onTouchButtonBg() {
                this.data && this.data.fOnClickPart(this.data.partId, this.data.bAd);
                mgrPart.deleteNewPart(this.data.partId);
                console.log("------------------------------------------------------------");
            }
        }

        class vRoomPartType extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vRoomPartType";
                this.exportNodeNames = [];
                this.size(72, 72);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                this.registerListeners({
                    MSG_ROOM_PART_REFRESH: this.onMsgRoomPartRefresh.bind(this),
                });
            }
            onClosed() {
            }
            onMsgRoomPartRefresh() {
                this.data && this.fillByData(this.data);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let typeData = mgrCfg.get_from_part_type_db(this.data.id);
                if (!typeData) {
                    if (this.data.id == Const.ROOM_SPECIAL_TYPE_ROLE) {
                        typeData = {
                            id: this.data.id,
                            icon: "res/ui/room_zz/icon_type_role.png",
                            iconSelect: "res/ui/room_zz/icon_type_role_s.png"
                        };
                    }
                    else if (this.data.id == Const.ROOM_SPECIAL_TYPE_DESIGN) {
                        typeData = {
                            id: this.data.id,
                            icon: "res/ui/room_zz/icon_type_design.png",
                            iconSelect: "res/ui/room_zz/icon_type_design_s.png"
                        };
                    }
                    else {
                        return;
                    }
                }
                Tools.loadImg(this.spriteNormal, typeData.icon);
                Tools.loadImg(this.spriteSelect, typeData.iconSelect);
                let bDressed = this.data.isDressedType(this.data.id);
                let bCurrent = this.data.fIsCurrentType(this.data.id);
                this.spriteUsed.visible = bDressed;
                this.spriteSelect.alpha = bCurrent ? 1 : 0;
                mgrGuide.registerGuideNode(`vRoomPartType.partType${this.data.id}`, this.spriteGuide);
            }
            onTouchButtonBg() {
                this.data && this.data.fOnClick(this.data.id);
            }
        }

        class vRoomRoleCell extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vRoomRoleCell";
                this.exportNodeNames = [];
                this.size(100, 170);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                this.registerListeners({
                    MSG_ROOM_PART_REFRESH: this.onMsgRoomPartRefresh.bind(this),
                });
            }
            onClosed() {
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag2"];
            }
            onMsgRoomPartRefresh() {
                this.data && this.fillByData(this.data);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let roleData = mgrCfg.get_from_role_db(this.data.partId);
                Tools.loadImg(this.spriteChangeIcon, roleData.changeIcon);
                this.labelName.text = roleData.name;
                this.spriteLockMask.visible = mgrPlayer.getItemAmount(this.data.partId) <= 0;
                let partTagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                Tools.loadImg(this.spriteTag, partTagData.icon);
                this.labelName.visible = true;
                this.spriteCurFlag.visible = this.data.fIsCurrentRole && this.data.fIsCurrentRole(this.data.partId);
                this.spriteActive.visible = this.spriteCurFlag.visible;
                for (let i = 0; i < 5; i++) {
                    let spriteStar = this.boxLevel.getChildAt(i);
                    spriteStar.visible = roleData.level > i;
                }
                if (mgrPlayer.getItemAmount(this.data.partId) > 0) {
                    this.boxAd.visible = false;
                    this.boxFragment.visible = false;
                    this.labelName.visible = true;
                }
                else {
                    let collectJumpData = mgrCfg.get_from_role_collect_jump_db(roleData.id);
                    if (collectJumpData) {
                        this.boxAd.visible = false;
                    }
                    else {
                        this.boxAd.visible = mgrPlayer.getItemAmount(this.data.partId) <= 0 && mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vRoleChangeScene_fragment);
                    }
                    this.boxFragment.visible = true;
                    this.labelName.visible = !this.boxAd.visible;
                    let curFragmentNum = mgrPlayer.getItemAmount(roleData.unlockItemId);
                    Tools.loadImg(this.spriteFragment, mgrPlayer.getIcon(roleData.unlockItemId));
                    let needFragmentNum = roleData.unlockItemAmount;
                    this.labelFragmentCurNum.text = `${curFragmentNum}`;
                    this.labelFragmentAllNum.text = `/${needFragmentNum}`;
                }
                if (roleData.bNewTagShow && mgrPlayer.getItemAmount(roleData.id) <= 0) {
                    this.spriteNew.visible = true;
                    if (!this.effNew) {
                        this.add3DEffectAtFront("117_ui_loop_newparticl_01", this.spriteEff, 0, 1, (model) => {
                            this.effNew = model;
                        });
                    }
                    this.spriteEff.visible = true;
                }
                else {
                    this.spriteNew.visible = false;
                    this.spriteEff.visible = false;
                }
            }
            onTouchButtonBg() {
                if (this.data && this.data.fOnClick) {
                    this.data.fOnClick(this.data.partId);
                }
            }
        }

        const CAMERA_PRARAM_LUCKY = {
            fov: 30,
            position: new Laya.Vector3(0, 0.77, 5.374),
            rotation: new Laya.Vector3(-5),
            lerpValue: 0.1,
        };
        class vRoomDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vRoomDialog";
                this.exportNodeNames = [];
                this.tryingPartIds = [];
                this.avatar = null;
                this.reuseListRole = null;
                this.reuseListDesign = null;
                this.reuseList = null;
                this.reuseListType = null;
                this.partTypeCameraParams = {
                    [0]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 0.77, 4.424),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [PartType.cloth]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 0.77, 4.424),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [PartType.shoe]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 0.27, 3.474),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [PartType.sock]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 0.27, 3.474),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [PartType.earDec]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 1.32, 1.574),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [PartType.handDec]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 1.02, 3.27),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [PartType.neckDec]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 1.32, 1.524),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [PartType.backDeco]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 0.77, 5.374),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [PartType.headDec]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 1.22, 2.524),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                    [Const.ROOM_SPECIAL_TYPE_ROLE]: {
                        fov: 30,
                        position: new Laya.Vector3(0, 0.77, 5.374),
                        rotation: new Laya.Vector3(-2.5),
                        lerpValue: 0.1,
                    },
                };
                this.type2RecommandPartIdDict = {};
                this.type2SortFlagDict = {};
                this.dressedLuckyPartIds = [];
                this.BODY_IDLE_ANI = "hz_idle-hz_idle";
                this.roomPopClickItemPartCount = 0;
                this.context.stageId = this.context.stageId || 2001;
                this.context.roleId = this.context.roleId || mgrRole.showingRoleId;
            }
            onOpened() {
                super.onOpened();
                Tools.registerTouchHander(this.boxOperation, this.onTouchSpriteBg.bind(this));
                Tools.registerTouchHander(this.boxFrontEvent, () => { });
                this.boxFrontEvent.visible = false;
                this.buildUi();
                this.fillData();
                this.widget();
                this.fadeIn();
                this.playOutUi();
                this.playInUi();
                if (!mgrGuide.isAllForceGuideFinished()) {
                    Timer.callLoop(1, (timer) => {
                        this.buttonBack.__node.visible = !!mgrGuide.isAllForceGuideFinished();
                        if (!!this.buttonBack.__node.visible) {
                            timer.stop();
                        }
                    }, this);
                }
                this.spriteStageTarget.visible = !this.stageData.bSpecialStage;
                this.spriteShowingPowerContainer.visible = !!this.stageData.bSpecialStage;
                mgrSound.play(4);
                if (mgrGuide.isAllForceGuideFinished()) {
                    if (this.context.fromSystemModel != SYSTEM_MODEL.stage) {
                        mgrSound.play(503);
                    }
                    else {
                        mgrSound.play(303);
                    }
                }
                if (this.context.stageId == 2001 || this.context.stageId == 2002) {
                    this.spriteTitle.visible = false;
                }
                else {
                    this.spriteTitle.visible = true;
                    let str = this.stageData.name.replace(",", "\n");
                    this.labelTitle.text = str;
                }
                Timer.callLater(Tools.random(100) / 100 * 3, () => {
                    mgrVideoRecorder.startRecord();
                }, this);
                this.registerListeners({
                    MSG_COIN_ROOM_TRY_SUCCESSED: this.onMsgCoinRoomTrySuccessed.bind(this),
                    MSG_AD_ROOM_TRY_SUCCESSED: this.onMsgAdRoomTrySuccessed.bind(this),
                    MSG_SHOP_BUY_SUCCESSED: this.onMsgShopBuySuccessed.bind(this),
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                    MSG_CLOSE_ROOM_DILAOG: this.onTouchButtonBack.bind(this),
                    MSG_ITEM_AMOUNT_CHANGED: this.onMsgItemAmountChanged.bind(this),
                });
                let stageId = this.context.stageId;
                let stageData = mgrCfg.get_from_stage_db(stageId);
                stageData.statisPointId && mgrSdk.statisOnStageStart(`${stageData.statisPointId}`, stageId);
                this.buttonMoreGameBox.__node.visible = mgrAd.showMoreGameBox(1);
            }
            startGuide() {
                mgrGuide.registerGuideNode("vRoomDialog.spriteGuideDress", this.spriteGuideDress);
                mgrGuide.registerGuideNode("vRoomDialog.spriteGuideShoe", this.spriteGuideShoe);
                mgrGuide.registerGuideNode("vRoomDialog.buttonSummit", this.buttonSummit.__node);
                if (!mgrGuide.isFinished(1700)) {
                    mgrGuide.startGuide(1700);
                }
                else if (!mgrGuide.isFinished(1900)) {
                    mgrGuide.startGuide(1900);
                }
            }
            onClosed() {
                if (!this.bStatisOnStageEnd) {
                    let stageId = this.context.stageId;
                    let stageData = mgrCfg.get_from_stage_db(stageId);
                    stageData.statisPointId && mgrSdk.statisOnStageEnd(`${stageData.statisPointId}`, 0, stageId);
                }
                if (this.lastHuangZhuangEffModel) {
                    Tools.unLink2Node(this.lastHuangZhuangEffModel);
                    this.lastHuangZhuangEffModel = null;
                }
                mgrTip.hideLoadingTip("vRoomDialog_loadingAvatar");
                mgrTip.hideLoadingTip("vRoomDialog_loadingPart");
                mgrTip.hideLoadingTip("vRoomDialog_designItem");
                super.onClosed();
            }
            getPreLoadModelIds() {
                return [
                    "e_huanzhuang",
                    "e_yanhua_09",
                    Const.ROLE_LUCKY_FULL_EFFECT_NAME,
                    "117_e_once_change_01"
                ];
            }
            getPreLoadAnimationIds() {
                return [
                    "zjm_bixin-zjm_bixin02",
                    "jiesuan_chuchang-jiesuan_chuchang",
                    "jiesuan_ruchang-jiesuan_ruchang",
                    this.BODY_IDLE_ANI
                ];
            }
            isShowShadow() {
                return false;
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.leftTopContainer);
                mgrLayout.widgetBottomMC(this.boxPartContainer);
                mgrLayout.widgetRightTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetRightBottomMC(this.buttonSummit.__node);
                mgrLayout.widgetRightTopMC(this.spriteScoreAreaContainer);
                mgrLayout.widgetLeftTopMC(this.spriteTitle);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            fadeIn() {
                this.onSelectType(PartType.cloth, true);
            }
            playOutUi() {
            }
            playInUi() {
                this.avatar.playAnimation(["zjm_bixin-zjm_bixin02"], 0, () => {
                    this.avatar.hideShouChi();
                }, () => {
                    this.avatar.showShouChi();
                });
                Timer.callLater(0.7, () => {
                    this.cameraFollow.position = this.partTypeCameraParams[0].position.clone();
                    this.cameraFollow.endRotation = this.partTypeCameraParams[0].rotation.clone();
                    this.cameraFollow.fov = this.partTypeCameraParams[0].fov;
                    this.cameraFollow.lerpValue = 0.02;
                }, this);
                if (!!this.buttonBack.__node.visible) {
                    mgrEffect.playComebackAction([this.buttonBack.__node], -150, 0, 2.5, 0.7);
                }
                mgrEffect.playComebackAction([this.buttonSummit.__node], 200, 0, 2.5, 0.7);
                mgrEffect.playComebackAction([this.spriteScoreAreaContainer], 200, 0, 2.5, 0.7);
                mgrEffect.playComebackAction([this.boxPartContainer], 0, 600, 2, 0.5, () => {
                    this.add3DEffectAtFront("117_ui_loop_bgparticle_01", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 });
                }, cc.Ease.circOut);
                this.boxPartContainer.mouseEnabled = false;
                Timer.callLater(2.5, () => {
                    this.startGuide();
                    this.boxPartContainer.mouseEnabled = true;
                }, this);
            }
            buildUi() {
                mgrLoader.loadFont("room_score", this.labelStagePower);
                let topBar = new vTopBar({ bDisableGold: true, bDisableEnergy: true });
                this.spriteTopBarHolder.addChild(topBar);
                this.avatar = this.context.avatar;
                this.cameraFollow = this.context.cameraFollow;
                this.reuseListRole = new ReuseList(5, 0, 10);
                this.reuseListRole.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseListRole);
                this.reuseListRole.setItemClass(vRoomRoleCell);
                this.reuseListRole.setVerticalMoveEnable(true);
                this.reuseListRole.setTouchEnable(true);
                this.reuseListRole.setSpaceX(16);
                this.reuseListRole.setSpaceY(-5);
                this.reuseListDesign = new ReuseList(6, 0, 20);
                this.reuseListDesign.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseListDesign);
                this.reuseListDesign.setItemClass(vDesignCollectCell);
                this.reuseListDesign.setVerticalMoveEnable(false);
                this.reuseListDesign.setTouchEnable(false);
                this.reuseListDesign.setSpaceX(4);
                this.reuseListDesign.setSpaceY(2);
                this.reuseList = new ReuseList(6, 0, 20);
                this.reuseList.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseList);
                this.reuseList.setItemClass(vRoomPart);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(4);
                this.reuseList.setSpaceY(2);
                this.reuseListType = new ReuseList(0, 1, 10);
                this.reuseListType.size(this.boxPartList.width, this.boxPartList.height);
                this.boxTypeList.addChild(this.reuseListType);
                this.reuseListType.setItemClass(vRoomPartType);
                this.reuseListType.setHorizontalMoveEnable(true);
                this.reuseListType.setSpaceX(4);
                this.spriteStageScoreUpFlag.visible = false;
                this.spriteStageScoreDownFlag.visible = false;
                this.refreshTargetScore(0);
            }
            checkMainAvatarClick(ray) {
                if (DialogBase.ShowingDialog.length > 0 || !this.avatar || this.avatar.destroyed || !this.avatar.isIdling()) {
                    return false;
                }
                for (let colliderName in this.avatar.avatarColliderSprite3dDict) {
                    let sprite3d = this.avatar.avatarColliderSprite3dDict[colliderName];
                    if (!sprite3d) {
                        continue;
                    }
                    let result = UVPickerByMesh.pick(ray, sprite3d);
                    if (result && result.bHit) {
                        let type = this.avatar.avatarColliderName2TypeDict[colliderName];
                        let datas = mgrCfg.get_from_center_role_click_feedback_db(type);
                        if (!datas) {
                            return false;
                        }
                        let data = Tools.randomGotOneArrayData(datas);
                        if (data.soundId) {
                            mgrSound.play(data.soundId);
                        }
                        this.avatar.playAnimation(data.animationId, 0, () => {
                            this.avatar.hideShouChi();
                        }, () => {
                            this.avatar.showShouChi();
                        });
                        return true;
                    }
                }
                return false;
            }
            fillData() {
                this.buttonBack.__node.visible = !!mgrGuide.isAllForceGuideFinished();
                this.roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let tagData = mgrCfg.get_from_part_tag_db(this.roleData.roleTagId);
                Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                this.stageData = mgrCfg.get("stage_db", this.context.stageId);
                this.stageScript = this.stageData["script"];
                if (this.context.partIds && this.context.partIds.length) {
                    this.avatar.fillByPartIds(this.context.partIds);
                }
                if (!!this.stageData && !!this.stageData.defaultPartIds && this.stageData.defaultPartIds.length > 0) {
                    this.avatar.fillByPartIds(this.stageData.defaultPartIds);
                }
                this.avatar.outForHide();
                mgrTip.showLoadingTip("vRoomDialog_loadingAvatar", null, null, true);
                this.avatar.registerLoadEndCallback(() => {
                    this.avatar.transform.position = new Laya.Vector3;
                    mgrTip.hideLoadingTip("vRoomDialog_loadingAvatar");
                });
                this.spriteStageTarget.visible = true;
                Timer.callLater(0.1, () => {
                    this.refreshTargetScore(100);
                }, this);
                let arr = [];
                let typeDatas = mgrCfg.forDb_from_part_type_db((k, v) => {
                    if (!!v.listOrder) {
                        arr.push({
                            id: v.id,
                            listOrder: v.listOrder,
                            fOnClick: this.onClickPartType.bind(this),
                            isDressedType: this.isDressedType.bind(this),
                            fIsCurrentType: this.isCurrentType.bind(this)
                        });
                    }
                });
                for (let k in arr) {
                    let data = arr[k];
                    let partIds = mgrStage.getRecommendPartByStageAndType(data.id, this.roleData.roleTagId);
                    if (!partIds || partIds.length == 0) {
                        this.type2RecommandPartIdDict[data.id] = [];
                        continue;
                    }
                    for (let tmp in partIds) {
                        this.type2RecommandPartIdDict[data.id] = this.type2RecommandPartIdDict[data.id] || {};
                        this.type2RecommandPartIdDict[data.id][partIds[tmp]] = true;
                    }
                }
                arr = Tools.sortArrayByField(arr, "listOrder");
                let defaultSelectTypeIndex = 0;
                if (!!this.stageData.bSpecialStage) {
                    let arrSpecial = [];
                    if (!!mgrDesign.getDesignPartCount()) {
                        arrSpecial.push({ id: Const.ROOM_SPECIAL_TYPE_DESIGN, insertIndex: 4, fOnClick: this.onClickPartTypeDesign.bind(this) });
                    }
                    let ownedRoleCount = 0;
                    mgrCfg.forDb_from_role_db((k, v) => {
                        if (mgrPlayer.getItemAmount(v.id) > 0) {
                            ownedRoleCount++;
                        }
                    });
                    if (!this.stageScript.isDisableChangeRole() && !(mgrGuide.isGuiding() || !mgrGuide.isAllGuideFinished())) {
                        arrSpecial.push({ id: Const.ROOM_SPECIAL_TYPE_ROLE, insertIndex: 0, fOnClick: this.onClickPartTypeRole.bind(this) });
                    }
                    for (let k in arrSpecial) {
                        let data = arrSpecial[k];
                        let typeId = data.id;
                        this.type2RecommandPartIdDict[typeId] = [];
                        arr.splice(data.insertIndex, 0, {
                            id: typeId,
                            listOrder: 0,
                            fOnClick: data.fOnClick,
                            isDressedType: this.isDressedType.bind(this),
                            fIsCurrentType: this.isCurrentType.bind(this)
                        });
                    }
                    defaultSelectTypeIndex = 1;
                }
                this.reuseListType.setDatas(arr);
                this.onSelectType(arr[defaultSelectTypeIndex].id, true);
            }
            isDressedType(type) {
                return !!this.avatar.getPartIdByType(type);
            }
            isCurrentType(type) {
                return (this.selectedType && this.selectedType == type) ? true : false;
            }
            onClickPartType(type) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vRoomDialog.clickPartType${type}` });
                this.onSelectType(type);
            }
            onSelectType(type, bIgnoreCameraFollow) {
                let bSame = type == this.selectedType;
                if (bSame) {
                    return;
                }
                this.selectedType = type;
                if (!bIgnoreCameraFollow) {
                    let params = this.partTypeCameraParams[type] || this.partTypeCameraParams[0];
                    this.cameraFollow.position = params.position.clone();
                    this.cameraFollow.endRotation = params.rotation.clone();
                    this.cameraFollow.fov = params.fov;
                    this.cameraFollow.lerpValue = 0.05;
                }
                let datas = this.getPartDatasByType(type);
                this.currentTypePartDatas = datas;
                this.reuseList.setDatas(datas);
                this.reuseList.setScroll(0);
                this.refreshTypeStatus();
            }
            getPartDatasByType(type) {
                let datas = [];
                if (!this.type2SortFlagDict[type]) {
                    let bTriggerTry = mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vRoomDialog_trial, true);
                    let specialPartArr = [];
                    let gotedPartIdArr = [];
                    let coinPartIdArr = [];
                    let lockedPartIdArr = [];
                    let db = mgrCfg.getDbArr("part_db", (data) => {
                        if (data.type != type || !!data.bDisableShowInRoom) {
                            return false;
                        }
                        if (mgrDesign.isDesignPart(data.id)) {
                            return false;
                        }
                        return true;
                    });
                    for (let k in db) {
                        let v = db[k];
                        let score = mgrCard.calculateRoleTagPartIdsPower(this.roleData.roleTagId, [v.id]);
                        let bAd = false;
                        if (bTriggerTry && this.tryingPartIds.indexOf(v.id) == -1 && mgrPlayer.getItemAmount(v.id) <= 0 && !mgrShop.isDiscount(v.id)) {
                            bAd = true;
                        }
                        let data = {
                            partId: v.id,
                            score: score,
                            level: v.level,
                            guideOrder: ((v.id == 13002 || v.id == 16002) ? 1 : 0),
                            fOnClickPart: this.onClickPart.bind(this),
                            fIsSelected: this.isSelectPart.bind(this),
                            fIsRecommend: (pId) => { return !!this.type2RecommandPartIdDict[type][pId]; },
                            fIsTry: this.isTry.bind(this),
                            fIsDressing: this.isDressedPart.bind(this),
                            fIsLuckyPart: this.isLuckyPart.bind(this),
                            fStaticsShow: () => {
                            },
                            order: v.id,
                            bAd: bAd,
                            __customOrderValue: 0,
                        };
                        if (this.isLuckyPart(v.id) || !!this.type2RecommandPartIdDict[type][v.id]) {
                            specialPartArr.push(data);
                        }
                        else {
                            if (mgrPlayer.getItemAmount(v.id) <= 0) {
                                let shopData = mgrCfg.get_from_shop_template_db(v.id);
                                if (!!shopData) {
                                    coinPartIdArr.push(data);
                                }
                                else {
                                    lockedPartIdArr.push(data);
                                }
                            }
                            else {
                                gotedPartIdArr.push(data);
                            }
                        }
                    }
                    let count = Math.max(Math.max(gotedPartIdArr.length, lockedPartIdArr.length), coinPartIdArr.length);
                    let dataDict = {
                        [0]: gotedPartIdArr,
                        [1]: lockedPartIdArr,
                        [2]: coinPartIdArr
                    };
                    for (let i = 0; i < count; i++) {
                        let indexDataArr = Tools.randomGotArrayDatas([0, 1, 2], 3);
                        for (let tmp in indexDataArr) {
                            let tmpDatas = dataDict[indexDataArr[tmp]];
                            if (tmpDatas.length > 0) {
                                let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                                datas.push(tmpData);
                            }
                            if (indexDataArr[tmp] == 1 && Tools.random(100) > 50 && tmpDatas.length > 0) {
                                let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                                datas.push(tmpData);
                            }
                        }
                    }
                    specialPartArr = Tools.randomGotArrayDatas(specialPartArr, specialPartArr.length);
                    for (let i = 0; i < specialPartArr.length; i++) {
                        let index = Tools.random(1, 9);
                        datas.splice(index, 0, specialPartArr[i]);
                    }
                    let sortedPartId2OrderDict = mgrPart.getGameRoomListSortedId2OrderDictByType(DailyGameType.cloth, type);
                    if (!!sortedPartId2OrderDict && Tools.getObjSize(sortedPartId2OrderDict) > 0) {
                        for (let i = 0; i < datas.length; i++) {
                            let sortedOrder = parseInt(sortedPartId2OrderDict[datas[i].partId]);
                            datas[i].__customOrderValue = !!isNaN(sortedOrder) ? i : sortedOrder;
                        }
                    }
                    else {
                        let sortedPartId2OrderDict = {};
                        for (let i = 0; i < datas.length; i++) {
                            datas[i].__customOrderValue = i;
                            sortedPartId2OrderDict[datas[i].partId] = i;
                        }
                        mgrPart.setGameRoomListSortedId2OrderDictByType(DailyGameType.cloth, type, sortedPartId2OrderDict);
                    }
                    datas = Tools.sortArrayByField(datas, ["-guideOrder", "__customOrderValue"]);
                    this.type2SortFlagDict[type] = datas;
                }
                else {
                    datas = this.type2SortFlagDict[type];
                }
                if (mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vRoomDialog_trial)) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vRoomDialog_trial);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
                return datas;
            }
            onClickPartTypeRole() {
                if (this.selectedType == Const.ROOM_SPECIAL_TYPE_ROLE) {
                    return;
                }
                this.selectedType = Const.ROOM_SPECIAL_TYPE_ROLE;
                this.fillListRoleData();
            }
            fillListRoleData() {
                let arr = [];
                mgrCfg.forDb_from_role_db((k, v) => {
                    arr.push({
                        bOwned: mgrPlayer.getItemAmount(v.id) > 0 ? 1 : 0,
                        partId: v.id,
                        fOnClick: this.onClickRoleItem.bind(this),
                        fIsCurrentRole: (id) => { return this.context.roleId == id; }
                    });
                });
                arr = Tools.sortArrayByField(arr, ["-bOwned", "partId"]);
                this.reuseListRole.setDatas(arr);
                this.refreshTypeStatus();
            }
            onClickPartTypeDesign() {
                if (this.selectedType == Const.ROOM_SPECIAL_TYPE_DESIGN) {
                    return;
                }
                this.selectedType = Const.ROOM_SPECIAL_TYPE_DESIGN;
                let arr = [];
                let dict = mgrDesign.getDesignPartDataDict();
                for (let k in dict) {
                    let partId = parseInt(k);
                    if (!mgrDesign.isDesignPart(partId)) {
                        continue;
                    }
                    arr.push({
                        partId: partId,
                        bShowSelectFlag: true,
                        fOnClick: this.onClickDesignItem.bind(this),
                        fIsSelect: this.isSelectPart.bind(this),
                    });
                }
                arr = Tools.sortArrayByField(arr, "partId");
                this.reuseListDesign.setDatas(arr);
                this.refreshTypeStatus();
            }
            onClickRoleItem(id) {
                if (id == this.context.roleId) {
                    mgrTip.showMsgTip("她已经站在舞台上啦");
                    return;
                }
                let roleData = mgrCfg.get_from_role_db(id);
                let collectJumpData = mgrCfg.get_from_role_collect_jump_db(id);
                if (collectJumpData && mgrPlayer.getItemAmount(id) <= 0) {
                    let scene = collectJumpData.jumpTargetScene;
                    let backScene = "vHubScene";
                    let promptStrTitle = collectJumpData.promptStrTitle || "";
                    let promptStrContent = collectJumpData.promptStrContent || "";
                    let promptStrGoBtn = collectJumpData.promptStrGoBtn || "";
                    switch (collectJumpData.jumpWay) {
                        case "open2DScene":
                            mgrTip.alertPrompt2(promptStrTitle, promptStrContent, "放弃", promptStrGoBtn, () => {
                            }, () => {
                                mgrDirector.open2DScene(scene, {
                                    backSceneName: backScene
                                });
                            });
                            break;
                        case "warpSceneWidthEffect":
                            mgrTip.alertPrompt2(promptStrTitle, promptStrContent, "放弃", promptStrGoBtn, () => {
                            }, () => {
                                mgrDirector.warpSceneWidthEffect(scene, {
                                    backSceneName: backScene
                                });
                            });
                            break;
                        default:
                            mgrTip.alertPrompt2(promptStrTitle, promptStrContent, "放弃", promptStrGoBtn, () => {
                            }, () => {
                                mgrDirector.openDialog(scene);
                            });
                            break;
                    }
                    return;
                }
                if (mgrPlayer.getItemAmount(roleData.unlockItemId) < roleData.unlockItemAmount &&
                    mgrPlayer.getItemAmount(id) <= 0 &&
                    mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vRoleChangeScene_fragment)) {
                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vRoleChangeScene_fragment, { roleId: id }, true);
                    return;
                }
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!roleData.statisPointId && mgrSdk.statisCommonEvent(roleData.statisPointId);
                }
                this.boxFrontEvent.visible = true;
                let partType = Const.ROOM_SPECIAL_TYPE_ROLE;
                let params = this.partTypeCameraParams[partType] || this.partTypeCameraParams[0];
                this.cameraFollow.position = params.position.clone();
                this.cameraFollow.endRotation = params.rotation.clone();
                this.cameraFollow.fov = params.fov;
                this.cameraFollow.lerpValue = 0.1;
                cc.tween(this.avatar.transform).to(0.1, { localRotationEulerX: 0, localRotationEulerY: 0, localRotationEulerZ: 0 }).start();
                this.avatar.playAnimation(["jiesuan_chuchang-jiesuan_chuchang"], 0, null, () => {
                    mgrRole.changeShowingRoleId(id);
                    this.context.roleId = id;
                    let roleData = mgrCfg.get_from_role_db(id);
                    this.avatar.changeRoleId(roleData.id);
                    this.avatar.setIdleId(this.BODY_IDLE_ANI);
                    this.avatar.fillByPartIds(roleData.centerPartIds, true);
                    let pos = this.avatar.transform.position.clone();
                    this.avatar.outForHide();
                    this.avatar.registerAllLoadEndCallback(() => {
                        this.roleData = roleData;
                        let tagData = mgrCfg.get_from_part_tag_db(this.roleData.roleTagId);
                        Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                        this.refreshTargetScore(500);
                        this.avatar.playAnimation(["jiesuan_ruchang-jiesuan_ruchang"], 0, () => {
                            this.avatar.transform.position = pos;
                        }, () => {
                            this.reuseListRole.refresh();
                            this.refreshTypeStatus();
                            this.boxFrontEvent.visible = false;
                        });
                    });
                }, false, true);
            }
            onClickDesignItem(id) {
                this.currentSelectPartId = id;
                this.avatar.fillByPartIds([id]);
                let partType = PartType.cloth;
                mgrTip.showLoadingTip("vRoomDialog_designItem");
                this.avatar.registerLoadEndCallback(() => {
                    mgrTip.hideLoadingTip("vRoomDialog_designItem");
                    this.reuseListDesign.refresh();
                    this.refreshTypeStatus();
                    this.addDressEffectByType(partType);
                    let params = this.partTypeCameraParams[PartType.cloth] || this.partTypeCameraParams[0];
                    this.cameraFollow.position = params.position.clone();
                    this.cameraFollow.endRotation = params.rotation.clone();
                    this.cameraFollow.fov = params.fov;
                    this.cameraFollow.lerpValue = 0.1;
                    let datas = mgrCfg.get_from_room_dress_role_feedback_db(partType);
                    if (datas) {
                        let data = Tools.randomGotOneArrayData(datas);
                        if (data.soundId) {
                            mgrSound.play(data.soundId);
                        }
                        if (this.avatar.isIdling()) {
                            this.avatar.playAnimation(data.animationId);
                        }
                    }
                });
            }
            refreshTypeStatus() {
                this.reuseListType.refresh();
                this.reuseList.y = (this.selectedType != Const.ROOM_SPECIAL_TYPE_ROLE && this.selectedType != Const.ROOM_SPECIAL_TYPE_DESIGN) ? 0 : 1000;
                this.reuseListRole.y = this.selectedType == Const.ROOM_SPECIAL_TYPE_ROLE ? 0 : 1000;
                this.reuseListDesign.y = this.selectedType == Const.ROOM_SPECIAL_TYPE_DESIGN ? 0 : 1000;
            }
            isSelectPart(partId) {
                return this.currentSelectPartId && this.currentSelectPartId == partId ? true : false;
            }
            isTry(partId) {
                return this.tryingPartIds.indexOf(partId) >= 0;
            }
            isDressedPart(partId) {
                return this.avatar.getPartIds().indexOf(partId) >= 0;
            }
            isLuckyPart(partId) {
                return mgrPart.isDailyLuckyPart(partId);
            }
            onClickPart(partId, bAd) {
                this.tryPopClickItemTrial(partId);
                this.onSelectPart(partId, bAd);
            }
            tryPopClickItemTrial(partId) {
                if (mgrGuide.isGuiding()) {
                    return;
                }
                if (mgrPlayer.getItemAmount(partId) <= 0 || mgrSdk.getCopNumberValueByKey("b_click_part_item_pop_trial") != 1) {
                    return;
                }
                let gap = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_gap") || 0;
                if (Tools.time() < (mgrPart.roomPopClickItemPartLastTime + gap)) {
                    return;
                }
                let popCount = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_count_per_stage") || 0;
                if (this.roomPopClickItemPartCount > popCount) {
                    return;
                }
                if (!mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vRoomDialog_trial, true)) {
                    return;
                }
                this.roomPopClickItemPartCount++;
                mgrPart.roomPopClickItemPartLastTime = Tools.time();
                let lockedPartIdArr = [];
                for (let k in this.currentTypePartDatas) {
                    let data = this.currentTypePartDatas[k];
                    let shopData = mgrCfg.get_from_shop_template_db(data.partId);
                    if (mgrPlayer.getItemAmount(data.partId) <= 0 && !shopData) {
                        lockedPartIdArr.push(data.partId);
                    }
                }
                if (lockedPartIdArr.length == 0) {
                    return;
                }
                let partIdAd = Tools.randomGotOneArrayData(lockedPartIdArr);
                mgrDirector.openDialog("vAdFreeTrialPartDialog", {
                    adEventId: AD_EVENT_ID.VIDEO.video_vRoomDialog_trial,
                    partId: partIdAd,
                    adTriggerParams: {
                        partId: partIdAd,
                    }
                });
            }
            onSelectPart(partId, bAd) {
                console.warn("----------------onSelectPart partId=", partId);
                this.sendMsg("MSG_GUIDE_EVENT", { id: `vRoomDialog.clickPart${partId}` });
                this.currentSelectPartId = partId;
                if (mgrPlayer.getItemAmount(partId) <= 0 && !this.isTry(partId)) {
                    let shopData = mgrCfg.get_from_shop_template_db(partId);
                    if (!shopData) {
                        if (mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vRoomDialog_trial, true)) {
                            if (mgrSdk.getCopNumberValueByKey(`b_room_try_ad_tip`) == 0) {
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vRoomDialog_trial, { partId: partId }, true);
                            }
                            else {
                                mgrTip.alertPrompt2("提示", "是否看视频免费试用？", "取消", "确定", null, () => {
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vRoomDialog_trial, { partId: partId }, true);
                                }, true, false);
                            }
                        }
                        else {
                            let coinAmount = Const.ROOM_TRIAL_PART_COST;
                            let coinTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                            mgrTip.alertPrompt2("提示", `是否花费${coinAmount}${coinTemplate.name}试用？`, "取消", "确定", null, () => {
                                if (mgrShop.tryConsumeItem(Const.ITEM_ID_DIAMONDS, coinAmount, "试用")) {
                                    this.sendMsg("MSG_COIN_ROOM_TRY_SUCCESSED", {
                                        partId: partId,
                                    });
                                }
                            });
                        }
                    }
                    else {
                        if (!shopData || !shopData.price || !shopData.priceUnit) {
                            mgrTip.showMsgTip("还未获得此部件");
                            return;
                        }
                        let doBuyFunc = () => {
                            if (mgrShop.requestBuy(partId, "换装")) {
                                Timer.callLoop(0.016, (timer) => {
                                    if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                        return;
                                    timer.stop();
                                    this.onSelectPart(partId, false);
                                }, this);
                            }
                            else {
                            }
                        };
                        if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                            let partData = mgrCfg.get_from_item_template_db(partId);
                            let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                            mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                doBuyFunc();
                            });
                        }
                        else {
                            doBuyFunc();
                        }
                    }
                    return;
                }
                let bPlaySound = true;
                let partData = mgrCfg.get_from_part_db(partId);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!partData.statisPointId && mgrSdk.statisCommonEvent(partData.statisPointId);
                }
                let partType = partData.type;
                let partTypeData = mgrCfg.get_from_part_type_db(partType);
                if (this.isDressedPart(partId)) {
                    if (partTypeData.defaultPartId) {
                        this.avatar.fillByPartIds([partTypeData.defaultPartId]);
                    }
                    else {
                        this.avatar.removePart(partId);
                    }
                    this.reuseList.refresh();
                    this.refreshTypeStatus();
                    if (partType == PartType.handHold) {
                        this.avatar.setIdleId(this.BODY_IDLE_ANI);
                        this.avatar.playAnimation(this.BODY_IDLE_ANI);
                    }
                }
                else {
                    if (bPlaySound) {
                        mgrSound.play(119);
                    }
                    this.avatar.fillByPartIds([partId]);
                    mgrTip.showLoadingTip("vRoomDialog_loadingPart");
                    this.avatar.registerLoadEndCallback(() => {
                        mgrTip.hideLoadingTip("vRoomDialog_loadingPart");
                        this.reuseList.refresh();
                        this.refreshTypeStatus();
                        this.addDressEffectByType(partType);
                        if (partType == PartType.handHold) {
                            this.avatar.setIdleId(partData.holdIdleAnimation);
                        }
                        let bLuckyPart = this.isLuckyPart(partId);
                        if (bLuckyPart) {
                            let eff = mgrLoader.Pool.getModel("e_yanhua_09");
                            eff.transform.position = new Laya.Vector3(this.avatar.transform.position.x, this.avatar.transform.position.y + 1.2, this.avatar.transform.position.z);
                            this.add3DEffectAtBack(eff);
                            this.avatar.playAnimation("hz_teshu-hz_teshu");
                            this.cameraFollow.position = CAMERA_PRARAM_LUCKY.position.clone();
                            this.cameraFollow.endRotation = CAMERA_PRARAM_LUCKY.rotation.clone();
                            this.cameraFollow.fov = CAMERA_PRARAM_LUCKY.fov;
                            this.cameraFollow.lerpValue = 0.1;
                        }
                        else {
                            let params = this.partTypeCameraParams[partType] || this.partTypeCameraParams[0];
                            this.cameraFollow.position = params.position.clone();
                            this.cameraFollow.endRotation = params.rotation.clone();
                            this.cameraFollow.fov = params.fov;
                            this.cameraFollow.lerpValue = 0.1;
                            let datas = mgrCfg.get_from_room_dress_role_feedback_db(partType);
                            if (datas) {
                                let data = Tools.randomGotOneArrayData(datas);
                                if (data.soundId && bPlaySound) {
                                    mgrSound.play(data.soundId);
                                }
                                if (this.avatar.isIdling()) {
                                    this.avatar.playAnimation(data.animationId, 0, () => {
                                        this.avatar.hideShouChi();
                                    }, () => {
                                        this.avatar.showShouChi();
                                    });
                                }
                            }
                            else {
                                this.avatar.playAnimation(partData.holdIdleAnimation);
                            }
                        }
                    });
                }
                this.refreshTargetScore(500);
                this.avatar.tryShowLuckEffect();
            }
            addDressEffectByType(partType) {
                if (this.lastHuangZhuangEffModel) {
                    Tools.unLink2Node(this.lastHuangZhuangEffModel);
                    mgrLoader.Pool.recoverModel(this.lastHuangZhuangEffModel);
                    this.lastHuangZhuangEffModel = null;
                }
                if (partType == PartType.cloth) {
                    this.lastHuangZhuangEffModel = mgrLoader.Pool.getModel("117_e_once_change_01");
                    this.add3DEffectAtBack(this.lastHuangZhuangEffModel);
                    this.lastHuangZhuangEffModel.transform.position = new Laya.Vector3(this.avatar.transform.position.x, this.avatar.transform.position.y + 1, this.avatar.transform.position.z);
                    return;
                }
                let type2LinkFunc = {
                    [PartType.headDec]: "linkMode2EffectHead",
                    [PartType.cloth]: "linkMode2EffectCloth",
                    [PartType.sock]: "linkMode2EffectSock",
                    [PartType.shoe]: "linkMode2EffectFoot",
                    [PartType.earDec]: "linkMode2EffectEar",
                    [PartType.handDec]: "linkMode2EffectCloth",
                    [PartType.neckDec]: "linkMode2EffectNeck",
                    [PartType.backDeco]: "linkMode2EffectCloth",
                };
                let funcName = type2LinkFunc[partType];
                if (!funcName) {
                    return;
                }
                this.lastHuangZhuangEffModel = mgrLoader.Pool.getModel("e_huanzhuang");
                this.avatar[funcName](this.lastHuangZhuangEffModel);
            }
            isDressAutoPopTrialPart() {
                return false;
            }
            refreshTargetScore(duration) {
                if (!this.context.stageId)
                    return;
                this.avatar.registerAllLoadEndCallback(() => {
                    let stageData = mgrCfg.get_from_stage_db(this.context.stageId);
                    let bDressedAutoPopTrialPart = this.isDressAutoPopTrialPart();
                    let score = mgrCard.calculateRoleTagPartIdsPower(this.roleData.roleTagId, this.avatar.getPartIds()) + (!!bDressedAutoPopTrialPart ? Const.SCORE_WHEN_ROOM_DRESSED_AUTO_POP_TRIAL_PART : 0);
                    let maxScore = Math.ceil(this.stageData.passScore / (2 / 3));
                    this.spriteStageRate01.visible = score < this.stageData.passScore ? true : false;
                    this.spriteStageRate02.visible = (score >= this.stageData.passScore && score < maxScore) ? true : false;
                    this.spriteStageRate03.visible = score >= maxScore ? true : false;
                    this.spriteStageScoreGood.visible = !!this.spriteStageRate03.visible;
                    this.spriteStageScoreBad.visible = !this.spriteStageScoreGood.visible;
                    this.labelShowingPower.text = `${score}`;
                    this.labelStagePower.text = `${score}`;
                    let level = mgrCard.calculateCardLevelStarByPower(score);
                    for (let i = 0; i < 5; i++) {
                        let spriteStar = this.spriteStarContainer.getChildAt(i);
                        spriteStar.visible = level > i;
                    }
                    if (!!this.lastRecordTargetScore) {
                        this.spriteStageScoreUpFlag.visible = !!score && this.lastRecordTargetScore < score ? true : false;
                        this.spriteStageScoreDownFlag.visible = !!score && this.lastRecordTargetScore > score ? true : false;
                        if (!!this.spriteStageScoreUpFlag.visible) {
                            this.add3DEffectAtFront("117_ui_once_up_01", this.spriteStageScoreUpFlag, 2);
                        }
                        else if (!!this.spriteStageScoreDownFlag.visible) {
                            this.add3DEffectAtFront("117_ui_once_down_01", this.spriteStageScoreDownFlag, 2);
                        }
                    }
                    this.lastRecordTargetScore = score;
                    if (this.spriteStageRate03.visible) {
                        mgrEffect.shineNode(this.spriteStageScoreGood);
                    }
                    else {
                        mgrEffect.stopShineNode(this.spriteStageScoreGood);
                    }
                });
            }
            onMsgAdRoomTrySuccessed(e) {
                if (this.tryingPartIds.indexOf(e.partId) >= 0)
                    return;
                this.tryingPartIds.push(e.partId);
                this.onSelectPart(e.partId, e.bAd);
                this.reuseList.refresh();
                mgrPartTrial.addPartTrialCount(e.partId);
                if (mgrPlayer.getItemAmount(e.partId) <= 0 && mgrPartTrial.canTrialGetPart()) {
                    mgrDirector.openDialog("vAdFreeTrialSuccesDialog", { partId: e.partId });
                }
                if (mgrSdk.getCopNumberValueByKey("b_after_trial_reward_coin") == 1) {
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, 10, "试用奖励");
                    mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, 10);
                }
            }
            onMsgCoinRoomTrySuccessed(e) {
                if (this.tryingPartIds.indexOf(e.partId) >= 0)
                    return;
                this.tryingPartIds.push(e.partId);
                this.onSelectPart(e.partId, false);
                this.reuseList.refresh();
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vRoomDialog_trial) {
                    this.sendMsg("MSG_AD_ROOM_TRY_SUCCESSED", {
                        partId: e.userData.partId,
                        bAd: e.userData.bAd,
                    });
                }
                else if (e.adEventId == AD_EVENT_ID.VIDEO.video_vRoleChangeScene_fragment) {
                    let roleId = e.userData.roleId;
                    let callback = () => {
                        this.reuseListRole.refresh();
                    };
                    mgrDirector.openDialog("vGotNewRoleDialog", { roleId: roleId, bVip: true, fOnClose: callback });
                }
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                    if (Math.abs(deltaX) < 20 && Math.abs(deltaY) < 20) {
                        let param = this.partTypeCameraParams[Const.ROOM_SPECIAL_TYPE_ROLE] || this.partTypeCameraParams[0];
                        this.cameraFollow.position = param.position.clone();
                        this.cameraFollow.endRotation = param.rotation.clone();
                        this.cameraFollow.fov = param.fov;
                        this.cameraFollow.lerpValue = param.lerpValue;
                        let screenWorldPos = new Laya.Vector2(e.pos.x, e.pos.y);
                        let ray = Tools.createRayFromScreenPos(this.cameraFollow.__node, screenWorldPos);
                        this.checkMainAvatarClick(ray);
                    }
                }
            }
            onTouchButtonBack() {
                this.stageScript.onTouchButtonBack(this);
            }
            onTouchButtonTypeHeadDec() {
                this.onSelectType(PartType.headDec);
            }
            onTouchButtonTypeEarDec() {
                this.onSelectType(PartType.earDec);
            }
            onTouchButtonTypeDress() {
                this.sendMsg("MSG_GUIDE_EVENT", { id: "vRoomDialog.clickButtonTypeDress" });
            }
            onTouchButtonTypeHandDec() {
                this.onSelectType(PartType.handDec);
            }
            onTouchButtonTypeNeckDec() {
                this.onSelectType(PartType.neckDec);
            }
            onTouchButtonSummit() {
                this.sendMsg("MSG_GUIDE_EVENT", { id: "vRoomDialog.clickButtonSummit" });
                let doExcFunc = () => {
                    let dressedLuckyPartIdArr = [];
                    let partIds = this.avatar.getPartIds();
                    for (let k in partIds) {
                        let partId = partIds[k];
                        if (mgrPlayer.isDailyDressedLuckyPartId(partId)) {
                            dressedLuckyPartIdArr.push(partId);
                        }
                    }
                    if (dressedLuckyPartIdArr.length > 0) {
                        mgrPlayer.addDailyDressedLuckyPartIds(dressedLuckyPartIdArr);
                    }
                    this.dressedLuckyPartIds = dressedLuckyPartIdArr;
                    this.stageScript.onRoomSceneFinishStage(this);
                };
                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                    mgrTip.alertPrompt2("提示", `确定提交进入下一步吗?`, "再想想", "确定", null, () => {
                        doExcFunc();
                    });
                }
                else {
                    doExcFunc();
                }
            }
            onTouchButtonTypeCloth() {
                this.onSelectType(PartType.cloth);
            }
            onTouchButtonTypeSock() {
                this.onSelectType(PartType.sock);
            }
            onTouchButtonTypeShoe() {
                this.onSelectType(PartType.shoe);
            }
            onTouchButtonTypeBackDeco() {
                this.onSelectType(PartType.backDeco);
            }
            onTouchButtonMoreGameBox() {
                mgrSdk.opentChannelMoreGameBox();
            }
            onMsgShopBuySuccessed() {
                if (this.selectedType) {
                    this.reuseList.refresh();
                }
            }
            onMsgItemAmountChanged() {
                this.fillListRoleData();
            }
        }

        class vSettingDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vSettingDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                if (mgrMidAutumn.isEnable()) {
                    this.imageMidAutumnBg.visible = true;
                }
                else {
                    this.imageMidAutumnBg.visible = false;
                }
                this.registerListeners({
                    MSG_SDK_USE_CDK_SUCCESSFUL: this.onMsgUseCdkSuccessful.bind(this),
                });
                this.imageBgContainer["_originHeight"] = this.imageBgContainer.height;
                this.imageMidAutumnBg["_originHeight"] = this.imageMidAutumnBg.height;
                this.fillData();
                this.adptUi();
                Tools.registerTouchHander(this, this.onTouchNodeBg.bind(this));
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGame);
            }
            onAnimationFinished() {
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonSwitchMusic() {
                let volume = mgrSound.getMusicVolmue();
                if (volume > 0) {
                    mgrSound.pauseMusic("settingDialog");
                }
                else {
                    mgrSound.resumeMusic("settingDialog");
                }
                this.fillData();
            }
            onTouchButtonSwitchEffect() {
                let volume = mgrSound.getEffectVolume();
                if (volume > 0) {
                    mgrSound.pauseEffect("settingDialog");
                }
                else {
                    mgrSound.resumeEffect("settingDialog");
                }
                this.fillData();
            }
            onTouchButtonSwitchRecord() {
                mgrChannel.setUserOpenVideoRecord(!mgrChannel.getUserOpenVideoRecord());
                this.fillData();
            }
            onTouchButtonCdkey() {
                if (this.input.text) {
                    mgrInnerCdk.receiveInnerCdk(this.input.text.trim());
                }
            }
            onTouchButtonAuthority() {
                let mode = mgrSdk.getCopNumberValueByKey("b_advanced_setting");
                if (mode == 1) {
                    mgrSdk.openAdvancedSetting();
                }
                else if (mode == 2) {
                    mgrDirector.openDialog("vAdvancedSettingDialog");
                }
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            fillData() {
                let bOpenVideoRecord = mgrChannel.getUserOpenVideoRecord();
                this.spriteOpenRecord.visible = bOpenVideoRecord;
                this.spriteCloseRecord.visible = !bOpenVideoRecord;
                let bOpenMusic = mgrSound.getMusicVolmue() == 1;
                this.spriteOpenMusic.visible = bOpenMusic;
                this.spriteCloseMusic.visible = !bOpenMusic;
                let bOpenSoundEffect = mgrSound.getEffectVolume() == 1;
                this.spriteOpenEffect.visible = bOpenSoundEffect;
                this.spriteCloseEffect.visible = !bOpenSoundEffect;
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vSettingDialog_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
            }
            adptUi() {
                this.boxRecord.visible = mgrChannel.haveVideoRecord();
                if (this.boxRecord.visible) {
                    this.imageBgContainer.height += this.boxRecord.height;
                    this.imageMidAutumnBg.height += this.boxRecord.height;
                    this.imageSwitchBg.height += this.boxRecord.height;
                }
                this.boxFuncContainer.y = this.imageBgContainer.height - 25;
                let startY = 0;
                this.spriteCdkNode.visible = mgrSdk.getCopNumberValueByKey("b_cdk") == 1 ? true : false;
                if (!!this.spriteCdkNode.visible) {
                    this.imageBgContainer.height += this.spriteCdkNode.height;
                    this.imageMidAutumnBg.height += this.spriteCdkNode.height;
                    this.spriteCdkNode.y = startY + this.spriteCdkNode.height / 2;
                    startY += this.spriteCdkNode.height;
                }
                this.boxAuthority.visible = (mgrSdk.getCopNumberValueByKey("b_advanced_setting") == 1 || mgrSdk.getCopNumberValueByKey("b_advanced_setting") == 2) ? true : false;
                if (!!this.boxAuthority.visible) {
                    this.imageBgContainer.height += this.boxAuthority.height;
                    this.imageMidAutumnBg.height += this.boxAuthority.height;
                    this.boxAuthority.y = startY + this.boxAuthority.height / 2;
                    startY += this.boxAuthority.height;
                }

                this.boxAuthority.visible = false;

                this.labelKeyfu.text = `${mgrSdk.getCopByKey("s_kefu_text") || ""}`;
                this.labelKeyfu.y = this.imageBgContainer.height - 20;
            }
            onTouchNodeBg(e) {
                console.log("-----onTouchNodeBg");
                if (e.isBegin) {
                    this["_b_drag_to_right"] = true;
                    this["_turn_count"] = 0;
                    this["_b_poped"] = false;
                    this[`_v_start_pos`] = e.pos;
                }
                else if (e.isMove) {
                    let p0 = this[`_v_start_pos`];
                    let p = e.pos;
                    if (this["_b_drag_to_right"]) {
                        if (p.x < p0.x - 20) {
                            this["_b_drag_to_right"] = false;
                            this["_turn_count"]++;
                            console.log("turn left", this["_turn_count"]);
                        }
                    }
                    else {
                        if (p.x > p0.x + 20) {
                            this["_b_drag_to_right"] = true;
                            this["_turn_count"]++;
                            console.log("turn right", this["_turn_count"]);
                        }
                    }
                    if (!this["_b_poped"]) {
                        if (this["_turn_count"] >= 20) {
                            mgrDirector.openDialog("vDebugDialog");
                            this["_b_poped"] = true;
                        }
                    }
                }
            }
            onMsgUseCdkSuccessful(data) {
            }
        }

        const SHARE_DIALOG_NAME = "share_dialog";
        class vShareDilaog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vShareDilaog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.registerListeners({
                    MSG_SDK_SHARE_RESULT: this.onMsgSdkShareResult.bind(this),
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            getPreLoadModelIds() {
                return [MODEL_ID.effect.eff_ui_xsyd];
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                this.labelCountReward.text = `${mgrChannel.getShareRewardAmount()}`;
                Tools.loadImg(this.imageIconReward, mgrPlayer.getIcon(1));
                this.add3DEffectAtFront("eff_ui_xunlianwancheng", this.spriteResultTitle);
                this.add3DEffectAtFront("eff_ui_wg_loop", this.imageIconReward);
                this.buttonMistake.__node.visible = mgrShare.isShareMistake();
                if (!!mgrShare.getShareGuideTime() && this.boxShareContent.visible) {
                    this.add3DEffectAtFront(MODEL_ID.effect.eff_ui_xsyd, this.buttonShare.__node, mgrShare.getShareGuideTime());
                }
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonShare() {
                mgrSdk.openShare();
            }
            onTouchButtonMistake() {
                mgrSdk.openShare();
            }
            onMsgSdkShareResult(e) {
                let data = e;
                let bSuccessful = data.bSuccessful;
                if (bSuccessful) {
                    mgrShare.recordShare(SHARE_DIALOG_NAME);
                    this.closeDialog();
                }
            }
        }

        class vSharePromptDilaog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vSharePromptDilaog";
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.registerListeners({
                    MSG_SDK_SHARE_RESULT: this.onMsgSdkShareResult.bind(this),
                    MSG_SDK_SHARE_VIDEO_RESULT: this.onMsgSdkShareVideoResult.bind(this),
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            getPreLoadModelIds() {
                return [MODEL_ID.effect.eff_ui_xsyd];
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                this.imageSharePromptTip.visible = mgrSdk.getCopNumberValueByKey("b_video_share_prompt_time_tip") != 1 ? false : true;
                this.shareCopName = this.context.shareCopName;
                this.buttonClose.__node.visible = true;
                if (this.shareCopName) {
                    this.boxShareContent.visible = !!mgrShare.isCanShare(this.shareCopName);
                    this.spriteResultTitle.visible = mgrShare.isCanShare(this.shareCopName);
                    this.buttonOk.__node.visible = !mgrShare.isCanShare(this.shareCopName);
                    this.labelNoShare.visible = !mgrShare.isCanShare(this.shareCopName);
                    this.labelContent.text = this.context.contextText;
                    if (this.boxShareContent.visible) {
                        let useShareBtn = this.buttonClose;
                        useShareBtn.__node.alpha = 0;
                        let delayTime = mgrShare.getShareDelayTime();
                        cc.tween(useShareBtn.__node)
                            .delay(delayTime)
                            .toAlpha(0.3, 1)
                            .start();
                    }
                    this.buttonMistake.__node.visible = mgrShare.isShareMistake();
                    if (!!mgrShare.getShareGuideTime() && this.boxShareContent.visible) {
                        this.add3DEffectAtFront(MODEL_ID.effect.eff_ui_xsyd, this.buttonShare.__node, mgrShare.getShareGuideTime());
                    }
                }
            }
            onMsgSdkShareResult(e) {
                let data = e;
                let bSuccessful = data.bSuccessful;
                if (bSuccessful) {
                    mgrShare.recordShare(this.shareCopName);
                    this.onTouchButtonOk();
                }
            }
            onMsgSdkShareVideoResult(e) {
                this.onMsgSdkShareResult(e);
            }
            onTouchButtonShare() {
                if (mgrVideoRecorder.canShare()) {
                    mgrVideoRecorder.share();
                }
                else if (mgrChannel.canShare()) {
                    mgrSdk.openShare();
                }
            }
            onTouchButtonClose() {
                if (this.context.fOnClick) {
                    this.context.fOnClick();
                }
                this.closeDialog();
            }
            onTouchButtonOk() {
                if (this.context.fOnClick) {
                    this.context.fOnClick();
                }
                this.closeDialog();
            }
            onTouchButtonMistake() {
                this.onTouchButtonShare();
            }
        }

        const SHARE_DIALOG_NAME$1 = "share_with_photo_dialog";
        class vShareWithPhotoDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vShareWithPhotoDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.registerListeners({
                    MSG_SDK_SHARE_RESULT: this.onMsgSdkShareResult.bind(this),
                    MSG_SDK_SHARE_VIDEO_RESULT: this.onMsgSdkShareVideoResult.bind(this),
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            getPreLoadModelIds() {
                return [MODEL_ID.effect.eff_ui_xsyd];
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            onAnimationFinished() {
            }
            fillData() {
                this.spritePartRewardContainer.visible = false;
                if (!!this.context.rewardPartId) {
                    let partData = mgrCfg.get_from_part_db(this.context.rewardPartId);
                    if (!!partData) {
                        Tools.loadImg(this.spritePartRewardItemIcon, partData.icon);
                        this.spritePartRewardContainer.visible = false;
                    }
                }
                this.labelShareTip.text = this.context.shareTipStr || this.labelShareTip.text;
                this.boxShareContent.visible = !!mgrChannel.canShare() && mgrGuide.isAllForceGuideFinished();
                this.buttonClose.__node.visible = !this.boxShareContent.visible;
                this.imageSharePromptTip.visible = mgrSdk.getCopNumberValueByKey("b_video_share_prompt_time_tip") != 1 ? false : true;
                this.buttonShareClose.__node.visible = true;
                if (this.boxShareContent.visible) {
                    let useShareBtn = this.buttonShareClose;
                    useShareBtn.__node.alpha = 0;
                    let delayTime = mgrShare.getShareDelayTime();
                    cc.tween(useShareBtn.__node)
                        .delay(delayTime)
                        .toAlpha(0.3, 1)
                        .start();
                }
                if (!!this.context.texture2dShot) {
                    if ((this.context.texture2dShot instanceof Laya.Texture2D) || (this.context.texture2dShot instanceof Laya.Texture)) {
                        let texture = new Laya.Texture(this.context.texture2dShot);
                        this.spritePhotoTexture.texture = texture;
                        if (Math.abs(texture.sourceWidth - texture.sourceHeight) > 5) {
                            let oldWidth = this.spritePhotoTexture.width;
                            let oldHeight = this.spritePhotoTexture.height;
                            this.spritePhotoTexture.size(texture.sourceWidth, texture.sourceHeight);
                            let sw = oldWidth / texture.sourceWidth;
                            let sh = oldHeight / texture.sourceHeight;
                            let scale = Math.min(sw, sh);
                            this.spritePhotoTexture.width = this.spritePhotoTexture.width * scale;
                            this.spritePhotoTexture.height = this.spritePhotoTexture.height * scale;
                            this.spritePhotoTexture.x = (oldWidth - this.spritePhotoTexture.width) / 2;
                        }
                    }
                    else {
                        Tools.loadImg(this.spritePhotoTexture, this.context.texture2dShot);
                    }
                }
                let shareRewardCount = mgrChannel.getRecordRewardAmount(true);
                this.labelShareRewardCount.text = `${mgrPlayer.getItemAmountStr(shareRewardCount)}`;
                this.buttonMistake.__node.visible = mgrShare.isShareMistake();
                if (!!mgrShare.getShareGuideTime() && this.boxShareContent.visible) {
                    this.add3DEffectAtFront(MODEL_ID.effect.eff_ui_xsyd, this.buttonShare.__node, mgrShare.getShareGuideTime());
                }
            }
            onMsgSdkShareResult(e) {
                let data = e;
                let bSuccessful = data.bSuccessful;
                if (bSuccessful) {
                    mgrShare.recordShare(SHARE_DIALOG_NAME$1);
                    this.closeDialog();
                }
            }
            onMsgSdkShareVideoResult(e) {
                this.onMsgSdkShareResult(e);
            }
            onTouchButtonShare() {
                if (mgrVideoRecorder.canShare()) {
                    mgrVideoRecorder.share();
                }
                else if (mgrChannel.canShare()) {
                    mgrSdk.openShare();
                }
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonMistake() {
                this.onTouchButtonShare();
            }
            onTouchButtonShareClose() {
                this.closeDialog();
            }
        }

        class vSignDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vSignDialog";
                this.exportNodeNames = [];
                vSignDialog.signDialg = this;
            }
            onOpened() {
                super.onOpened();
                this.spriteAdFlag.visible = false;
                this.buildUi();
                this.fillData();
                Timer.callLoop(0.016, this.fillData.bind(this), this);
                this.widget();
                this.fadeIn();
                mgrSound.play(501);
                let bAd = mgrSign.getState() != SignState.signed && !!mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSignDialog_got_item);
                this.adaptAdMode(bAd);
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
            }
            onClosed() {
                super.onClosed();
                vSignDialog.signDialg = null;
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag1", "spriteAdFlag2", "spriteAdFlag3", "spriteAdFlag4", "spriteAdFlag5"];
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
                mgrLayout.widgetBottomMC(this.spriteBtns);
            }
            onAnimationFinished() {
            }
            trySign(index) {
                index -= 1;
                let signDay = mgrSign.getSignDay();
                let signState = mgrSign.getState();
                let signIndex = mgrSign.getSignIndex();
                if (signIndex > index) {
                    mgrTip.showMsgTip("已签到");
                }
                else if (signIndex == index) {
                    if (signState == SignState.signed) {
                        mgrTip.showMsgTip("已签到");
                    }
                    else if (signState == SignState.waitGap) {
                        mgrTip.showMsgTip("冷却中, 请稍后");
                    }
                    else {
                        let result = mgrSign.sign();
                        if (result.bSuccessd) {
                            this.closeDialog();
                        }
                    }
                }
                else {
                    mgrTip.showMsgTip("需要依次签到哟~");
                }
            }
            fadeIn() {
                if (mgrSdk.getCopNumberValueByKey("b_disable_ui_enter_effect") == 1) {
                    return;
                }
                this.buttonClose.__node.alpha = 0;
                this.buttonGet.__node.alpha = 0;
                this.buttonGetAd.__node.alpha = 0;
                this.buttonGiveupAd.__node.alpha = 0;
                this.buttonCd.__node.alpha = 0;
                this.buttonTomorrow.__node.alpha = 0;
                let delay;
                for (let i = 1; i <= 5; i++) {
                    delay = i * 0.2;
                    cc.tween(this[`buttonItem${i}`].__node)
                        .toScale(0, 0)
                        .delay(delay)
                        .toScale(0.3, 1, cc.Ease.backOut)
                        .call(() => {
                        this.add3DEffectAtFront(i == 5 ? "117_ui_loop_outparticle_01" : "117_ui_loop_recparticle_02", i == 5 ? this.spriteSeventhDayReward : this[`buttonItem${i}`].__node, 0, 1.4);
                    })
                        .start();
                }
                cc.tween(this.buttonGet.__node).toAlpha(0, 0).delay(delay + 0.3).toAlpha(0.3, 1).start();
                cc.tween(this.buttonGetAd.__node).toAlpha(0, 0).delay(delay + 0.3).toAlpha(0.3, 1).start();
                cc.tween(this.buttonGiveupAd.__node).toAlpha(0, 0).delay(delay + 0.3).toAlpha(0.3, 1).start();
                cc.tween(this.buttonClose.__node).toAlpha(0, 0).delay(delay + 0.3).toAlpha(0.3, 1).start();
                cc.tween(this.buttonCd.__node).toAlpha(0, 0).delay(delay + 0.3).toAlpha(0.3, 1).start();
                cc.tween(this.buttonTomorrow.__node).toAlpha(0, 0).delay(delay + 0.3).toAlpha(0.3, 1).start();
            }
            adaptAdMode(bAd) {
                this.buttonGetAd.__node.visible = false;
                this.buttonAdAreaContent.__node.visible = false;
                this.buttonAdAreaScreen.__node.visible = false;
                this.buttonGiveupAd.__node.visible = false;
                if (!bAd) {
                    return;
                }
                this.buttonGetAd.__node.visible = true;
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                this.buttonGiveupAd.__node.visible = true;
                this.buttonClose.__node.visible = true;
                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vSignDialog_got_item);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
            }
            buildUi() {
                let signInfo = mgrCfg.get_from_sign_db(7)[3];
                Tools.loadImg(this.spriteSeventhDayReward, mgrPlayer.getIcon(signInfo.rewardItemId));
            }
            fillData() {
                let bAd = mgrSign.getState() != SignState.signed && !!mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSignDialog_got_item);
                for (let i = 1; i <= 5; i++) {
                    this["spriteAdFlag" + i].visible = ((mgrSdk.getCopNumberValueByKey("b_sign_all_item_ad_trigger") == 1 && bAd) ? true : false);
                }
                this.buttonCd.__node.visible = false;
                this.buttonGet.__node.visible = false;
                let signDay = mgrSign.getSignDay();
                let signIndex = mgrSign.getSignIndex();
                let signState = mgrSign.getState();
                let signInfo = mgrCfg.get_from_sign_db(signDay, signIndex);
                if (signState == SignState.canSign) {
                    this.labelGet.text = !!bAd ? "只领一个" : "签到";
                    this.labelRemainTime.text = ``;
                    this.buttonGet.__node.visible = true;
                }
                else if (signState == SignState.waitGap) {
                    this.labelGet.text = !!bAd ? "只领一个" : "签到";
                    let remainTime = mgrSign.getRemainTime();
                    this.labelRemainTime.text = `冷却中${Tools.formatTime(remainTime, "%M:%S")}`;
                    this.buttonCd.__node.visible = true;
                }
                else if (signState == SignState.signed) {
                    this.labelRemainTime.text = ``;
                    this.labelGet.text = "今日已签到";
                }
                if (mgrSign.getState() == SignState.signed) {
                    signDay += 1;
                    this.buttonGet.__node.visible = false;
                    this.buttonCd.__node.visible = false;
                    this.buttonGetAd.__node.visible = false;
                    this.buttonGiveupAd.__node.visible = false;
                    this.buttonTomorrow.__node.visible = true;
                    this.buttonClose.__node.visible = true;
                }
                else {
                    this.buttonTomorrow.__node.visible = false;
                }
                for (let i = 1; i <= 4; i++) {
                    let node = this[`buttonItem${i}`].__node;
                    let spritePartIcon = node.getChildByName(`iconPart`);
                    let spriteCoinIcon = node.getChildByName(`iconCoin`);
                    let labelCoinCount = node.getChildByName(`labelAmount`);
                    let spriteGeted = node.getChildByName(`tagGeted`);
                    let index = i - 1;
                    let data = mgrCfg.get_from_sign_db(signDay, index);
                    if (index < signIndex) {
                        spriteGeted.visible = true;
                    }
                    else if (index == signIndex) {
                        if (signState == SignState.signed) {
                            spriteGeted.visible = true;
                        }
                        else if (signState == SignState.waitGap) {
                            spriteGeted.visible = false;
                        }
                        else if (signState == SignState.canSign) {
                            spriteGeted.visible = false;
                        }
                        else if (signState == SignState.signOver) {
                            spriteGeted.visible = true;
                        }
                    }
                    else if (index > signIndex) {
                        spriteGeted.visible = false;
                    }
                    if (spriteGeted.visible) {
                        this.removeEffectAtFront(node);
                    }
                    let len = data.rewardItemId.length;
                    spritePartIcon.visible = false;
                    spriteCoinIcon.visible = false;
                    for (let i = 1; i <= len; i++) {
                        let itemId = data.rewardItemId[i - 1];
                        let amount = data.rewardAmount[i - 1];
                        let partData = mgrCfg.get_from_part_db(itemId);
                        if (!!partData) {
                            Tools.loadImg(spritePartIcon, mgrPlayer.getIcon(itemId));
                            spritePartIcon.visible = true;
                            labelCoinCount.text = `*1`;
                        }
                        else {
                            Tools.loadImg(spriteCoinIcon, mgrPlayer.getIcon(itemId));
                            labelCoinCount.text = `*${amount}`;
                            spriteCoinIcon.visible = true;
                        }
                    }
                    if (mgrSign.getState() == SignState.signed) {
                        spriteGeted.visible = false;
                    }
                }
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vSignDialog_got_item) {
                    this.buttonGetAd.__node.visible = false;
                    this.bCostSuccess = true;
                    let result = mgrSign.signTodayAll(true);
                    if (result.bSuccessd) {
                        this.closeDialog();
                    }
                }
            }
            onClickSignItem() {
                if (!this.buttonGetAd.__node.visible || mgrSdk.getCopNumberValueByKey("b_sign_all_item_ad_trigger") != 1) {
                    return;
                }
                this.onTouchButtonGetAd();
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonGet() {
                this.trySign(mgrSign.getSignIndex() + 1);
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonCd() {
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vSignDialog_got_item, null, true);
            }
            onTouchButtonGiveupAd() {
                this.onTouchButtonClose();
            }
            onTouchButtonTomorrow() {
                this.closeDialog();
            }
            onTouchButtonItem1() {
                this.onClickSignItem();
            }
            onTouchButtonItem2() {
                this.onClickSignItem();
            }
            onTouchButtonItem3() {
                this.onClickSignItem();
            }
            onTouchButtonItem4() {
                this.onClickSignItem();
            }
            onTouchButtonItem5() {
                this.onClickSignItem();
            }
        }

        class vStagePreResultDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vStagePreResultDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.fillData();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            onAnimationFinished() {
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            fillData() {
                this.buttonGetAd.__node.visible = true;
                this.labelAddScore.text = `+${Const.CHANGE_ROLE_ADD_SCORE}分`;
                this.buttonCheckAdModeClose.__node.visible = false;
                this.spriteAdCheckModeContainer.visible = false;
                this.buttonClose.__node.visible = true;
                if (mgrSdk.getCopNumberValueByKey("b_ad_check_mode") == 1) {
                    this.buttonCheckAdModeClose.__node.visible = true;
                    this.spriteAdCheckModeContainer.visible = true;
                    this.buttonClose.__node.visible = false;
                    if (!this.adCheckModeConfig) {
                        let config = mgrAd.randomGetAdCheckModeConfig("免费变身");
                        this.labelAdCheckModelTip.text = config.text;
                        this.spriteAdCheckModeCheckFlag.visible = !!config.bDefaultChecked;
                        this.adCheckModeConfig = config;
                    }
                }
                this.spriteAdFlag.visible = mgrSdk.getCopNumberValueByKey("b_ad_hide_ad_flag_icon") == 1 ? false : true;
                this.buttonAdAreaContent.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 1 ? true : false;
                this.buttonAdAreaScreen.__node.visible = mgrSdk.getCopNumberValueByKey("ad_view_area_click_mode") == 2 ? true : false;
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == this.context.adEventId) {
                    if (this.context.fOnAdResult) {
                        this.context.fOnAdResult(true);
                    }
                    this.closeDialog(true);
                }
            }
            onTouchButtonCheckAdModeClose() {
                if ((this.adCheckModeConfig.bCheckedTriggerAd && this.spriteAdCheckModeCheckFlag.visible) || (!this.spriteAdCheckModeCheckFlag.visible && !this.adCheckModeConfig.bCheckedTriggerAd)) {
                    this.onTouchButtonGetAd();
                }
                else {
                    this.onTouchButtonClose();
                }
            }
            onTouchButtonAdCheckModel() {
                this.spriteAdCheckModeCheckFlag.visible = !this.spriteAdCheckModeCheckFlag.visible;
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(this.context.adEventId, null, true);
            }
            onTouchButtonClose() {
                if (this.context.fOnAdResult) {
                    this.context.fOnAdResult(false);
                }
                this.closeDialog(true);
            }
            onTouchButtonAdAreaScreen() {
                this.onTouchButtonGetAd();
            }
            onTouchButtonAdAreaContent() {
                this.onTouchButtonGetAd();
            }
        }

        class FSMObject {
            constructor() {
                this.currStateInTimer = 0;
                this.curState = -1;
                this.nextState = this.curState;
                this.lastState = this.curState;
                this.stateMap = {};
            }
            reset() {
                this.curState = -1;
                this.nextState = this.curState;
                this.lastState = this.curState;
                this.stateMap = {};
            }
            registerState(state, enter, execute, leave) {
                if (enter || execute || leave) {
                    this.stateMap[state] = {
                        enter: enter,
                        execute: execute,
                        leave: leave,
                    };
                }
            }
            registerStateEx(state, enter, execute, leave, caller) {
                let fenter = caller[enter].bind(caller);
                let fexecute = caller[execute].bind(caller);
                let fleave = caller[leave].bind(caller);
                this.stateMap[state] = {
                    enter: fenter,
                    execute: fexecute,
                    leave: fleave,
                };
            }
            setNextState(state) {
                this.nextState = state;
            }
            update(deltaTime = 0) {
                let curStateInvokeInfo = this.stateMap[this.curState];
                let nextStateInvokeInfo = this.stateMap[this.nextState];
                if (this.nextState != this.curState) {
                    this.lastState = this.curState;
                    this.curState = this.nextState;
                    if (curStateInvokeInfo) {
                        if (curStateInvokeInfo.leave)
                            curStateInvokeInfo.leave();
                    }
                    if (nextStateInvokeInfo) {
                        this.currStateInTimer = Tools.time();
                        if (nextStateInvokeInfo.enter)
                            nextStateInvokeInfo.enter();
                    }
                }
                if (nextStateInvokeInfo && nextStateInvokeInfo.execute)
                    nextStateInvokeInfo.execute(deltaTime);
            }
            getCurState() {
                return this.curState;
            }
            clear() {
                this.curState = -1;
                this.lastState = -1;
                this.nextState = -1;
            }
            getNextState() {
                return this.nextState;
            }
            getLastState() {
                return this.lastState;
            }
            getCurrStateRanTime() {
                if (!this.currStateInTimer) {
                    return 0;
                }
                return (Tools.time() - this.currStateInTimer);
            }
            startUpdate(caller, extralLoopFunc) {
                if (!caller || !!this.updateTimer) {
                    return;
                }
                let timerLastUpdateTime = Tools.gameExecuteTime();
                this.updateTimer = Timer.callLoop(0.016, () => {
                    let tmpTime = Tools.gameExecuteTime();
                    let deltaTime = tmpTime - timerLastUpdateTime;
                    timerLastUpdateTime = tmpTime;
                    this.update(deltaTime);
                    if (extralLoopFunc) {
                        extralLoopFunc(deltaTime);
                    }
                }, caller);
                this.update(0);
            }
            stopUpdate() {
                if (this.updateTimer) {
                    this.updateTimer.stop();
                    this.updateTimer = null;
                }
            }
        }

        var STORY_STATE;
        (function (STORY_STATE) {
            STORY_STATE[STORY_STATE["ready"] = 1] = "ready";
            STORY_STATE[STORY_STATE["playing"] = 2] = "playing";
            STORY_STATE[STORY_STATE["ending"] = 3] = "ending";
            STORY_STATE[STORY_STATE["clear"] = 4] = "clear";
            STORY_STATE[STORY_STATE["clicking"] = 5] = "clicking";
        })(STORY_STATE || (STORY_STATE = {}));
        var showType;
        (function (showType) {
            showType[showType["bg"] = 1] = "bg";
            showType[showType["left"] = 2] = "left";
            showType[showType["right"] = 3] = "right";
            showType[showType["img"] = 4] = "img";
            showType[showType["text"] = 5] = "text";
        })(showType || (showType = {}));
        var easingType;
        (function (easingType) {
            easingType[easingType["fadeIn"] = 1] = "fadeIn";
            easingType[easingType["fadeOut"] = 2] = "fadeOut";
            easingType[easingType["oneByOne"] = 3] = "oneByOne";
        })(easingType || (easingType = {}));
        class vStoryDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vStoryDialog";
                this.exportNodeNames = [];
                this.curStep = 0;
            }
            onOpened() {
                super.onOpened();
                this.imageBgLeft["_originX"] = this.imageBgLeft.x;
                this.imageBgRight["_originX"] = this.imageBgRight.x;
                this.imageRoleLeft["_originPos"] = new Laya.Vector2(this.imageRoleLeft.x, this.imageRoleLeft.y);
                this.imageRoleRight["_originPos"] = new Laya.Vector2(this.imageRoleRight.x, this.imageRoleRight.y);
                this.stManager = new FSMObject();
                this.stManager.registerState(STORY_STATE.ready, this.onReadyIn.bind(this), this.onReadyExe.bind(this), this.onReadyOut.bind(this));
                this.stManager.registerState(STORY_STATE.playing, this.onPlayingIn.bind(this), this.onPlayingExe.bind(this), this.onPlayingOut.bind(this));
                this.stManager.registerState(STORY_STATE.ending, this.onEndingIn.bind(this), this.onEndingExe.bind(this), this.onEndingOut.bind(this));
                this.stManager.registerState(STORY_STATE.clear, this.onClearIn.bind(this), this.onClearExe.bind(this), this.onClearOut.bind(this));
                this.stManager.registerState(STORY_STATE.clicking, this.onClickingIn.bind(this), this.onClickingExe.bind(this), this.onClickingOut.bind(this));
                this.stManager.setNextState(STORY_STATE.ready);
                Timer.callLoop(0.016, () => {
                    if (!this.stManager)
                        return;
                    this.stManager.update();
                }, this);
            }
            onClosed() {
                super.onClosed();
            }
            registerGuideNode() {
                mgrGuide.registerGuideNode("vStoryDialog.buttonSkip", this.imageRoleLeft.alpha > 0.5 ? this.buttonSkipLeft.__node : this.buttonSkipRight.__node);
                if (!mgrGuide.isFinished(800)) {
                    mgrGuide.startGuide(800);
                }
            }
            isShadowClose() {
                return this.stManager && this.stManager.getCurState() == STORY_STATE.clear;
            }
            showLeftTalk(storyData) {
                this.labelContentLeft.text = storyData.text;
                if (storyData.bSelf) {
                    let roleData = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                    this.labelNameLeft.text = roleData.name;
                }
                else {
                    this.labelNameLeft.text = storyData.name;
                }
                if (storyData.sprite && storyData.sprite != "") {
                    this.imageRoleLeft.scale(Math.abs(storyData.scaleSprite || 1) * (!!storyData.bFlipX ? -1 : 1), storyData.scaleSprite || 1);
                    Tools.loadImg(this.imageRoleLeft, storyData.sprite, true);
                    let offsetPos = storyData.offsetPos || [0, 0];
                    this.imageRoleLeft.pos(this.imageRoleLeft["_originPos"].x + offsetPos[0], this.imageRoleLeft["_originPos"].y + offsetPos[1]);
                }
                else {
                    this.imageRoleLeft.scale(0, 0);
                }
                cc.tween(this.imageRoleLeft, true).toAlpha(0.3, 1).start();
                cc.tween(this.imageBgLeft, true).toPos(0.3, this.imageBgLeft["_originX"], this.imageBgLeft.y).start();
            }
            hideLeftTalk(bImmi, callback) {
                let dur = !bImmi ? 0.3 : 0;
                cc.tween(this.imageRoleLeft, true).toAlpha(dur, 0).call(() => {
                    if (callback) {
                        callback();
                    }
                }).start();
                cc.tween(this.imageBgLeft, true).toPos(dur, this.imageBgLeft["_originX"] - mgrDirector.width, this.imageBgLeft.y).call(() => {
                }).start();
            }
            showRightTalk(storyData) {
                this.labelContentRight.text = storyData.text;
                if (storyData.bSelf && !storyData.name) {
                    let roleData = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                    this.labelNameRight.text = roleData.name;
                }
                else {
                    this.labelNameRight.text = storyData.name;
                }
                if (storyData.sprite && storyData.sprite != "") {
                    this.imageRoleRight.scale(Math.abs(storyData.scaleSprite || 1) * (!!storyData.bFlipX ? -1 : 1), storyData.scaleSprite || 1);
                    Tools.loadImg(this.imageRoleRight, storyData.sprite, true);
                    let offsetPos = storyData.offsetPos || [0, 0];
                    this.imageRoleRight.pos(this.imageRoleRight["_originPos"].x + offsetPos[0], this.imageRoleRight["_originPos"].y + offsetPos[1]);
                }
                else {
                    this.imageRoleRight.scale(0, 0);
                }
                cc.tween(this.imageRoleRight, true).toAlpha(0.3, 1).start();
                cc.tween(this.imageBgRight, true).toPos(0.3, this.imageBgRight["_originX"], this.imageBgRight.y).start();
            }
            hideRightTalk(bImmi, callback) {
                let dur = !bImmi ? 0.3 : 0;
                cc.tween(this.imageRoleRight, true).toAlpha(dur, 0).call(() => {
                    if (callback) {
                        callback();
                    }
                }).start();
                cc.tween(this.imageBgRight, true).toPos(dur, this.imageBgRight["_originX"] + mgrDirector.width, this.imageBgRight.y).start();
            }
            onReadyIn() {
                this.currStoryData = mgrCfg.get("story_db", this.context.storyId, this.curStep);
                if (!this.currStoryData) {
                    this.stManager.setNextState(STORY_STATE.clear);
                    return;
                }
                mgrSound.play(this.currStoryData.soundId);
                if (this.currStoryData.type == showType.bg) {
                    Tools.loadImg(this.imageBg, this.currStoryData.sprite);
                }
                else if (this.currStoryData.type == showType.left) {
                    this.hideRightTalk(true);
                    this.showLeftTalk(this.currStoryData);
                }
                else {
                    this.hideLeftTalk(true);
                    this.showRightTalk(this.currStoryData);
                }
                this.stManager.setNextState(STORY_STATE.playing);
            }
            onReadyExe() { }
            onReadyOut() { }
            onPlayingIn() {
                this.registerGuideNode();
                if (mgrGuide.isAllForceGuideFinished()) {
                    let stepDuration = this.currStoryData.stepDuration;
                    if (this.currStoryData.type == showType.right || this.currStoryData.type == showType.left) {
                        stepDuration = stepDuration;
                    }
                    this._playingTimer = Timer.callLater(stepDuration, () => {
                        this.stManager.setNextState(STORY_STATE.ending);
                    }, this);
                }
                this.buttonBackground.__node.visible = true;
            }
            onPlayingExe() { }
            onPlayingOut() {
                if (this._playingTimer) {
                    this._playingTimer.stop();
                    this._playingTimer = null;
                }
            }
            onEndingIn() {
                this.curStep++;
                this.currStoryData = mgrCfg.get("story_db", this.context.storyId, this.curStep);
                if (!this.currStoryData) {
                    this.stManager.setNextState(STORY_STATE.clear);
                }
                else {
                    this.stManager.setNextState(STORY_STATE.ready);
                }
            }
            onEndingExe() { }
            onEndingOut() { }
            onClearIn() {
                this.shadowAlpha = 0;
                this.hideLeftTalk(true);
                this.hideRightTalk(true);
                this.buttonBackground.__node.visible = false;
                this.onStoreCompleted();
            }
            onClearExe() { }
            onClearOut() { }
            onClickingIn() { }
            onClickingExe() { }
            onClickingOut() { }
            onStoreCompleted() {
                this.sendMsg("MSG_GUIDE_EVENT", { id: "vStoryDialog.clickButtonSkip" });
                this.context.finishCallback && this.context.finishCallback();
                this.closeDialog(true);
            }
            tryGoNext() {
                if (this.stManager.getCurState() == STORY_STATE.playing || this.stManager.getCurState() == STORY_STATE.clicking) {
                    this.hideLeftTalk(true);
                    this.hideRightTalk(true, () => {
                        this.stManager.setNextState(STORY_STATE.ending);
                    });
                }
            }
            onTouchButtonSkipRight() {
                this.onStoreCompleted();
            }
            onTouchButtonNextRight() {
                this.tryGoNext();
            }
            onTouchButtonSkipLeft() {
                this.onStoreCompleted();
            }
            onTouchButtonNextLeft() {
                this.tryGoNext();
            }
            onTouchButtonBackground() {
                this.tryGoNext();
            }
        }

        class vSuitShowingListItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vSuitShowingListItem";
                this.size(114, 115);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let icon = mgrPlayer.getIcon(this.data.id);
                Tools.loadImg(this.spritePart, icon);
                this.spriteHad.visible = mgrPlayer.getItemAmount(this.data.id) > 0;
            }
            onTouchButtonBg() {
                mgrDirector.openDialog("vPartDetailDialog", { itemId: this.data.id });
            }
        }

        const CAMERA_PRARAM_INIT = {
            fov: 30,
            position: new Laya.Vector3(0, 0.88, 5.24),
            rotation: new Laya.Vector3(-5),
            lerpValue: 0.1,
        };
        class vSuitShowingDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vSuitShowingDialog";
                this.avatarPresetPosition = new Laya.Vector3;
                this.index = 0;
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_CLOSE_SUIT_SHOWING: this.closeDialog.bind(this),
                });
                mgrSound.play(3);
                this.buildUi();
                this.fillData();
                this.widget();
                this.playUiAction();
                Laya.stage.on(Laya.Event.KEY_DOWN, this, this.onSystemKeyDown);
            }
            onClosed() {
                super.onClosed();
            }
            getPreLoadModelIds() {
                let preloadModelIdArr = [
                    "eff_ui_baoxiang_glow",
                ];
                return preloadModelIdArr;
            }
            getPreLoadAnimationIds() {
                let arr = [];
                mgrCfg.forDb_from_suit_db((k, v) => {
                    if (!!v.showAnimationId) {
                        arr.push(v.showAnimationId);
                    }
                    if (!!v.showFaceAnimationId) {
                        arr.push(v.showFaceAnimationId);
                    }
                });
                return [];
            }
            onSystemKeyDown(e) {
                let keyCode = e.keyCode;
                switch (keyCode) {
                    case Laya.Keyboard.E:
                        let saveName = `vSuitShowingDialog-shot-${this.suitId}`;
                        Tools.cameraForSaveImg(this.cameraBack, saveName);
                        break;
                    default:
                        break;
                }
            }
            buildUi() {
                this.add3DEffectAtFront("eff_ui_tzzs_loop", this.boxContainerMC, 0, 1);
                this.avatar = new RoleAvatar({ roleId: mgrRole.showingRoleId, bDisableFaceTimeScale: true });
                this.add3DEffectAtBack(this.avatar, 0);
                let cf = this.cameraBack.getComponent(CameraFollow);
                cf.lookMode = E_CAMERA_MODE.fixMode;
                cf.fov = CAMERA_PRARAM_INIT.fov;
                cf.position = CAMERA_PRARAM_INIT.position;
                cf.endRotation = CAMERA_PRARAM_INIT.rotation;
                cf.lerpValue = 1;
                cf.onLateUpdate();
                this.progressBar.barName = this.progressBar.__node.name;
                this.progressBar.style = ULPROGRESSBAR_STYLE.hor;
                this.reuseListLine1 = new ReuseList(5, 0, 4);
                this.reuseListLine1.size(this.boxList.width, this.boxList.height / 2);
                this.boxList.addChild(this.reuseListLine1);
                this.reuseListLine1.setItemClass(vSuitShowingListItem);
                this.reuseListLine1.setSpaceX(0);
                this.reuseListLine1.setSpaceY(0);
                this.reuseListLine2 = new ReuseList(5, 0, 4);
                this.reuseListLine2.size(this.boxList.width, this.boxList.height / 2);
                this.boxList.addChild(this.reuseListLine2);
                this.reuseListLine2.pos(0, this.boxList.height / 2);
                this.reuseListLine2.setItemClass(vSuitShowingListItem);
                this.reuseListLine2.setSpaceX(0);
                this.reuseListLine2.setSpaceY(0);
            }
            fillData() {
                let categoryId = this.context.categoryId;
                this.categorySuits = mgrPart.getSuitDatasByCategory(categoryId);
                let categorySuits = this.categorySuits;
                for (let i = 0; i < categorySuits.length; i++) {
                    let suitData = categorySuits[i];
                    if (mgrPart.canObtainSuitReward(suitData.id)) {
                        this.index = i;
                        break;
                    }
                }
                this.refreshSuit(this.index);
            }
            playUiAction() {
                if (mgrSdk.getCopNumberValueByKey("b_disable_ui_enter_effect") == 1) {
                    return;
                }
                mgrEffect.playComebackAction([this.spriteBottom], 0, 600, 0.5, 0.5, () => {
                }, cc.Ease.circOut);
                mgrEffect.playComebackAction([this.spriteTitle], -500, 0, 1, 0.5, () => { });
                this.buttonBack.__node.scale(0, 0);
                cc.tween(this.buttonBack.__node, true)
                    .delay(2)
                    .toScale(0.5, 1, cc.Ease.backOut).call(() => {
                }).start();
                this.buttonToLeft.__node[`oldPosX`] = this.buttonToLeft.__node.x;
                this.buttonToRight.__node[`oldPosX`] = this.buttonToRight.__node.x;
                this.buttonToLeft.__node.x = 288;
                this.buttonToRight.__node.x = 288;
                this.buttonToLeft.__node.alpha = 0;
                this.buttonToRight.__node.alpha = 0;
                cc.tween(this.buttonToLeft.__node)
                    .delay(1.5)
                    .to(0.5, { x: this.buttonToLeft.__node[`oldPosX`], alpha: 1 }, cc.Ease.backOut)
                    .start();
                cc.tween(this.buttonToRight.__node)
                    .delay(1.5)
                    .to(0.5, { x: this.buttonToRight.__node[`oldPosX`], alpha: 1 }, cc.Ease.backOut)
                    .start();
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    this.lastTouchBgPos = e.pos;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            widget() {
                mgrLayout.widgetLeftMC(this.boxLeft);
                mgrLayout.widgetLeftMC(this.buttonToLeft.__node);
                mgrLayout.widgetRightMC(this.buttonToRight.__node);
                mgrLayout.widgetLeftTopMC(this.spriteTitle);
            }
            palyOutUi() {
            }
            palyInUi() {
            }
            refreshSuit(index) {
                this.suitNum = this.categorySuits.length;
                let suitData = this.categorySuits[index];
                this.suitId = suitData.id;
                let partIds = suitData.partIds;
                this.partIds = partIds;
                let collectionRewards = suitData.collectionRewards;
                let itemId = collectionRewards[0][0];
                let amount = collectionRewards[0][1];
                let icon = mgrPlayer.getIcon(itemId);
                Tools.loadImg(this.spriteReward, icon);
                this.labelAmount.text = `x${amount}`;
                if (this.suitNum <= 1) {
                    this.buttonToLeft.__node.visible = false;
                    this.buttonToRight.__node.visible = false;
                }
                this.labelSuitName.text = suitData.name;
                this.avatar.timeScale = 0.0000000001;
                this.avatar.changeRoleId(suitData.roleId);
                this.avatar.setIdleId(suitData.showAnimationId || ANIMATION_ID.idle, suitData.showFaceAnimationId || ANIMATION_ID.face.idle);
                this.avatar.fillByPartIds(suitData.onlyDressPartIds || suitData.partIds, true);
                this.avatar.registerLoadEndCallback(() => {
                    if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                        return;
                    }
                    this.avatar.playAnimation(suitData.showAnimationId || ANIMATION_ID.idle, 0, () => {
                        this.avatar.transform.rotationEuler = new Laya.Vector3(0, 0, 0);
                        this.avatar.transform.position = this.avatarPresetPosition;
                    }, null, true, true);
                    this.avatar.playRoleFaceAnimation(suitData.showFaceAnimationId || ANIMATION_ID.face.idle, 0, null, null, true, true);
                    if (!this.boxContainerMC["_registerTouched"]) {
                        Tools.registerTouchHander(this.boxContainerMC, this.onTouchSpriteBg.bind(this));
                        this.boxContainerMC["_registerTouched"] = true;
                    }
                });
                this.spriteBg.zOrder = -100;
                this.palyOutUi();
                this.palyInUi();
                this.progressBar.progress = 0;
                let unlockedPartNum = 0;
                let arrLine1 = [];
                let arrLine2 = [];
                partIds.forEach(v => {
                    if (mgrPlayer.getItemAmount(v) > 0) {
                        unlockedPartNum++;
                    }
                    if (arrLine1.length < 5) {
                        arrLine1.push({ id: v });
                    }
                    else {
                        arrLine2.push({ id: v });
                    }
                });
                this.labelProgress.text = `${unlockedPartNum}/${partIds.length}`;
                this.progressBar.progress = unlockedPartNum / partIds.length;
                cc.clearTween(this.buttonReward.__node);
                this.removeEffectAtFront(this.spriteEffect1);
                if (unlockedPartNum >= partIds.length) {
                    cc.tween(this.buttonReward.__node).repeatForever(cc.tween().to(0.8, { scaleX: 1.1, scaleY: 1.1 }).to(0.8, { scaleX: 0.9, scaleY: 0.9 })).start();
                    this.add3DEffectAtFront("eff_ui_baoxiang_glow", this.spriteEffect1, 0, 2);
                }
                this.buttonReward.__node.visible = !mgrPart.isSuitRewardGeted(this.suitId);
                this.spriteEffect1.visible = !mgrPart.isSuitRewardGeted(this.suitId);
                this.reuseListLine1.setDatas(arrLine1);
                this.reuseListLine2.setDatas(arrLine2);
                this.reuseListLine1.pos((this.reuseListLine1.width - (114 * arrLine1.length)) / 2, arrLine2.length == 0 ? this.boxList.height / 4 : 0);
                this.reuseListLine2.pos((this.reuseListLine2.width - (114 * arrLine2.length)) / 2, this.boxList.height / 2);
            }
            onTouchButtonToLeft() {
                this.index--;
                if (this.index < 0) {
                    this.index = this.suitNum - 1;
                }
                if (this.index >= this.suitNum) {
                    this.index = 0;
                }
                this.refreshSuit(this.index);
            }
            onTouchButtonToRight() {
                this.index++;
                if (this.index < 0) {
                    this.index = this.suitNum - 1;
                }
                if (this.index >= this.suitNum) {
                    this.index = 0;
                }
                this.refreshSuit(this.index);
            }
            onTouchButtonBack() {
                this.closeDialog();
            }
            onTouchButtonReward() {
                if (mgrPart.isSuitRewardGeted(this.suitId)) {
                    mgrTip.showMsgTip("已领取");
                    return;
                }
                if (!mgrPart.canObtainSuitReward(this.suitId)) {
                    mgrTip.showMsgTip("还没有收集完毕, 点击卡片查看详情");
                    return;
                }
                mgrPart.obtainSuitReward(this.suitId);
                this.refreshSuit(this.index);
            }
            onTouchButtonGo() {
            }
        }

        class vSurpriseRewardDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vSurpriseRewardDialog";
            }
            onOpened() {
                super.onOpened();
                this.nativeBanner = mgrActivingBanner.activingAlertBanner(6, this);
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.buildUi();
                this.fillData();
                if (!this.partData) {
                    this.closeDialog(true);
                }
            }
            onClosed() {
                super.onClosed();
                if (this.nativeBanner) {
                    this.nativeBanner.activingBannerClose();
                    this.nativeBanner = null;
                }
            }
            buildUi() {
                let partId = this.context.partId;
                let partData = mgrCfg.get_from_part_db(partId) || mgrCfg.get_from_amuse_card_style_db(partId);
                if (!partData) {
                    return;
                }
                this.partData = partData;
                this.labelPartName.text = partData.name;
                this.boxTwoTablets.visible = partData.unlockItemAmount == 2;
                this.boxFourTablets.visible = partData.unlockItemAmount == 4;
                this.boxSixTablets.visible = partData.unlockItemAmount == 6;
                if (partData.unlockItemAmount == 2) {
                    Tools.loadImg(this.spritePartIcon3, partData.unlockShowIcon);
                    Tools.loadImg(this.spritePartIconGray3, partData.unlockShowIcon);
                    this.spritePartIconGray3.mask = this.spriteFragIconMask3;
                    mgrEffect.filterGray(this.spritePartIconGray3, 0.7);
                }
                else if (partData.unlockItemAmount == 4) {
                    Tools.loadImg(this.spritePartIcon, partData.unlockShowIcon);
                    Tools.loadImg(this.spritePartIconGray, partData.unlockShowIcon);
                    this.spritePartIconGray.mask = this.spriteFragIconMask;
                    mgrEffect.filterGray(this.spritePartIconGray, 0.7);
                }
                else if (partData.unlockItemAmount == 6) {
                    Tools.loadImg(this.spritePartIcon2, partData.unlockShowIcon);
                    Tools.loadImg(this.spritePartIconGray2, partData.unlockShowIcon);
                    this.spritePartIconGray2.mask = this.spriteFragIconMask2;
                    mgrEffect.filterGray(this.spritePartIconGray2, 0.7);
                }
                this.refreshFragUi();
            }
            fillData() {
                if (!this.partData) {
                    return;
                }
                let adaptBtnFunc = () => {
                    this.buttonAd.__node.visible = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment);
                    if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment)) {
                        let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment);
                        adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                    else {
                        this.buttonAd.__node.visible = false;
                    }
                };
                if (this.context.bVip) {
                    this.labelAd.text = "额外碎片";
                    this.boxButtons.scale(0, 0, true);
                    Timer.callLater(0.5, () => {
                        this.boxButtons.scale(1, 1, true);
                        this.gotFragment();
                        adaptBtnFunc();
                    }, this);
                }
                else {
                    this.labelAd.text = "免费碎片";
                    adaptBtnFunc();
                }
            }
            gotFragment(callback) {
                this.boxButtons.visible = false;
                let partId = this.context.partId;
                let partData = mgrCfg.get_from_part_db(partId) || mgrCfg.get_from_amuse_card_style_db(partId);
                mgrPlayer.addItemAmount(partData.unlockItemId, 1, "");
                mgrTip.addGotItemTip(partData.unlockItemId, 1, null, {
                    fOnClose: () => {
                        let img = new Laya.Image(mgrPlayer.getIcon(partData.unlockItemId));
                        img.size(100, 100);
                        img.anchorX = 0.5;
                        img.anchorY = 0.5;
                        let parent = this.boxEffect;
                        parent.addChild(img);
                        let endNode;
                        endNode = this.boxEnd;
                        this.add3DEffectAtFront(MODEL_ID.effect.eff_ui_jiesuan_tuowei, img);
                        let wPos = this.boxEffect.localToGlobal(new Laya.Point(this.boxEffect.width / 2, this.boxEffect.height / 2));
                        let pos = parent.globalToLocal(wPos, true);
                        img.pos(pos.x, pos.y);
                        img.zOrder = 1000;
                        let deltaX = Math.random() > 0.5 ? Tools.random(200, 500) : Tools.random(-200, -500);
                        let pos2 = new Laya.Vector2(pos.x + deltaX, pos.y);
                        let endWPos = endNode.localToGlobal(new Laya.Point(endNode.width / 2, endNode.height / 2));
                        endWPos = parent.globalToLocal(endWPos);
                        mgrSound.play(117);
                        CustomTween.bezierCurveMotion(pos, pos2, endWPos, img, 800)
                            .delayTime(100)
                            .callback(() => {
                            this.add3DEffectAtFront('116_ui_once_bao_08', this.boxEnd);
                            this.refreshFragUi();
                            this.boxButtons.visible = true;
                            let curFragmentNum = mgrPlayer.getItemAmount(partData.unlockItemId);
                            if (curFragmentNum >= partData.unlockItemAmount) {
                                mgrPlayer.addItemAmount(partId, 1, "惊喜奖励部件");
                                mgrPlayer._setItemAmount(partData.unlockItemId, 0);
                                mgrTip.addGotItemTip(partId, 1, null, {
                                    fOnClose: this.closeDialog.bind(this)
                                });
                            }
                            else {
                                if (callback) {
                                    callback();
                                }
                            }
                            img.destroy();
                        })
                            .start(1);
                    }
                });
            }
            refreshFragUi() {
                let partId = this.context.partId;
                let partData = mgrCfg.get_from_part_db(partId) || mgrCfg.get_from_amuse_card_style_db(partId);
                let curFragmentNum = mgrPlayer.getItemAmount(partData.unlockItemId);
                this.labelProgress.text = `${curFragmentNum}/${partData.unlockItemAmount}`;
                let needAmount = Math.max(0, partData.unlockItemAmount - curFragmentNum);
                this.labelGotNumAgain.text = `${needAmount}`;
                this.spriteGotTip.visible = needAmount > 0 ? true : false;
                if (this.boxTwoTablets.visible) {
                    this.spritePartIconGray3.addChild(this.spriteFragIconMask3);
                    this.spriteFragIconMask3.removeSelf();
                    for (let i = 0; i < 2; i++) {
                        let spriteFragmentMask = this.spriteFragIconMask3.getChildAt(i);
                        spriteFragmentMask.visible = curFragmentNum <= i;
                    }
                    if (curFragmentNum >= partData.unlockItemAmount) {
                        this.spritePartIconGray3.visible = false;
                    }
                }
                else if (this.boxFourTablets.visible) {
                    this.spritePartIconGray.addChild(this.spriteFragIconMask);
                    this.spriteFragIconMask.removeSelf();
                    for (let i = 0; i < 4; i++) {
                        let spriteFragmentMask = this.spriteFragIconMask.getChildAt(i);
                        spriteFragmentMask.visible = curFragmentNum <= i;
                    }
                    if (curFragmentNum >= partData.unlockItemAmount) {
                        this.spritePartIconGray.visible = false;
                    }
                }
                else if (this.boxSixTablets.visible) {
                    this.spritePartIconGray2.addChild(this.spriteFragIconMask2);
                    this.spriteFragIconMask2.removeSelf();
                    for (let i = 0; i < 6; i++) {
                        let spriteFragmentMask = this.spriteFragIconMask2.getChildAt(i);
                        spriteFragmentMask.visible = curFragmentNum <= i;
                    }
                    if (curFragmentNum >= partData.unlockItemAmount) {
                        this.spritePartIconGray2.visible = false;
                    }
                }
            }
            onTouchButtonGiveUp() {
                this.closeDialog();
            }
            onTouchButtonAd() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment, null, true);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment) {
                    this.gotFragment(() => {
                        this.boxButtons.visible = false;
                        Timer.callLater(1, () => {
                            this.closeDialog();
                        });
                    });
                }
            }
        }

        const PHOTO_WIDTH = 158;
        const PHOTO_HEIGHT = 210;
        class vTakePhotoDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vTakePhotoDialog";
                this.exportNodeNames = [];
                this.photos = [];
            }
            onOpened() {
                super.onOpened();
                this.init();
                mgrSound.play(215);
                this.sendMsg(`MSG_MERGE_SCENE_BACK_BUTTON_OUT`);
            }
            onClosed() {
                super.onClosed();
            }
            isShowShadow() {
                return false;
            }
            init() {
                this.avatar = this.context.avatar;
                this.cameraFollow = this.context.cameraFollow;
                this.camera = this.cameraFollow.__node;
                this.spriteSelectTip.alpha = 0;
                this.buttonSure.__node.visible = false;
                this.spriteSelected1.visible = false;
                this.spriteSelected2.visible = false;
                this.spriteSelected3.visible = false;
                this.spritePhoto1.alpha = 0.5;
                this.spritePhoto2.alpha = 0.5;
                this.spritePhoto3.alpha = 0.5;
                this.avatar.playAnimation(ANIMATION_ID.idle);
                this.buttonCamera.fOnClick = this.onTouchButtonCamera.bind(this);
                this.buttonSure.fOnClick = this.onTouchButtonSure.bind(this);
                this.buttonCamera.bPlaySoundEffect = false;
            }
            onTouchButtonCamera() {
                mgrSound.play(120);
                let index = this.photos.length;
                let originWidth = PHOTO_WIDTH * 3;
                let originHeight = PHOTO_HEIGHT * 3;
                let showWidth = originWidth * 2;
                let showHeight = originHeight * 2;
                Tools.takeAPhoto(showWidth, showHeight, this.camera, (tex2d) => {
                    Tools.takeAPhoto(originWidth, originWidth, this.camera, (tex2dCache) => {
                        this.photos.push({
                            time: Tools.time(),
                            tex2d: tex2dCache,
                        });
                        let image = new Laya.Image();
                        image.size(showWidth, showHeight);
                        image.anchorX = 0.5;
                        image.anchorY = 0.5;
                        this.addChild(image);
                        image.graphics.clear();
                        image.graphics.drawTexture(new Laya.Texture(tex2d), 0, 0, showWidth, showHeight);
                        mgrLayout.widget(0.5, 0.5, image, { x: 0.5, y: 0.5 });
                        let endPos = this[`spritePhoto${index + 1}`].localToGlobal(new Laya.Point(PHOTO_WIDTH / 2, PHOTO_HEIGHT / 2));
                        let localEndPos = this.globalToLocal(endPos);
                        CustomTween.to(image, { x: localEndPos.x, y: localEndPos.y, scaleX: 1 / 6, scaleY: 1 / 6 }, 500)
                            .callback(() => {
                            image.destroy();
                            this[`spritePhoto${index + 1}`].graphics.drawTexture(new Laya.Texture(tex2d), 0, 0, PHOTO_WIDTH, PHOTO_HEIGHT);
                            this[`spritePhoto${index + 1}`].alpha = 1;
                            if (this.photos.length >= 3) {
                                CustomTween.to(this.spriteSelectTip, { alpha: 1 }, 300).start(1);
                                Tools.registerTouchHander(this.spritePhotoBg1, (e) => {
                                    if (!e.isClick)
                                        return;
                                    this.selectPhoto(1);
                                });
                                Tools.registerTouchHander(this.spritePhotoBg2, (e) => {
                                    if (!e.isClick)
                                        return;
                                    this.selectPhoto(2);
                                });
                                Tools.registerTouchHander(this.spritePhotoBg3, (e) => {
                                    if (!e.isClick)
                                        return;
                                    this.selectPhoto(3);
                                });
                                this.context.oldCameraPosition = this.cameraFollow.position.clone();
                                this.cameraFollow.position = new Laya.Vector3(-3.35, 1.29, 0.44);
                            }
                        })
                            .start(1);
                        if (this.photos.length >= 3) {
                            this.buttonCamera.__node.visible = false;
                        }
                        ;
                    });
                });
            }
            selectPhoto(index) {
                this.curSelectPhotoIndex = index;
                this.spriteSelected1.visible = index == 1;
                this.spriteSelected2.visible = index == 2;
                this.spriteSelected3.visible = index == 3;
                this.buttonSure.__node.visible = true;
                this.buttonSure.__node.scale(0.5, 0.5);
                CustomTween.to(this.buttonSure.__node, { scaleX: 1, scaleY: 1 }, 300, Laya.Ease.backOut).start(1);
            }
            onTouchButtonSure() {
                mgrTip.showMsgTip("TODO");
            }
            playPhotoFly(index) {
                let texture = this.photos[index - 1].tex2d;
                let node = this[`spritePhotoBg${index}`];
                let startPos = this.nodeResource.localToGlobal(new Laya.Point(node.x, node.y));
                this.sendMsg(`MSG_GET_ROOM_PHOTO_FLY`, {
                    callback: (endPos) => {
                        let centerPos = new Laya.Point((startPos.x + endPos.x) / 2, (startPos.y + endPos.y) / 2 - 300);
                        let image = new Laya.Image;
                        image.size(PHOTO_WIDTH, PHOTO_HEIGHT);
                        image.anchorX = 0.5;
                        image.anchorY = 0.5;
                        this.addChild(image);
                        image.x = 10000;
                        image.graphics.drawTexture(new Laya.Texture(texture), 0, 0, PHOTO_WIDTH, PHOTO_HEIGHT);
                        CustomTween.bezierCurveMotion(startPos, centerPos, endPos, image, 300, true)
                            .callback(() => {
                            image.destroy();
                            this.sendMsg(`MSG_REFRESH_ROOM_PHOTO`);
                            this.sendMsg(`MSG_MERGE_SCENE_BACK_BUTTON_IN`);
                            this.closeDialog();
                        })
                            .start(1);
                    }
                });
            }
        }

        class GameRemoteRouter {
            constructor(seasion) {
                this.__seasion = null;
                this.__registedRouter = null;
                this.seasion = seasion;
                if (!this.seasion) {
                    console.error("没有设置seasion");
                    return;
                }
                this.seasion.on('data', this, (data) => {
                    this.__router(data);
                });
            }
            get seasion() {
                return this.__seasion;
            }
            set seasion(value) {
                this.__seasion = value;
            }
            sendMsgToServer(reqData) {
                this.seasion.write(reqData);
            }
            registerRouter(route, callback) {
                if (!!route && !!callback) {
                    this.__registedRouter[route] = callback;
                }
            }
            __router(data) {
                if (!data)
                    return;
                if (!data.route)
                    return;
                if (!this.__registedRouter[data.route])
                    return;
                let router = this.__registedRouter[data.route];
                router(data.data);
            }
        }

        const ST_READ_HEAD = 1;
        const ST_READ_DATA = 2;
        class SeasionWS extends Laya.EventDispatcher {
            constructor() {
                super();
                this.instanceId = 0;
                this.uuid = null;
                this.revDataBuffer = "";
                this.socket = null;
                this.readState = ST_READ_HEAD;
                this.head = {};
                this.instanceId = 0;
                this.uuid = null;
                this.revDataBuffer = "";
                this.socket = null;
                this.readState = ST_READ_HEAD;
                this.head = {};
            }
            setUuid(uuid) {
                this.uuid = uuid;
            }
            setSocket(socket) {
                this.socket = socket;
                this.socket.onopen = () => {
                    this.event('open');
                };
                this.socket.onclose = () => {
                    this.event("close");
                };
                this.socket.onerror = (errEvent) => {
                    this.event("error");
                };
                this.socket.onmessage = (msgEvent) => {
                    this.revDataBuffer += msgEvent.data;
                    if (this.readState == ST_READ_HEAD) {
                        let rep = /({.+?})/;
                        let result = rep.exec(this.revDataBuffer);
                        if (!!result) {
                            let headStr = result.shift();
                            this.revDataBuffer = this.revDataBuffer.replace(headStr, "");
                            this.head = JSON.parse(headStr);
                            this.readState = ST_READ_DATA;
                        }
                    }
                    if (this.readState == ST_READ_DATA) {
                        if (this.revDataBuffer.length >= this.head.dataLength) {
                            let dataStr = this.revDataBuffer.slice(0, this.revDataBuffer.length);
                            try {
                                let data = JSON.parse(dataStr);
                                this.event("data", data);
                            }
                            catch (error) {
                                console.error("ST_READ_DATA error:", error);
                            }
                            this.revDataBuffer = this.revDataBuffer.replace(dataStr, "");
                            this.readState = ST_READ_HEAD;
                        }
                    }
                };
            }
            write(data) {
                let content = JSON.stringify(data);
                let head = {
                    dataLength: content.length,
                };
                this.socket.send(JSON.stringify(head) + content);
            }
            close() {
                this.socket.close();
            }
        }

        class NetworkWS {
            static newSeasion(ip, port) {
                let address = 'ws://' + ip + ':' + port.toString();
                console.log("连接地址:", address);
                let client = new WebSocket(address);
                let seasionWs = new SeasionWS();
                seasionWs.setSocket(client);
                return seasionWs;
            }
        }

        class vTestReuseListItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vTestReuseListItem";
                this.exportNodeNames = [];
                this.width = 170;
                this.height = 60;
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                this.data && this.fillByData(this.data);
                this.buttonBg.fOnClick = () => {
                    this.data && this.data.fOnClick();
                };
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.labelContent.text = this.data.name;
            }
        }

        class vTestDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vTestDialog";
                this.exportNodeNames = [];
                this.reuseList = null;
            }
            onOpened() {
                super.onOpened();
                this.buttonClose.fOnClick = this.closeDialog.bind(this);
                this.buildUi();
                this.fillData();
                let node = Laya.stage.getChildByName(Const.CUSTOM_LAYA_STAGE_BASE_BG_NAME);
                if (!!node) {
                    node.alpha = 0;
                }
            }
            cameraForSaveImg() {
                Tools.takeAPhoto(768, 1280, this.cameraBack, (tex2d) => {
                    if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                        return;
                    }
                    let pixels = tex2d.getPixels();
                    this.test(pixels);
                }, Laya.RenderTextureFormat.R8G8B8A8, Laya.TextureFormat.R8G8B8A8);
            }
            test(pixels) {
                let saveImgName = "icon.png";
                var newCanvas = document.createElement("canvas");
                var image = new Image();
                image.crossOrigin = "Anonymous";
                image.onload = function () {
                    newCanvas.width = image.width;
                    newCanvas.height = image.height;
                    newCanvas.getContext("2d").drawImage(image, 0, 0, image.width, image.height);
                    var targetPx = new Uint8ClampedArray(pixels);
                    var ctx = newCanvas.getContext("2d");
                    var imageData = ctx.getImageData(0, 0, newCanvas.width, newCanvas.height);
                    var px = imageData.data;
                    for (var i = 0; i < px.length; i += 4) {
                        px[i] = targetPx[i];
                        px[i + 1] = targetPx[i + 1];
                        px[i + 2] = targetPx[i + 2];
                        px[i + 3] = targetPx[i + 3];
                    }
                    ctx.putImageData(imageData, 0, 0);
                    var dataUri = newCanvas.toDataURL("image/png");
                    var link = document.createElement('a');
                    link.href = dataUri;
                    link.download = saveImgName;
                    link.click();
                };
                let index = window.location.href.indexOf("index.html");
                image.src = window.location.href.substring(0, index - 1) + "/res/ui/common/mask.png";
                document.body.insertAdjacentElement('afterbegin', newCanvas);
            }
            getPreLoadAnimationIds() {
                return [];
            }
            getPreLoadModelIds() {
                return [];
            }
            onClosed() {
                super.onClosed();
            }
            onClickButton1() {
                console.log("点击按钮1");
            }
            onClickButton2() {
                mgrTip.showMsgTip("点击按钮2");
            }
            onClickButton3() {
                mgrDirector.openDialog("vTestDialog", { parm1: "参数1" });
            }
            buildUi() {
                this.spriteBg.zOrder = -4;
                this.reuseList = new ReuseList(4, 0, 10);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vTestReuseListItem);
                this.reuseList.setVerticalMoveEnable(true);
            }
            fillData() {
                let functionList = [
                    {
                        name: "vDebugDialog",
                        fOnClick: () => {
                            mgrDirector.openDialog("vDebugDialog");
                        }
                    },
                    {
                        name: "Laya性能面板",
                        fOnClick: () => {
                            if (!Laya.Stat["_bHiding"]) {
                                Laya.Stat.hide();
                                Laya.Stat["_bHiding"] = true;
                            }
                            else {
                                Laya.Stat.show(0, 100);
                                Laya.Stat["_bHiding"] = false;
                            }
                        }
                    },
                    {
                        name: "显示开发测试按钮",
                        fOnClick: () => {
                            if (!!mgrDebug.bShowDevButton) {
                                return;
                            }
                            mgrDebug.bShowDevButton = true;
                        }
                    },
                    {
                        name: "显示打点信息",
                        fOnClick: () => {
                            mgrDebug.bShowStatisticsInfo = true;
                            this.sendMsg("MSG_SHOW_POINT_DEBUG_INFO", { state: !!mgrDebug.bShowStatisticsInfo ? 1 : 0 });
                        }
                    },
                    {
                        name: "弹出UI搜索框",
                        fOnClick: () => { mgrDirector.openDialog("vEditorUiTipInfoDialog"); this.closeDialog(); },
                    },
                    {
                        name: "回到主界面",
                        fOnClick: () => { mgrDirector.warpSceneWidthEffect("vHubScene"); this.closeDialog(); },
                    },
                    {
                        name: "添加100w金币 + 100w钻石",
                        fOnClick: () => {
                            mgrPlayer.addItemAmount(Const.ITEM_ID_GOLD, 1000000, "测试");
                            mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, 1000000, "测试");
                            mgrPlayer.addItemAmount(Const.ITEM_ID_ENERGY, 100, "测试");
                        }
                    },
                    {
                        name: "3D特效查看",
                        fOnClick: () => { mgrDirector.openDialog("vEditorTDEffDialog"); this.closeDialog(); },
                    },
                    {
                        name: "测试所有spine动画",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorSpineCheckScene`);
                        }
                    },
                    {
                        name: "测试所有人物动作",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorAnimationCheckScene`);
                        }
                    },
                    {
                        name: "卡通材质编辑器",
                        fOnClick: () => { mgrDirector.open2DScene("vEditorShaderCartonScene"); this.closeDialog(); },
                    },
                    {
                        name: "身体服装材质编辑器",
                        fOnClick: () => { mgrDirector.open2DScene("vEditorShaderSkinScene"); this.closeDialog(); },
                    },
                    {
                        name: "动态骨骼编辑器",
                        fOnClick: () => { mgrDirector.open2DScene("vEditorDynamicBone"); this.closeDialog(); }
                    },
                    {
                        name: "人形",
                        fOnClick: () => { mgrDirector.open2DScene("vEditorHumanBone"); this.closeDialog(); }
                    },
                    {
                        name: "部件截图",
                        fOnClick: () => {
                            mgrDirector.open2DScene("vEditorPartIconShotScene");
                            this.closeDialog();
                        }
                    },
                    {
                        name: "套装截图",
                        fOnClick: () => {
                            mgrDirector.open2DScene("vEditorPartSuitShotScene");
                            this.closeDialog();
                        }
                    },
                    {
                        name: "蛋糕关卡",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorCakeStageScene`);
                        }
                    },
                    {
                        name: "服装搭配关卡",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorClothStageScene`);
                        }
                    },
                    {
                        name: "服装定制关卡",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorDesignStageScene`);
                        }
                    },
                    {
                        name: "服装跑酷关卡",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorParkourStageScene`);
                        }
                    },
                    {
                        name: "卡牌关卡",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorCardStageScene`);
                        }
                    },
                    {
                        name: "女神挑战关卡",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorClothCrossingStageScene`);
                        }
                    },
                    {
                        name: "测试得到物品-货币",
                        fOnClick: () => { mgrTip.addGotItemTip(1, 100); this.closeDialog(); }
                    },
                    {
                        name: "测试得到物品-部件",
                        fOnClick: () => {
                            let partIds = [13001, 13001];
                            mgrTip.addGotItemTip(Tools.randomGotOneArrayData(partIds), 100);
                            this.closeDialog();
                        }
                    },
                    {
                        name: "测试获得所有部件",
                        fOnClick: () => {
                            mgrCfg.forDb_from_suit_db((k, v) => {
                                for (let i = 0; i < v.partIds.length; i++) {
                                    const partId = v.partIds[i];
                                    mgrPlayer.addItemAmount(partId, 1, "");
                                }
                            });
                        }
                    },
                    {
                        name: "连接shader服务器",
                        fOnClick: () => {
                            if (!Const.GlobalRouter) {
                                mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                                let seasion = NetworkWS.newSeasion(`127.0.0.1`, 8081);
                                seasion.on("open", this, () => {
                                    Timer.callLater(1, () => {
                                        mgrTip.showMsgTip("链接存档服务器成功!可以存档！");
                                    });
                                    Const.GlobalRouter = new GameRemoteRouter(seasion);
                                });
                                seasion.on("error", this, () => {
                                    mgrTip.showMsgTip("链接存档服务器失败!请打开本地服务器!");
                                });
                            }
                            else {
                            }
                        }
                    },
                    {
                        name: "获得角色界面",
                        fOnClick: () => {
                            mgrDirector.openDialog("vGotNewRoleDialog", { roleId: 109 });
                        }
                    },
                    {
                        name: "部件试用",
                        fOnClick: () => {
                            mgrDirector.openDialog("vAdFreeTrialPartDialog", { partId: 13002 });
                        }
                    },
                    {
                        name: "跑酷皮肤选择",
                        fOnClick: () => {
                            mgrDirector.openDialog("vAmusePenChooseDialog", { partId: 13002 });
                        }
                    },
                    {
                        name: "获得新角色",
                        fOnClick: () => {
                            mgrDirector.openDialog("vGotNewRoleDialog", { roleId: 109, bVip: true });
                        }
                    },
                    {
                        name: "惊喜奖励",
                        fOnClick: () => {
                            mgrDirector.openDialog("vSurpriseRewardDialog", { partId: 13101, bVip: true });
                        }
                    },
                    {
                        name: "抽套装",
                        fOnClick: () => {
                            mgrDirector.openDialog("vAdSuitDialog");
                        }
                    },
                    {
                        name: "转盘",
                        fOnClick: () => {
                            mgrDirector.openDialog("vAdTurntableDialog");
                        }
                    },
                    {
                        name: "timeline",
                        fOnClick: () => {
                            this.closeDialog();
                            mgrDirector.warpSceneWidthEffect(`vEditorTimelineTestScene`);
                        }
                    },
                    {
                        name: "抖音关注",
                        fOnClick: () => {
                            mgrSdk.getFollowOfficialAccountState();
                            mgrDirector.openDialog("vDouyinFollow");
                        }
                    },
                    {
                        name: "泡泡机",
                        fOnClick: () => {
                            mgrDirector.openDialog("vAdPopMachineDialog");
                        }
                    },
                    {
                        name: "解锁所有双人卡牌",
                        fOnClick: () => {
                            mgrCfg.forDb("amuse_double_card_npc_db", (k, v) => {
                                let cardId = v.cardId;
                                mgrPlayer.addItemAmount(cardId, 1, "DDEBUG");
                            });
                        }
                    }
                ];
                this.reuseList.setDatas(functionList);
            }
        }

        class vWebViewDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "dialog/vWebViewDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                mgrLayout.widget(1, 0, this.buttonClose.__node, { x: 1, y: 0 });
                this.buttonClose.fOnClick = () => {
                    window[`conch`].closeExternalLink();
                    this.closeDialog(true);
                };
                let l = 50;
                let t = 100;
                let w = window.innerWidth - l * 2;
                let h = window.innerHeight - t * 2;
                window[`conch`].setExternalLinkEx(this.context.url, l, t, w, h, false);
            }
            onClosed() {
                super.onClosed();
            }
            static openWebView(url) {
                mgrDirector.openDialog(`vWebViewDialog`, {
                    url: url,
                }, true);
            }
        }

        class vEditorSelectDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "editor/vEditorSelectDialog";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.reuseListData = new ReuseList(1, 0, 100);
                this.reuseListData.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseListData);
                this.reuseListData.setItemClass(vDanceItem);
                this.reuseListData.setVerticalMoveEnable(true);
                for (let i = 0; i < this.context.datas.length; i++) {
                    const data = this.context.datas[i];
                    data.closeDialog = () => {
                        this.closeDialog();
                    };
                }
                this.reuseListData.setDatas(this.context.datas);
                this.buttonClose.fOnClick = () => {
                    this.closeDialog();
                };
            }
            onClosed() {
                super.onClosed();
            }
        }
        class vDanceItem extends ReuseListItem {
            constructor() {
                super();
                let width = 395;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.label.anchorX = 0.5;
                this.label.anchorY = 0.5;
                this.addChild(this.label);
                this.label.x = width / 2;
                this.label.y = height / 2;
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.data);
                this.data["closeDialog"]();
            }
            fillByData(data) {
                this.data = data;
                this.label.text = this.data.text;
            }
        }

        class vEditorTDEffDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "editor/vEditorTDEffDialog";
                this.PER_PAGE_COUNT = 6;
                this.showingEffModelDict = {};
            }
            onOpened() {
                super.onOpened();
                mgrDirector.adaptStageSize(2304, 1580);
                Tools.registerTouchHander(this.nodeResource, this.onTouchSpriteBg.bind(this));
                let effModelDataArr = [];
                mgrCfg.forDb_from_model_db((k, v) => {
                    if (v.id == "117_ui_loop_card_anim") {
                        console.log("iD", v.id);
                    }
                    if (!v.id.startsWith("eff_") && !v.id.startsWith("e_") && v.id.indexOf("_ui_") < 0 && v.id.indexOf("_e_") < 0) {
                        return;
                    }
                    if (v.id == "eff_ui_gongxihuode" || v.id == "eff_ui_hb_switch") {
                        return;
                    }
                    effModelDataArr.push(v);
                });
                this.effModelDataArr = effModelDataArr;
                this.currentPageIndex = 0;
                this.fillData();
            }
            fillData() {
                for (let i = 0; i < this.PER_PAGE_COUNT; i++) {
                    this.addEff(i + 1);
                }
                let startIndex = this.currentPageIndex > 0 ? this.currentPageIndex * this.PER_PAGE_COUNT : 0;
                this.labelProgress.text = `当前：${startIndex + 1}-${startIndex + this.PER_PAGE_COUNT} 总数量:${this.effModelDataArr.length}`;
            }
            addEff(holderIndex) {
                let startIndex = this.currentPageIndex > 0 ? this.currentPageIndex * this.PER_PAGE_COUNT : 0;
                let oldModelData = this.showingEffModelDict[holderIndex - 1];
                if (oldModelData) {
                    mgrLoader.Pool.recoverModel(oldModelData.model);
                    delete this.showingEffModelDict[holderIndex - 1];
                }
                let index = startIndex + holderIndex - 1;
                let data = this.effModelDataArr[index];
                if (data) {
                    this[`labelHolder${holderIndex}`].text = data.id;
                    let modelId = data.id;
                    let holder = this[`imageHolder${holderIndex}`];
                    let pos = holder.parent.localToGlobal(new Laya.Point(holder.x, holder.y), false);
                    this.add3DEffectAtFront(modelId, pos, 0, 1, (model) => {
                        let oldModelData = this.showingEffModelDict[holderIndex - 1];
                        if (oldModelData) {
                            mgrLoader.Pool.recoverModel(oldModelData.model);
                            delete this.showingEffModelDict[holderIndex - 1];
                        }
                        this.showingEffModelDict[holderIndex - 1] = { model: model, modelId: modelId };
                    });
                }
            }
            onClosed() {
                super.onClosed();
                for (let i = 0; i < this.PER_PAGE_COUNT; i++) {
                    let oldModelData = this.showingEffModelDict[i];
                    if (oldModelData) {
                        mgrLoader.Pool.recoverModel(oldModelData.model);
                        delete this.showingEffModelDict[i];
                    }
                }
                mgrDirector.adaptStageSize();
            }
            onClickHolder(index) {
                let oldModelData = this.showingEffModelDict[index - 1];
                if (!oldModelData) {
                    mgrTip.showMsgTip("此处没有特效");
                    return;
                }
                this.labelSelectedModelName.text = oldModelData.modelId;
                mgrTip.showMsgTip("点击" + oldModelData.modelId);
            }
            onClickReplay(index) {
                let oldModelData = this.showingEffModelDict[index - 1];
                if (!oldModelData) {
                    mgrTip.showMsgTip("此处没有特效");
                    return;
                }
                this.addEff(index);
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.beginTouchHolderIndex = 0;
                    for (let i = 0; i < this.PER_PAGE_COUNT; i++) {
                        let oldModelData = this.showingEffModelDict[i];
                        if (!oldModelData) {
                            break;
                        }
                        let node = this["imageHolder" + (i + 1)];
                        if (Tools.isWorldLocaInNode(node, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            this.beginTouchHolderIndex = i + 1;
                            break;
                        }
                    }
                }
                if (!this.beginTouchHolderIndex) {
                    return;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    this.lastTouchBgPos = e.pos;
                    let oldModelData = this.showingEffModelDict[this.beginTouchHolderIndex - 1];
                    let avatar = oldModelData.model;
                    avatar && avatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            onTouchButtonPre() {
                this.currentPageIndex = this.currentPageIndex > 0 ? this.currentPageIndex - 1 : 0;
                this.fillData();
            }
            onTouchButtonNext() {
                this.currentPageIndex = this.currentPageIndex < Math.floor(this.effModelDataArr.length / this.PER_PAGE_COUNT) ? this.currentPageIndex + 1 : this.currentPageIndex;
                this.fillData();
                this.add3DEffectAtFront("117_ui_once_flash_01", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 1);
            }
            onTouchButtonClose() {
                this.closeDialog();
            }
            onTouchButtonHolder1() {
                this.onClickHolder(1);
            }
            onTouchButtonReplay1() {
                this.onClickReplay(1);
            }
            onTouchButtonHolder2() {
                this.onClickHolder(2);
            }
            onTouchButtonHolder3() {
                this.onClickHolder(3);
            }
            onTouchButtonHolder4() {
                this.onClickHolder(4);
            }
            onTouchButtonHolder5() {
                this.onClickHolder(5);
            }
            onTouchButtonHolder6() {
                this.onClickHolder(6);
            }
            onTouchButtonReplay2() {
                this.onClickReplay(2);
            }
            onTouchButtonReplay3() {
                this.onClickReplay(3);
            }
            onTouchButtonReplay4() {
                this.onClickReplay(4);
            }
            onTouchButtonReplay5() {
                this.onClickReplay(5);
            }
            onTouchButtonReplay6() {
                this.onClickReplay(6);
            }
            onTouchButtonConfirm() {
                if (this.labelSelectedModelName.text.length == 0) {
                    return;
                }
                this.sendMsg("MSG_EDITOR_TDEFF_CLICK_HOLDER", { modelId: this.labelSelectedModelName.text });
            }
        }

        class vAmuseCardFightBloodTip extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vAmuseCardFightBloodTip";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.labelTip.text = `-${this.context.amount || "0"}`;
                this.spriteSkill1.visible = !!this.context.bSkill;
                let byPos = this.context.byPos || new Laya.Vector2(60, 60);
                cc.tween(this)
                    .parallel(cc.tween().then(cc.jumpBy(0.4, byPos.x, byPos.y, 50, 1)), cc.tween().toScale(0.6, 1))
                    .toAlpha(0.3, 0)
                    .start();
                Timer.callLater(1, () => {
                    this.destroy();
                }, this);
            }
            onClosed() {
            }
        }

        class vAmuseCardPhotoMakeListItem extends ViewBase {
            constructor(context) {
                super(context);
                this.TAB_ANI = 1;
                this.TAB_MASK = 2;
                this.sourceName = "node/vAmuseCardPhotoMakeListItem";
                this.exportNodeNames = [];
                this.size(110, 172);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.spriteAchFlag.visible = false;
                let dbName = this.data.dbName;
                let adName = this.data.adName;
                let cardData = mgrCfg.get(dbName, this.data.id);
                let shopData = mgrCfg.get_from_shop_template_db(this.data.id);
                this.boxPrice.mouseEnabled = false;
                this.spriteAdFlag.visible = false;
                this.boxPrice.visible = false;
                this.imageMask.visible = false;
                this.labelAddPower1.visible = false;
                this.labelAddPower2.visible = false;
                if (this.data.tab == this.TAB_ANI) {
                    Tools.loadImg(this.imageIcon, cardData.icon);
                    this.labelAddPower1.visible = true;
                }
                else {
                    this.imageMask.visible = true;
                    Tools.loadImg(this.imageMask, cardData.icon);
                    this.labelAddPower2.visible = true;
                }
                this.labelAddPower1.text = `+${cardData.addPower}`;
                this.labelAddPower2.text = `+${cardData.addPower}`;
                if (mgrPlayer.getItemAmount(cardData.id) <= 0) {
                    if (!!shopData) {
                        this.boxPrice.visible = true;
                        this.labelPrice.text = `${shopData.price}`;
                    }
                    else {
                        this.spriteAdFlag.visible = true;
                    }
                }
                this.spriteSelected.visible = this.data.fIsSelected(this.data.id);
                if (this.spriteAdFlag.visible) {
                }
            }
            onTouchButtonBg() {
                if (this.spriteAdFlag.visible) {
                    this.data && this.data.fOnClick(this.data.id, this.spriteAdFlag.visible);
                }
                else {
                    if (this.boxPrice.visible) {
                        this.data && this.data.fOnClick(this.data.id);
                    }
                    else {
                        this.data && this.data.fOnClick(this.data.id);
                    }
                }
            }
        }

        class vCakePart extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vCakePart";
                this.exportNodeNames = [];
                this.size(90, 96);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                this.registerListeners({
                    MSG_ROOM_PART_REFRESH: this.onMsgRoomPartRefresh.bind(this),
                });
            }
            onClosed() {
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag2"];
            }
            onMsgRoomPartRefresh() {
                this.data && this.fillByData(this.data);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let shopData = mgrCfg.get_from_shop_template_db(this.data.id);
                let partData = mgrCfg.get(this.data.dbName, this.data.id);
                Tools.loadImg(this.imageIcon, partData.icon);
                this.spriteSelect.visible = (!!this.data && this.data.fIsCurrent && this.data.fIsCurrent(this.data.id)) ? true : false;
                let bShowTrialText = mgrSdk.getCopNumberValueByKey("b_hide_trail_text") == 0 ? true : false;
                this.imageTrial.visible = !!bShowTrialText;
                this.imageTrialNoText.visible = !this.imageTrial.visible;
                let bRecommend = this.data.fIsRecommend && this.data.fIsRecommend(this.data.id) ? true : false;
                this.spriteRecommendBg.visible = bRecommend;
                this.spriteRecommend.visible = bRecommend;
                this.spriteCoin.visible = (mgrPlayer.getItemAmount(this.data.id) <= 0 && !!shopData && shopData.price > 0) ? true : false;
                if (!!shopData) {
                    this.labelPrice.text = `${shopData.price}`;
                }
                let bTrying = this.data.fIsTry(this.data.id);
                this.spriteTrialContainer.visible = false;
                if (!this.spriteCoin.visible && mgrPlayer.getItemAmount(this.data.id) <= 0 && !bTrying) {
                    this.spriteTrialContainer.visible = !!this.data.bCanAd;
                    if (this.spriteTrialContainer.visible) {
                    }
                }
            }
            onTouchButtonBg() {
                this.data && this.data.fOnClick(this.data.id, this.data.bCanAd);
                mgrPart.deleteNewPart(this.data.id);
            }
        }

        class vCakeTypeBtn extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vCakeTypeBtn";
                this.size(126, 52);
                this.anchorX = 0;
                this.anchorY = -0.2;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                this.registerListeners({
                    MSG_REFRESH_TAB_USED_STATUS: this.onMsgRefreshTabUsedStatus.bind(this),
                    MSG_REFRESH_TAB_SEL_STATUS: this.onMsgRefreshTabSelStatus.bind(this),
                });
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.refreshSelectStatus();
                this.refreshUsedStatus();
            }
            refreshSelectStatus() {
                if (!this.bResLoaded || !this.data)
                    return;
                if (this.data.fIsCurrentTab && this.data.fIsCurrentTab(this.data.id)) {
                    Tools.loadImg(this.spriteSelected, this.data.selTexture);
                }
                else {
                    Tools.loadImg(this.spriteSelected, this.data.normalTexture);
                }
            }
            refreshUsedStatus() {
                if (!this.bResLoaded || !this.data)
                    return;
                this.spriteUsed.visible = (this.data.fIsUsedTab && this.data.fIsUsedTab(this.data.id)) ? true : false;
            }
            onTouchButtonTab() {
                if (this.data.fOnClick) {
                    this.data.fOnClick(this.data.id);
                }
            }
            onMsgRefreshTabUsedStatus(e) {
                this.refreshUsedStatus();
            }
            onMsgRefreshTabSelStatus(e) {
                this.refreshSelectStatus();
            }
        }

        class vCardPreviewItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vCardPreviewItem";
                this.size(294, 170);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelFightPower);
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let npcId = data.previewNpcId;
                if (npcId <= 30) {
                    Tools.loadImg(this.spriteBg, "res/ui/amuse_card_start/boss_bg.png");
                    this.spriteShadow.visible = true;
                }
                else {
                    Tools.loadImg(this.spriteBg, "res/ui/amuse_card_start/normal_bg.png");
                    this.spriteShadow.visible = false;
                }
                let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                Tools.loadImg(this.spriteNpc, npcData.imgCardTexture);
                this.labelFightPower.text = npcData.fightPower.toString();
                let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                Tools.loadImg(this.spriteItemIcon2, "res/ui/amuse_card_start/color.png");
                this.labelItemAmount2.text = `+${data.successRewardColorPoint}`;
                if (mgrCard.getStageProgress() + 1 > data.id) {
                    this.buttonBg.__node.visible = false;
                    this.spriteSuccess.visible = true;
                }
                else {
                    this.buttonBg.__node.visible = true;
                    this.spriteSuccess.visible = false;
                }
            }
            onTouchButtonBg() {
                if (this.data.fOnClick) {
                    this.data.fOnClick();
                }
            }
        }

        class vEditorCartonMaterialPart extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vEditorCartonMaterialPart";
                this.exportNodeNames = [];
                this.width = 200;
                this.height = 65;
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                if (this.data)
                    this.fillByData(this.data);
                this.buttonBg.fOnClick = () => {
                    if (this.data.fOnClickModel) {
                        this.data.fOnClickModel(this.data.modelId);
                    }
                    else {
                        this.data.fOnClickSkinName(this.data.skinName);
                    }
                };
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                if (this.data.fOnClickModel) {
                    this.labelContent.text = this.data.modelId;
                }
                else {
                    this.labelContent.text = this.data.skinName;
                }
                if (this.data.skinName) {
                    let material = null;
                    if (mgrMaterial[`materialInfos`][this.data.modelId] &&
                        mgrMaterial[`materialInfos`][this.data.modelId][this.data.modelMaterialNo] &&
                        mgrMaterial[`materialInfos`][this.data.modelId][this.data.modelMaterialNo][this.data.skinName]) {
                        material = mgrMaterial[`materialInfos`][this.data.modelId][this.data.modelMaterialNo][this.data.skinName];
                    }
                    this.labelContent.color = (material ? `#00ff00` : `#ff0000`);
                }
                else {
                    let material = mgrMaterial[`materialInfos`][this.data.modelId];
                    this.labelContent.color = (material ? `#00ff00` : `#ff0000`);
                }
            }
        }

        class vEditorDynamicBoneAnimationItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vEditorDynamicBoneAnimationItem";
                this.exportNodeNames = [];
                this.width = 200;
                this.height = 65;
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                Tools.registerTouchHander(this.nodeResource, (e) => {
                    if (!e.isClick)
                        return;
                    this.data.fOnClickAnimation && this.data.fOnClickAnimation(this.data.animationId);
                });
                if (this.data)
                    this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.labelContent.text = `${this.data.animationId}`;
            }
            onSelect(data) {
            }
        }

        class vEditorDynamicBoneChild extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vEditorDynamicBoneChild";
                this.exportNodeNames = [];
                this.width = 1024;
                this.height = 60;
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                this.buttonBg.fOnClick = () => {
                    this.data.onClickNode && this.data.onClickNode(this.data);
                };
                this.buttonAdd.fOnClick = () => {
                    this.data.onClickAdd && this.data.onClickAdd(this.data);
                };
                this.buttonRemove.fOnClick = () => {
                    this.data.onClickRemove && this.data.onClickRemove(this.data);
                };
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.labelContent.text = (!!this.data.node && !!this.data.node.name) ? this.data.node.name : this.data.router;
                this.buttonAdd.__node.visible = !!this.data.bShowBtnAddRemove;
                this.buttonRemove.__node.visible = !!this.data.bShowBtnAddRemove;
                if (!!this.data.bShowBtnAddRemove) {
                    if (this.data.isAddedRouter) {
                        this.buttonRemove.__node.visible = !!this.data.isAddedRouter(this.data);
                        this.buttonAdd.__node.visible = !this.buttonRemove.__node.visible;
                    }
                }
            }
        }

        class vEditorDynamicBonePart extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vEditorDynamicBonePart";
                this.exportNodeNames = [];
                this.width = 200;
                this.height = 65;
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                if (this.data)
                    this.fillByData(this.data);
                this.buttonBg.fOnClick = () => {
                    this.data.fOnClickPart && this.data.fOnClickPart(this.data.partId);
                };
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let partData = mgrCfg.get_from_part_db(this.data.partId);
                this.labelContent.text = `${partData.id}:${partData.name}`;
            }
        }

        class vEditorDynamicBoneSearchRouterItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vEditorDynamicBoneSearchRouterItem";
                this.exportNodeNames = [];
                this.width = 2200;
                this.height = 60;
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                this.buttonBg.fOnClick = () => {
                    this.data.fOnClick && this.data.fOnClick(this.data.router);
                };
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.labelContent.text = `${!!this.data.bSelected ? "[已选中]" : "[未选中]"}${this.data.router}`;
                this.labelContent.color = !!this.data.bSelected ? `#00ff00` : `#ffffff`;
            }
        }

        class vGuideTipNode extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vGuideTipNode";
                this.exportNodeNames = [];
            }
            onOpened() {
                this.fillData();
                this.fadeIn();
                Timer.callLoop(0.016, () => {
                    mgrLayout.widget(this.context.widget.x || 0.5, this.context.widget.y || 0.5, this, { x: 0.5, y: 0.5 });
                    if (this.context.fPosUpdateFunc) {
                        this.context.fPosUpdateFunc();
                    }
                }, this);
            }
            onClosed() {
            }
            fadeIn() {
                if (this.context.tipDelayTime && this.context.tipDelayTime > 0) {
                    this.spriteDialogBg1.scale(0, 0);
                    this.spriteDialogBg2.scale(0, 0);
                    Timer.callLater(this.context.tipDelayTime, () => {
                        CustomTween.to(this.spriteDialogBg1, { scaleX: 1, scaleY: 1 }, 300, Laya.Ease.backOut).start(1);
                        CustomTween.to(this.spriteDialogBg2, { scaleX: 1, scaleY: 1 }, 300, Laya.Ease.backOut).start(1);
                    }, this);
                }
                else {
                    this.spriteDialogBg1.scale(0, 0);
                    this.spriteDialogBg2.scale(0, 0);
                    CustomTween.to(this.spriteDialogBg1, { scaleX: 1, scaleY: 1 }, 300, Laya.Ease.backOut).start(1);
                    CustomTween.to(this.spriteDialogBg2, { scaleX: 1, scaleY: 1 }, 300, Laya.Ease.backOut).start(1);
                }
            }
            fillData() {
                this.labelContent1.text = this.context.content;
                this.labelContent2.text = this.context.content;
                let type = this.context.type;
                if (type == 2) {
                    this.spriteDialogBg1.visible = false;
                    this.spriteDialogBg2.visible = true;
                }
                else {
                    this.spriteDialogBg1.visible = true;
                    this.spriteDialogBg2.visible = false;
                }
            }
        }

        class vItemTip extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vItemTip";
                this.exportNodeNames = [];
            }
            onOpened() {
                this.labelTip.text = this.context.pointStr || (`${this.context.amount > 0 ? "+" : ""}${this.context.amount}`);
                let itemData = mgrCfg.get_from_item_template_db(this.context.itemId);
                Tools.loadImg(this.imageIcon, itemData.icon);
                this.alpha = 0;
                this.scale(0.5, 0.5);
                this.y -= 180;
                CustomTween.to(this, { scaleX: 1, scaleY: 1, alpha: 1, y: this.y - 40 }, 300)
                    .to({ y: this.y - 120 }, 600)
                    .to({ y: this.y - 160, alpha: 0 }, 300)
                    .callback(() => {
                    this.destroy();
                })
                    .start(1);
                this.spriteBg.width = ul.clamp(this.imageIcon.width + this.labelTip.width + 50, 154, 300);
            }
            onClosed() {
            }
        }

        class vJumpOtherDragLeft extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vJumpOtherDragLeft";
                this.exportNodeNames = [];
                this.bOpen = false;
                this.size(183, 370);
                this.anchorX = 112 / 183;
                this.anchorY = 0.5;
            }
            onOpened() {
                super.onOpened();
                mgrSdk.openJump(Const.gameIndex, "list");
                this.visible = false;
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                });
            }
            onClosed() {
            }
            buildUi(datas) {
                if (datas.length > 0) {
                    this.visible = true;
                }
                else {
                    this.visible = false;
                }
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(1, 0, 5);
                    this.reuseList.size(this.boxList.width, this.boxList.height);
                    this.boxList.addChild(this.reuseList);
                    this.reuseList.setItemClass(vJumpOtherGameItemLeft);
                    this.reuseList.setVerticalMoveEnable(true);
                    this.reuseList.setSpaceY(10);
                }
                this.reuseList.setDatas(datas);
                this.context.index = 0;
                let dir = 1;
                this.context.scroolTimer = Timer.callLoop(2, () => {
                    if (this.reuseList) {
                        this.context.index += dir;
                        let len = this.reuseList.getDatas().length;
                        if (this.context.index <= 0 || this.context.index >= len - 6)
                            dir = -dir;
                        this.reuseList.tweenTo(this.context.index, 2000);
                    }
                }, this);
                let startPos;
                Tools.registerTouchHander(this.reuseList, (e) => {
                    if (e.isBegin) {
                        this.context.scroolTimer.stop();
                        startPos = e.pos;
                    }
                    else if (e.isEnd || e.isCancel) {
                        this.context.scroolTimer.start(false);
                    }
                });
            }
            onMsgOpenJumpResult(e) {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (e.type == "list") {
                    let datas = e.jumpInfo;
                    this.buildUi(datas);
                }
            }
            onTouchButtonOpen() {
                if (this.context[`__originX`] == null)
                    this.context[`__originX`] = this.x;
                let __originX = this.context[`__originX`];
                if (!this.bOpen) {
                    CustomTween.to(this, { x: __originX + 115 }, 300).start(1);
                    this.bOpen = true;
                }
                else {
                    CustomTween.to(this, { x: __originX }, 300).start(1);
                    this.bOpen = false;
                }
                let spriteOpened = this.buttonOpen.__node.getChildByName("spriteOpened");
                let spriteClosed = this.buttonOpen.__node.getChildByName("spriteClosed");
                spriteOpened.visible = !!this.bOpen;
                spriteClosed.visible = !this.bOpen;
            }
        }
        class vJumpOtherGameItemLeft extends ReuseListItem {
            constructor() {
                super();
                let width = 124 * 0.6;
                let height = 160 * 0.6;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.image = new Laya.Image;
                this.image.size(width, height);
                this.image.anchorX = 0.5;
                this.image.anchorY = 0.5;
                this.image.x = width / 2;
                this.image.y = height / 2;
                this.addChild(this.image);
                this.button = this.image.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                mgrSdk.jumpOtherGame(this.data.index, "list");
            }
            fillByData(data) {
                Tools.loadImg(this.image, data.url);
                this.data = data;
            }
        }

        class vJumpOtherDragRight extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vJumpOtherDragRight";
                this.exportNodeNames = [];
                this.bOpen = false;
                this.size(183, 370);
                this.anchorX = (183 - 112) / 183;
                this.anchorY = 0.5;
            }
            onOpened() {
                super.onOpened();
                mgrSdk.openJump(Const.gameIndex, "list");
                this.visible = false;
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                });
            }
            onClosed() {
            }
            buildUi(datas) {
                if (datas.length > 0) {
                    this.visible = true;
                }
                else {
                    this.visible = false;
                }
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(1, 0, 5);
                    this.reuseList.size(this.boxList.width, this.boxList.height);
                    this.boxList.addChild(this.reuseList);
                    this.reuseList.setItemClass(vJumpOtherGameItemRight);
                    this.reuseList.setVerticalMoveEnable(true);
                    this.reuseList.setSpaceY(10);
                }
                this.reuseList.setDatas(datas);
                this.context.index = 0;
                let dir = 1;
                this.context.scroolTimer = Timer.callLoop(2, () => {
                    if (this.reuseList) {
                        this.context.index += dir;
                        let len = this.reuseList.getDatas().length;
                        if (this.context.index <= 0 || this.context.index >= len - 6)
                            dir = -dir;
                        this.reuseList.tweenTo(this.context.index, 2000);
                    }
                }, this);
                let startPos;
                Tools.registerTouchHander(this.reuseList, (e) => {
                    if (e.isBegin) {
                        this.context.scroolTimer.stop();
                        startPos = e.pos;
                    }
                    else if (e.isEnd || e.isCancel) {
                        this.context.scroolTimer.start(false);
                    }
                });
            }
            onMsgOpenJumpResult(e) {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (e.type == "list") {
                    let datas = e.jumpInfo;
                    this.buildUi(datas);
                }
            }
            onTouchButtonOpen() {
                if (this.context[`__originX`] == null)
                    this.context[`__originX`] = this.x;
                let __originX = this.context[`__originX`];
                if (!this.bOpen) {
                    CustomTween.to(this, { x: __originX - 115 }, 300).start(1);
                    this.bOpen = true;
                }
                else {
                    CustomTween.to(this, { x: __originX }, 300).start(1);
                    this.bOpen = false;
                }
                let spriteOpened = this.buttonOpen.__node.getChildByName("spriteOpened");
                let spriteClosed = this.buttonOpen.__node.getChildByName("spriteClosed");
                spriteOpened.visible = !!this.bOpen;
                spriteClosed.visible = !this.bOpen;
            }
        }
        class vJumpOtherGameItemRight extends ReuseListItem {
            constructor() {
                super();
                let width = 124 * 0.6;
                let height = 160 * 0.6;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.image = new Laya.Image;
                this.image.size(width, height);
                this.image.anchorX = 0.5;
                this.image.anchorY = 0.5;
                this.image.x = width / 2;
                this.image.y = height / 2;
                this.addChild(this.image);
                this.button = this.image.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                mgrSdk.jumpOtherGame(this.data.index, "list");
            }
            fillByData(data) {
                Tools.loadImg(this.image, data.url);
                this.data = data;
            }
        }

        class vJumpOtherGameBanner extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vJumpOtherGameBanner";
                this.exportNodeNames = [];
                this.size(576, 150);
                this.anchorX = 0.5;
                this.anchorY = 1;
            }
            onOpened() {
                super.onOpened();
                mgrSdk.openJump(Const.gameIndex, "list");
                this.visible = false;
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                });
            }
            onClosed() {
            }
            buildUi(datas) {
                this.datas = datas;
                if (datas.length > 0) {
                    this.visible = true;
                }
                else {
                    this.visible = false;
                }
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(0, 1, 10);
                    this.reuseList.size(this.boxList.width, this.boxList.height);
                    this.boxList.addChild(this.reuseList);
                    this.reuseList.setItemClass(vJumpOtherGameItemBanner);
                    this.reuseList.setHorizontalMoveEnable(true);
                    this.reuseList.setSpaceX(10);
                }
                this.reuseList.setDatas(datas);
                this.context.index = 0;
                let dir = 1;
                this.context.scroolTimer = Timer.callLoop(2, () => {
                    if (this.reuseList) {
                        this.context.index += dir;
                        let len = this.reuseList.getDatas().length;
                        if (this.context.index <= 0 || this.context.index >= len - 6)
                            dir = -dir;
                        this.reuseList.tweenTo(this.context.index, 2000);
                    }
                }, this);
                let startPos;
                Tools.registerTouchHander(this.reuseList, (e) => {
                    if (e.isBegin) {
                        this.context.scroolTimer.stop();
                        startPos = e.pos;
                    }
                    else if (e.isEnd || e.isCancel) {
                        this.context.scroolTimer.start(false);
                    }
                });
            }
            onMsgOpenJumpResult(e) {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (e.type == "list") {
                    let datas = e.jumpInfo;
                    this.buildUi(datas);
                }
            }
        }
        class vJumpOtherGameItemBanner extends ReuseListItem {
            constructor() {
                super();
                let width = 124 * 0.6;
                let height = 160 * 0.6;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.image = new Laya.Image;
                this.image.size(width, height);
                this.image.anchorX = 0.5;
                this.image.anchorY = 0.5;
                this.image.x = width / 2;
                this.image.y = height / 2;
                this.addChild(this.image);
                this.button = this.image.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                mgrSdk.jumpOtherGame(this.data.index, "list");
            }
            fillByData(data) {
                Tools.loadImg(this.image, data.url);
                this.data = data;
            }
        }

        class vJumpOtherGameBannerVertical extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vJumpOtherGameBannerVertical";
                this.size(112, 300);
                this.anchorX = 1;
                this.anchorY = 0.5;
            }
            onOpened() {
                super.onOpened();
                mgrSdk.openJump(Const.gameIndex, "list");
                this.visible = false;
                this.registerListeners({
                    MSG_ON_OPEN_JUMP_RESULT: this.onMsgOpenJumpResult.bind(this),
                });
            }
            onClosed() {
            }
            buildUi(datas) {
                if (datas.length > 0) {
                    this.visible = true;
                }
                else {
                    this.visible = false;
                }
                if (!this.reuseList) {
                    this.reuseList = new ReuseList(1, 0, 10);
                    this.reuseList.size(this.boxList.width, this.boxList.height);
                    this.boxList.addChild(this.reuseList);
                    this.reuseList.setItemClass(vJumpOtherGameItemBannerVertical);
                    this.reuseList.setVerticalMoveEnable(true);
                    this.reuseList.setSpaceY(10);
                }
                this.reuseList.setDatas(datas);
                this.context.index = 0;
                let dir = 1;
                this.context.scroolTimer = Timer.callLoop(2, () => {
                    if (this.reuseList) {
                        this.context.index += dir;
                        let len = this.reuseList.getDatas().length;
                        if (this.context.index <= 0 || this.context.index >= len - 6)
                            dir = -dir;
                        this.reuseList.tweenTo(this.context.index, 2000);
                    }
                }, this);
                let startPos;
                Tools.registerTouchHander(this.reuseList, (e) => {
                    if (e.isBegin) {
                        this.context.scroolTimer.stop();
                        startPos = e.pos;
                    }
                    else if (e.isEnd || e.isCancel) {
                        this.context.scroolTimer.start(false);
                    }
                });
            }
            onMsgOpenJumpResult(e) {
                if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                    return;
                }
                if (e.type == "list") {
                    let datas = e.jumpInfo;
                    this.buildUi(datas);
                }
            }
        }
        class vJumpOtherGameItemBannerVertical extends ReuseListItem {
            constructor() {
                super();
                let width = 124 * 0.6;
                let height = 160 * 0.6;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.image = new Laya.Image;
                this.image.size(width, height);
                this.image.anchorX = 0.5;
                this.image.anchorY = 0.5;
                this.image.x = width / 2;
                this.image.y = height / 2;
                this.addChild(this.image);
                this.button = this.image.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                mgrSdk.jumpOtherGame(this.data.index, "list");
            }
            fillByData(data) {
                Tools.loadImg(this.image, data.url);
                this.data = data;
            }
        }

        class vMsgTip extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vMsgTip";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.labelTip.text = this.context.content || "没有传入提示!!";
                this.y -= 150;
                CustomTween.to(this, { y: this.y - 100 }, 1000).
                    to({ alpha: 0, y: this.y - 150 }, 500)
                    .callback(() => { this.destroy(); })
                    .start(1);
                Timer.callLater(2, () => {
                    this.destroy();
                }, this);
            }
            onClosed() {
            }
        }

        class vRankItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vRankItem";
                this.exportNodeNames = [];
                this.size(489, 80);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelScore);
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                this.labelName.text = this.data.player.name;
                this.labelRank.text = this.data.player.rank.toString();
                if (this.data.player.uid == mgrPlayer.getUid()) {
                    this.labelName.text = mgrPlayer.getName();
                }
                this.labelScore.text = `${this.data.player.score}`;
            }
            onTouchButtonBg() {
                this.data && this.data.fOnClick(this.data.player);
            }
        }

        class vRoleChangeItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vRoleChangeItem";
                this.bAnim = true;
                this.size(190, 260);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
            }
            onClosed() {
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                if (this.bAnim) {
                    this.bAnim = false;
                    let delayTime = 0;
                    let timeGap = 0.2;
                    delayTime += timeGap * this.data.index;
                    let deltaX = Math.random() > 0.5 ? Tools.random(768, 1536) : Tools.random(-500, -1536);
                    let deltaY = Math.random() > 0.5 ? Tools.random(1280, 2560) : Tools.random(-1280, -2560);
                    mgrEffect.playComebackAction([this.buttonRole.__node], deltaX, deltaY, delayTime, 0.5, () => { }, cc.Ease.circOut);
                }
                let roleData = mgrCfg.get_from_role_db(this.data.id);
                Tools.loadImg(this.spriteChangeIcon, roleData.changeIcon);
                this.labelName.text = roleData.name;
                this.spriteLockMask.visible = mgrPlayer.getItemAmount(this.data.id) <= 0;
                for (let i = 0; i < 5; i++) {
                    let spriteStar = this.boxLevel.getChildAt(i);
                    spriteStar.visible = roleData.level > i;
                }
                let partTagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                Tools.loadImg(this.spriteTag, partTagData.icon);
                this.spriteActive.visible = this.data.fIsSelected(this.data.id);
                this.spriteCurFlag.visible = this.data.fIsUsing(this.data.id);
                let worldDay = mgrWorldDaily.getFirstTimeRewardWorldDayByRoleId(this.data.id);
                if (!!worldDay) {
                    this.labelWroldDay.text = `第${worldDay}天`;
                    this.labelWroldDay.visible = true;
                    this.labelRiCheng.visible = true;
                }
                else {
                    this.labelWroldDay.visible = false;
                    this.labelRiCheng.visible = false;
                }
                if (mgrPlayer.getItemAmount(this.data.id) > 0) {
                    this.boxAd.visible = false;
                    this.boxFragment.visible = false;
                    this.labelName.visible = true;
                }
                else {
                    this.boxFragment.visible = true;
                    this.boxAd.visible = this.data.bAd;
                    this.labelName.visible = !this.boxAd.visible;
                    let curFragmentNum = mgrPlayer.getItemAmount(roleData.unlockItemId);
                    Tools.loadImg(this.spriteFragment, mgrPlayer.getIcon(roleData.unlockItemId));
                    let needFragmentNum = roleData.unlockItemAmount;
                    this.labelFragmentCurNum.text = `${curFragmentNum}`;
                    this.labelFragmentAllNum.text = `/${needFragmentNum}`;
                }
                if (roleData.bNewTagShow && mgrPlayer.getItemAmount(this.data.id) <= 0) {
                    this.spriteNew.visible = true;
                    if (!this.effNew) {
                        this.add3DEffectAtFront("117_ui_loop_newparticl_01", this.spriteEff, 0, 1, (model) => {
                            this.effNew = model;
                        });
                    }
                    this.spriteEff.visible = true;
                }
                else {
                    this.spriteNew.visible = false;
                    this.spriteEff.visible = false;
                }
            }
            onTouchButtonRole() {
                if (this.data.fOnClick) {
                    this.data.fOnClick(this.data.id, this.boxAd.visible);
                }
            }
        }

        class vRoomDesignPart extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vRoomDesignPart";
                this.exportNodeNames = [];
                this.size(90, 96);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                this.registerListeners({
                    MSG_ROOM_PART_REFRESH: this.onMsgRoomPartRefresh.bind(this),
                });
                Tools.registerTouchHander(this.spriteEaseTrigger, (e) => {
                    if (e.isBegin) {
                        this.onTouchButtonBg();
                    }
                });
            }
            onClosed() {
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag2"];
            }
            onMsgRoomPartRefresh() {
                this.data && this.fillByData(this.data);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let shopData = mgrCfg.get_from_shop_template_db(this.data.id);
                let icon = mgrPlayer.getIcon(this.data.id);
                Tools.loadImg(this.imageIcon, icon);
                this.spriteDressed.visible = false;
                this.spriteSelect.visible = this.data.fIsSelected(this.data.id);
                let bRecommend = this.data.fIsRecommend && this.data.fIsRecommend(this.data.id) ? true : false;
                this.spriteRecommendBg.visible = bRecommend;
                this.spriteRecommend.visible = bRecommend;
                this.spriteCoin.visible = (mgrPlayer.getItemAmount(this.data.id) <= 0 && !!shopData && shopData.price > 0) ? true : false;
                if (!!shopData) {
                    this.labelPrice.text = `${shopData.price}`;
                }
                let bShowTrialText = mgrSdk.getCopNumberValueByKey("b_hide_trail_text") == 0 ? true : false;
                this.imageTrial.visible = !!bShowTrialText;
                this.imageTrialNoText.visible = !this.imageTrial.visible;
                let bTrying = this.data.fIsTry(this.data.id);
                this.spriteTrialContainer.visible = false;
                this.spriteEaseTrigger.visible = false;
                if (!this.spriteCoin.visible && mgrPlayer.getItemAmount(this.data.id) <= 0 && !bTrying) {
                    this.spriteTrialContainer.visible = !!this.data.bAd;
                    if (this.spriteTrialContainer.visible) {
                    }
                    let b_trail_easy_trigger = mgrSdk.getCopNumberValueByKey("b_trail_easy_trigger") == 1 ? true : false;
                    this.spriteEaseTrigger.visible = !!b_trail_easy_trigger;
                }
            }
            onTouchButtonBg() {
                this.data && this.data.fOnClickItem(this.data.id, this.data.tab, (this.spriteTrialContainer.visible || this.spriteCoin.visible) ? true : false);
                mgrPart.deleteNewPart(this.data.id);
            }
        }

        class vSuitTypeListItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vSuitTypeListItem";
                this.bAnim = true;
                this.size(506, 228);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                Timer.callLoop(2, () => {
                    if (!!this.data) {
                        mgrTip.showBadgeWithNumber(this.spriteType, mgrPart.getBadgeCountByCategory(this.data.id), new Laya.Point(10, 28));
                    }
                }, this);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                if (this.bAnim && mgrSdk.getCopNumberValueByKey("b_disable_ui_enter_effect") != 1) {
                    this.bAnim = false;
                    let delayTime = 0;
                    let timeGap = 0.3;
                    this.spriteType.alpha = 0;
                    this.spriteType["_originPos"] = new Laya.Vector2(this.spriteType.x, this.spriteType.y);
                    this.spriteType.y += (300 + 100 * this.data.id);
                    cc.tween(this.spriteType)
                        .delay(delayTime)
                        .parallel(cc.tween().toAlpha(0.8, 1), cc.tween().toPos(1, this.spriteType["_originPos"].x, this.spriteType["_originPos"].y, cc.Ease.backOut))
                        .start();
                    cc.tween(this.spriteBox)
                        .delay(2.4)
                        .to(0.3, { scaleX: 1, scaleY: 1 }, cc.Ease.backOut)
                        .start();
                }
                let id = data.id;
                let categoryData = mgrCfg.get_from_suit_type_db(this.data.id);
                let bHandwork = categoryData.bHandwork;
                let progressPos = categoryData.progressPos;
                let fontColor = categoryData.fontColor;
                let icon = categoryData.icon;
                let [cur, max] = [0, 1];
                if (bHandwork) {
                    [cur, max] = [mgrDesign.getDesignPartCount(), 12];
                }
                else {
                    [cur, max] = mgrPart.getSuitsProgressByCategoryId(id);
                }
                this.progressBar.barName = this.progressBar.__node.name;
                this.progressBar.style = ULPROGRESSBAR_STYLE.ver;
                this.labelProgress.text = `${Math.floor((cur / max) * 100)}%`;
                this.progressBar.progress = cur / max;
                mgrTip.showBadgeWithNumber(this.spriteType, mgrPart.getBadgeCountByCategory(data.id), new Laya.Point(10, 28));
                Tools.loadImg(this.spriteType, icon);
                this.spriteBox.visible = true;
                this.spriteBox.pos(progressPos[0], progressPos[1]);
                this.labelFontColor.strokeColor = fontColor;
            }
            onClosed() {
            }
            onTouchButtonBg() {
                if (this.data.fOnClick) {
                    this.data.fOnClick(this.data.id);
                }
            }
        }

        class vWarpSceneNode extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vWarpSceneNode";
                this.exportNodeNames = [];
            }
            onOpened() {
                Tools.registerTouchHander(this, () => {
                    console.log("切屏中，拦截点击事件");
                });
                cc.tween(this.spriteDown)
                    .repeatForever(cc.tween().byRotation(0.3, 15).byRotation(0.6, -30).byRotation(0.3, 15))
                    .start();
                this.spriteMinute.rotation = Tools.random(360);
                this.spriteSecond.rotation = this.spriteMinute.rotation - Tools.random(150);
                cc.tween(this.spriteMinute)
                    .repeatForever(cc.tween().byRotation(3, 180))
                    .start();
                cc.tween(this.spriteSecond)
                    .repeatForever(cc.tween().byRotation(1.5, 180))
                    .start();
            }
            onClosed() {
            }
            playCloseAnimation(callback, force = false) {
                if (this.bPlayingClose && !force)
                    return;
                this.bPlayingClose = true;
                this.visible = true;
                this.closeCallback = callback;
                Timer.callLater(0.3, () => {
                    this.closeCallback && this.closeCallback();
                    this.bPlayingClose = false;
                }, this);
            }
            playOpenAnimation(callback) {
                callback && callback();
                this.visible = false;
            }
        }

        class vWarpSceneNodeWhite extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vWarpSceneNodeWhite";
                this.exportNodeNames = [];
            }
            onOpened() {
                if (!!this.context.bBlackWarp) {
                    let texture2d = Laya.Texture2D.blackTexture;
                    texture2d.width = 768;
                    texture2d.height = 1280;
                    let texture = new Laya.Texture(texture2d, undefined, 768, 1280);
                    this.spriteBg.graphics.drawTexture(texture);
                    this.spriteBg.texture = new Laya.Texture(Laya.Texture2D.blackTexture, undefined, 768, 1280);
                }
                Tools.registerTouchHander(this.spriteBg, () => {
                    console.log("切屏中，拦截点击事件");
                });
                if (this.bPlayingClose) {
                    this.playCloseAnimation(this.closeCallback.bind(this), true);
                }
            }
            onClosed() {
            }
            playCloseAnimation(callback, force = false) {
                if (this.bPlayingClose && !force)
                    return;
                this.bPlayingClose = true;
                this.closeCallback = callback;
                if (!this.bResLoaded)
                    return;
                this.spriteBg.alpha = 0;
                cc.tween(this.spriteBg).toAlpha(0.3, 1).call(() => {
                    this.bPlayingClose = false;
                    this.closeCallback && this.closeCallback();
                }).start();
            }
            playOpenAnimation(callback) {
                this.spriteBg.alpha = 1;
                cc.tween(this.spriteBg).delay(0.1).toAlpha(0.3, 0).call(() => {
                    Timer.callLater(0.016, () => {
                        callback && callback();
                    }, this);
                }).start();
            }
        }

        class vWorldDailyGameItem extends ViewBase {
            constructor(context) {
                super(context);
                this.sourceName = "node/vWorldDailyGameItem";
                this.exportNodeNames = [];
                this.size(140, 180);
                this.anchorX = 0;
                this.anchorY = 0;
            }
            onOpened() {
                super.onOpened();
                this.data && this.fillByData(this.data);
                this.registerListeners({
                    MSG_ROOM_PART_REFRESH: this.onMsgRoomPartRefresh.bind(this),
                });
            }
            onClosed() {
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag2"];
            }
            onMsgRoomPartRefresh() {
                this.data && this.fillByData(this.data);
            }
            fillByData(data) {
                this.data = data;
                if (!this.bResLoaded)
                    return;
                let worldDay = mgrWorldDaily.getWorldDay();
                let template = mgrCfg.get_from_world_game_db(this.data.id);
                let rewardCount = 0;
                this.spriteNewFlag.visible = template.id == DailyGameType.parkour ? true : false;
                if (this.spriteNewFlag.visible) {
                    mgrEffect.shineNode(this.spriteNewFlag);
                }
                else {
                    mgrEffect.stopShineNode(this.spriteNewFlag);
                }
                this.spriteMidAutumnFlag.visible = mgrMidAutumn.isEnable() && mgrMidAutumn.isMidAutumnSystem(template.id);
                switch (template.id) {
                    case DailyGameType.cake: {
                        let config = mgrCfg.get_from_cake_daily_quest_config(worldDay);
                        rewardCount = config.rewardItemAmount;
                        break;
                    }
                    case DailyGameType.pen: {
                        let config = mgrCfg.get_from_pen_daily_quest_config(worldDay);
                        rewardCount = config.rewardItemAmount;
                        break;
                    }
                    case DailyGameType.cloth: {
                        let config = mgrCfg.get_from_cloth_daily_quest_config(worldDay);
                        rewardCount = config.rewardItemAmount;
                        break;
                    }
                    case DailyGameType.custom_made: {
                        let config = mgrCfg.get_from_custom_made_cloth_daily_quest_config(worldDay);
                        rewardCount = config.rewardItemAmount;
                        break;
                    }
                    case DailyGameType.parkour: {
                        let config = mgrCfg.get_from_parkour_daily_quest_config(worldDay);
                        rewardCount = config.rewardItemAmount;
                        break;
                    }
                    case DailyGameType.clothcrossing: {
                        let config = mgrCfg.get_from_cloth_crossing_daily_quest_config(worldDay);
                        rewardCount = config.rewardItemAmount;
                        break;
                    }
                    case DailyGameType.dailyTurntable: {
                    }
                    case DailyGameType.dailyFightEvent: {
                    }
                    default:
                        break;
                }
                this.spriteWarnContainer.visible = template.id == DailyGameType.dailyFightEvent ? true : false;
                this.spriteDailyReward.visible = template.id == (DailyGameType.dailyTurntable || DailyGameType.dailyFightEvent) ? false : true;
                this.imageIcon.visible = !this.spriteWarnContainer.visible;
                if (template.id == DailyGameType.dailyTurntable) {
                    this.imageIcon.size(161, 165);
                    this.imageIcon.y = 85;
                }
                else {
                    this.imageIcon.size(139, 149);
                    this.imageIcon.y = 75;
                }
                if (template.id == DailyGameType.dailyFightEvent) {
                    let worldDay = mgrWorldDaily.getWorldDay();
                    if (!mgrWorldDaily.isCardFightedDay(worldDay)) {
                        let template = mgrCfg.get_from_world_daily_quest(worldDay);
                        let warnCardStageData = mgrCfg.get_from_amaze_card_stage_db(template.cardFightStageId);
                        let bossNpcData = null;
                        let npcIdArr = warnCardStageData.npcIdArr || [];
                        for (let k in npcIdArr) {
                            let npcId = npcIdArr[k];
                            let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                            if (!npcData) {
                                continue;
                            }
                            bossNpcData = npcData;
                            break;
                        }
                        Tools.loadImg(this.spriteWarnNpcImg, bossNpcData.imgWarn);
                    }
                }
                else {
                    Tools.loadImg(this.imageIcon, template.icon);
                }
                this.labelPointNum.text = `+${rewardCount}`;
                this.spriteTrialContainer.visible = false;
            }
            getDailyIconWorldPos() {
                return this.spriteDailyIcon.parent.localToGlobal(new Laya.Point(this.spriteDailyIcon.x, this.spriteDailyIcon.y));
            }
            onTouchButtonBg() {
                this.data && this.data.fOnClick(this.data.id);
                mgrPart.deleteNewPart(this.data.id);
            }
        }

        class OffScreenRender extends Laya.Sprite3D {
            constructor() {
                super();
                this.quadPool = [];
                this.usingQuad = [];
                this.init();
            }
            init() {
                this.camera = new Laya.Camera;
                this.addChild(this.camera);
                this.camera.transform.localPositionZ = 1;
                this.camera.renderingOrder = 2;
                this.camera.orthographic = true;
                this.camera.nearPlane = 0.01;
                this.camera.farPlane = 10000;
                this.camera.aspectRatio = 1;
                this.camera.orthographicVerticalSize = 10;
                this.transform.position = new Laya.Vector3(10);
                this.setCulling(5);
                this.oldRender = this.camera.render.bind(this.camera);
                this.camera.render = () => { };
                this.enableIncrementDraw();
            }
            enableIncrementDraw() {
                this.camera.clearFlag = Laya.CameraClearFlags.Nothing;
                this.enableAddDraw();
            }
            enableRealTimeDraw() {
                this.camera.clearFlag = Laya.CameraClearFlags.SolidColor;
                this.camera.clearColor = new Laya.Vector4;
                this.enableNormalDraw();
            }
            setCulling(layer) {
                this.cullingLayer = layer;
                this.camera.cullingMask = 0;
                this.camera.cullingMask = this.camera.cullingMask | Math.pow(2, layer);
            }
            enableAddDraw() {
                this.curRenderMode = NormalMaterial.RENDERMODE_TRANSPARENT_BLEND_ADD;
            }
            enableNormalDraw() {
                this.curRenderMode = NormalMaterial.RENDERMODE_TRANSPARENT;
            }
            getQuadFromPool() {
                if (this.quadPool.length == 0) {
                    if (!this.quadMesh)
                        this.quadMesh = Laya.PrimitiveMesh.createQuad(1, 1);
                    let quad = new Laya.MeshSprite3D(this.quadMesh);
                    quad.layer = this.cullingLayer;
                    return quad;
                }
                return this.quadPool.shift();
            }
            recoverQuad(quad) {
                quad.removeSelf();
                this.recoverMaterial(quad.meshRenderer.sharedMaterial);
                this.quadPool.push(quad);
            }
            getMaterialFromPool(classObj, bNotReuse) {
                if (!this.materialPool)
                    this.materialPool = {};
                if (this.materialPool[classObj.name] == null)
                    this.materialPool[classObj.name] = [];
                if (this.materialPool[classObj.name].length == 0) {
                    let material = new classObj;
                    return material;
                }
                if (bNotReuse) {
                    let material = new classObj;
                    return material;
                }
                else {
                    let mat = this.materialPool[classObj.name].shift();
                    mat[`_bRecover_`] = false;
                    return mat;
                }
            }
            recoverMaterial(material) {
                if (material[`_bRecover_`])
                    return;
                material[`_bRecover_`] = true;
                let className = material.constructor.name;
                this.materialPool[className].push(material);
            }
            destroy() {
                for (let i = 0; i < this.quadPool.length; i++) {
                    const element = this.quadPool[i];
                    element.destroy();
                }
                super.destroy();
            }
            recoverAllUsingQuad() {
                for (let i = 0; i < this.usingQuad.length; i++) {
                    const element = this.usingQuad[i];
                    this.recoverQuad(element);
                }
                this.usingQuad = [];
            }
            draw(drawObj, renderTarget) {
                this.drawSprites([drawObj], renderTarget);
            }
            drawSprites(drawObjs, renderTarget, bShareMaterial = false) {
                this.camera.renderTarget = renderTarget;
                if (!this.camera.renderTarget)
                    return;
                let sharedMat = null;
                if (bShareMaterial) {
                    sharedMat = this.getMaterialFromPool(NormalMaterial);
                }
                for (let i = 0; i < drawObjs.length; i++) {
                    const drawObj = drawObjs[i];
                    this.createQuadWithDrawObj(drawObj, sharedMat);
                }
                this.oldRender();
                this.recoverAllUsingQuad();
            }
            createQuadWithDrawObj(drawObj, sharedMat) {
                let quad = this.getQuadFromPool();
                quad.transform.localPositionZ = drawObj.sprite.zOrder - 1001 || -1;
                let scaleX = drawObj.sprite.width / this.camera.renderTarget.width * drawObj.sprite.scaleX * this.camera.orthographicVerticalSize;
                let scaleY = drawObj.sprite.height / this.camera.renderTarget.height * drawObj.sprite.scaleY * this.camera.orthographicVerticalSize;
                quad.transform.localScaleX = scaleX;
                quad.transform.localScaleY = scaleY;
                let posX = (-0.5 + drawObj.offsetX / this.camera.renderTarget.width) * this.camera.orthographicVerticalSize;
                let posY = (0.5 - drawObj.offsetY / this.camera.renderTarget.height) * this.camera.orthographicVerticalSize;
                quad.transform.localPositionX = posX;
                quad.transform.localPositionY = posY;
                quad.transform.localRotationEulerZ = -drawObj.sprite.rotation;
                if (!drawObj.shaderClass) {
                    let material = sharedMat || this.getMaterialFromPool(NormalMaterial);
                    material.renderMode = this.curRenderMode;
                    material.albedoTexture = drawObj.sprite.texture.bitmap;
                    material.alpha = drawObj.sprite.alpha;
                    quad.meshRenderer.sharedMaterial = material;
                }
                else {
                    let material = this.getMaterialFromPool(drawObj.shaderClass, drawObj.shaderParam.bNotReuse);
                    for (const k in drawObj.shaderParam) {
                        let param = drawObj.shaderParam[k];
                        if (param) {
                            material[k] = param;
                        }
                    }
                    material.alpha && (material.alpha = drawObj.sprite.alpha);
                    quad.meshRenderer.sharedMaterial = material;
                }
                this.addChild(quad);
                this.usingQuad.push(quad);
            }
        }

        class PaintBrush extends Laya.Sprite3D {
            constructor() {
                super();
                this.brushPools = {};
                this.bInitedBrush = false;
                this.bRealTimeRender = false;
                this.drawObjs = [];
                this.bRecorderPersent = true;
                this.initPaintContext();
                this.initPaintBrush();
                Timer.callLoop(0.032, this.update.bind(this), this);
            }
            initPaintContext() {
                this.offScreenRender = new OffScreenRender;
                this.addChild(this.offScreenRender);
            }
            initPaintBrush() {
                this.clearBrush = PaintBrush.createClearBrush(2, 2);
                this.whiteBrush = PaintBrush.createWhiteBrush(2, 2);
                this.setCurBrushFlowRate(1);
                this.bInitedBrush = true;
            }
            destroy() {
                this.curBrush = null;
                this.offScreenRender.destroy();
                super.destroy();
            }
            setbrush(key, url, width, height, callback) {
                if (this.brushPools[key]) {
                    this.curBrush = this.brushPools[key];
                    this.curBrush.width = width || this.curBrush.width;
                    this.curBrush.height = height || this.curBrush.height;
                    callback && callback();
                    return;
                }
                mgrLoader.Load2dRes(url, Laya.Loader.IMAGE, this, (res) => {
                    let sprite = new Laya.Sprite;
                    sprite.width = width || res.width;
                    sprite.height = height || res.height;
                    sprite.texture = res;
                    res.bitmap.lock = true;
                    this.brushPools[key] = sprite;
                    sprite[`url`] = url;
                    sprite[`key`] = key;
                    this.curBrush = sprite;
                    callback && callback();
                });
            }
            setBrushSprite(sprite) {
                this.curBrush = sprite;
            }
            modifyCurBrushSize(width, height) {
                if (!this.curBrush)
                    return;
                this.curBrush.width = width;
                this.curBrush.height = height;
            }
            randomRotateBrush() {
                if (!this.curBrush)
                    return;
                this.curBrush.rotation = Tools.random(0, 360);
            }
            setCurBrushFlowRate(rate) {
                rate = ul.clamp(rate, 0, 1);
                this.curFlowRate = rate;
            }
            draw(uv, bRandomOffset = false) {
                if (!this.bInitedBrush)
                    return;
                if (!this.curBrush)
                    return;
                if (!this.paintCavas)
                    return;
                if (this.destroyed)
                    return;
                if (!this.scene)
                    return;
                this.curBrush.alpha = this.curFlowRate;
                let ofx = bRandomOffset ? Math.random() * 4 - 2 : 0;
                let ofy = bRandomOffset ? Math.random() * 4 - 2 : 0;
                this.offScreenRender.draw({
                    sprite: this.curBrush,
                    offsetX: uv.x * this.paintCavas.width + ofx,
                    offsetY: uv.y * this.paintCavas.height + ofy,
                }, this.paintCavas);
                this.bRecorderPersent && this.paintCavas.updateDrawState(this.curBrush, this.curFlowRate, uv);
            }
            drawUvs(uvs) {
                if (!this.bInitedBrush)
                    return;
                if (!this.curBrush)
                    return;
                if (!this.paintCavas)
                    return;
                if (this.destroyed)
                    return;
                if (!this.scene)
                    return;
                this.curBrush.alpha = this.curFlowRate;
                let offobjs = [];
                for (let i = 0; i < uvs.length; i++) {
                    const uv = uvs[i];
                    offobjs.push({
                        sprite: this.curBrush,
                        offsetX: uv.x * this.paintCavas.width,
                        offsetY: uv.y * this.paintCavas.height,
                    });
                    this.bRecorderPersent && this.paintCavas.updateDrawState(this.curBrush, this.curFlowRate, uv);
                }
                this.offScreenRender.drawSprites(offobjs, this.paintCavas, true);
            }
            drawCavas(uv, cavas) {
                if (!this.paintCavas)
                    return;
                if (this.destroyed)
                    return;
                if (!this.scene)
                    return;
                let sprite = new Laya.Sprite;
                sprite.size(cavas.width, cavas.height);
                let drawObj = {
                    sprite: sprite,
                    offsetX: uv.x * this.paintCavas.width,
                    offsetY: uv.y * this.paintCavas.height,
                    shaderClass: NormalMaterial,
                    shaderParam: {
                        renderMode: NormalMaterial.RENDERMODE_TRANSPARENT,
                        albedoTexture: cavas,
                    }
                };
                this.offScreenRender.enableRealTimeDraw();
                this.offScreenRender.draw(drawObj, this.paintCavas);
                !this.bRealTimeRender && this.offScreenRender.enableIncrementDraw();
            }
            drawSetedObjects() {
                if (!this.paintCavas)
                    return;
                if (this.destroyed)
                    return;
                if (!this.scene)
                    return;
                this.offScreenRender.drawSprites(this.drawObjs, this.paintCavas);
            }
            reset(cavas) {
                this.clearBrush.width = cavas.width;
                this.clearBrush.height = cavas.height;
                this.offScreenRender.enableRealTimeDraw();
                this.offScreenRender.draw({
                    sprite: this.clearBrush,
                    offsetX: cavas.width / 2,
                    offsetY: cavas.height / 2,
                }, cavas);
                !this.bRealTimeRender && this.offScreenRender.enableIncrementDraw();
            }
            static reset(cavas, offrender) {
                let clearBrush = this.createClearBrush(cavas.width, cavas.height);
                offrender.enableRealTimeDraw();
                offrender.draw({
                    sprite: clearBrush,
                    offsetX: cavas.width / 2,
                    offsetY: cavas.height / 2,
                }, cavas);
            }
            resetWidthWhite(cavas) {
                this.whiteBrush.width = cavas.width;
                this.whiteBrush.height = cavas.height;
                this.offScreenRender.enableRealTimeDraw();
                this.offScreenRender.draw({
                    sprite: this.whiteBrush,
                    offsetX: cavas.width / 2,
                    offsetY: cavas.height / 2,
                }, cavas);
                !this.bRealTimeRender && this.offScreenRender.enableIncrementDraw();
            }
            fullWithRGB(cavas, r, g, b, bRealTime) {
                let brush = PaintBrush.createColorBrush(cavas.width, cavas.height, r, g, b);
                this.offScreenRender.enableRealTimeDraw();
                this.offScreenRender.draw({
                    sprite: brush,
                    offsetX: cavas.width / 2,
                    offsetY: cavas.height / 2,
                }, cavas);
                !!bRealTime && this.offScreenRender.enableIncrementDraw();
            }
            fullWithTexture2D(cavas, tex2d) {
                let texture = new Laya.Texture(tex2d);
                let brush = new Laya.Sprite;
                brush.size(cavas.width, cavas.height);
                brush.texture = texture;
                this.offScreenRender.draw({
                    sprite: brush,
                    offsetX: cavas.width / 2,
                    offsetY: cavas.height / 2,
                }, cavas);
            }
            enableRealTimeRender() {
                this.offScreenRender.enableRealTimeDraw();
                this.bRealTimeRender = true;
            }
            setDrawObjs(drawObjs) {
                this.drawObjs = drawObjs;
            }
            disableRealTimerRender() {
                this.offScreenRender.enableIncrementDraw();
                this.bRealTimeRender = false;
            }
            update() {
                if (!this.bRealTimeRender)
                    return;
                if (!this.paintCavas)
                    return;
                if (this.destroyed)
                    return;
                if (!this.scene)
                    return;
                this.offScreenRender.drawSprites(this.drawObjs, this.paintCavas);
            }
            static createPureColorTexture(color) {
                let pixels = new Uint8Array(16);
                for (let i = 0; i < 4; i++) {
                    pixels[i * 4 + 0] = color.r * 255;
                    pixels[i * 4 + 1] = color.g * 255;
                    pixels[i * 4 + 2] = color.b * 255;
                    pixels[i * 4 + 3] = color.a * 255;
                }
                let tex2d = new Laya.Texture2D(2, 2, Laya.TextureFormat.R8G8B8A8);
                tex2d.setPixels(pixels);
                let texture = new Laya.Texture(tex2d);
                return texture;
            }
            static createClearBrush(width, height) {
                let pixels = new Uint8Array(16);
                for (let i = 0; i < 4; i++) {
                    pixels[i * 4 + 0] = 0;
                    pixels[i * 4 + 1] = 0;
                    pixels[i * 4 + 2] = 0;
                    pixels[i * 4 + 3] = 0;
                }
                let tex2d = new Laya.Texture2D(2, 2, Laya.TextureFormat.R8G8B8A8);
                tex2d.setPixels(pixels);
                let texture = new Laya.Texture(tex2d);
                let sprite = new Laya.Sprite;
                sprite.size(width, height);
                sprite.texture = texture;
                return sprite;
            }
            static createWhiteBrush(width, height) {
                let pixels = new Uint8Array(16);
                for (let i = 0; i < 4; i++) {
                    pixels[i * 4 + 0] = 255;
                    pixels[i * 4 + 1] = 255;
                    pixels[i * 4 + 2] = 255;
                    pixels[i * 4 + 3] = 255;
                }
                let tex2d = new Laya.Texture2D(2, 2, Laya.TextureFormat.R8G8B8A8);
                tex2d.setPixels(pixels);
                let texture = new Laya.Texture(tex2d);
                let sprite = new Laya.Sprite;
                sprite.size(width, height);
                sprite.texture = texture;
                return sprite;
            }
            static createColorBrush(width, height, r, g, b) {
                let pixels = new Uint8Array(16);
                for (let i = 0; i < 4; i++) {
                    pixels[i * 4 + 0] = Math.floor(r);
                    pixels[i * 4 + 1] = Math.floor(g);
                    pixels[i * 4 + 2] = Math.floor(b);
                    pixels[i * 4 + 3] = 255;
                }
                let tex2d = new Laya.Texture2D(2, 2, Laya.TextureFormat.R8G8B8A8);
                tex2d.setPixels(pixels);
                let texture = new Laya.Texture(tex2d);
                let sprite = new Laya.Sprite;
                sprite.size(width, height);
                sprite.texture = texture;
                return sprite;
            }
        }

        class PaintCavas extends Laya.RenderTexture {
            constructor(...args) {
                super(args[0], args[1], args[2], args[3]);
                this.uvStates = [];
                this.drawHistorys = [];
                this.initDrawState([{
                        startUv: new Laya.Vector2(0, 0),
                        endUv: new Laya.Vector2(1, 1),
                    }], 5);
            }
            initDrawState(uvBounds, splicSize) {
                for (let i = 0; i < uvBounds.length; i++) {
                    const element = uvBounds[i];
                    let uvBound = {
                        startUv: element.startUv.clone(),
                        endUv: element.endUv.clone(),
                    };
                    uvBound.startUv.x = Math.floor(uvBound.startUv.x * this.width);
                    uvBound.startUv.y = Math.floor(uvBound.startUv.y * this.height);
                    uvBound.endUv.x = Math.floor(uvBound.endUv.x * this.width);
                    uvBound.endUv.y = Math.floor(uvBound.endUv.y * this.height);
                    this.uvStates.push({
                        uvBound: uvBound,
                        size: splicSize,
                        uvState: {},
                        persent: 0,
                        width: Math.ceil((uvBound.endUv.x - uvBound.startUv.x) / splicSize),
                        height: Math.ceil((uvBound.endUv.y - uvBound.startUv.y) / splicSize),
                    });
                }
            }
            getDrawPersent() {
                let totalBlock = 0;
                let curBlock = 0;
                for (let i = 0; i < this.uvStates.length; i++) {
                    const element = this.uvStates[i];
                    let width = element.width;
                    let height = element.height;
                    totalBlock += width * height;
                    curBlock += element.persent;
                }
                return curBlock / totalBlock;
            }
            updateDrawState(brush, flowRate, uv) {
                let startX = uv.x * this.width - brush.width / 2;
                let startY = uv.y * this.height - brush.width / 2;
                let endX = uv.x * this.width + brush.width / 2;
                let endY = uv.y * this.height + brush.width / 2;
                for (let i = 0; i < this.uvStates.length; i++) {
                    const element = this.uvStates[i];
                    let newStartX = Math.max(startX, element.uvBound.startUv.x) - element.uvBound.startUv.x;
                    let newStartY = Math.max(startY, element.uvBound.startUv.y) - element.uvBound.startUv.y;
                    let newEndX = Math.min(endX, element.uvBound.endUv.x) - element.uvBound.startUv.x;
                    let newEndY = Math.min(endY, element.uvBound.endUv.y) - element.uvBound.startUv.y;
                    let mapStartX = Math.ceil(newStartX / element.size);
                    let mapStartY = Math.ceil(newStartY / element.size);
                    let mapEndX = Math.ceil(newEndX / element.size);
                    let mapEndY = Math.ceil(newEndY / element.size);
                    for (let indexX = mapStartX; indexX <= mapEndX; indexX++) {
                        for (let indexY = mapStartY; indexY <= mapEndY; indexY++) {
                            let mapIndex = indexY * element.width + indexX;
                            if (!element.uvState[mapIndex])
                                element.uvState[mapIndex] = 0;
                            let maxDelta = 1 - element.uvState[mapIndex];
                            let delta = Math.min(flowRate, maxDelta);
                            element.uvState[mapIndex] += delta;
                            element.persent += delta;
                            this.recordDrawHistory({
                                index: mapIndex,
                                url: brush.texture.url,
                                flowRate: flowRate,
                                width: brush.width,
                                height: brush.height,
                            });
                        }
                    }
                }
            }
            recordDrawHistory(history) {
                let oldHistoryIndex = -1;
                for (let i = 0; i < this.drawHistorys.length; i++) {
                    const element = this.drawHistorys[i];
                    if (element.index == history.index) {
                        oldHistoryIndex = i;
                        break;
                    }
                }
                if (oldHistoryIndex >= 0) {
                    this.drawHistorys.splice(oldHistoryIndex, 1);
                    this.drawHistorys.push(history);
                    return;
                }
                if (this.drawHistorys.length > 100) {
                    this.drawHistorys.shift();
                }
                this.drawHistorys.push(history);
            }
            getDrawHistory() {
                return Tools.deepCopy(this.drawHistorys);
            }
            updateState(brush, flowRate, uv) {
                this.updateDrawState(brush, flowRate, uv);
            }
            static createCavas(width = 256, height = 256) {
                let cavas = PaintCavas.getFromPool(width, height);
                cavas.width = width;
                cavas.height = height;
                cavas.lock = true;
                return cavas;
            }
            static createWhiteCavas(brush, width = 256, height = 256) {
                let cavas = PaintCavas.getFromPool(width, height);
                cavas.width = width;
                cavas.height = height;
                cavas.lock = true;
                brush.resetWidthWhite(cavas);
                return cavas;
            }
            static getFromPool(width, height) {
                let key = `${width}_${height}`;
                if (!this.cavasPool[key])
                    this.cavasPool[key] = [];
                let pool = this.cavasPool[key];
                if (pool.length == 0) {
                    let cavas = new PaintCavas(width, height, Laya.TextureFormat.R8G8B8A8);
                    cavas.lock = true;
                    return cavas;
                }
                return pool.shift();
            }
            static recoverCavas(cavas) {
                let width = cavas.width;
                let height = cavas.height;
                let key = `${width}_${height}`;
                if (!this.cavasPool[key])
                    this.cavasPool[key] = [];
                let pool = this.cavasPool[key];
                pool.push(cavas);
            }
        }
        PaintCavas.cavasPool = {};

        class CakeCreamScriptHorzontal {
            constructor(parasitifer) {
                this._calculateMeshScaleFunc = (startScaleplateValue, currScaleplateValue, originMeshPosY, perGap) => {
                    perGap = perGap || this.parasitifer.SCALEPLATE_2_NORMAL_DIS;
                    let scale = -1;
                    let dis = Math.max(0.00001, currScaleplateValue - startScaleplateValue);
                    if (dis <= perGap * 2) {
                        let func = null;
                        scale = (originMeshPosY - startScaleplateValue) / (dis / 2);
                        if (func <= 1) {
                            func = this.cubicOut;
                        }
                        else {
                            func = this.cubicOut;
                        }
                        scale = scale <= 1 ? scale : 2 - scale;
                        let tmpMaxScale = Math.min(1.0, dis / 2 / perGap);
                        scale = scale * tmpMaxScale;
                        scale = func(scale);
                    }
                    else {
                        scale = (originMeshPosY - startScaleplateValue) / perGap;
                        if (scale > 1) {
                            scale = (currScaleplateValue - originMeshPosY) / perGap;
                            scale = (scale <= 1 && scale >= 0) ? scale : 1;
                            scale = this.cubicOut(scale);
                        }
                        else {
                            scale = this.cubicOut(scale);
                        }
                    }
                    return scale;
                };
                this.parasitifer = parasitifer;
            }
            initCreamModel() {
                let modelTeamplateDict = {};
                this.parasitifer.creamModelInfoArr = this.parasitifer.creamModelInfoArr || [];
                let creamArr = this.parasitifer.stageData.creamArr || [];
                for (let i = 0; i < creamArr.length; i++) {
                    let creamData = creamArr[i];
                    if (creamData.creamType != CreamType.horzontal) {
                        continue;
                    }
                    let posY = creamData.creamPos;
                    let modelName = creamData.modelName;
                    if (!modelTeamplateDict[modelName]) {
                        let tmpModel = mgrLoader.Pool.getModel(modelName);
                        mgrMaterial.setCustomMaterial(tmpModel, modelName);
                        modelTeamplateDict[modelName] = tmpModel;
                    }
                    let templateModel = modelTeamplateDict[modelName];
                    let sharedMaterials = templateModel.getChildAt(0).meshRenderer.sharedMaterials;
                    let creamModel = new Laya.Sprite3D;
                    creamModel.name = templateModel.name;
                    let child = new Laya.MeshSprite3D(templateModel.getChildAt(0).meshFilter.sharedMesh.clone(), templateModel.getChildAt(0).name);
                    creamModel.addChild(child);
                    let materialArr = [];
                    let materialCount = sharedMaterials.length;
                    for (let matIndex = 0; matIndex < materialCount; matIndex++) {
                        let matOld = sharedMaterials[matIndex];
                        let mat = new Laya.UnlitMaterial();
                        mat.albedoTexture = matOld.albedoTexture;
                        materialArr.push(mat);
                    }
                    child.meshRenderer.sharedMaterials = materialArr;
                    creamModel["__modelId"] = modelName;
                    mgrMaterial.setCustomMaterial(creamModel, modelName);
                    this.parasitifer.avatar.addChild(creamModel);
                    let modelData = this.parasitifer.getModelMeshData(creamModel);
                    modelData.creamType = creamData.creamType;
                    modelData.creamIndex = creamData.creamIndex;
                    this.parasitifer.creamModelInfoArr.push(modelData);
                }
                for (let k in modelTeamplateDict) {
                    mgrLoader.Pool.recoverModel(modelTeamplateDict[k]);
                }
            }
            adaptCreamPosition() {
                let creamArr = this.parasitifer.stageData.creamArr || [];
                for (let i = 0; i < creamArr.length; i++) {
                    let creamData = creamArr[i];
                    if (creamData.creamType != CreamType.horzontal) {
                        continue;
                    }
                    let posY = creamData.creamPos;
                    let relateCaleROfY = this.parasitifer.getGoodCakeRByPosY(posY) + creamData.offsetR;
                    let creamModelInfo = this.parasitifer.creamModelInfoArr[i];
                    creamModelInfo.modelArr[0].transform.localPositionY = posY;
                    creamModelInfo.modelArr[0].transform.localPositionZ = relateCaleROfY;
                    creamModelInfo.modelArr[0].transform.localRotationEulerZ = -90;
                    creamModelInfo.creamCakeR = relateCaleROfY;
                }
            }
            preHandleCreamShape() {
                let rotateModelMeshY = (positionArr, rot) => {
                    let arr = [];
                    for (let i = 0; i < positionArr.length; i++) {
                        let posModel = positionArr[i];
                        let r = Math.sqrt(Math.abs(posModel.x * posModel.x) + Math.abs(posModel.z * posModel.z));
                        if (!r) {
                            arr.push(posModel);
                            continue;
                        }
                        let tmpCircleCenterPos = new Laya.Vector2(0, 0);
                        let oRot = Tools.getAngle(posModel.x, posModel.z);
                        let posBorder = Tools.getCircleBorderPosPoint(tmpCircleCenterPos, r, oRot + rot);
                        let cPos = new Laya.Vector3(posModel.x + posBorder.y, posModel.y, posModel.z + posBorder.x);
                        arr.push(cPos);
                    }
                    return arr;
                };
                for (let index = 0; index < this.parasitifer.creamModelInfoArr.length; index++) {
                    let creamData = this.parasitifer.creamModelInfoArr[index];
                    if (creamData.creamType != CreamType.horzontal) {
                        continue;
                    }
                    let stageCreamData = this.parasitifer.stageData.creamArr[index];
                    let rotatedPosArr = creamData.positionArr;
                    let r = creamData.creamCakeR;
                    let s = 2 * Math.PI * r;
                    let tmpCircleCenterPos = new Laya.Vector2(-r, 0);
                    let ampHalfValue = (stageCreamData.ampOffset || 0) / 2;
                    let ampSValue = s / (stageCreamData.ampCount || 10);
                    let handledPosArr = [];
                    let handledRPosArr = [];
                    for (let i = 0; i < rotatedPosArr.length; i++) {
                        let posModel = rotatedPosArr[i];
                        let useR = this.parasitifer.getGoodCakeRByPosY(creamData.modelArr[0].transform.localPositionY - posModel.x) + Math.abs(posModel.z);
                        let cl = Math.abs(posModel.y);
                        let rot = (cl / s) * 360;
                        let soffset = (ampSValue && ampHalfValue) ? Math.sin((cl % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue : 0;
                        let posBorder = Tools.getCircleBorderPosPoint(tmpCircleCenterPos, useR, rot);
                        let posBorderR = Tools.getCircleBorderPosPoint(tmpCircleCenterPos, r, rot);
                        handledRPosArr.push(new Laya.Vector3(soffset, posBorderR.y, posBorderR.x));
                        handledPosArr.push(new Laya.Vector3(posModel.x + soffset, posBorder.y, posBorder.x));
                    }
                    creamData.handledPosArr = handledPosArr;
                    creamData.handledRPosArr = handledRPosArr;
                    this.parasitifer.creamShowedScaleInfoArr[index] = new Array(handledRPosArr.length);
                    if (!!stageCreamData.bDefaultComplete) {
                        creamData.modelArr[0]["bDefaultComplete"] = true;
                        creamData.meshData["_setVerticeElementData"](Tools.deepCopy(handledPosArr), Laya.VertexMesh.MESH_POSITION0);
                        this.parasitifer.creamShowingPosArr[index] = Tools.deepCopy(handledPosArr);
                        for (let i = 0; i < handledRPosArr.length; i++) {
                            this.parasitifer.creamShowedScaleInfoArr[index][i] = 1;
                        }
                        if (!!stageCreamData.completeColorId) {
                            let doChangeColor = (render) => {
                                let colorData = mgrCfg.get_from_cake_cream_color_db(stageCreamData.completeColorId);
                                for (let k in render.sharedMaterials) {
                                    let mat = render.sharedMaterials[k];
                                    mat.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                }
                            };
                            let model = creamData.modelArr[0];
                            let render = Tools.getMeshRender(model);
                            if (!!render) {
                                doChangeColor(render);
                            }
                            else {
                                doChangeColor(Tools.getMeshRender(model.getChildAt(0)));
                            }
                        }
                    }
                    else {
                        creamData.modelArr[0]["bDefaultComplete"] = false;
                        creamData.meshData["_setVerticeElementData"](Tools.deepCopy(handledRPosArr), Laya.VertexMesh.MESH_POSITION0);
                        this.parasitifer.creamShowingPosArr[index] = Tools.deepCopy(handledRPosArr);
                    }
                }
            }
            tryGetCreamIndexByHitedPoint(point) {
                let minIndex = -1;
                let minDis = 9999;
                for (let i = 0; i < this.parasitifer.stageData.creamArr.length; i++) {
                    let creamData = this.parasitifer.stageData.creamArr[i];
                    if (creamData.creamType != CreamType.horzontal && creamData.creamType != CreamType.flowerHorzontal) {
                        continue;
                    }
                    let posY = creamData.creamPos;
                    if (Math.abs(point.y - posY) < minDis && Math.abs(point.y - posY) <= 0.1) {
                        minDis = Math.abs(point.y - posY);
                        minIndex = i;
                    }
                }
                return minIndex;
            }
            initDataWhenTouchedCream(point) {
                let creamData = this.parasitifer.creamModelInfoArr[this.parasitifer.operatingCreamIndex];
                if (creamData.creamType != CreamType.horzontal) {
                    return;
                }
                this.parasitifer.startScaleplateValue = this.getCreamScaleplate();
                this.parasitifer.startCakeRotatedYValue = this.parasitifer.cakeRotatedYValue;
            }
            getCreamScaleplate() {
                let creamData = this.parasitifer.creamModelInfoArr[this.parasitifer.operatingCreamIndex];
                let rot = this.parasitifer.avatar.transform.localRotationEulerY - this.parasitifer.currentCreamTouchOffsetRot;
                rot = rot <= 0 ? rot : rot - 360;
                let scalePlateValue = Math.abs(rot % 360) * Math.PI * creamData.creamCakeR / 180;
                return scalePlateValue;
            }
            inCream() {
            }
            exeCream() {
                if (!this.parasitifer.bTouchBg || this.parasitifer.operatingCreamIndex < 0) {
                    return;
                }
                let creamIndex = this.parasitifer.operatingCreamIndex;
                let creamData = this.parasitifer.creamModelInfoArr[creamIndex];
                let startScaleplateValue = this.parasitifer.startScaleplateValue;
                let currScaleplateValue = this.getCreamScaleplate();
                let creamShowingPos = this.parasitifer.creamShowingPosArr[creamIndex];
                let creamShowingScaleDict = this.parasitifer.creamShowedScaleInfoArr[creamIndex];
                let r = creamData.creamCakeR;
                let s = 2 * Math.PI * r + 0.014;
                let model = creamData.modelArr[0];
                let customIndex2ColorDict = model["tmpCustomIndex2ColorDict"] = model["tmpCustomIndex2ColorDict"] || {};
                let bColorChanged = false;
                let template = mgrCfg.get_from_cake_cream_color_db(this.parasitifer.curSelectCreamColorId);
                let color = new Laya.Vector4(template.color[0] / 255, template.color[1] / 255, template.color[2] / 255, 1);
                let stageCreamData = this.parasitifer.stageData.creamArr[creamIndex];
                let ampHalfValue = (stageCreamData.ampOffset || 0) / 2;
                let ampSValue = s / (stageCreamData.ampCount || 10);
                let soffset = (ampSValue && ampHalfValue) ? Math.sin((currScaleplateValue % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue : 0;
                this.parasitifer.naiyoudai.transform.localPositionY = creamData.modelArr[0].transform.localPositionY + soffset;
                let colorStartIndex = Math.floor(Math.abs(startScaleplateValue) / 0.96 * Const.CREAM_COLOR_TEXTURE_WH);
                customIndex2ColorDict[colorStartIndex] = color;
                for (let i = 0; i < creamData.positionArr.length; i++) {
                    let originMeshPos = creamData.positionArr[i];
                    let handledPos = creamData.handledPosArr[i];
                    let handledRPos = creamData.handledRPosArr[i];
                    if (originMeshPos.y > s) {
                        continue;
                    }
                    let scale = -1;
                    if (Math.abs(this.parasitifer.cakeRotatedYValue - this.parasitifer.startCakeRotatedYValue) >= 359) {
                        scale = 1;
                    }
                    else {
                        if (startScaleplateValue < currScaleplateValue) {
                            if (originMeshPos.y < startScaleplateValue || originMeshPos.y > currScaleplateValue) {
                                continue;
                            }
                            scale = this._calculateMeshScaleFunc(startScaleplateValue, currScaleplateValue, originMeshPos.y);
                        }
                        else {
                            if (originMeshPos.y < startScaleplateValue && originMeshPos.y > currScaleplateValue) {
                                continue;
                            }
                            let tmpCurrScaleplateValue = currScaleplateValue + s;
                            let tmpOriginMeshPosY = originMeshPos.y <= currScaleplateValue ? originMeshPos.y + s : originMeshPos.y;
                            scale = this._calculateMeshScaleFunc(startScaleplateValue, tmpCurrScaleplateValue, tmpOriginMeshPosY);
                        }
                    }
                    let colorIndex = Math.ceil(Math.abs(originMeshPos.y) / (0.96) * Const.CREAM_COLOR_TEXTURE_WH);
                    customIndex2ColorDict[ul.clamp(colorIndex, 0, Const.CREAM_COLOR_TEXTURE_WH - 1)] = color;
                    bColorChanged = true;
                    creamShowingScaleDict[i] = scale = Math.max(scale, (creamShowingScaleDict[i] || 0));
                    creamShowingPos[i] = new Laya.Vector3(handledRPos.x + (handledPos.x - handledRPos.x) * scale, handledRPos.y + (handledPos.y - handledRPos.y) * scale, handledRPos.z + (handledPos.z - handledRPos.z) * scale);
                }
                creamData.meshData["_setVerticeElementData"](creamShowingPos, Laya.VertexMesh.MESH_POSITION0);
                let sharedMaterials = model.getChildAt(0).meshRenderer.sharedMaterials;
                let materialCount = sharedMaterials.length;
                model["tmpCustomIndex2ColorDict"] = customIndex2ColorDict;
                if (bColorChanged) {
                    this.parasitifer.usedCreamColorIdDict[this.parasitifer.curSelectCreamColorId] = true;
                    for (let matIndex = 0; matIndex < materialCount; matIndex++) {
                        let matOld = sharedMaterials[matIndex];
                        if (!matOld["_bSetedCustomCreamColorTex"]) {
                            matOld["_bSetedCustomCreamColorTex"] = true;
                            let useColorData = null;
                            if (stageCreamData.bDefaultComplete && !!stageCreamData.completeColorId) {
                                useColorData = mgrCfg.get_from_cake_cream_color_db(stageCreamData.completeColorId);
                            }
                            else {
                                useColorData = template;
                            }
                            let data = this.createTempPureColorTexture2D(new Laya.Color(useColorData.color[0] / 255, useColorData.color[1] / 255, useColorData.color[2] / 255, 1));
                            var text2d = data.tex2d;
                            if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                text2d.wrapModeU = Laya.WarpMode.Repeat;
                                text2d.wrapModeV = Laya.WarpMode.Repeat;
                                text2d.filterMode = Laya.FilterMode.Bilinear;
                            }
                            matOld.CustomCreamColorTexture = text2d;
                            matOld["SetedCustomCreamColorTexPixels"] = data.pixels;
                        }
                        else {
                            let pixels = matOld["SetedCustomCreamColorTexPixels"];
                            for (let k in customIndex2ColorDict) {
                                let index = parseInt(k);
                                if (!customIndex2ColorDict[index]) {
                                    continue;
                                }
                                let indexColorVector4 = customIndex2ColorDict[index];
                                for (let i = 0; i < Const.CREAM_COLOR_TEXTURE_WH; i++) {
                                    let pixelsIndex = index * Const.CREAM_COLOR_TEXTURE_WH + i;
                                    pixels[pixelsIndex * 4 + 0] = indexColorVector4.x * 255;
                                    pixels[pixelsIndex * 4 + 1] = indexColorVector4.y * 255;
                                    pixels[pixelsIndex * 4 + 2] = indexColorVector4.z * 255;
                                    pixels[pixelsIndex * 4 + 3] = 255;
                                }
                                if (!index) {
                                    for (let i = 0; i < Const.CREAM_COLOR_TEXTURE_WH; i++) {
                                        let pixelsIndex = (Const.CREAM_COLOR_TEXTURE_WH - 1) * Const.CREAM_COLOR_TEXTURE_WH + i;
                                        pixels[pixelsIndex * 4 + 0] = indexColorVector4.x * 255;
                                        pixels[pixelsIndex * 4 + 1] = indexColorVector4.y * 255;
                                        pixels[pixelsIndex * 4 + 2] = indexColorVector4.z * 255;
                                        pixels[pixelsIndex * 4 + 3] = 255;
                                    }
                                }
                            }
                            matOld.CustomCreamColorTexture.setPixels(pixels);
                            matOld["SetedCustomCreamColorTexPixels"] = pixels;
                        }
                    }
                }
            }
            outCream() {
            }
            createTempPureColorTexture2D(color) {
                let pointCount = Const.CREAM_COLOR_TEXTURE_WH * Const.CREAM_COLOR_TEXTURE_WH;
                let pixels = new Uint8Array(pointCount * 4);
                for (let i = 0; i < pointCount; i++) {
                    pixels[i * 4 + 0] = color.r * 255;
                    pixels[i * 4 + 1] = color.g * 255;
                    pixels[i * 4 + 2] = color.b * 255;
                    pixels[i * 4 + 3] = color.a * 255;
                }
                let tex2d = new Laya.Texture2D(Const.CREAM_COLOR_TEXTURE_WH, Const.CREAM_COLOR_TEXTURE_WH, Laya.TextureFormat.R8G8B8A8);
                tex2d.setPixels(pixels);
                return { tex2d: tex2d, pixels: pixels };
            }
            createTempCustomColorTexture2D(color, customIndex2ColorDict) {
                let pointCount = Const.CREAM_COLOR_TEXTURE_WH * Const.CREAM_COLOR_TEXTURE_WH;
                let pixels = new Uint8Array(pointCount * 4);
                for (let i = 0; i < pointCount; i++) {
                    pixels[i * 4 + 0] = (i % Const.CREAM_COLOR_TEXTURE_WH) == 0 ? 255 : 0;
                    pixels[i * 4 + 1] = 0;
                    pixels[i * 4 + 2] = 0;
                    pixels[i * 4 + 3] = (i % Const.CREAM_COLOR_TEXTURE_WH) == 0 ? 255 : 0;
                }
                let tex2d = new Laya.Texture2D(Const.CREAM_COLOR_TEXTURE_WH, Const.CREAM_COLOR_TEXTURE_WH, Laya.TextureFormat.R8G8B8A8);
                tex2d.setPixels(pixels);
                return { tex2d: tex2d, pixels: pixels };
            }
            getCreamProgress() {
                if (!this.parasitifer.avatar || this.parasitifer.avatar.destroyed) {
                    return [0, 0];
                }
                let totalProgress = 0;
                let currProgress = 0;
                for (let creamIndex = 0; creamIndex < this.parasitifer.creamModelInfoArr.length; creamIndex++) {
                    let creamData = this.parasitifer.creamModelInfoArr[creamIndex];
                    if (creamData.creamType != CreamType.horzontal) {
                        continue;
                    }
                    let creamShowingScaleDict = this.parasitifer.creamShowedScaleInfoArr[creamIndex];
                    let r = creamData.creamCakeR;
                    let s = 2 * Math.PI * r + 0.003;
                    for (let i = 0; i < creamData.positionArr.length; i++) {
                        if (creamShowingScaleDict[i] >= 1) {
                            totalProgress += 1;
                            currProgress += 1;
                            continue;
                        }
                        let originMeshPos = creamData.positionArr[i];
                        if (originMeshPos.y > s) {
                            continue;
                        }
                        totalProgress += 1;
                        currProgress += (creamShowingScaleDict[i] || 0);
                    }
                }
                return [currProgress, totalProgress];
            }
            cubicIn(k) {
                return k * k * k;
            }
            cubicOut(k) {
                return --k * k * k + 1;
            }
        }

        class CakeCreamScriptFlowerHorzontal extends CakeCreamScriptHorzontal {
            constructor(parasitifer) {
                super(parasitifer);
            }
            initCreamModel() {
                this.parasitifer.creamModelInfoArr = this.parasitifer.creamModelInfoArr || [];
                let creamArr = this.parasitifer.stageData.creamArr || [];
                for (let i = 0; i < creamArr.length; i++) {
                    let creamData = creamArr[i];
                    if (creamData.creamType != CreamType.flowerHorzontal) {
                        continue;
                    }
                    let modelArr = [];
                    let modelName = creamData.modelName;
                    for (let index = 0; index < creamData.flowerCount; index++) {
                        let creamModel = mgrLoader.Pool.getModel(modelName);
                        mgrMaterial.setCustomMaterial(creamModel, modelName);
                        this.parasitifer.avatar.addChild(creamModel);
                        modelArr.push(creamModel);
                    }
                    let modelData = {
                        modelArr: modelArr,
                        render: null,
                        meshData: null,
                        positionArr: null,
                        localPositionY: null,
                        handledPosArr: null,
                        handledRPosArr: null,
                        vertices: null,
                        indices: null,
                        normals: null,
                        creamCakeR: 0.3,
                        creamType: creamData.creamType,
                        creamIndex: creamData.creamIndex
                    };
                    this.parasitifer.creamModelInfoArr.push(modelData);
                }
            }
            adaptCreamPosition() {
                let creamArr = this.parasitifer.stageData.creamArr || [];
                for (let i = 0; i < creamArr.length; i++) {
                    let creamData = creamArr[i];
                    if (creamData.creamType != CreamType.flowerHorzontal) {
                        continue;
                    }
                    let posY = creamData.creamPos;
                    let relateCaleROfY = this.parasitifer.getGoodCakeRByPosY(posY);
                    let creamModelInfo = this.parasitifer.creamModelInfoArr[i];
                    creamModelInfo.creamCakeR = relateCaleROfY;
                    let rotGap = 360 / (creamData.flowerCount || 1);
                    for (let tmp = 0; tmp < creamData.flowerCount; tmp++) {
                        let rot = rotGap * tmp;
                        let useRot = rot - 90 < 0 ? 360 + (rot - 90) : rot - 90;
                        creamModelInfo.modelArr[tmp]["sY"] = (1 - useRot / 360) * 2 * Math.PI * creamModelInfo.creamCakeR;
                        let s = 2 * Math.PI * relateCaleROfY;
                        let ampHalfValue = (creamData.ampOffset || 0) / 2;
                        let ampSValue = s / (creamData.ampCount || 10);
                        let cl = Math.abs(creamModelInfo.modelArr[tmp]["sY"]);
                        let soffset = Math.sin((cl % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue;
                        let usePosY = posY + soffset;
                        let useRelateCaleROfY = this.parasitifer.getGoodCakeRByPosY(usePosY) + creamData.offsetR;
                        let posBorder = Tools.getCircleBorderPosPoint(new Laya.Vector2(0, 0), useRelateCaleROfY, rot);
                        creamModelInfo.modelArr[tmp].transform.localPositionX = posBorder.x;
                        creamModelInfo.modelArr[tmp].transform.localPositionY = posY;
                        creamModelInfo.modelArr[tmp].transform.localPositionZ = posBorder.y;
                        creamModelInfo.modelArr[tmp].transform.localRotationEulerX = creamData.offsetRotationX || 0;
                        creamModelInfo.modelArr[tmp].transform.localRotationEulerY = (rot > 180 ? 360 - rot : -rot) + 90 + (creamData.offsetRotationY || 0);
                        creamModelInfo.modelArr[tmp].transform.localRotationEulerZ = creamData.offsetRotationZ || 0;
                    }
                }
            }
            preHandleCreamShape() {
                for (let index = 0; index < this.parasitifer.creamModelInfoArr.length; index++) {
                    let creamData = this.parasitifer.creamModelInfoArr[index];
                    if (creamData.creamType != CreamType.flowerHorzontal) {
                        continue;
                    }
                    let stageCreamData = this.parasitifer.stageData.creamArr[index];
                    let r = creamData.creamCakeR;
                    let s = 2 * Math.PI * r;
                    let ampHalfValue = (stageCreamData.ampOffset || 0) / 2;
                    let ampSValue = s / (stageCreamData.ampCount || 10);
                    let modelArr = creamData.modelArr;
                    for (let i = 0; i < modelArr.length; i++) {
                        let model = modelArr[i];
                        let cl = Math.abs(model["sY"]);
                        let soffset = (ampSValue && ampHalfValue) ? Math.sin((cl % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue : 0;
                        model.transform.localPositionY += soffset;
                        model.transform.setWorldLossyScale(new Laya.Vector3(0, 0, 0));
                    }
                    this.parasitifer.creamShowingPosArr[index] = [];
                    this.parasitifer.creamShowedScaleInfoArr[index] = new Array(creamData.modelArr.length);
                    if (!!stageCreamData.bDefaultComplete) {
                        for (let i = 0; i < modelArr.length; i++) {
                            let model = modelArr[i];
                            model["bDefaultComplete"] = true;
                            model.transform.setWorldLossyScale(new Laya.Vector3(1, 1, 1));
                            this.parasitifer.creamShowedScaleInfoArr[index][i] = 1;
                            if (!!stageCreamData.completeColorId) {
                                let doChangeColor = (render) => {
                                    let colorData = mgrCfg.get_from_cake_cream_color_db(stageCreamData.completeColorId);
                                    for (let k in render.sharedMaterials) {
                                        let mat = render.sharedMaterials[k];
                                        mat.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                    }
                                };
                                let render = Tools.getMeshRender(model);
                                if (!!render) {
                                    doChangeColor(render);
                                }
                                else {
                                    doChangeColor(Tools.getMeshRender(model.getChildAt(0)));
                                }
                            }
                        }
                    }
                    else {
                        for (let i = 0; i < modelArr.length; i++) {
                            let model = modelArr[i];
                            model["bDefaultComplete"] = false;
                        }
                    }
                }
            }
            initDataWhenTouchedCream(point) {
                let creamData = this.parasitifer.creamModelInfoArr[this.parasitifer.operatingCreamIndex];
                if (creamData.creamType != CreamType.flowerHorzontal) {
                    return;
                }
                this.parasitifer.startScaleplateValue = this.getCreamScaleplate();
                this.parasitifer.startCakeRotatedYValue = this.parasitifer.cakeRotatedYValue;
            }
            getCreamScaleplate() {
                let creamData = this.parasitifer.creamModelInfoArr[this.parasitifer.operatingCreamIndex];
                let rot = this.parasitifer.avatar.transform.localRotationEulerY - this.parasitifer.currentCreamTouchOffsetRot;
                rot = rot <= 0 ? rot : rot - 360;
                let scalePlateValue = Math.abs(rot % 360) * Math.PI * creamData.creamCakeR / 180;
                return scalePlateValue;
            }
            inCream() {
            }
            exeCream() {
                if (!this.parasitifer.bTouchBg || this.parasitifer.operatingCreamIndex < 0) {
                    return;
                }
                let creamIndex = this.parasitifer.operatingCreamIndex;
                let creamData = this.parasitifer.creamModelInfoArr[creamIndex];
                let startScaleplateValue = this.parasitifer.startScaleplateValue;
                let currScaleplateValue = this.getCreamScaleplate();
                let creamShowingScaleDict = this.parasitifer.creamShowedScaleInfoArr[creamIndex];
                let r = creamData.creamCakeR;
                let s = 2 * Math.PI * r;
                let perGap = Math.min(s / creamData.modelArr.length / 4, this.parasitifer.SCALEPLATE_2_NORMAL_DIS);
                let stageCreamData = this.parasitifer.stageData.creamArr[creamIndex];
                let ampHalfValue = (stageCreamData.ampOffset || 0) / 2;
                let ampSValue = s / (stageCreamData.ampCount || 10);
                let soffset = (ampSValue && ampHalfValue) ? Math.sin((currScaleplateValue % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue : 0;
                let ampHalfValue2 = (0.015) / 2;
                let ampSValue2 = s / ((stageCreamData.flowerCount || 0));
                let soffset2 = (ampSValue2 && ampHalfValue2) ? Math.sin((currScaleplateValue % ampSValue2) / ampSValue2 * 360 * Math.PI / 180) * ampHalfValue2 : 0;
                this.parasitifer.naiyoudai.transform.localPositionY = creamData.modelArr[0].transform.localPositionY + soffset + soffset2;
                for (let i = 0; i < creamData.modelArr.length; i++) {
                    let model = creamData.modelArr[i];
                    let sy = model["sY"];
                    let scale = -1;
                    if (Math.abs(this.parasitifer.cakeRotatedYValue - this.parasitifer.startCakeRotatedYValue) >= 359) {
                        scale = 1;
                    }
                    else {
                        if (startScaleplateValue < currScaleplateValue) {
                            if (sy < startScaleplateValue || sy > currScaleplateValue) {
                                continue;
                            }
                            scale = this._calculateMeshScaleFunc(startScaleplateValue, currScaleplateValue, sy, perGap);
                        }
                        else {
                            if (sy < startScaleplateValue && sy > currScaleplateValue) {
                                continue;
                            }
                            let tmpCurrScaleplateValue = currScaleplateValue + s;
                            let tmpOriginMeshPosY = sy <= currScaleplateValue ? sy + s : sy;
                            scale = this._calculateMeshScaleFunc(startScaleplateValue, tmpCurrScaleplateValue, tmpOriginMeshPosY, perGap);
                        }
                    }
                    if (!!this.parasitifer.curSelectCreamColorId) {
                        let template = mgrCfg.get_from_cake_cream_color_db(this.parasitifer.curSelectCreamColorId);
                        let color = new Laya.Vector4(template.color[0] / 255, template.color[1] / 255, template.color[2] / 255, 1);
                        let sharedMaterials = model.getChildAt(0).meshRenderer.sharedMaterials;
                        let materialCount = sharedMaterials.length;
                        for (let matIndex = 0; matIndex < materialCount; matIndex++) {
                            let matOld = sharedMaterials[matIndex];
                            matOld.albedoColor = color;
                        }
                    }
                    model["_creamColorId"] = this.parasitifer.curSelectCreamColorId || model["_creamColorId"];
                    creamShowingScaleDict[i] = scale = Math.max(scale, (creamShowingScaleDict[i] || 0));
                    model.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                    this.parasitifer.usedCreamColorIdDict[this.parasitifer.curSelectCreamColorId] = true;
                }
            }
            outCream() {
            }
            getCreamProgress() {
                if (!this.parasitifer.avatar || this.parasitifer.avatar.destroyed) {
                    return [0, 0];
                }
                let totalProgress = 0;
                let currProgress = 0;
                for (let creamIndex = 0; creamIndex < this.parasitifer.creamModelInfoArr.length; creamIndex++) {
                    let creamData = this.parasitifer.creamModelInfoArr[creamIndex];
                    if (creamData.creamType != CreamType.flowerHorzontal) {
                        continue;
                    }
                    let creamShowingScaleDict = this.parasitifer.creamShowedScaleInfoArr[creamIndex];
                    for (let i = 0; i < creamData.modelArr.length; i++) {
                        if (creamShowingScaleDict[i] >= 1) {
                            totalProgress += 1;
                            currProgress += 1;
                            continue;
                        }
                        totalProgress += 1;
                        currProgress += (creamShowingScaleDict[i] || 0);
                    }
                }
                return [currProgress, totalProgress];
            }
        }

        class CakeCreamScriptVertical extends CakeCreamScriptHorzontal {
            constructor(parasitifer) {
                super(parasitifer);
            }
            initCreamModel() {
                let modelTeamplateDict = {};
                this.parasitifer.creamModelInfoArr = this.parasitifer.creamModelInfoArr || [];
                let creamArr = this.parasitifer.stageData.creamArr || [];
                for (let i = 0; i < creamArr.length; i++) {
                    let creamData = creamArr[i];
                    if (creamData.creamType != CreamType.vertical) {
                        continue;
                    }
                    let posY = creamData.creamPos;
                    let modelName = creamData.modelName;
                    if (!modelTeamplateDict[modelName]) {
                        let tmpModel = mgrLoader.Pool.getModel(modelName);
                        mgrMaterial.setCustomMaterial(tmpModel, modelName);
                        modelTeamplateDict[modelName] = tmpModel;
                    }
                    let templateModel = modelTeamplateDict[modelName];
                    let sharedMaterials = templateModel.getChildAt(0).meshRenderer.sharedMaterials;
                    let creamModel = new Laya.Sprite3D;
                    creamModel.name = templateModel.name;
                    let child = new Laya.MeshSprite3D(templateModel.getChildAt(0).meshFilter.sharedMesh.clone(), templateModel.getChildAt(0).name);
                    creamModel.addChild(child);
                    let materialArr = [];
                    let materialCount = sharedMaterials.length;
                    for (let matIndex = 0; matIndex < materialCount; matIndex++) {
                        let matOld = sharedMaterials[matIndex];
                        let mat = new Laya.UnlitMaterial();
                        mat.albedoTexture = matOld.albedoTexture;
                        materialArr.push(mat);
                    }
                    child.meshRenderer.sharedMaterials = materialArr;
                    creamModel["__modelId"] = modelName;
                    mgrMaterial.setCustomMaterial(creamModel, modelName);
                    this.parasitifer.avatar.addChild(creamModel);
                    let modelData = this.parasitifer.getModelMeshData(creamModel);
                    modelData.creamType = creamData.creamType;
                    modelData.creamIndex = creamData.creamIndex;
                    this.parasitifer.creamModelInfoArr.push(modelData);
                }
                for (let k in modelTeamplateDict) {
                    mgrLoader.Pool.recoverModel(modelTeamplateDict[k]);
                }
            }
            adaptCreamPosition() {
                let creamArr = this.parasitifer.stageData.creamArr || [];
                for (let i = 0; i < creamArr.length; i++) {
                    let creamData = creamArr[i];
                    if (creamData.creamType != CreamType.vertical) {
                        continue;
                    }
                    let rot = creamData.creamPos;
                    let relateCaleROfY = this.parasitifer.getGoodCakeRByPosY(0);
                    let posBorder = Tools.getCircleBorderPosPoint(new Laya.Vector2(0, 0), relateCaleROfY, rot);
                    let creamModelInfo = this.parasitifer.creamModelInfoArr[i];
                    creamModelInfo.modelArr[0].transform.localPositionX = posBorder.x;
                    creamModelInfo.modelArr[0].transform.localPositionZ = posBorder.y;
                    creamModelInfo.modelArr[0].transform.localRotationEulerY = (rot > 180 ? 360 - rot : -rot) + 90;
                    creamModelInfo.creamCakeR = relateCaleROfY;
                }
            }
            preHandleCreamShape() {
                let s = this.parasitifer.stageData.cakeHeight;
                let zeroPointR = this.parasitifer.getGoodCakeRByPosY(0);
                for (let index = 0; index < this.parasitifer.creamModelInfoArr.length; index++) {
                    let creamData = this.parasitifer.creamModelInfoArr[index];
                    if (creamData.creamType != CreamType.vertical) {
                        continue;
                    }
                    let stageCreamData = this.parasitifer.stageData.creamArr[index];
                    let useS = stageCreamData.verticalCreamHeight || s;
                    let rotatedPosArr = creamData.positionArr;
                    let tmpCircleCenterPos = new Laya.Vector2(0, 0);
                    let ampHalfValue = (stageCreamData.ampOffset || 0) / 2;
                    let ampSValue = useS / (stageCreamData.ampCount || 10);
                    let handledPosArr = [];
                    let handledRPosArr = [];
                    for (let i = 0; i < rotatedPosArr.length; i++) {
                        let posModel = rotatedPosArr[i];
                        if (posModel.y > useS) {
                            handledRPosArr.push(new Laya.Vector3(0, useS, -zeroPointR));
                            handledPosArr.push(new Laya.Vector3(0, useS, -zeroPointR));
                            continue;
                        }
                        let r = this.parasitifer.getGoodCakeRByPosY(posModel.y) + stageCreamData.offsetR;
                        let cl = Math.abs(posModel.y);
                        let soffset = (ampSValue && ampHalfValue) ? Math.sin((cl % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue : 0;
                        handledRPosArr.push(new Laya.Vector3(soffset, posModel.y, Math.min(0, r - zeroPointR)));
                        handledPosArr.push(new Laya.Vector3(posModel.x + soffset, posModel.y, posModel.z + r - zeroPointR));
                    }
                    creamData.handledPosArr = handledPosArr;
                    creamData.handledRPosArr = handledRPosArr;
                    this.parasitifer.creamShowedScaleInfoArr[index] = new Array(handledRPosArr.length);
                    if (!!stageCreamData.bDefaultComplete) {
                        creamData.modelArr[0]["bDefaultComplete"] = true;
                        creamData.meshData["_setVerticeElementData"](Tools.deepCopy(handledPosArr), Laya.VertexMesh.MESH_POSITION0);
                        this.parasitifer.creamShowingPosArr[index] = Tools.deepCopy(handledPosArr);
                        for (let i = 0; i < handledRPosArr.length; i++) {
                            this.parasitifer.creamShowedScaleInfoArr[index][i] = 1;
                        }
                        if (!!stageCreamData.completeColorId) {
                            let doChangeColor = (render) => {
                                let colorData = mgrCfg.get_from_cake_cream_color_db(stageCreamData.completeColorId);
                                for (let k in render.sharedMaterials) {
                                    let mat = render.sharedMaterials[k];
                                    mat.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                }
                            };
                            let model = creamData.modelArr[0];
                            let render = Tools.getMeshRender(model);
                            if (!!render) {
                                doChangeColor(render);
                            }
                            else {
                                doChangeColor(Tools.getMeshRender(model.getChildAt(0)));
                            }
                        }
                    }
                    else {
                        creamData.modelArr[0]["bDefaultComplete"] = false;
                        creamData.meshData["_setVerticeElementData"](Tools.deepCopy(handledRPosArr), Laya.VertexMesh.MESH_POSITION0);
                        this.parasitifer.creamShowingPosArr[index] = Tools.deepCopy(handledRPosArr);
                    }
                }
            }
            tryGetCreamIndexByHitedPoint(point) {
                let minIndex = -1;
                let minDis = 9999;
                let rot = this.parasitifer.avatar.transform.localRotationEulerY;
                rot += 90;
                rot = (rot <= 0 ? 360 + rot : rot);
                for (let i = 0; i < this.parasitifer.stageData.creamArr.length; i++) {
                    let creamData = this.parasitifer.stageData.creamArr[i];
                    if (creamData.creamType != CreamType.vertical && creamData.creamType != CreamType.flowerVertical) {
                        continue;
                    }
                    let rotCream = creamData.creamPos;
                    if (Math.abs(rot - rotCream) < minDis && Math.abs(rot - rotCream) < 45) {
                        minDis = Math.abs(rot - rotCream);
                        minIndex = i;
                    }
                }
                return minIndex;
            }
            initDataWhenTouchedCream() {
                let creamData = this.parasitifer.creamModelInfoArr[this.parasitifer.operatingCreamIndex];
                if (creamData.creamType != CreamType.vertical) {
                    return;
                }
                this.parasitifer.startScaleplateValue = this.getCreamScaleplate();
                this.parasitifer.startCakeRotatedYValue = this.parasitifer.cakeRotatedYValue;
            }
            getCreamScaleplate() {
                let curr = (Tools.time() - this.parasitifer.startTouchTime) / Const.CAKE_VERTICAL_FULL_TIME * this.parasitifer.stageData.cakeHeight;
                return curr;
            }
            inCream() {
            }
            exeCream() {
                if (!this.parasitifer.bTouchBg || this.parasitifer.operatingCreamIndex < 0) {
                    return;
                }
                let creamIndex = this.parasitifer.operatingCreamIndex;
                let creamData = this.parasitifer.creamModelInfoArr[creamIndex];
                let startScaleplateValue = this.parasitifer.startScaleplateValue;
                let currScaleplateValue = this.getCreamScaleplate();
                let creamShowingPos = this.parasitifer.creamShowingPosArr[creamIndex];
                let creamShowingScaleDict = this.parasitifer.creamShowedScaleInfoArr[creamIndex];
                let s = this.parasitifer.stageData.cakeHeight;
                let stageCreamData = this.parasitifer.stageData.creamArr[creamIndex];
                let model = creamData.modelArr[0];
                let customIndex2ColorDict = model["tmpCustomIndex2ColorDict"] = model["tmpCustomIndex2ColorDict"] || {};
                let bColorChanged = false;
                let template = mgrCfg.get_from_cake_cream_color_db(this.parasitifer.curSelectCreamColorId);
                let color = new Laya.Vector4(template.color[0] / 255, template.color[1] / 255, template.color[2] / 255, 1);
                let ampHalfValue = (stageCreamData.ampOffset || 0) / 2;
                let ampSValue = s / (stageCreamData.ampCount || 10);
                let soffset = (ampSValue && ampHalfValue) ? Math.sin((currScaleplateValue % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue : 0;
                this.parasitifer.naiyoudai.transform.localPositionX = creamData.modelArr[0].transform.position.x + soffset;
                this.parasitifer.naiyoudai.transform.localPositionY = currScaleplateValue > (this.parasitifer.stageData.cakeHeight + 0.01) ? this.parasitifer.stageData.cakeHeight + 0.01 : currScaleplateValue;
                for (let i = 0; i < creamData.positionArr.length; i++) {
                    let originMeshPos = creamData.positionArr[i];
                    let handledPos = creamData.handledPosArr[i];
                    let handledRPos = creamData.handledRPosArr[i];
                    let useS = stageCreamData.verticalCreamHeight || s;
                    if (originMeshPos.y > useS) {
                        continue;
                    }
                    let scale = -1;
                    if (originMeshPos.y < startScaleplateValue || originMeshPos.y > currScaleplateValue) {
                        continue;
                    }
                    scale = this._calculateMeshScaleFunc(startScaleplateValue, currScaleplateValue, originMeshPos.y);
                    let colorIndex1 = Math.ceil(Math.abs(originMeshPos.y) / (0.96) * Const.CREAM_COLOR_TEXTURE_WH);
                    let colorIndex2 = Math.floor(Math.abs(originMeshPos.y) / (0.96) * Const.CREAM_COLOR_TEXTURE_WH);
                    customIndex2ColorDict[ul.clamp(colorIndex1, 0, Const.CREAM_COLOR_TEXTURE_WH - 1)] = color;
                    customIndex2ColorDict[ul.clamp(colorIndex2, 0, Const.CREAM_COLOR_TEXTURE_WH - 1)] = color;
                    bColorChanged = true;
                    creamShowingScaleDict[i] = scale = Math.max(scale, (creamShowingScaleDict[i] || 0));
                    creamShowingPos[i] = new Laya.Vector3(handledRPos.x + (handledPos.x - handledRPos.x) * scale, handledPos.y, handledPos.z);
                }
                creamData.meshData["_setVerticeElementData"](creamShowingPos, Laya.VertexMesh.MESH_POSITION0);
                let sharedMaterials = model.getChildAt(0).meshRenderer.sharedMaterials;
                let materialCount = sharedMaterials.length;
                model["tmpCustomIndex2ColorDict"] = customIndex2ColorDict;
                if (bColorChanged) {
                    this.parasitifer.usedCreamColorIdDict[this.parasitifer.curSelectCreamColorId] = true;
                    for (let matIndex = 0; matIndex < materialCount; matIndex++) {
                        let matOld = sharedMaterials[matIndex];
                        if (!matOld["_bSetedCustomCreamColorTex"]) {
                            matOld["_bSetedCustomCreamColorTex"] = true;
                            let useColorData = null;
                            if (stageCreamData.bDefaultComplete && !!stageCreamData.completeColorId) {
                                useColorData = mgrCfg.get_from_cake_cream_color_db(stageCreamData.completeColorId);
                            }
                            else {
                                useColorData = template;
                            }
                            let data = this.createTempPureColorTexture2D(new Laya.Color(useColorData.color[0] / 255, useColorData.color[1] / 255, useColorData.color[2] / 255, 1));
                            var text2d = data.tex2d;
                            if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                text2d.wrapModeU = Laya.WarpMode.Repeat;
                                text2d.wrapModeV = Laya.WarpMode.Repeat;
                                text2d.filterMode = Laya.FilterMode.Bilinear;
                            }
                            matOld.CustomCreamColorTexture = text2d;
                            matOld["SetedCustomCreamColorTexPixels"] = data.pixels;
                        }
                        else {
                            let pixels = matOld["SetedCustomCreamColorTexPixels"];
                            for (let k in customIndex2ColorDict) {
                                let index = parseInt(k);
                                if (!customIndex2ColorDict[index]) {
                                    continue;
                                }
                                let indexColorVector4 = customIndex2ColorDict[index];
                                for (let i = 0; i < Const.CREAM_COLOR_TEXTURE_WH; i++) {
                                    let pixelsIndex = index * Const.CREAM_COLOR_TEXTURE_WH + i;
                                    pixels[pixelsIndex * 4 + 0] = indexColorVector4.x * 255;
                                    pixels[pixelsIndex * 4 + 1] = indexColorVector4.y * 255;
                                    pixels[pixelsIndex * 4 + 2] = indexColorVector4.z * 255;
                                    pixels[pixelsIndex * 4 + 3] = 255;
                                }
                                if (!index) {
                                    for (let i = 0; i < Const.CREAM_COLOR_TEXTURE_WH; i++) {
                                        let pixelsIndex = (Const.CREAM_COLOR_TEXTURE_WH - 1) * Const.CREAM_COLOR_TEXTURE_WH + i;
                                        pixels[pixelsIndex * 4 + 0] = indexColorVector4.x * 255;
                                        pixels[pixelsIndex * 4 + 1] = indexColorVector4.y * 255;
                                        pixels[pixelsIndex * 4 + 2] = indexColorVector4.z * 255;
                                        pixels[pixelsIndex * 4 + 3] = 255;
                                    }
                                }
                            }
                            matOld.CustomCreamColorTexture.setPixels(pixels);
                            matOld["SetedCustomCreamColorTexPixels"] = pixels;
                        }
                    }
                }
            }
            outCream() {
            }
            getCreamProgress() {
                if (!this.parasitifer.avatar || this.parasitifer.avatar.destroyed) {
                    return [0, 0];
                }
                let totalProgress = 0;
                let currProgress = 0;
                for (let creamIndex = 0; creamIndex < this.parasitifer.creamModelInfoArr.length; creamIndex++) {
                    let creamData = this.parasitifer.creamModelInfoArr[creamIndex];
                    if (creamData.creamType != CreamType.vertical) {
                        continue;
                    }
                    let creamShowingScaleDict = this.parasitifer.creamShowedScaleInfoArr[creamIndex];
                    let s = this.parasitifer.stageData.cakeHeight;
                    let stageCreamData = this.parasitifer.stageData.creamArr[creamIndex];
                    for (let i = 0; i < creamData.positionArr.length; i++) {
                        if (creamShowingScaleDict[i] >= 1) {
                            totalProgress += 1;
                            currProgress += 1;
                            continue;
                        }
                        let originMeshPos = creamData.positionArr[i];
                        let handledPos = creamData.handledPosArr[i];
                        let handledRPos = creamData.handledRPosArr[i];
                        let useS = stageCreamData.verticalCreamHeight || s;
                        if (originMeshPos.y > useS) {
                            continue;
                        }
                        totalProgress += 1;
                        currProgress += (creamShowingScaleDict[i] || 0);
                    }
                }
                return [currProgress, totalProgress];
            }
        }

        class CakeCreamScriptFlowerVertical extends CakeCreamScriptVertical {
            constructor(parasitifer) {
                super(parasitifer);
            }
            initCreamModel() {
                this.parasitifer.creamModelInfoArr = this.parasitifer.creamModelInfoArr || [];
                let creamArr = this.parasitifer.stageData.creamArr || [];
                for (let i = 0; i < creamArr.length; i++) {
                    let creamData = creamArr[i];
                    if (creamData.creamType != CreamType.flowerVertical) {
                        continue;
                    }
                    let modelArr = [];
                    let modelName = creamData.modelName;
                    for (let index = 0; index < creamData.flowerCount; index++) {
                        let creamModel = mgrLoader.Pool.getModel(modelName);
                        mgrMaterial.setCustomMaterial(creamModel, modelName);
                        this.parasitifer.avatar.addChild(creamModel);
                        modelArr.push(creamModel);
                    }
                    let modelData = {
                        modelArr: modelArr,
                        render: null,
                        meshData: null,
                        positionArr: null,
                        localPositionY: null,
                        handledPosArr: null,
                        handledRPosArr: null,
                        vertices: null,
                        indices: null,
                        normals: null,
                        creamCakeR: 0.3,
                        creamType: creamData.creamType,
                        creamIndex: creamData.creamIndex
                    };
                    this.parasitifer.creamModelInfoArr.push(modelData);
                }
            }
            adaptCreamPosition() {
                let s = this.parasitifer.stageData.cakeHeight;
                let creamArr = this.parasitifer.stageData.creamArr || [];
                for (let i = 0; i < creamArr.length; i++) {
                    let creamData = creamArr[i];
                    if (creamData.creamType != CreamType.flowerVertical) {
                        continue;
                    }
                    let useS = creamData.verticalCreamHeight || s;
                    let rot = creamData.creamPos;
                    let creamModelInfo = this.parasitifer.creamModelInfoArr[i];
                    creamModelInfo.creamCakeR = this.parasitifer.getGoodCakeRByPosY(0);
                    for (let tmp = 0; tmp < creamData.flowerCount; tmp++) {
                        let posY = useS / creamData.flowerCount * tmp;
                        let relateCaleROfY = this.parasitifer.getGoodCakeRByPosY(posY) + creamData.offsetR;
                        let posBorder = Tools.getCircleBorderPosPoint(new Laya.Vector2(0, 0), relateCaleROfY, rot);
                        creamModelInfo.modelArr[tmp].transform.localPositionX = posBorder.x;
                        creamModelInfo.modelArr[tmp].transform.localPositionY = posY;
                        creamModelInfo.modelArr[tmp].transform.localPositionZ = posBorder.y;
                        creamModelInfo.modelArr[tmp].transform.localRotationEulerX = creamData.offsetRotationX || 0;
                        creamModelInfo.modelArr[tmp].transform.localRotationEulerY = (rot > 180 ? 360 - rot : -rot) + 90 + (creamData.offsetRotationY || 0);
                        creamModelInfo.modelArr[tmp].transform.localRotationEulerZ = creamData.offsetRotationZ || 0;
                    }
                }
            }
            preHandleCreamShape() {
                for (let index = 0; index < this.parasitifer.creamModelInfoArr.length; index++) {
                    let creamData = this.parasitifer.creamModelInfoArr[index];
                    if (creamData.creamType != CreamType.flowerVertical) {
                        continue;
                    }
                    let stageCreamData = this.parasitifer.stageData.creamArr[index];
                    let s = this.parasitifer.stageData.cakeHeight;
                    let useS = creamData.verticalCreamHeight || s;
                    let ampHalfValue = (stageCreamData.ampOffset || 0) / 2;
                    let ampSValue = s / (stageCreamData.ampCount || 10);
                    let modelArr = creamData.modelArr;
                    for (let i = 0; i < modelArr.length; i++) {
                        let model = modelArr[i];
                        let cl = Math.abs(useS);
                        let soffset = (ampSValue && ampHalfValue) ? Math.sin((cl % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue : 0;
                        model.transform.localPositionX += soffset;
                        model.transform.setWorldLossyScale(new Laya.Vector3(0, 0, 0));
                    }
                    this.parasitifer.creamShowingPosArr[index] = [];
                    this.parasitifer.creamShowedScaleInfoArr[index] = new Array(creamData.modelArr.length);
                    if (!!stageCreamData.bDefaultComplete) {
                        for (let i = 0; i < modelArr.length; i++) {
                            let model = modelArr[i];
                            model["bDefaultComplete"] = true;
                            model.transform.setWorldLossyScale(new Laya.Vector3(1, 1, 1));
                            this.parasitifer.creamShowedScaleInfoArr[index][i] = 1;
                            if (!!stageCreamData.completeColorId) {
                                let doChangeColor = (render) => {
                                    let colorData = mgrCfg.get_from_cake_cream_color_db(stageCreamData.completeColorId);
                                    for (let k in render.sharedMaterials) {
                                        let mat = render.sharedMaterials[k];
                                        mat.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                    }
                                };
                                let render = Tools.getMeshRender(model);
                                if (!!render) {
                                    doChangeColor(render);
                                }
                                else {
                                    doChangeColor(Tools.getMeshRender(model.getChildAt(0)));
                                }
                            }
                        }
                    }
                    else {
                        for (let i = 0; i < modelArr.length; i++) {
                            let model = modelArr[i];
                            model["bDefaultComplete"] = false;
                        }
                    }
                }
            }
            initDataWhenTouchedCream() {
                let creamData = this.parasitifer.creamModelInfoArr[this.parasitifer.operatingCreamIndex];
                if (creamData.creamType != CreamType.flowerVertical) {
                    return;
                }
                this.parasitifer.startScaleplateValue = this.getCreamScaleplate();
                this.parasitifer.startCakeRotatedYValue = this.parasitifer.cakeRotatedYValue;
            }
            getCreamScaleplate() {
                let curr = (Tools.time() - this.parasitifer.startTouchTime) / Const.CAKE_VERTICAL_FULL_TIME * this.parasitifer.stageData.cakeHeight;
                return curr;
            }
            inCream() {
            }
            exeCream() {
                if (!this.parasitifer.bTouchBg || this.parasitifer.operatingCreamIndex < 0) {
                    return;
                }
                let creamIndex = this.parasitifer.operatingCreamIndex;
                let creamData = this.parasitifer.creamModelInfoArr[creamIndex];
                let startScaleplateValue = this.parasitifer.startScaleplateValue;
                let currScaleplateValue = this.getCreamScaleplate();
                let creamShowingScaleDict = this.parasitifer.creamShowedScaleInfoArr[creamIndex];
                let s = this.parasitifer.stageData.cakeHeight;
                let stageCreamData = this.parasitifer.stageData.creamArr[creamIndex];
                let perGap = Math.min(s / creamData.modelArr.length / 4, this.parasitifer.SCALEPLATE_2_NORMAL_DIS);
                let ampHalfValue = (stageCreamData.ampOffset || 0) / 2;
                let ampSValue = s / (stageCreamData.ampCount || 10);
                let soffset = (ampSValue && ampHalfValue) ? Math.sin((currScaleplateValue % ampSValue) / ampSValue * 360 * Math.PI / 180) * ampHalfValue : 0;
                let ampHalfValue2 = (0.015) / 2;
                let ampSValue2 = s / ((stageCreamData.flowerCount || 0));
                let soffset2 = (ampSValue2 && ampHalfValue2) ? Math.sin((currScaleplateValue % ampSValue2) / ampSValue2 * 360 * Math.PI / 180) * ampHalfValue2 : 0;
                this.parasitifer.naiyoudai.transform.localPositionX = creamData.modelArr[0].transform.position.x + soffset;
                this.parasitifer.naiyoudai.transform.localPositionY = (currScaleplateValue > (this.parasitifer.stageData.cakeHeight + 0.01) ? this.parasitifer.stageData.cakeHeight + 0.01 : currScaleplateValue) + soffset2;
                for (let i = 0; i < creamData.modelArr.length; i++) {
                    let model = creamData.modelArr[i];
                    let useS = stageCreamData.verticalCreamHeight || s;
                    if (model.transform.localPositionY > useS) {
                        continue;
                    }
                    let scale = -1;
                    if (model.transform.localPositionY < startScaleplateValue || model.transform.localPositionY > currScaleplateValue) {
                        continue;
                    }
                    scale = this._calculateMeshScaleFunc(startScaleplateValue, currScaleplateValue, model.transform.localPositionY);
                    if (!!this.parasitifer.curSelectCreamColorId) {
                        let template = mgrCfg.get_from_cake_cream_color_db(this.parasitifer.curSelectCreamColorId);
                        let color = new Laya.Vector4(template.color[0] / 255, template.color[1] / 255, template.color[2] / 255, 1);
                        let sharedMaterials = model.getChildAt(0).meshRenderer.sharedMaterials;
                        let materialCount = sharedMaterials.length;
                        for (let matIndex = 0; matIndex < materialCount; matIndex++) {
                            let matOld = sharedMaterials[matIndex];
                            matOld.albedoColor = color;
                        }
                    }
                    model["_creamColorId"] = this.parasitifer.curSelectCreamColorId || model["_creamColorId"];
                    creamShowingScaleDict[i] = scale = Math.max(scale, (creamShowingScaleDict[i] || 0));
                    model.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                    this.parasitifer.usedCreamColorIdDict[this.parasitifer.curSelectCreamColorId] = true;
                }
            }
            outCream() {
            }
            getCreamProgress() {
                if (!this.parasitifer.avatar || this.parasitifer.avatar.destroyed) {
                    return [0, 0];
                }
                let totalProgress = 0;
                let currProgress = 0;
                for (let creamIndex = 0; creamIndex < this.parasitifer.creamModelInfoArr.length; creamIndex++) {
                    let creamData = this.parasitifer.creamModelInfoArr[creamIndex];
                    if (creamData.creamType != CreamType.flowerVertical) {
                        continue;
                    }
                    let creamShowingScaleDict = this.parasitifer.creamShowedScaleInfoArr[creamIndex];
                    for (let i = 0; i < creamData.modelArr.length; i++) {
                        if (creamShowingScaleDict[i] >= 1) {
                            totalProgress += 1;
                            currProgress += 1;
                            continue;
                        }
                        totalProgress += 1;
                        currProgress += (creamShowingScaleDict[i] || 0);
                    }
                }
                return [currProgress, totalProgress];
            }
        }

        const uvPrecision = 100;
        var AMUSE_CAKE_MAKE_STATE;
        (function (AMUSE_CAKE_MAKE_STATE) {
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["init"] = 1] = "init";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["selectShape"] = 2] = "selectShape";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["cakeShape"] = 3] = "cakeShape";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["cakeShapeAutoComplete"] = 4] = "cakeShapeAutoComplete";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["paintColor"] = 5] = "paintColor";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["cream"] = 6] = "cream";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["deco"] = 7] = "deco";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["sticker"] = 8] = "sticker";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["getShow"] = 9] = "getShow";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["reward"] = 10] = "reward";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["palette"] = 11] = "palette";
            AMUSE_CAKE_MAKE_STATE[AMUSE_CAKE_MAKE_STATE["finish"] = 12] = "finish";
        })(AMUSE_CAKE_MAKE_STATE || (AMUSE_CAKE_MAKE_STATE = {}));
        const CAMERA_PRARAM_CAKE_SHAPE = {
            fov: 45,
            position: new Laya.Vector3(0, 0.34, 0.91),
            rotation: new Laya.Vector3(-7),
            lerpValue: 1,
        };
        const CAMERA_PRARAM_CAKE_MAKE = {
            fov: 45,
            position: new Laya.Vector3(0, 0.23, 0.84),
            rotation: new Laya.Vector3(-11),
            lerpValue: 0.04,
        };
        const CAMERA_PRARAM_ROLE_IN = {
            fov: 60,
            position: new Laya.Vector3(0, 0.51, 1.05),
            rotation: new Laya.Vector3(-11),
            lerpValue: 0.04,
        };
        class vAmuseCakeMakeScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseCakeMakeScene";
                this.roleAvatarPosRotDict = {
                    [0]: { pos: new Laya.Vector3(0, -0.88 + 0.06, -0.5), rot: new Laya.Vector3 },
                };
                this.creamShowedScaleInfoArr = [];
                this.creamShowingPosArr = [];
                this.startScaleplateValue = 0;
                this.startCakeRotatedYValue = 0;
                this.SCALEPLATE_2_NORMAL_DIS = 0.03;
                this.cakeRotatedYValue = 0;
                this.BAD_CAKE_R = 0.15;
                this.badCakeMeshPosScaleDict = {};
                this.operatingCreamIndex = -1;
                this.calculatedPosY2RDict = {};
                this.shapeCakeRangedMeshPositionDict = {};
                this.shapeKnifedY2RData = null;
                this.STATE_2_NEXT_DICT = {
                    [AMUSE_CAKE_MAKE_STATE.cakeShapeAutoComplete]: AMUSE_CAKE_MAKE_STATE.paintColor,
                    [AMUSE_CAKE_MAKE_STATE.paintColor]: AMUSE_CAKE_MAKE_STATE.cream,
                    [AMUSE_CAKE_MAKE_STATE.cream]: AMUSE_CAKE_MAKE_STATE.deco,
                };
                this.bEnabledSplitUv = true;
                this.tryingPartIds = [];
                this.decoModelArr = [];
                this.stickerModelArr = [];
                this.currentCreamTouchOffsetRot = 0;
                this.state2ScoreDict = {};
                this.usedPaintColorIdDict = {};
                this.usedCreamColorIdDict = {};
                this.usedDecoIdDict = {};
                this.usedStickerIdDict = {};
                this.usedShapeIdDict = {};
                this.MAX_DECO_MODEL_COUNT = 80;
                this.MAX_STICKER_MODEL_COUNT = 30;
                this.bSuccess = false;
                this.GOOD_WORD_DESC_ARR = [
                    "做得真好，喜欢",
                    "好好看呀，真漂亮",
                ];
                this.BAD_WORD_DESC_ARR = [
                    "还需要加把劲呢",
                    "咦，好像不是我想要的",
                    "再努力下吧",
                ];
                this.dbName2DatasDict = {};
                this.TAB_PAINT = 1;
                this.TAB_CRAEM = 2;
                this.TAB_DECO = 3;
                this.TAB_STICKER = 4;
                this.TAB_SHAPE = 5;
                this.imgCreamGuideIndedx = 0;
                this.brushSizeInfo = {
                    1: {
                        size: 20,
                        scale: 0.5,
                        uvEularX: -11.34,
                    },
                    2: {
                        size: 40,
                        scale: 0.75,
                        uvEularX: -9.34,
                    },
                    3: {
                        size: 80,
                        scale: 1.0,
                        uvEularX: -7.34,
                    }
                };
                this.curBrushSizeId = 3;
                this.badCakeShowingPositionArr = [];
                this.badCakeShowingPositionRotArr = [];
                let stageId = this.context.stageId || 1;
                let stageData = mgrCfg.get_from_cake_stage_db(stageId);
                this.stageData = stageData;
                stageData.statisPointId && mgrSdk.statisOnStageStart(`${stageData.statisPointId}`, `${stageId}`);
                this.horizontalCreamScript = new CakeCreamScriptHorzontal(this);
                this.verticalCreamScript = new CakeCreamScriptVertical(this);
                this.flowerHorzontalCreamScript = new CakeCreamScriptFlowerHorzontal(this);
                this.flowerVerticalCreamScript = new CakeCreamScriptFlowerVertical(this);
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_SHOP_BUY_SUCCESSED: this.onMsgShopBuySuccessed.bind(this),
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                mgrSound.play(5);
                this.buildUi();
                this.fillData();
                this.widget();
                this.playUiAction();
                this.stManager = new FSMObject;
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.selectShape, this.inSelectShape.bind(this), this.exeSelectShape.bind(this), this.outSelectShape.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.cakeShape, this.inCakeShape.bind(this), this.exeCakeShape.bind(this), this.outCakeShape.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.cakeShapeAutoComplete, this.inCakeShapeAutoComplete.bind(this), this.exeCakeShapeAutoComplete.bind(this), this.outCakeShapeAutoComplete.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.paintColor, this.inPaintColor.bind(this), this.exePaintColor.bind(this), this.outPaintColor.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.cream, this.inCream.bind(this), this.exeCream.bind(this), this.outCream.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.deco, this.inDeco.bind(this), this.exeDeco.bind(this), this.outDeco.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.sticker, this.inSticker.bind(this), this.exeSticker.bind(this), this.outSticker.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.getShow, this.inGetShow.bind(this), this.exeGetShow.bind(this), this.outGetShow.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.reward, this.inReward.bind(this), this.exeReward.bind(this), this.outReward.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.palette, this.inPalette.bind(this), this.exePalette.bind(this), this.outPalette.bind(this));
                this.stManager.registerState(AMUSE_CAKE_MAKE_STATE.finish, this.inFinish.bind(this), this.exeFinish.bind(this), this.outFinish.bind(this));
                this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.init);
                this.stManager.startUpdate(this, this.onTimerLoop.bind(this));
            }
            onClosed() {
                this.resetModelData();
                if (this.touchLoopSoundTimer) {
                    this.touchLoopSoundTimer.stop();
                    this.touchLoopSoundTimer = null;
                }
                mgrTip.hideLoadingTip("loading_deco_model");
                mgrTip.hideLoadingTip("loading_sticker_model");
                mgrTip.hideLoadingTip("loading_preload_cream_model");
                if (this.penguanEffModel) {
                    mgrLoader.Pool.recoverModel(this.penguanEffModel);
                    this.penguanEffModel = null;
                }
                if (this.knifeEffModel) {
                    mgrLoader.Pool.recoverModel(this.knifeEffModel);
                    this.knifeEffModel = null;
                }
                if (this.avatar && !this.avatar.destroyed) {
                    let numChildren = this.avatar.numChildren;
                    for (let i = numChildren - 1; i >= 0; i--) {
                        let node = this.avatar.removeChildAt(i);
                        mgrLoader.Pool.recoverModel(node);
                    }
                    this.avatar.destroy();
                    this.avatar = null;
                }
                mgrVideoRecorder.stopRecord();
                super.onClosed();
            }
            getPreLoadModelIds() {
                let arr = [
                    "gaoti_jimo",
                    "penping",
                    "tuopan",
                    "xiaodao",
                    "naiyoudai",
                    "boliping",
                    "map11",
                    "117_ui_loop_particle_01",
                    "117_ui_loop_spraysmoke_01",
                ];
                arr.push(this.stageData.cakeHumanModelName);
                return arr;
            }
            getPreLoadAnimationIds() {
                return [
                    "dangao-dg_zjl",
                    "dangao-dg_idle02",
                    "dangao-dg_gq",
                    "dangao-dg_kx",
                    "dangao-dg_lk",
                    "dangao-dg_sq",
                    "dangao_lian-dg_zjl",
                    "dangao_lian-dg_idle02",
                    "dangao_lian-dg_gq",
                    "dangao_lian-dg_kx",
                    "dangao_lian-dg_lk",
                    "dangao_lian-dg_sq",
                ];
            }
            getPreLoadImagePaths() {
                let arr = [
                    "res/ui/amuse_cake_result/sprite_palette.png"
                ];
                mgrCfg.forDb_from_world_color_db((key, v) => {
                    arr.push(v.icon);
                });
                return arr;
            }
            buildUi() {
                mgrLoader.loadFont("room_score", this.labelStagePower);
                let topBar = new vTopBar({ bDisableGold: true, bDisableEnergy: true });
                this.spriteTopBarHolder.addChild(topBar);
                this.spriteTitle.visible = false;
                let map = mgrLoader.Pool.getModel("map11");
                map.transform.position = new Laya.Vector3(0, -0.17 + 0.06, 0.2);
                this.add3DEffectAtBack(map, 0);
                this.mapModel = map;
                this.reuseList = new ReuseList(6, 0, 20);
                this.reuseList.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseList);
                this.reuseList.setItemClass(vCakePart);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(4);
                this.reuseList.setSpaceY(2);
                this.spriteJudgePop.scale(0, 0, true);
                this.reuseTypeBtnList = new ReuseList(0, 1, 4);
                this.reuseTypeBtnList.size(this.boxTypeList.width, this.boxTypeList.height);
                this.boxTypeList.addChild(this.reuseTypeBtnList);
                this.reuseTypeBtnList.setItemClass(vCakeTypeBtn);
                this.reuseTypeBtnList.setHorizontalMoveEnable(true);
                this.reuseTypeBtnList.setSpaceX(14);
                let params = {
                    roleId: mgrRole.showingRoleId
                };
                this.roleAvatar = new RoleAvatar(params);
                this.add3DEffectAtBack(this.roleAvatar, 0);
                this.roleAvatar.fillByPartIds(mgrPart.getLastClothes(mgrRole.showingRoleId));
                this.avatar = new Laya.Sprite3D;
                this.add3DEffectAtBack(this.avatar, 0);
                let dangaorenModel = mgrLoader.Pool.getModel(this.stageData.cakeHumanModelName);
                dangaorenModel.transform.localPositionY = -0.019;
                this.avatar.addChild(dangaorenModel);
                mgrMaterial.setCustomMaterial(dangaorenModel, this.stageData.cakeHumanModelName);
                this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                this.cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                this.cameraFollow.fov = CAMERA_PRARAM_CAKE_SHAPE.fov;
                this.cameraFollow.position = CAMERA_PRARAM_CAKE_SHAPE.position;
                this.cameraFollow.endRotation = CAMERA_PRARAM_CAKE_SHAPE.rotation;
                this.cameraFollow.lerpValue = CAMERA_PRARAM_CAKE_SHAPE.lerpValue;
                this.cameraFollow.onLateUpdate();
                this.boxPartContainer.scale(0, 0, true);
                this.spriteStageScoreUpFlag.visible = false;
                this.spriteStageScoreDownFlag.visible = false;
                this.refreshTargetScore();
            }
            registerGuideNode() {
                mgrGuide.registerGuideNode("vAmuseCakeMakeScene.spriteGuideDragStart", this.spriteGuideDragStart);
                mgrGuide.registerGuideNode("vAmuseCakeMakeScene.spriteGuideDragEnd", this.spriteGuideDragEnd);
                mgrGuide.registerGuideNode("vAmuseCakeMakeScene.spriteGuide", this.spriteGuide);
                mgrGuide.registerGuideNode("vAmuseCakeMakeScene.tab01Item", this.spriteTab01ItemGuide);
                mgrGuide.registerGuideNode("vAmuseCakeMakeScene.tab02Item", this.spriteTab02ItemGuide);
                mgrGuide.registerGuideNode("vAmuseCakeMakeScene.tab03Item", this.spriteTab03ItemGuide);
                mgrGuide.registerGuideNode("vAmuseCakeMakeScene.tab04Item", this.spriteTab04ItemGuide);
            }
            onTimerLoop() {
                if (!this.avatar || this.avatar.destroyed) {
                    return;
                }
                if (!!this.knifeModel && !this.knifeModel.destroyed && !!this.knifeEffModel && !this.knifeEffModel.destroyed) {
                    this.knifeEffModel.transform.position = this.knifeModel.transform.position;
                }
            }
            activeAvatarIn(callback) {
                cc.tween(this.roleAvatar.transform)
                    .to(0.3, { localPositionX: this.roleAvatarPosRotDict[0].pos.x, localPositionY: this.roleAvatarPosRotDict[0].pos.y, localPositionZ: this.roleAvatarPosRotDict[0].pos.z })
                    .call(() => {
                    callback && callback();
                })
                    .start();
            }
            showJudgeWord(delayTime, callback) {
                cc.tween(this.spriteJudgePop, true).delay(delayTime || 0).toScale(0.3, 1)
                    .call(() => {
                    callback && callback();
                })
                    .start();
            }
            hideJudgeWord(delayTime, callback) {
                cc.tween(this.spriteJudgePop, true).toScale(0.3, 0)
                    .call(() => {
                    ``;
                    callback && callback();
                })
                    .start();
            }
            fillData() {
                this.initTarget();
                this.initCake();
                let typeBtnDatas = [
                    {
                        id: 5,
                        normalTexture: "res/ui/amuse_cake/sprite_tab_05_normal.png",
                        selTexture: "res/ui/amuse_cake/sprite_tab_05_select.png",
                        fOnClick: this.onClickTab.bind(this),
                        fIsCurrentTab: this.isCurrentTab.bind(this),
                        fIsUsedTab: this.isUsedTab.bind(this)
                    },
                    {
                        id: 1,
                        normalTexture: "res/ui/amuse_cake/sprite_tab_01_normal.png",
                        selTexture: "res/ui/amuse_cake/sprite_tab_01_select.png",
                        fOnClick: this.onClickTab.bind(this),
                        fIsCurrentTab: this.isCurrentTab.bind(this),
                        fIsUsedTab: this.isUsedTab.bind(this)
                    },
                    {
                        id: 2,
                        normalTexture: "res/ui/amuse_cake/sprite_tab_02_normal.png",
                        selTexture: "res/ui/amuse_cake/sprite_tab_02_select.png",
                        fOnClick: this.onClickTab.bind(this),
                        fIsCurrentTab: this.isCurrentTab.bind(this),
                        fIsUsedTab: this.isUsedTab.bind(this)
                    },
                    {
                        id: 3,
                        normalTexture: "res/ui/amuse_cake/sprite_tab_03_normal.png",
                        selTexture: "res/ui/amuse_cake/sprite_tab_03_select.png",
                        fOnClick: this.onClickTab.bind(this),
                        fIsCurrentTab: this.isCurrentTab.bind(this),
                        fIsUsedTab: this.isUsedTab.bind(this)
                    },
                    {
                        id: 4,
                        normalTexture: "res/ui/amuse_cake/sprite_tab_04_normal.png",
                        selTexture: "res/ui/amuse_cake/sprite_tab_04_select.png",
                        fOnClick: this.onClickTab.bind(this),
                        fIsCurrentTab: this.isCurrentTab.bind(this),
                        fIsUsedTab: this.isUsedTab.bind(this)
                    }
                ];
                if (!this.stageData.bCanSelectShape) {
                    typeBtnDatas.shift();
                }
                this.reuseTypeBtnList.setDatas(typeBtnDatas);
                this.reuseTypeBtnList.setScroll(0);
            }
            initTarget() {
                let str = this.stageData.name.replace(",", "\n");
                this.labelTarget.text = str;
                this.spriteStageTarget.visible = !this.stageData.bCanSelectShape;
                this.spriteTarget.visible = !this.stageData.bCanSelectShape;
            }
            initCake() {
                let tuopanModel = mgrLoader.Pool.getModel("tuopan");
                let badCakeModel = mgrLoader.Pool.getModel("gaoti_jimo");
                let knifeModel = mgrLoader.Pool.getModel("xiaodao");
                this.avatar.addChild(tuopanModel);
                this.avatar.addChild(badCakeModel);
                mgrMaterial.setCustomMaterial(badCakeModel, "gaoti_jimo");
                mgrMaterial.setCustomMaterial(tuopanModel, "tuopan");
                mgrMaterial.setCustomMaterial(knifeModel, "xiaodao");
                let knifeEffModel = mgrLoader.Pool.getModel("117_ui_loop_particle_01");
                this.add3DEffectAtBack(knifeEffModel);
                knifeEffModel.active = false;
                let colliderMesh = Laya.PrimitiveMesh.createQuad(100, 100);
                this.colliderQuad = new Laya.MeshSprite3D(colliderMesh);
                this.colliderQuad.transform.position = new Laya.Vector3(0, 0, 0);
                this.colliderQuad.meshRenderer.enable = false;
                this.add3DEffectAtBack(this.colliderQuad, 0);
                this.add3DEffectAtBack(knifeModel, 0);
                knifeModel.transform.localRotationEulerX = 45;
                knifeModel.transform.position = new Laya.Vector3(0.2, 0.1, 0);
                knifeModel['_originPos'] = knifeModel.transform.position.clone();
                knifeModel.active = false;
                let colliderMeshPaint = Laya.PrimitiveMesh.createQuad(100, 100);
                this.colliderQuadPaint = new Laya.MeshSprite3D(colliderMeshPaint);
                this.colliderQuadPaint.transform.position = new Laya.Vector3(0, 0, 0.31);
                this.colliderQuadPaint.meshRenderer.enable = false;
                this.add3DEffectAtBack(this.colliderQuadPaint, 0);
                this.boliping = mgrLoader.Pool.getModel("boliping");
                this.add3DEffectAtBack(this.boliping, 0);
                mgrMaterial.setCustomMaterial(this.boliping, "boliping");
                this.boliping.transform.position = new Laya.Vector3(0.2, 0.0, 0.2);
                this.boliping['_originPos'] = this.boliping.transform.position.clone();
                this.boliping.active = false;
                this.knifeEffModel = knifeEffModel;
                this.tuopanModel = tuopanModel;
                this.badCakeModel = badCakeModel;
                this.knifeModel = knifeModel;
                this.badCakeMeshData = this.getModelMeshData(this.badCakeModel);
                this.badCakeModel.active = false;
                this.initColorOpt();
                this.useSmallBrush();
            }
            syncBadCakeMaterialFromGoodCake() {
                let renderGood = Tools.getMeshRender(this.goodCakeModel.getChildAt(0));
                let renderBad = Tools.getMeshRender(this.badCakeModel.getChildAt(0));
                renderBad.sharedMaterials = renderGood.sharedMaterials;
            }
            splitShapePosRange() {
                let positionRangeDict = {};
                let positionArr = this.shapeCakeMeshData.positionArr;
                for (let index = 0; index < positionArr.length; index++) {
                    let posModel = positionArr[index];
                    let yFlag = Math.floor(posModel.y / 0.1);
                    positionRangeDict[yFlag] = positionRangeDict[yFlag] || [];
                    positionRangeDict[yFlag].push(posModel);
                }
                this.shapeCakeRangedMeshPositionDict = positionRangeDict;
            }
            getGoodCakeRByPosY(posY) {
                if (this.calculatedPosY2RDict && this.calculatedPosY2RDict[posY]) {
                    return this.calculatedPosY2RDict[posY];
                }
                if (posY < 0) {
                    return 0;
                }
                let yFlag = Math.floor(posY / 0.1);
                let positionArr = this.shapeCakeRangedMeshPositionDict[yFlag] || this.shapeCakeRangedMeshPositionDict[yFlag - 1];
                if (!positionArr) {
                    return 0;
                }
                let tmpDis = 0;
                let biggerInfo = {
                    tmpPos: new Laya.Vector3,
                    minDisY: 9999,
                    bSeted: false
                };
                let smallerInfo = {
                    tmpPos: new Laya.Vector3,
                    minDisY: 9999,
                    bSeted: false
                };
                for (let index = 0; index < positionArr.length; index++) {
                    let posModel = positionArr[index];
                    tmpDis = Math.abs(posModel.y - posY);
                    if (posModel.y > posY) {
                        if (tmpDis > biggerInfo.minDisY) {
                            continue;
                        }
                        biggerInfo.minDisY = tmpDis;
                        biggerInfo.tmpPos = new Laya.Vector3(posModel.x, posModel.y, posModel.z);
                        biggerInfo.bSeted = true;
                    }
                    else {
                        if (tmpDis > smallerInfo.minDisY) {
                            continue;
                        }
                        smallerInfo.minDisY = tmpDis;
                        smallerInfo.tmpPos = new Laya.Vector3(posModel.x, posModel.y, posModel.z);
                        smallerInfo.bSeted = true;
                    }
                }
                let r = 0;
                if (!biggerInfo.bSeted) {
                    r = Math.abs(smallerInfo.tmpPos.x);
                }
                else if (!smallerInfo.bSeted) {
                    r = Math.abs(biggerInfo.tmpPos.x);
                }
                else {
                    let totalDis = biggerInfo.tmpPos.y - smallerInfo.tmpPos.y;
                    let currDis = smallerInfo.tmpPos.y - posY;
                    let bigR = Math.max(Math.abs(smallerInfo.tmpPos.x), Math.abs(biggerInfo.tmpPos.x));
                    let smallR = Math.min(Math.abs(smallerInfo.tmpPos.x), Math.abs(biggerInfo.tmpPos.x));
                    r = smallR + (currDis / totalDis) * (bigR - smallR);
                }
                r = Math.max(0.00001, r);
                this.calculatedPosY2RDict[posY] = r;
                return r;
            }
            initCream() {
                this.initCreamModel();
                this.adaptCreamPosition();
            }
            resetModelData() {
                this.resetBadCakeMeshData();
                this.resetCreamData();
            }
            resetBadCakeMeshData() {
                let datas = [this.badCakeMeshData];
                for (let k in datas) {
                    let cakeData = datas[k];
                    if (!!cakeData && !!cakeData.meshData) {
                        cakeData.meshData.setPositions(cakeData.positionArr);
                        cakeData.meshData.setNormals(cakeData.normals);
                    }
                }
            }
            resetCreamData() {
                console.log("--------------resetCreamData");
                if (!this.creamModelInfoArr || this.creamModelInfoArr.length == 0) {
                    return;
                }
                for (let i = 0; i < this.creamModelInfoArr.length; i++) {
                    let creamData = this.creamModelInfoArr[i];
                    if (!!creamData) {
                        if (!!creamData.meshData) {
                            for (let k in creamData.modelArr) {
                                let model = creamData.modelArr[k];
                                model.destroy();
                            }
                        }
                        else {
                            for (let k in creamData.modelArr) {
                                let model = creamData.modelArr[k];
                                delete model["_creamColorId"];
                                mgrLoader.Pool.recoverModel(model);
                            }
                        }
                    }
                }
                this.creamModelInfoArr = [];
                this.usedCreamColorIdDict = {};
                this.refreshTabUsedStatus();
            }
            resetPaintColor() {
                this.usedPaintColorIdDict = {};
                this.refreshTabUsedStatus();
            }
            resetDeco() {
                if (!this.decoModelArr || this.decoModelArr.length == 0) {
                    return;
                }
                for (let i = 0; i < this.decoModelArr.length; i++) {
                    let decoData = this.decoModelArr[i];
                    if (!!decoData) {
                        if (!!decoData) {
                            mgrLoader.Pool.recoverModel(decoData);
                        }
                        else {
                        }
                    }
                }
                this.decoModelArr = [];
                this.usedDecoIdDict = {};
                this.refreshTabUsedStatus();
            }
            resetSticker() {
                if (!this.stickerModelArr || this.stickerModelArr.length == 0) {
                    return;
                }
                for (let i = 0; i < this.stickerModelArr.length; i++) {
                    let stickerData = this.stickerModelArr[i];
                    if (!!stickerData) {
                        if (!!stickerData) {
                            mgrLoader.Pool.recoverModel(stickerData);
                        }
                        else {
                        }
                    }
                }
                this.stickerModelArr = [];
                this.usedStickerIdDict = {};
                this.refreshTabUsedStatus();
            }
            initCreamModel() {
                this.horizontalCreamScript.initCreamModel();
                this.verticalCreamScript.initCreamModel();
                this.flowerHorzontalCreamScript.initCreamModel();
                this.flowerVerticalCreamScript.initCreamModel();
                this.creamModelInfoArr = Tools.sortArrayByField(this.creamModelInfoArr, "creamIndex");
            }
            adaptCreamPosition() {
                this.horizontalCreamScript.adaptCreamPosition();
                this.verticalCreamScript.adaptCreamPosition();
                this.flowerHorzontalCreamScript.adaptCreamPosition();
                this.flowerVerticalCreamScript.adaptCreamPosition();
            }
            preHandleModel() {
                this.horizontalCreamScript.preHandleCreamShape();
                this.verticalCreamScript.preHandleCreamShape();
                this.flowerHorzontalCreamScript.preHandleCreamShape();
                this.flowerVerticalCreamScript.preHandleCreamShape();
            }
            getCreamIndexByHitedPoint(point) {
                let index = this.horizontalCreamScript.tryGetCreamIndexByHitedPoint(point);
                if (index >= 0) {
                    return index;
                }
                index = this.verticalCreamScript.tryGetCreamIndexByHitedPoint(point);
                if (index >= 0) {
                    return index;
                }
                return -1;
            }
            initDataWhenTouchedCream(point) {
                this.currentCreamTouchOffsetRot = Tools.getAngle(point.x, point.z);
                let creamData = this.stageData.creamArr[this.operatingCreamIndex];
                switch (creamData.creamType) {
                    case CreamType.horzontal:
                        this.horizontalCreamScript.initDataWhenTouchedCream(point);
                        break;
                    case CreamType.vertical:
                        this.verticalCreamScript.initDataWhenTouchedCream(point);
                        break;
                    case CreamType.flowerHorzontal:
                        this.flowerHorzontalCreamScript.initDataWhenTouchedCream(point);
                        break;
                    case CreamType.flowerVertical:
                        this.flowerVerticalCreamScript.initDataWhenTouchedCream(point);
                        break;
                    default:
                        break;
                }
            }
            getCreamProgress() {
                let [curr1, max1] = this.horizontalCreamScript.getCreamProgress();
                let [curr2, max2] = this.verticalCreamScript.getCreamProgress();
                let [curr3, max3] = this.flowerHorzontalCreamScript.getCreamProgress();
                let [curr4, max4] = this.flowerVerticalCreamScript.getCreamProgress();
                return (curr1 + curr2 + curr3 + curr4) / (max1 + max2 + max3 + max4 + 0.00001);
            }
            adaptCreamNormal() {
                for (let index = 0; index < this.creamModelInfoArr.length; index++) {
                    let creamData = this.creamModelInfoArr[index];
                    if (creamData.creamType == CreamType.flowerHorzontal || creamData.creamType == CreamType.flowerVertical) {
                        continue;
                    }
                    let handledPosArr = creamData.handledPosArr;
                    let indices = creamData.indices;
                    let normalArr = new Array(handledPosArr.length);
                    let tmpP12 = new Laya.Vector3;
                    let tmpP13 = new Laya.Vector3;
                    let tmpNormal = new Laya.Vector3;
                    for (let i = 0; i < indices.length / 3; i++) {
                        let posIndex0 = indices[i * 3 + 0];
                        let posIndex1 = indices[i * 3 + 1];
                        let posIndex2 = indices[i * 3 + 2];
                        let p1 = handledPosArr[posIndex0];
                        let p2 = handledPosArr[posIndex1];
                        let p3 = handledPosArr[posIndex2];
                        Laya.Vector3.subtract(p1, p2, tmpP12);
                        Laya.Vector3.subtract(p1, p3, tmpP13);
                        Laya.Vector3.cross(tmpP13, tmpP12, tmpNormal);
                        Laya.Vector3.normalize(tmpNormal, tmpNormal);
                        normalArr[posIndex0] = normalArr[posIndex0] || new Laya.Vector3;
                        Laya.Vector3.add(normalArr[posIndex0], tmpNormal, normalArr[posIndex0]);
                        normalArr[posIndex1] = normalArr[posIndex1] || new Laya.Vector3;
                        Laya.Vector3.add(normalArr[posIndex1], tmpNormal, normalArr[posIndex1]);
                        normalArr[posIndex2] = normalArr[posIndex2] || new Laya.Vector3;
                        Laya.Vector3.add(normalArr[posIndex2], tmpNormal, normalArr[posIndex2]);
                    }
                    for (let i = 0; i < normalArr.length; i++) {
                        normalArr[i] = normalArr[i] || new Laya.Vector3;
                        Laya.Vector3.normalize(normalArr[i], normalArr[i]);
                    }
                    creamData.meshData.setNormals(normalArr);
                }
            }
            getModelMeshData(model) {
                let meshData;
                let positionArr = [];
                let vertices;
                let indices;
                let normals = [];
                let render = null;
                let getDataFunc = (model) => {
                    render = Tools.getMeshRender(model);
                    if (render) {
                        let meshFilter = model["_meshFilter"];
                        if (meshFilter) {
                            meshData = meshFilter.sharedMesh;
                            meshData.getPositions(positionArr);
                            vertices = meshData.getVertices();
                            indices = meshData.getIndices();
                            meshData.getNormals(normals);
                        }
                    }
                };
                getDataFunc(model);
                if (!meshData) {
                    let numChildren = model.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let node = model.getChildAt(i);
                        getDataFunc(node);
                        if (meshData) {
                            break;
                        }
                    }
                }
                return {
                    modelArr: [model],
                    render: render,
                    meshData: meshData,
                    positionArr: positionArr,
                    localPositionY: model.transform.localPositionY,
                    handledPosArr: null,
                    handledRPosArr: null,
                    vertices: vertices,
                    indices: indices,
                    normals: normals,
                    creamCakeR: 0.3,
                    creamType: 0,
                };
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.buttonSummit.__node);
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetBottomMC(this.boxPartContainer);
                mgrLayout.widgetRightBottomMC(this.spriteOperation);
                mgrLayout.widgetLeftTopMC(this.spriteTarget);
                mgrLayout.widgetRightTopMC(this.spriteStageTarget);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            playUiAction() {
                mgrEffect.playComebackAction([this.buttonBack.__node], -500, 0, 0.6, 0.6);
            }
            startShapeCake() {
                this.add3DEffectAtBack(this.knifeModel, 0);
                this.knifeModel.transform.localRotationEulerX = 45;
                this.knifeModel.transform.position = new Laya.Vector3(0.2, 0.1, 0);
                this.knifeModel['_originPos'] = this.knifeModel.transform.position.clone();
                this.knifeModel.active = true;
                Tools.unRegisterTouchHander(this.spriteTouch);
                Tools.registerTouchHander(this.spriteTouch, (e) => {
                    this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.spriteGuide.click` });
                    try {
                        if (e.isBegin && !Tools.isWorldLocaInNode(this.boxPartContainer, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            this.bTouchBg = true;
                            rayScreenPos = new Laya.Vector2(e.pos.x, e.pos.y);
                            startCastRay();
                        }
                        if ((e.isEnd || e.isCancel) && this.bTouchBg) {
                            this.bTouchBg = false;
                            rayScreenPos = new Laya.Vector2(e.pos.x, e.pos.y);
                            endCastRay();
                        }
                        if (this.bTouchBg && e.isMove) {
                            rayScreenPos = new Laya.Vector2(e.pos.x, e.pos.y);
                        }
                    }
                    catch (error) {
                    }
                });
                let rayScreenPos;
                let bPlay = false;
                let playSound = () => {
                };
                let startCastRay = () => {
                    bPlay = true;
                    this.knifeEffModel.active = true;
                    playSound();
                    this.cakeShapeTimer = Timer.callLoop(0.001, () => {
                        castRay();
                    }, this);
                };
                let endCastRay = () => {
                    try {
                        bPlay = false;
                        if (this.cakeShapeTimer) {
                            this.cakeShapeTimer.stop();
                            this.cakeShapeTimer = null;
                        }
                        this.knifeEffModel.active = false;
                        this.refreshTabUsedStatus();
                        this.refreshTargetScore();
                        let originPos = this.knifeModel['_originPos'];
                        cc.tween(this.knifeModel.transform)
                            .to(0.5, { localPositionX: originPos.x, localPositionY: originPos.y, localPositionZ: originPos.z, localRotationEulerX: 45 })
                            .start();
                    }
                    catch (error) {
                    }
                };
                this.shapeEndCastRay = endCastRay;
                let castRay = () => {
                    if (!this.avatar || this.avatar.destroyed) {
                        return;
                    }
                    let pos = rayScreenPos;
                    let ray = new Laya.Ray(new Laya.Vector3(0, 0, 10), new Laya.Vector3(0, 0, -1000));
                    Tools.createRayFromScreenPos(this.cameraBack, pos, ray);
                    let result = UVPickerByMesh.pick(ray, this.colliderQuad);
                    if (!result) {
                        return;
                    }
                    let factor = (Math.max((Laya.stage.width / 2 - pos.x) - 200), 0) / 50;
                    factor = ul.clamp(factor, -1, 1);
                    this.knifeModel.transform.localRotationEulerX = Math.abs(factor) * (45);
                    this.knifeModel.transform.position = new Laya.Vector3(result.point.x, ul.clamp(result.point.y, -0.1, 2), (1 - Math.abs(factor)) * 0.1);
                    let factorY = (Laya.stage.height / 5 * 2 - pos.y) / 200;
                    factorY = ul.clamp(factorY, -1, 1);
                    let node = Tools.findNode("guadian_eff", this.knifeModel);
                    let spinfo = Tools.tranlateWorld3D2Screen(this.cameraBack, node.transform.position);
                    let newPos = new Laya.Vector2(spinfo.outPos.x, spinfo.outPos.y);
                    Tools.createRayFromScreenPos(this.cameraBack, newPos, ray);
                    let mesh = Tools.findMeshSprite3d(this.badCakeModel);
                    result = UVPickerByMesh.pick(ray, mesh, true);
                    if (result && result.bHit) {
                        this.shapeKnifedY2RData = { x: result.point.x, y: result.point.y };
                    }
                };
            }
            initPaintMaterial() {
                let model = this.goodCakeModel;
                for (let i = 0; i < model.numChildren; i++) {
                    let child = model.getChildAt(i);
                    let renderer = Tools.getMeshRender(child);
                    if (renderer) {
                        this.goodCakeMaterial = renderer.sharedMaterial;
                        this.goodCakeMaterial.paintLayer1TilingOffset = new Laya.Vector4(1, 1, 0, 0);
                        this.goodCakeMaterial.paintLayer1Texture = null;
                        break;
                    }
                }
            }
            initColorOpt() {
                this.createbrush();
                this.createPaintCavas();
            }
            startDrawColor() {
                Tools.unRegisterTouchHander(this.spriteTouch);
                Tools.registerTouchHander(this.spriteTouch, (e) => {
                    this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.spriteGuide.click` });
                    try {
                        if (e.isBegin && !Tools.isWorldLocaInNode(this.boxPartContainer, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            this.bTouchBg = true;
                            rayScreenPos = new Laya.Vector2(e.pos.x, e.pos.y);
                            startCastRay();
                        }
                        if ((e.isEnd || e.isCancel) && this.bTouchBg) {
                            this.bTouchBg = false;
                            rayScreenPos = new Laya.Vector2(e.pos.x, e.pos.y);
                            endCastRay();
                        }
                        if (this.bTouchBg && e.isMove) {
                            rayScreenPos = new Laya.Vector2(e.pos.x, e.pos.y);
                        }
                    }
                    catch (error) {
                    }
                });
                let rayScreenPos;
                let bPlay = false;
                let playSound = () => {
                };
                let startCastRay = () => {
                    bPlay = true;
                    this.penguanEffModel.active = true;
                    this.changePenguanColor();
                    playSound();
                    this.colorDrawTimer = Timer.callLoop(0.001, () => {
                        castRay();
                    }, this);
                };
                let endCastRay = () => {
                    try {
                        bPlay = false;
                        if (this.colorDrawTimer) {
                            this.colorDrawTimer.stop();
                            this.colorDrawTimer = null;
                        }
                        this.penguanEffModel.active = false;
                        this.refreshTabUsedStatus();
                        this.refreshTargetScore();
                        let originPos = this.penguan['_originPos'];
                        cc.tween(this.penguan.transform)
                            .to(0.5, { localPositionX: originPos.x, localPositionY: originPos.y, localPositionZ: originPos.z, localRotationEulerY: 60 })
                            .start();
                    }
                    catch (error) {
                    }
                };
                let castRay = () => {
                    let pos = rayScreenPos;
                    let ray = new Laya.Ray(new Laya.Vector3(0, 0, 10), new Laya.Vector3(0, 0, -1000));
                    Tools.createRayFromScreenPos(this.cameraBack, pos, ray);
                    let result = UVPickerByMesh.pick(ray, this.colliderQuadPaint);
                    if (!result) {
                        return;
                    }
                    let factor = (Laya.stage.width / 2 - pos.x) / 200;
                    factor = ul.clamp(factor, -1, 1);
                    this.penguan.transform.localRotationEulerY = factor * (-60);
                    this.penguan.transform.position = result.point;
                    let factorY = (Laya.stage.height / 5 * 2 - pos.y) / 200;
                    factorY = ul.clamp(factorY, -1, 1);
                    let node = Tools.findNode("guadian_eff", this.penguan);
                    let spinfo = Tools.tranlateWorld3D2Screen(this.cameraBack, node.transform.position);
                    let newPos = new Laya.Vector2(spinfo.outPos.x, spinfo.outPos.y);
                    Tools.createRayFromScreenPos(this.cameraBack, newPos, ray);
                    let mesh = Tools.findMeshSprite3d(this.goodCakeModel);
                    result = UVPickerByMesh.pick(ray, mesh, true);
                    if (result && result.bHit) {
                        this.usedPaintColorIdDict[this.curSelectColorId] = true;
                        this.doDrawUvs([new Laya.Vector2(result.uv.x, result.uv.y)]);
                    }
                };
            }
            createbrush() {
                this.brush = new PaintBrush();
                this.add3DEffectAtBack(this.brush, 0);
                this.brush.transform.position = new Laya.Vector3(0, 1, 0.5);
            }
            createPaintCavas() {
                this.colorCavas1 = PaintCavas.createCavas(512, 512);
                this.colorCavas2 = PaintCavas.createCavas(512, 512);
                this.colorMask = PaintCavas.createCavas(256, 256);
                this.brush.reset(this.colorCavas1);
                this.brush.reset(this.colorCavas2);
                this.brush.reset(this.colorMask);
            }
            onClickItem(id, bAd = false) {
                this.tryPopClickItemTrial(id);
                this.doClickItem(id, bAd);
            }
            tryPopClickItemTrial(partId) {
                if (mgrGuide.isGuiding()) {
                    return;
                }
                if (mgrPlayer.getItemAmount(partId) <= 0 || mgrSdk.getCopNumberValueByKey("b_click_part_item_pop_trial") != 1) {
                    return;
                }
                let gap = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_gap") || 0;
                if (Tools.time() < (mgrPart.roomPopClickItemPartLastTime + gap)) {
                    return;
                }
                let popCount = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_count_per_stage") || 0;
                if (this.roomPopClickItemPartCount > popCount) {
                    return;
                }
                if (!mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial, true)) {
                    return;
                }
                this.roomPopClickItemPartCount++;
                mgrPart.roomPopClickItemPartLastTime = Tools.time();
                let dbName = null;
                let cakeColorData = mgrCfg.get_from_cake_paint_color_db(partId);
                let creamColorData = mgrCfg.get_from_cake_cream_color_db(partId);
                let decoData = mgrCfg.get_from_cake_deco_db(partId);
                let stickerData = mgrCfg.get_from_cake_sticker_db(partId);
                let shapeData = mgrCfg.get_from_cake_shape_db(partId);
                if (!!cakeColorData) {
                    dbName = "cake_paint_color_db";
                }
                else if (!!creamColorData) {
                    dbName = "cake_cream_color_db";
                }
                else if (!!decoData) {
                    dbName = "cake_deco_db";
                }
                else if (!!stickerData) {
                    dbName = "cake_sticker_db";
                }
                else if (!!shapeData) {
                    dbName = "cake_shape_db";
                }
                if (!dbName) {
                    return;
                }
                let lockedPartIdArr = [];
                let dbData = mgrCfg.getDb(dbName);
                for (let k in dbData) {
                    let data = dbData[k];
                    let shopData = mgrCfg.get_from_shop_template_db(data.id);
                    if (mgrPlayer.getItemAmount(data.id) <= 0 && !shopData) {
                        lockedPartIdArr.push(data.id);
                    }
                }
                if (lockedPartIdArr.length == 0) {
                    return;
                }
                let partIdAd = Tools.randomGotOneArrayData(lockedPartIdArr);
                mgrDirector.openDialog("vAdFreeTrialPartDialog", {
                    adEventId: AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial,
                    partId: partIdAd,
                    adTriggerParams: {
                        partId: partIdAd,
                    }
                });
            }
            doClickItem(id, bAd = false) {
                let cakeColorData = mgrCfg.get_from_cake_paint_color_db(id);
                let creamColorData = mgrCfg.get_from_cake_cream_color_db(id);
                let decoData = mgrCfg.get_from_cake_deco_db(id);
                let stickerData = mgrCfg.get_from_cake_sticker_db(id);
                let shapeData = mgrCfg.get_from_cake_shape_db(id);
                if (!!cakeColorData) {
                    this.onClickColor(id, bAd);
                }
                else if (!!creamColorData) {
                    this.onClickCreamColor(id, bAd);
                }
                else if (!!decoData) {
                    this.onClickDeco(id, bAd);
                }
                else if (!!stickerData) {
                    this.onClickSticker(id, bAd);
                }
                else if (!!shapeData) {
                    this.onClickShape(id, bAd);
                }
            }
            isRecommend(id) {
                let idDict = {};
                return !!idDict[id];
            }
            isTrialingItem(partId) {
                return this.tryingPartIds.indexOf(partId) >= 0;
            }
            isCurrentColor(id) {
                return (this.curSelectColorId && this.curSelectColorId == id) ? true : false;
            }
            onClickColor(id, bAd = false) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.tab01Item.click` });
                let shopData = mgrCfg.get_from_shop_template_db(id);
                if (mgrPlayer.getItemAmount(id) <= 0) {
                    if (!!shopData) {
                        let doBuyFunc = () => {
                            if (mgrShop.requestBuy(id, "蛋糕")) {
                                Timer.callLoop(0.016, (timer) => {
                                    if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                        return;
                                    timer.stop();
                                    this.onClickColor(id, false);
                                    this.reuseList.refresh();
                                }, this);
                            }
                        };
                        if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                            let partData = mgrCfg.get_from_item_template_db(id);
                            let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                            mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                doBuyFunc();
                            });
                        }
                        else {
                            doBuyFunc();
                        }
                        return;
                    }
                }
                if (bAd && mgrPlayer.getItemAmount(id) <= 0 && !this.isTrialingItem(id)) {
                    if (!shopData) {
                        if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial)) {
                            if (mgrSdk.getCopNumberValueByKey(`b_room_try_ad_tip`) == 0) {
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                            }
                            else {
                                mgrTip.alertPrompt2("提示", "是否看视频免费试用？", "取消", "确定", null, () => {
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                                }, true, false);
                            }
                        }
                        else {
                            mgrTip.showMsgTip("广告准备中,请稍后再试");
                        }
                    }
                    else {
                        let partData = mgrCfg.get_from_item_template_db(id);
                        let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                        if (!shopData || !shopData.price || !shopData.priceUnit) {
                            mgrTip.showMsgTip("还未获得此部件");
                            return;
                        }
                        if (mgrShop.requestBuy(id, "蛋糕")) {
                            Timer.callLoop(0.016, (timer) => {
                                if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                    return;
                                timer.stop();
                                this.onClickColor(id, false);
                                this.reuseList.refresh();
                            }, this);
                        }
                        else {
                        }
                    }
                    return;
                }
                this.selectColor(id, () => {
                    let colorData = mgrCfg.get_from_cake_paint_color_db(this.curSelectColorId);
                    if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                        !!colorData.statisPointId && mgrSdk.statisCommonEvent(colorData.statisPointId);
                    }
                    let node = this.penguan.getChildByName("penping");
                    let render = Tools.getMeshRender(node);
                    var text2d = null;
                    if (colorData.paint == "") {
                        text2d = PaintBrush.createPureColorTexture(new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1.0)).bitmap;
                    }
                    else {
                        let texture = mgrLoader.get2dRes(colorData.paint);
                        text2d = texture.bitmap;
                    }
                    if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                        text2d.wrapModeU = Laya.WarpMode.Repeat;
                        text2d.wrapModeV = Laya.WarpMode.Repeat;
                        text2d.filterMode = Laya.FilterMode.Bilinear;
                        text2d.generateMipmap();
                    }
                    render.sharedMaterials[1].paintLayer1Texture = text2d;
                    render.sharedMaterials[1].paintLayer1TilingOffset = new Laya.Vector4(colorData.tillingOffset[0], colorData.tillingOffset[1], colorData.tillingOffset[2], colorData.tillingOffset[3]);
                    this.startDrawColor();
                });
            }
            selectColor(id, callback) {
                if (!id) {
                    callback && callback();
                    return;
                }
                this.curSelectColorId = id;
                if (!this.P_Color || !this.P0_Color) {
                    this.P0_Color = this.colorCavas1;
                    this.P_Color = this.colorCavas2;
                    this.goodCakeMaterial.paintLayer1Texture = this.P_Color;
                }
                else {
                    this.goodCakeMaterial.paintLayer1Texture = this.P_Color;
                    this.brush.paintCavas = this.P0_Color;
                    this.brush.drawCavas(new Laya.Vector2(0.5, 0.5), this.P_Color);
                }
                this.brush.curFlowRate = 1;
                this.brush.reset(this.colorMask);
                let colorData = mgrCfg.get_from_cake_paint_color_db(this.curSelectColorId);
                let brushSzieInfo = this.brushSizeInfo[this.curBrushSizeId];
                mgrLoader.batchLoadResources([], [], [colorData.brush, colorData.paint], () => {
                    this.brush.setbrush(this.curSelectColorId, colorData.brush, brushSzieInfo.size, brushSzieInfo.size, () => {
                        this.bPaintColorReadied = true;
                        callback && callback();
                    });
                });
            }
            doDrawUvs(uvArr) {
                this.brush.paintCavas = this.colorMask;
                this.brush.drawUvs(uvArr);
                let colorData = mgrCfg.get_from_cake_paint_color_db(this.curSelectColorId);
                this.brush.paintCavas = this.P_Color;
                let sprite = new Laya.Sprite;
                sprite.size(this.P_Color.width, this.P_Color.height);
                var text2d = null;
                if (colorData.paint == "") {
                    text2d = PaintBrush.createPureColorTexture(new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1.0)).bitmap;
                }
                else {
                    let texture = mgrLoader.get2dRes(colorData.paint);
                    text2d = texture.bitmap;
                }
                if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                    text2d.wrapModeU = Laya.WarpMode.Repeat;
                    text2d.wrapModeV = Laya.WarpMode.Repeat;
                    text2d.filterMode = Laya.FilterMode.Bilinear;
                    text2d.generateMipmap();
                }
                let drawObj = {
                    sprite: sprite,
                    offsetX: this.P_Color.width / 2,
                    offsetY: this.P_Color.height / 2,
                    shaderClass: PaintMaterial,
                    shaderParam: {
                        pageBase: this.P0_Color,
                        paintMask: this.colorMask,
                        paintTexture: text2d,
                        paintTilingOffset: new Laya.Vector4(colorData.tillingOffset[0], colorData.tillingOffset[1], colorData.tillingOffset[2], colorData.tillingOffset[3]),
                    }
                };
                this.brush.setDrawObjs([drawObj]);
                this.brush.drawSetedObjects();
            }
            useSmallBrush() {
                let brushSzieInfo = this.brushSizeInfo[this.curBrushSizeId];
                this.brush.modifyCurBrushSize(brushSzieInfo.size, brushSzieInfo.size);
            }
            onClickCreamColor(id, bAd = false) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.tab02Item.click` });
                let shopData = mgrCfg.get_from_shop_template_db(id);
                if (mgrPlayer.getItemAmount(id) <= 0) {
                    if (!!shopData) {
                        let doBuyFunc = () => {
                            if (mgrShop.requestBuy(id, "蛋糕")) {
                                Timer.callLoop(0.016, (timer) => {
                                    if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                        return;
                                    timer.stop();
                                    this.onClickCreamColor(id, false);
                                    this.reuseList.refresh();
                                }, this);
                            }
                        };
                        if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                            let partData = mgrCfg.get_from_item_template_db(id);
                            let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                            mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                doBuyFunc();
                            });
                        }
                        else {
                            doBuyFunc();
                        }
                        return;
                    }
                }
                if (bAd && mgrPlayer.getItemAmount(id) <= 0 && !this.isTrialingItem(id)) {
                    let shopData = mgrCfg.get_from_shop_template_db(id);
                    if (!shopData) {
                        if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial)) {
                            if (mgrSdk.getCopNumberValueByKey(`b_room_try_ad_tip`) == 0) {
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                            }
                            else {
                                mgrTip.alertPrompt2("提示", "是否看视频免费试用？", "取消", "确定", null, () => {
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                                }, true, false);
                            }
                        }
                        else {
                            mgrTip.showMsgTip("广告准备中,请稍后再试");
                        }
                    }
                    else {
                        let partData = mgrCfg.get_from_item_template_db(id);
                        let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                        if (!shopData || !shopData.price || !shopData.priceUnit) {
                            mgrTip.showMsgTip("还未获得此部件");
                            return;
                        }
                        if (mgrShop.requestBuy(id, "蛋糕")) {
                            Timer.callLoop(0.016, (timer) => {
                                if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                    return;
                                timer.stop();
                                this.onClickCreamColor(id, false);
                                this.reuseList.refresh();
                            }, this);
                        }
                        else {
                        }
                    }
                    return;
                }
                this.curSelectCreamColorId = id;
                this.reuseList.refresh();
                let node = this.naiyoudai.getChildByName("naiyoudai");
                let render = Tools.getMeshRender(node);
                let colorData = mgrCfg.get_from_cake_cream_color_db(this.curSelectCreamColorId);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!colorData.statisPointId && mgrSdk.statisCommonEvent(colorData.statisPointId);
                }
                for (let k in render.sharedMaterials) {
                    let material = render.sharedMaterials[k];
                    if (material.name == "naiyoudai_2") {
                        material.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                        break;
                    }
                }
            }
            isCurrentCreamColor(id) {
                return (this.curSelectCreamColorId && this.curSelectCreamColorId == id) ? true : false;
            }
            onClickDeco(id, bAd = false) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.tab03Item.click` });
                let shopData = mgrCfg.get_from_shop_template_db(id);
                if (mgrPlayer.getItemAmount(id) <= 0) {
                    if (!!shopData) {
                        let doBuyFunc = () => {
                            if (mgrShop.requestBuy(id, "蛋糕")) {
                                Timer.callLoop(0.016, (timer) => {
                                    if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                        return;
                                    timer.stop();
                                    this.onClickDeco(id, false);
                                    this.reuseList.refresh();
                                }, this);
                            }
                        };
                        if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                            let partData = mgrCfg.get_from_item_template_db(id);
                            let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                            mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                doBuyFunc();
                            });
                        }
                        else {
                            doBuyFunc();
                        }
                        return;
                    }
                }
                if (bAd && mgrPlayer.getItemAmount(id) <= 0 && !this.isTrialingItem(id)) {
                    let shopData = mgrCfg.get_from_shop_template_db(id);
                    if (!shopData) {
                        if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial)) {
                            if (mgrSdk.getCopNumberValueByKey(`b_room_try_ad_tip`) == 0) {
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                            }
                            else {
                                mgrTip.alertPrompt2("提示", "是否看视频免费试用？", "取消", "确定", null, () => {
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                                }, true, false);
                            }
                        }
                        else {
                            mgrTip.showMsgTip("广告准备中,请稍后再试");
                        }
                    }
                    else {
                        let partData = mgrCfg.get_from_item_template_db(id);
                        let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                        if (!shopData || !shopData.price || !shopData.priceUnit) {
                            mgrTip.showMsgTip("还未获得此部件");
                            return;
                        }
                        if (mgrShop.requestBuy(id, "蛋糕")) {
                            Timer.callLoop(0.016, (timer) => {
                                if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                    return;
                                timer.stop();
                                this.onClickDeco(id, false);
                                this.reuseList.refresh();
                            }, this);
                        }
                        else {
                        }
                    }
                    return;
                }
                this.curSelectDecoId = id;
                let decoData = mgrCfg.get_from_cake_deco_db(this.curSelectDecoId);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!decoData.statisPointId && mgrSdk.statisCommonEvent(decoData.statisPointId);
                }
                mgrTip.showLoadingTip("loading_deco_model");
                mgrLoader.loadModeWithModeId(decoData.modelName, (bSuccess) => {
                    mgrTip.hideLoadingTip("loading_deco_model");
                }, this, 1);
            }
            isCurrentDeco(id) {
                return (this.curSelectDecoId && this.curSelectDecoId == id) ? true : false;
            }
            onClickSticker(id, bAd = false) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.tab04Item.click` });
                let shopData = mgrCfg.get_from_shop_template_db(id);
                if (mgrPlayer.getItemAmount(id) <= 0) {
                    if (!!shopData) {
                        let doBuyFunc = () => {
                            if (mgrShop.requestBuy(id, "蛋糕")) {
                                Timer.callLoop(0.016, (timer) => {
                                    if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                        return;
                                    timer.stop();
                                    this.onClickSticker(id, false);
                                    this.reuseList.refresh();
                                }, this);
                            }
                        };
                        if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                            let partData = mgrCfg.get_from_item_template_db(id);
                            let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                            mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                doBuyFunc();
                            });
                        }
                        else {
                            doBuyFunc();
                        }
                        return;
                    }
                }
                if (bAd && mgrPlayer.getItemAmount(id) <= 0 && !this.isTrialingItem(id)) {
                    let shopData = mgrCfg.get_from_shop_template_db(id);
                    if (!shopData) {
                        if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial)) {
                            if (mgrSdk.getCopNumberValueByKey(`b_room_try_ad_tip`) == 0) {
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                            }
                            else {
                                mgrTip.alertPrompt2("提示", "是否看视频免费试用？", "取消", "确定", null, () => {
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                                }, true, false);
                            }
                        }
                        else {
                            mgrTip.showMsgTip("广告准备中,请稍后再试");
                        }
                    }
                    else {
                        let partData = mgrCfg.get_from_item_template_db(id);
                        let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                        if (!shopData || !shopData.price || !shopData.priceUnit) {
                            mgrTip.showMsgTip("还未获得此部件");
                            return;
                        }
                        if (mgrShop.requestBuy(id, "蛋糕")) {
                            Timer.callLoop(0.016, (timer) => {
                                if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                    return;
                                timer.stop();
                                this.onClickSticker(id, false);
                                this.reuseList.refresh();
                            }, this);
                        }
                        else {
                        }
                    }
                    return;
                }
                this.curSelectStickerId = id;
                let stickerData = mgrCfg.get_from_cake_sticker_db(this.curSelectStickerId);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!stickerData.statisPointId && mgrSdk.statisCommonEvent(stickerData.statisPointId);
                }
                mgrTip.showLoadingTip("loading_sticker_model");
                mgrLoader.loadModeWithModeId(stickerData.modelName, (bSuccess) => {
                    mgrTip.hideLoadingTip("loading_sticker_model");
                }, this, 1);
            }
            isCurrentSticker(id) {
                return (this.curSelectStickerId && this.curSelectStickerId == id) ? true : false;
            }
            onClickShape(id, bAd = false) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.tab05Item.click` });
                let shopData = mgrCfg.get_from_shop_template_db(id);
                console.log("onClickShape========", shopData);
                if (mgrPlayer.getItemAmount(id) <= 0) {
                    if (!!shopData) {
                        let doBuyFunc = () => {
                            if (mgrShop.requestBuy(id, "蛋糕")) {
                                Timer.callLoop(0.016, (timer) => {
                                    if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                        return;
                                    timer.stop();
                                    this.onClickShape(id, false);
                                    this.reuseList.refresh();
                                }, this);
                            }
                        };
                        if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                            let partData = mgrCfg.get_from_item_template_db(id);
                            let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                            mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                doBuyFunc();
                            });
                        }
                        else {
                            doBuyFunc();
                        }
                        return;
                    }
                }
                if (bAd && mgrPlayer.getItemAmount(id) <= 0 && !this.isTrialingItem(id)) {
                    let shopData = mgrCfg.get_from_shop_template_db(id);
                    if (!shopData) {
                        if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial)) {
                            if (mgrSdk.getCopNumberValueByKey(`b_room_try_ad_tip`) == 0) {
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                            }
                            else {
                                mgrTip.alertPrompt2("提示", "是否看视频免费试用？", "取消", "确定", null, () => {
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial, { partId: id }, true);
                                }, true, false);
                            }
                        }
                        else {
                            mgrTip.showMsgTip("广告准备中,请稍后再试");
                        }
                    }
                    else {
                        let partData = mgrCfg.get_from_item_template_db(id);
                        let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                        if (!shopData || !shopData.price || !shopData.priceUnit) {
                            mgrTip.showMsgTip("还未获得此部件");
                            return;
                        }
                        if (mgrShop.requestBuy(id, "蛋糕")) {
                            Timer.callLoop(0.016, (timer) => {
                                if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                    return;
                                timer.stop();
                                this.onClickShape(id, false);
                                this.reuseList.refresh();
                            }, this);
                        }
                        else {
                        }
                    }
                    return;
                }
                let tab2SelectIdDict = {
                    [this.TAB_PAINT]: this.usedPaintColorIdDict,
                    [this.TAB_CRAEM]: this.usedCreamColorIdDict,
                    [this.TAB_DECO]: this.usedDecoIdDict,
                    [this.TAB_STICKER]: this.usedStickerIdDict,
                    [this.TAB_SHAPE]: this.usedShapeIdDict,
                };
                let bOtherTypeFinished = false;
                for (let i = 1; i <= 4; i++) {
                    if (Tools.getObjSize(tab2SelectIdDict[i]) > 0) {
                        bOtherTypeFinished = true;
                        break;
                    }
                }
                let onConfirmShape = () => {
                    this.usedShapeIdDict = {};
                    this.resetCreamData();
                    this.resetDeco();
                    this.resetPaintColor();
                    this.resetSticker();
                    this.curSelectShapeId = id;
                    let shapeData = mgrCfg.get_from_cake_shape_db(id);
                    let targetCreamCombineId = Tools.randomGotOneArrayData(shapeData.standbyCreamCombineIdArr);
                    this.imgCreamGuideIndedx = shapeData.standbyCreamCombineIdArr.indexOf(targetCreamCombineId);
                    if (shapeData.standbyImgCreamGuide && shapeData.standbyImgCreamGuide[this.imgCreamGuideIndedx]) {
                        this.stageData.imgCreamGuide = shapeData.standbyImgCreamGuide[this.imgCreamGuideIndedx];
                    }
                    else {
                        this.stageData.imgCreamGuide = "";
                    }
                    this.stageData.targetCreamCombineId = targetCreamCombineId;
                    this.stageData.creamArr = (mgrCfg.get_from_cake_cream_combine_db(this.stageData.targetCreamCombineId) || []);
                    this.stageData.cakeHeight = shapeData.cakeHeight;
                    this.doClickShape(() => {
                        this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.cakeShape);
                    });
                };
                if (!this.badCakeModel.active && bOtherTypeFinished) {
                    mgrTip.alertPrompt2("提示", "切换糕体将会重置所有的蛋糕操作，确定切换吗？", "取消", "确定", () => { }, () => {
                        onConfirmShape();
                    });
                }
                else {
                    onConfirmShape();
                }
            }
            doClickShape(callback) {
                this.resetModelData();
                this.badCakeMeshPosScaleDict = {};
                this.badCakeShowingPositionArr = [];
                this.badCakeShowingPositionRotArr = [];
                this.calculatedPosY2RDict = {};
                if (this.goodCakeModel) {
                    this.goodCakeModel.destroy();
                    this.goodCakeModel = null;
                }
                if (this.badCakeModel) {
                    this.badCakeModel.destroy();
                    this.badCakeModel = null;
                }
                if (this.shapeCakeModel) {
                    this.shapeCakeModel.destroy();
                    this.shapeCakeModel = null;
                }
                let badCakeModel = mgrLoader.Pool.getModel("gaoti_jimo");
                this.avatar.addChild(badCakeModel);
                mgrMaterial.setCustomMaterial(badCakeModel, "gaoti_jimo");
                this.badCakeModel = badCakeModel;
                this.badCakeMeshData = this.getModelMeshData(this.badCakeModel);
                let shapeData = mgrCfg.get_from_cake_shape_db(this.curSelectShapeId);
                console.log("shapeData", shapeData, this.curSelectShapeId);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!shapeData.statisPointId && mgrSdk.statisCommonEvent(shapeData.statisPointId);
                }
                this.badCakeShowingPositionArr = Tools.deepCopy(this.badCakeMeshData.positionArr);
                let positionArr = this.badCakeMeshData.positionArr;
                for (let index = 0; index < positionArr.length; index++) {
                    let posModel = positionArr[index];
                    let oRot = Tools.getAngle(posModel.x, posModel.z);
                    this.badCakeShowingPositionRotArr[index] = oRot;
                }
                shapeData.imgShapeGuide && this.tryShowShapeGuide(shapeData.imgShapeGuide);
                let tmpCallback = () => {
                    mgrTip.hideLoadingTip("loading_shape_model");
                    callback && callback();
                };
                let preloadImgArr = [];
                if (!!shapeData.defaultCakeColorId) {
                    let colorData = mgrCfg.get_from_cake_paint_color_db(shapeData.defaultCakeColorId);
                    preloadImgArr.push(colorData.paint);
                    preloadImgArr.push(colorData.brush);
                }
                mgrTip.showLoadingTip("loading_shape_model");
                mgrLoader.batchLoadResources([shapeData.cakeModelName, shapeData.cakeShapeModelName], null, null, () => {
                    if (this.goodCakeMaterial) {
                        this.goodCakeMaterial.paintLayer1TilingOffset = new Laya.Vector4(1, 1, 0, 0);
                        this.goodCakeMaterial.paintLayer1Texture = null;
                        this.goodCakeMaterial = null;
                    }
                    if (this.goodCakeModel && !this.goodCakeModel.destroyed) {
                        mgrLoader.Pool.recoverModel(this.goodCakeModel);
                        this.goodCakeModel = null;
                    }
                    if (this.shapeCakeModel && !this.shapeCakeModel.destroyed) {
                        mgrLoader.Pool.recoverModel(this.shapeCakeModel);
                        this.shapeCakeModel = null;
                    }
                    let cakeData = mgrCfg.get_from_cake_shape_db(this.curSelectShapeId);
                    console.log("cakeData.cakeModelName========", cakeData.cakeModelName);
                    let goodCakeModel = mgrLoader.Pool.getModel(cakeData.cakeModelName);
                    let shapeCakeModel = mgrLoader.Pool.getModel(cakeData.cakeShapeModelName);
                    mgrMaterial.setCustomMaterial(goodCakeModel, cakeData.cakeModelName);
                    this.avatar.addChild(goodCakeModel);
                    this.goodCakeModel = goodCakeModel;
                    this.shapeCakeModel = shapeCakeModel;
                    this.shapeCakeMeshData = this.getModelMeshData(shapeCakeModel);
                    this.syncBadCakeMaterialFromGoodCake();
                    this.splitShapePosRange();
                    this.goodCakeModel.active = true;
                    this.badCakeModel.active = true;
                    this.initPaintMaterial();
                    if (!!shapeData.defaultCakeColorId) {
                        this.selectColor(shapeData.defaultCakeColorId, () => {
                            let text2dBrush = PaintBrush.createPureColorTexture(new Laya.Color(1.0, 1.0, 1.0, 1.0)).bitmap;
                            if (text2dBrush.wrapModeU != Laya.WarpMode.Repeat) {
                                text2dBrush.wrapModeU = Laya.WarpMode.Repeat;
                                text2dBrush.wrapModeV = Laya.WarpMode.Repeat;
                                text2dBrush.filterMode = Laya.FilterMode.Bilinear;
                                text2dBrush.generateMipmap();
                            }
                            this.brush.paintCavas = this.colorMask;
                            this.brush.fullWithTexture2D(this.colorMask, text2dBrush);
                            let colorData = mgrCfg.get_from_cake_paint_color_db(shapeData.defaultCakeColorId);
                            var text2d = null;
                            if (colorData.paint == "") {
                                text2d = PaintBrush.createPureColorTexture(new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1.0)).bitmap;
                            }
                            else {
                                let texture = mgrLoader.get2dRes(colorData.paint);
                                text2d = texture.bitmap;
                            }
                            if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                text2d.wrapModeU = Laya.WarpMode.Repeat;
                                text2d.wrapModeV = Laya.WarpMode.Repeat;
                                text2d.filterMode = Laya.FilterMode.Bilinear;
                                text2d.generateMipmap();
                            }
                            let sprite = new Laya.Sprite;
                            sprite.size(this.P_Color.width, this.P_Color.height);
                            this.brush.paintCavas = this.P_Color;
                            let drawObj = {
                                sprite: sprite,
                                offsetX: this.P_Color.width / 2,
                                offsetY: this.P_Color.height / 2,
                                shaderClass: PaintMaterial,
                                shaderParam: {
                                    pageBase: this.P0_Color,
                                    paintMask: this.colorMask,
                                    paintTexture: text2d,
                                    paintTilingOffset: new Laya.Vector4(colorData.tillingOffset[0], colorData.tillingOffset[1], colorData.tillingOffset[2], colorData.tillingOffset[3]),
                                }
                            };
                            this.brush.setDrawObjs([drawObj]);
                            this.brush.drawSetedObjects();
                            tmpCallback && tmpCallback();
                        });
                    }
                    else {
                        tmpCallback && tmpCallback();
                    }
                });
            }
            isCurrentShape(id) {
                return (this.curSelectShapeId && this.curSelectShapeId == id) ? true : false;
            }
            showPartContainer(bImmi) {
                if (bImmi) {
                    cc.tween(this.boxPartContainer).removeAllActions();
                    this.boxPartContainer.scale(1, 1, true);
                    return;
                }
                cc.tween(this.boxPartContainer, true).toScale(0.2, 1).start();
            }
            hidePartContainer(bImmi) {
                if (bImmi) {
                    cc.tween(this.boxPartContainer).removeAllActions();
                    this.boxPartContainer.scale(0, 0, true);
                    return;
                }
                cc.tween(this.boxPartContainer, true).toScale(0.2, 0).start();
            }
            tryShowCreamGuide(bImmi) {
                if (!this.stageData) {
                    return;
                }
                if (!this.stageData.imgCreamGuide) {
                    return;
                }
                mgrLoader.Load2dRes(this.stageData.imgCreamGuide, Laya.Loader.IMAGE, this, (res) => {
                    let scale = 0.32;
                    let textureBg = Laya.loader.getRes(this.stageData.imgCreamGuide);
                    let quadMeshBg = Laya.PrimitiveMesh.createQuad(scale, scale);
                    let quadBg = new Laya.MeshSprite3D(quadMeshBg);
                    let materialBg = new Laya.UnlitMaterial;
                    materialBg.renderMode = Laya.UnlitMaterial.RENDERMODE_TRANSPARENT;
                    materialBg.cull = Laya.RenderState.CULL_NONE;
                    materialBg.albedoTexture = textureBg.bitmap;
                    quadBg.meshRenderer.sharedMaterial = materialBg;
                    quadBg.transform.localPositionZ = 0.2;
                    quadBg.transform.localPositionY = 0.15;
                    this.add3DEffectAtBack(quadBg, 0);
                    this.creamGuideModel = quadBg;
                });
            }
            tryExecShineCreamGuide() {
                if (!this.creamGuideModel || this.creamGuideModel.destroyed) {
                    return;
                }
                let _tmpMaterialIntensityFlag = this.creamGuideModel["_tmpMaterialIntensityFlag"] || 1;
                let albedoIntensity = this.creamGuideModel.meshRenderer.sharedMaterial.albedoIntensity;
                albedoIntensity += (0.03 * _tmpMaterialIntensityFlag);
                if (_tmpMaterialIntensityFlag > 0) {
                    if (albedoIntensity > 1) {
                        albedoIntensity = 1;
                        this.creamGuideModel["_tmpMaterialIntensityFlag"] = -1;
                    }
                }
                else {
                    if (albedoIntensity < 0.5) {
                        albedoIntensity = 0.5;
                        this.creamGuideModel["_tmpMaterialIntensityFlag"] = 1;
                    }
                }
                this.creamGuideModel.meshRenderer.sharedMaterial.albedoIntensity = albedoIntensity;
            }
            tryHideCreamGuide(bImmi) {
                if (!this.creamGuideModel || this.creamGuideModel.destroyed) {
                    return;
                }
                this.creamGuideModel.destroy();
                this.creamGuideModel = null;
            }
            tryShowShapeGuide(imgShapeGuide) {
                if (this.shapeGuideModel) {
                    this.shapeGuideModel.destroy();
                    this.shapeGuideModel = null;
                }
                mgrLoader.Load2dRes(imgShapeGuide, Laya.Loader.IMAGE, this, (res) => {
                    let scale = 0.32;
                    let textureBg = Laya.loader.getRes(imgShapeGuide);
                    let quadMeshBg = Laya.PrimitiveMesh.createQuad(scale, scale);
                    let quadBg = new Laya.MeshSprite3D(quadMeshBg);
                    let materialBg = new Laya.UnlitMaterial;
                    materialBg.renderMode = Laya.UnlitMaterial.RENDERMODE_TRANSPARENT;
                    materialBg.cull = Laya.RenderState.CULL_NONE;
                    materialBg.albedoTexture = textureBg.bitmap;
                    quadBg.meshRenderer.sharedMaterial = materialBg;
                    quadBg.transform.localPositionZ = 0.2;
                    quadBg.transform.localPositionY = 0.15;
                    this.add3DEffectAtBack(quadBg, 0);
                    this.shapeGuideModel = quadBg;
                });
            }
            tryExecShineShapeGuide() {
                if (!this.shapeGuideModel || this.shapeGuideModel.destroyed) {
                    return;
                }
                let _tmpMaterialIntensityFlag = this.shapeGuideModel["_tmpMaterialIntensityFlag"] || 1;
                let albedoIntensity = this.shapeGuideModel.meshRenderer.sharedMaterial.albedoIntensity;
                albedoIntensity += (0.03 * _tmpMaterialIntensityFlag);
                if (_tmpMaterialIntensityFlag > 0) {
                    if (albedoIntensity > 1) {
                        albedoIntensity = 1;
                        this.shapeGuideModel["_tmpMaterialIntensityFlag"] = -1;
                    }
                }
                else {
                    if (albedoIntensity < 0.5) {
                        albedoIntensity = 0.5;
                        this.shapeGuideModel["_tmpMaterialIntensityFlag"] = 1;
                    }
                }
                this.shapeGuideModel.meshRenderer.sharedMaterial.albedoIntensity = albedoIntensity;
            }
            tryHideShapeGuide(bImmi) {
                if (!this.shapeGuideModel || this.shapeGuideModel.destroyed) {
                    return;
                }
                this.shapeGuideModel.destroy();
                this.shapeGuideModel = null;
            }
            onTouchSpriteBg(e) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.spriteGuide.click` });
                if (e.isBegin && !Tools.isWorldLocaInNode(this.boxPartContainer, new Laya.Vector2(e.pos.x, e.pos.y))) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.startTouchTime = Tools.time();
                    if (this.touchLoopSoundTimer) {
                        this.touchLoopSoundTimer.stop();
                        this.touchLoopSoundTimer = null;
                    }
                    if (this.stManager.getCurState() == AMUSE_CAKE_MAKE_STATE.cream) {
                        this.operatingCreamIndex = -1;
                        let screenWorldPos = new Laya.Vector2(this.lastTouchBgPos.x, this.lastTouchBgPos.y);
                        let ray = Tools.createRayFromScreenPos(this.cameraBack, screenWorldPos);
                        let result = UVPickerByMesh.pick(ray, Tools.findMeshSprite3d(this.goodCakeModel), true);
                        if (!result || !result.bHit) {
                            return;
                        }
                        if (!this.stageData || !this.stageData.creamArr) {
                            return;
                        }
                        this.operatingCreamIndex = this.getCreamIndexByHitedPoint(result.point);
                        if (this.operatingCreamIndex < 0) {
                            return;
                        }
                        this.initDataWhenTouchedCream(result.point);
                        cc.tween(this.naiyoudai.transform).removeAllActions();
                        this.naiyoudai.transform.position = result.point;
                        this.touchLoopSoundTimer = Timer.callLoop(0.2, () => {
                            mgrSound.play(423);
                        }, this);
                    }
                    else if (this.stManager.getCurState() == AMUSE_CAKE_MAKE_STATE.cakeShape) {
                        this.touchLoopSoundTimer = Timer.callLoop(0.2, () => {
                            mgrSound.play(424);
                        }, this);
                    }
                    else if (this.stManager.getCurState() == AMUSE_CAKE_MAKE_STATE.paintColor) {
                        this.touchLoopSoundTimer = Timer.callLoop(0.2, () => {
                            mgrSound.play(425);
                        }, this);
                    }
                    else if (this.stManager.getCurState() == AMUSE_CAKE_MAKE_STATE.deco) {
                        if (!Tools.isWorldLocaInNode(this.boxPartContainer, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            if (this.decoModelArr.length > this.MAX_DECO_MODEL_COUNT) {
                                mgrTip.showMsgTip("太多啦，不能再加的啦");
                            }
                            else {
                                mgrSound.play(426);
                                this.tryAddDeco();
                            }
                        }
                    }
                    else if (this.stManager.getCurState() == AMUSE_CAKE_MAKE_STATE.sticker) {
                        if (!Tools.isWorldLocaInNode(this.boxPartContainer, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            if (this.stickerModelArr.length > this.MAX_STICKER_MODEL_COUNT) {
                                mgrTip.showMsgTip("太多啦，不能再加的啦");
                            }
                            else {
                                mgrSound.play(427);
                                this.tryAddSticker();
                            }
                        }
                    }
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                    if (this.touchLoopSoundTimer) {
                        this.touchLoopSoundTimer.stop();
                        this.touchLoopSoundTimer = null;
                    }
                    if (this.stManager.getCurState() == AMUSE_CAKE_MAKE_STATE.cream) {
                        let originPos = this.naiyoudai['_originPos'];
                        cc.tween(this.naiyoudai.transform)
                            .to(0.5, { localPositionX: originPos.x, localPositionY: originPos.y, localPositionZ: originPos.z })
                            .start();
                    }
                    this.refreshTabUsedStatus();
                    this.refreshTargetScore();
                }
                if (this.bTouchBg) {
                    this.lastTouchBgPos = e.pos;
                }
            }
            tryAddDeco() {
                if (!this.curSelectDecoId) {
                    return;
                }
                let decoData = mgrCfg.get_from_cake_deco_db(this.curSelectDecoId);
                if (!decoData) {
                    return;
                }
                this.usedDecoIdDict[this.curSelectDecoId] = true;
                this.refreshTabUsedStatus();
                this.refreshTargetScore();
                let delayTime = Tools.random() * 0.1;
                let decoModel = mgrLoader.Pool.getModel(decoData.modelName);
                mgrMaterial.setCustomMaterial(decoModel, decoData.modelName);
                Tools.setModelAlbedoColor(decoModel, new Laya.Color(decoData.color[0] / 255, decoData.color[1] / 255, decoData.color[2] / 255, 1));
                this.add3DEffectAtBack(decoModel, 0);
                this.decoModelArr.push(decoModel);
                let gudndianNode = this.boliping.getChildByName("guadian_eff");
                decoModel.transform.position = gudndianNode.transform.position.clone();
                decoModel.transform.localRotationEulerX = Tools.random(30) * (Tools.random(100) > 50 ? 1 : -1);
                decoModel.transform.localRotationEulerZ = Tools.random(360);
                let startPos = decoModel.transform.position.clone();
                let shapeData = mgrCfg.get_from_cake_shape_db(this.curSelectShapeId);
                let targetPosition = new Laya.Vector3(0, shapeData.cakeHeight * 0.1 + Tools.random(100) / 100 * shapeData.cakeHeight * 0.7, 0);
                let oRot = Tools.getAngle(startPos.x, startPos.z);
                let tmpPos = new Laya.Vector3;
                let offsetHeight = 0.1;
                let doLerpPosFunc = (percent) => {
                    Laya.Vector3.lerp(startPos, targetPosition, percent, tmpPos);
                    let offsetY = cc.Ease.expoOut((percent > 0.5 ? 1 - percent : percent) / 0.5) * offsetHeight;
                    tmpPos.y += offsetY;
                    decoModel.transform.position = tmpPos.clone();
                    let relateCakeROfY = this.getGoodCakeRByPosY(tmpPos.y) + (shapeData.decoOffsetDistance || 0.018);
                    if (Math.abs(tmpPos.x) <= relateCakeROfY && Math.abs(tmpPos.z) <= relateCakeROfY && Laya.Vector3.distance(tmpPos, new Laya.Vector3(0, tmpPos.y, 0)) <= relateCakeROfY) {
                        decoTimer.stop();
                        let posBorder = Tools.getCircleBorderPosPoint(new Laya.Vector2(0, 0), relateCakeROfY, oRot);
                        let cPos = new Laya.Vector3(posBorder.y, tmpPos.y, posBorder.x);
                        decoModel.removeSelf();
                        this.avatar.addChild(decoModel);
                        decoModel.transform.position = cPos.clone();
                        decoModel.transform.localRotationEulerY = Tools.getAngle(decoModel.transform.localPositionX, decoModel.transform.localPositionZ);
                    }
                };
                let startTime = Tools.time();
                let dur = 0.5;
                let decoTimer = Timer.callLoop(0.016, (timer) => {
                    delayTime -= 0.016;
                    if (delayTime > 0) {
                        return;
                    }
                    let passTime = Tools.time() - startTime;
                    if (passTime >= dur) {
                        doLerpPosFunc(1);
                        timer.stop();
                        return;
                    }
                    doLerpPosFunc(passTime / dur);
                }, this);
            }
            tryAddSticker() {
                if (!this.curSelectStickerId) {
                    return;
                }
                let decoData = mgrCfg.get_from_cake_sticker_db(this.curSelectStickerId);
                if (!decoData) {
                    return;
                }
                this.usedStickerIdDict[this.curSelectStickerId] = true;
                this.refreshTabUsedStatus();
                this.refreshTargetScore();
                let decoModel = mgrLoader.Pool.getModel(decoData.modelName);
                mgrMaterial.setCustomMaterial(decoModel, decoData.modelName);
                Tools.setModelAlbedoColor(decoModel, new Laya.Color(decoData.color[0] / 255, decoData.color[1] / 255, decoData.color[2] / 255, 1));
                this.add3DEffectAtBack(decoModel, 0);
                this.stickerModelArr.push(decoModel);
                let gudndianNode = this.boliping.getChildByName("guadian_eff");
                decoModel.transform.position = gudndianNode.transform.position.clone();
                decoModel.transform.localRotationEulerX = Tools.random(30) * (Tools.random(100) > 50 ? 1 : -1);
                decoModel.transform.localRotationEulerZ = Tools.random(360);
                let shapeData = mgrCfg.get_from_cake_shape_db(this.curSelectShapeId);
                let startPos = decoModel.transform.position.clone();
                let targetPosition = new Laya.Vector3(0, shapeData.cakeHeight * 0.1 + Tools.random(100) / 100 * shapeData.cakeHeight * 0.5, 0);
                let oRot = Tools.getAngle(startPos.x, startPos.z);
                let tmpPos = new Laya.Vector3;
                let offsetHeight = 0.1;
                let doLerpPosFunc = (percent) => {
                    Laya.Vector3.lerp(startPos, targetPosition, percent, tmpPos);
                    let offsetY = cc.Ease.expoOut((percent > 0.5 ? 1 - percent : percent) / 0.5) * offsetHeight;
                    tmpPos.y += offsetY;
                    decoModel.transform.position = tmpPos.clone();
                    let relateCakeROfY = this.getGoodCakeRByPosY(tmpPos.y) + (shapeData.decoOffsetDistance || 0.018);
                    if (Math.abs(tmpPos.x) <= relateCakeROfY && Math.abs(tmpPos.z) <= relateCakeROfY && Laya.Vector3.distance(tmpPos, new Laya.Vector3(0, tmpPos.y, 0)) <= relateCakeROfY) {
                        decoTimer.stop();
                        let posBorder = Tools.getCircleBorderPosPoint(new Laya.Vector2(0, 0), relateCakeROfY, oRot);
                        let cPos = new Laya.Vector3(posBorder.y, tmpPos.y, posBorder.x);
                        decoModel.removeSelf();
                        this.avatar.addChild(decoModel);
                        decoModel.transform.position = cPos.clone();
                        decoModel.transform.localRotationEulerY = Tools.getAngle(decoModel.transform.localPositionX, decoModel.transform.localPositionZ);
                    }
                };
                let startTime = Tools.time();
                let dur = 0.5;
                let decoTimer = Timer.callLoop(0.016, (timer) => {
                    let passTime = Tools.time() - startTime;
                    if (passTime >= dur) {
                        doLerpPosFunc(1);
                        timer.stop();
                        return;
                    }
                    doLerpPosFunc(passTime / dur);
                }, this);
            }
            inInit() {
                this.buttonSummit.__node.scale(0, 0, true);
                this.refreshTabUsedStatus();
                this.refreshTargetScore();
                this.registerGuideNode();
                mgrVideoRecorder.startRecord();
                if (this.stageData.bCanSelectShape) {
                    this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.selectShape);
                    this.onSelectTab(this.TAB_SHAPE);
                }
                else {
                    this.curSelectShapeId = this.stageData.defaultShapeId;
                    this.usedShapeIdDict = {};
                    this.resetCreamData();
                    this.resetDeco();
                    this.resetPaintColor();
                    this.resetSticker();
                    let shapeData = mgrCfg.get_from_cake_shape_db(this.curSelectShapeId);
                    let targetCreamCombineId = Tools.randomGotOneArrayData(shapeData.standbyCreamCombineIdArr);
                    this.imgCreamGuideIndedx = shapeData.standbyCreamCombineIdArr.indexOf(targetCreamCombineId);
                    if (shapeData.standbyImgCreamGuide && shapeData.standbyImgCreamGuide[this.imgCreamGuideIndedx]) {
                        this.stageData.imgCreamGuide = shapeData.standbyImgCreamGuide[this.imgCreamGuideIndedx];
                    }
                    else {
                        this.stageData.imgCreamGuide = "";
                    }
                    this.stageData.targetCreamCombineId = targetCreamCombineId;
                    this.stageData.creamArr = (mgrCfg.get_from_cake_cream_combine_db(this.stageData.targetCreamCombineId) || []);
                    this.stageData.cakeHeight = shapeData.cakeHeight;
                    this.doClickShape(() => {
                        this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.cakeShape);
                    });
                }
            }
            exeInit() {
            }
            outInit() {
            }
            inSelectShape() {
                this.cameraFollow.fov = CAMERA_PRARAM_CAKE_MAKE.fov;
                this.cameraFollow.position = CAMERA_PRARAM_CAKE_MAKE.position;
                this.cameraFollow.endRotation = CAMERA_PRARAM_CAKE_MAKE.rotation;
                this.cameraFollow.lerpValue = CAMERA_PRARAM_CAKE_MAKE.lerpValue;
                let arr = this.getPartDataByDbName("cake_shape_db", this.onClickItem.bind(this), this.isCurrentShape.bind(this));
                this.reuseList.setDatas(arr);
                Timer.callLater(0.016, () => {
                    this.reuseList.scrollTo(0);
                }, this);
                this.showPartContainer();
                if (!!this.curSelectShapeId) {
                    return;
                }
                let shapeId = 0;
                mgrCfg.forDb_from_cake_shape_db((k, v) => {
                    if (mgrPlayer.getItemAmount(parseInt(k)) > 0) {
                        shapeId = parseInt(k);
                    }
                });
                this.onClickShape(shapeId);
            }
            exeSelectShape() {
                this.cakeRotatedYValue -= 1;
                this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
            }
            outSelectShape() {
                Tools.unRegisterTouchHander(this.spriteTouch);
            }
            inCakeShape() {
                if (!!this.stageData.bDisableShape && !this.stageData.bCanSelectShape) {
                    this.bTouchBg = false;
                    this.shapeKnifedY2RData = null;
                    this.knifeModel.active = false;
                    this.badCakeModel.active = false;
                    this.goodCakeModel.active = true;
                    this.reInitHandleCream(() => {
                        this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.paintColor);
                        this.onSelectTab(this.TAB_PAINT);
                    });
                    return;
                }
                this.shapeKnifedY2RData = {};
                this.badCakeModel.active = true;
                this.badCakeShowingPositionArr = Tools.deepCopy(this.badCakeMeshData.positionArr);
                let positionArr = this.badCakeMeshData.positionArr;
                for (let index = 0; index < positionArr.length; index++) {
                    let posModel = positionArr[index];
                    let oRot = Tools.getAngle(posModel.x, posModel.z);
                    this.badCakeShowingPositionRotArr[index] = oRot;
                }
                this.startShapeCake();
                if (!mgrGuide.isFinished(2100)) {
                    mgrGuide.startGuide(2100);
                }
            }
            exeCakeShape() {
                if (!!mgrGuide.isGuiding()) {
                    this.buttonBack.__node.scale(0, 0, true);
                }
                this.cakeRotatedYValue -= 1;
                this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
                this.tryExecShineShapeGuide();
                if (!this.bTouchBg || !this.shapeKnifedY2RData || (!this.shapeKnifedY2RData.x && !this.shapeKnifedY2RData.y)) {
                    return;
                }
                let currTouchData = this.shapeKnifedY2RData;
                let positionArr = this.badCakeMeshData.positionArr;
                let totalDis = 0.0000001;
                let shapedDis = 0;
                for (let index = 0; index < positionArr.length; index++) {
                    let posModel = positionArr[index];
                    let rData = this.badCakeMeshPosScaleDict[index] = this.badCakeMeshPosScaleDict[index] || {};
                    rData.targetGoodR = rData.targetGoodR || this.getGoodCakeRByPosY(posModel.y);
                    rData.startR = rData.startR || this.BAD_CAKE_R;
                    rData.currR = rData.currR || this.BAD_CAKE_R;
                    totalDis += (rData.startR - rData.targetGoodR);
                    if (Math.abs(currTouchData.y - posModel.y) > 0.03) {
                        shapedDis += (rData.startR - rData.currR);
                        continue;
                    }
                    let tmpCurrR = Math.max(rData.currR - 0.007, rData.targetGoodR);
                    if (tmpCurrR < Math.abs(currTouchData.x)) {
                        shapedDis += (rData.startR - rData.currR);
                        continue;
                    }
                    rData.currR = tmpCurrR;
                    shapedDis += (rData.startR - rData.currR);
                    let oRot = this.badCakeShowingPositionRotArr[index];
                    let posBorder = Tools.getCircleBorderPosPoint(new Laya.Vector2(0, 0), rData.currR, oRot);
                    this.badCakeMeshPosScaleDict[index] = rData;
                    this.badCakeShowingPositionArr[index] = new Laya.Vector3(posBorder.y, posModel.y, posBorder.x);
                }
                this.badCakeMeshData.meshData["_setVerticeElementData"](this.badCakeShowingPositionArr, Laya.VertexMesh.MESH_POSITION0);
                if (shapedDis / totalDis > 0.7) {
                    this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.cakeShapeAutoComplete);
                }
            }
            outCakeShape() {
                Tools.unRegisterTouchHander(this.spriteTouch);
                if (this.shapeEndCastRay) {
                    this.shapeEndCastRay();
                }
                this.tryHideShapeGuide();
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCakeMakeScene.outCakeShape` });
            }
            inCakeShapeAutoComplete() {
                this.hidePartContainer(true);
                this.knifeEffModel.active = true;
                let positionArr = this.badCakeMeshData.positionArr;
                let totalDis = 0.0000001;
                let shapedDis = 0;
                for (let index = 0; index < positionArr.length; index++) {
                    let posModel = positionArr[index];
                    let rData = this.badCakeMeshPosScaleDict[index] = this.badCakeMeshPosScaleDict[index] || {};
                    rData.targetGoodR = rData.targetGoodR || this.getGoodCakeRByPosY(posModel.y);
                    rData.startR = rData.startR || this.BAD_CAKE_R;
                    rData.currR = rData.currR || this.BAD_CAKE_R;
                    totalDis += (rData.startR - rData.targetGoodR);
                    let tmpCurrR = Math.max(rData.currR - 0.007, rData.targetGoodR);
                    rData.currR = tmpCurrR;
                    shapedDis += (rData.startR - rData.currR);
                }
                this.state2ScoreDict[AMUSE_CAKE_MAKE_STATE.cakeShape] = shapedDis / totalDis * 100;
                this.bTouchBg = false;
                this.shapeKnifedY2RData = null;
                cc.tween(this.knifeModel.transform, true)
                    .repeatForever(cc.tween().to(0.1, { localPositionX: 0.05, localPositionY: 0.3, localRotationEulerX: 0 }).to(0.1, { localPositionY: 0 }))
                    .start();
            }
            exeCakeShapeAutoComplete() {
                this.cakeRotatedYValue -= 1;
                this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
                let positionArr = this.badCakeMeshData.positionArr;
                let totalDis = 0.0000001;
                let shapedDis = 0;
                for (let index = 0; index < positionArr.length; index++) {
                    let posModel = positionArr[index];
                    let rData = this.badCakeMeshPosScaleDict[index] = this.badCakeMeshPosScaleDict[index] || {};
                    rData.targetGoodR = rData.targetGoodR || this.getGoodCakeRByPosY(posModel.y);
                    rData.startR = rData.startR || this.BAD_CAKE_R;
                    rData.currR = rData.currR || this.BAD_CAKE_R;
                    totalDis += (rData.startR - rData.targetGoodR);
                    let tmpCurrR = Math.max(rData.currR - 0.001, rData.targetGoodR);
                    if (tmpCurrR < Math.abs(rData.targetGoodR)) {
                        shapedDis += (rData.startR - rData.currR);
                        continue;
                    }
                    rData.currR = tmpCurrR;
                    shapedDis += (rData.startR - rData.currR);
                    let oRot = this.badCakeShowingPositionRotArr[index];
                    let posBorder = Tools.getCircleBorderPosPoint(new Laya.Vector2(0, 0), rData.currR, oRot);
                    this.badCakeMeshPosScaleDict[index] = rData;
                    this.badCakeShowingPositionArr[index] = new Laya.Vector3(posBorder.y, posModel.y, posBorder.x);
                }
                this.badCakeMeshData.meshData["_setVerticeElementData"](this.badCakeShowingPositionArr, Laya.VertexMesh.MESH_POSITION0);
                if (shapedDis / totalDis > 0.98) {
                    this.knifeModel.active = false;
                    this.badCakeModel.active = false;
                    this.goodCakeModel.active = true;
                    if (!!this.knifeEffModel.active) {
                        if (!this.stageData.bCanSelectShape) {
                            this.reInitHandleCream(() => {
                                this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.paintColor);
                                this.add3DEffectAtFront("117_ui_once_flash_01", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 1);
                                this.onSelectTab(this.TAB_PAINT);
                            });
                        }
                        else {
                            this.usedShapeIdDict[this.curSelectShapeId] = true;
                            this.refreshTabUsedStatus();
                            this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.selectShape);
                        }
                    }
                    this.knifeEffModel.active = false;
                }
            }
            outCakeShapeAutoComplete() {
                cc.tween(this.knifeModel.transform).removeAllActions();
                this.buttonSummit.__node.scale(1, 1, true);
                this.buttonBack.__node.scale(1, 1, true);
            }
            removeInitedCream() {
                this.resetCreamData();
            }
            reInitHandleCream(callback) {
                console.log("--------------reInitHandleCream");
                this.resetCreamData();
                if (!this.creamModelInfoArr || this.creamModelInfoArr.length == 0) {
                    let modelIdArr = [];
                    let dict = {};
                    for (let k in this.stageData.creamArr) {
                        let data = this.stageData.creamArr[k];
                        dict[data.modelName] = true;
                    }
                    for (let name in dict) {
                        modelIdArr.push(name);
                    }
                    if (!modelIdArr || modelIdArr.length == 0) {
                        callback && callback();
                        return;
                    }
                    mgrTip.showLoadingTip("loading_preload_cream_model");
                    mgrLoader.batchLoadResources(modelIdArr, null, null, () => {
                        mgrTip.hideLoadingTip("loading_preload_cream_model");
                        this.initCream();
                        this.preHandleModel();
                        this.adaptCreamNormal();
                        callback && callback();
                    });
                }
                else {
                    callback && callback();
                }
            }
            changePenguanColor() {
                if (!this.penguanEffModel || !this.curSelectColorId) {
                    return;
                }
                let colorData = mgrCfg.get_from_cake_paint_color_db(this.curSelectColorId);
                let color = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1.0);
                let numChildren = this.penguanEffModel.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let child = this.penguanEffModel.getChildAt(i);
                    child.particleSystem.startColorConstant = color;
                    child.particleSystem.startColorConstantMin = color;
                    child.particleSystem.startColorConstantMax = color;
                    let numChildren2 = child.numChildren;
                    for (let i = 0; i < numChildren2; i++) {
                        let child2 = child.getChildAt(i);
                        child2.particleSystem.startColorConstant = color;
                        child2.particleSystem.startColorConstantMin = color;
                        child2.particleSystem.startColorConstantMax = color;
                    }
                }
            }
            inPaintColor() {
                this.cameraFollow.fov = CAMERA_PRARAM_CAKE_MAKE.fov;
                this.cameraFollow.position = CAMERA_PRARAM_CAKE_MAKE.position;
                this.cameraFollow.endRotation = CAMERA_PRARAM_CAKE_MAKE.rotation;
                this.cameraFollow.lerpValue = CAMERA_PRARAM_CAKE_MAKE.lerpValue;
                if (!this.penguan) {
                    this.penguan = mgrLoader.Pool.getModel("penping");
                    this.add3DEffectAtBack(this.penguan, 0);
                    mgrMaterial.setCustomMaterial(this.penguan, "penping");
                    this.penguan.transform.localRotationEulerY = 60;
                    this.penguan.transform.position = new Laya.Vector3(0.15, 0.3, 0.31);
                    this.penguan['_originPos'] = this.penguan.transform.position.clone();
                }
                else {
                    this.penguan.active = true;
                }
                if (!this.penguanEffModel) {
                    let penguanEffNode = Tools.findNode("guadian_eff", this.penguan);
                    let penguanEffModel = mgrLoader.Pool.getModel("117_ui_loop_spraysmoke_01");
                    penguanEffNode.addChild(penguanEffModel);
                    penguanEffModel.active = false;
                    penguanEffModel.transform.localRotationEulerY = -90;
                    this.penguanEffModel = penguanEffModel;
                }
                else {
                    this.penguanEffModel.active = false;
                }
                let arr = this.getPartDataByDbName("cake_paint_color_db", this.onClickItem.bind(this), this.isCurrentColor.bind(this));
                this.reuseList.setDatas(arr);
                Timer.callLater(0.016, () => {
                    this.reuseList.scrollTo(0);
                }, this);
                this.showPartContainer();
                this.onClickColor(arr[0].id);
                if (!mgrGuide.isFinished(2111)) {
                    mgrGuide.startGuide(2111);
                }
            }
            exePaintColor() {
                this.cakeRotatedYValue -= (this.bTouchBg ? 6 : 1);
                this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
            }
            outPaintColor() {
                this.bTouchBg = false;
                Tools.unRegisterTouchHander(this.spriteTouch);
                if (this.penguan) {
                    this.penguan.active = false;
                }
            }
            inCream() {
                this.cameraFollow.fov = CAMERA_PRARAM_CAKE_MAKE.fov;
                this.cameraFollow.position = CAMERA_PRARAM_CAKE_MAKE.position;
                this.cameraFollow.endRotation = CAMERA_PRARAM_CAKE_MAKE.rotation;
                this.cameraFollow.lerpValue = CAMERA_PRARAM_CAKE_MAKE.lerpValue;
                if (this.bTouchBg) {
                    this.bTouchBg = false;
                }
                Tools.registerTouchHander(this.spriteTouch, this.onTouchSpriteBg.bind(this));
                if (!this.naiyoudai) {
                    this.naiyoudai = mgrLoader.Pool.getModel("naiyoudai");
                    this.add3DEffectAtBack(this.naiyoudai, 0);
                    mgrMaterial.setCustomMaterial(this.naiyoudai, "naiyoudai");
                    this.naiyoudai.transform.position = new Laya.Vector3(0.15, 0.1, 0.31);
                    this.naiyoudai['_originPos'] = this.naiyoudai.transform.position.clone();
                }
                else {
                    this.naiyoudai.active = true;
                }
                let arr = this.getPartDataByDbName("cake_cream_color_db", this.onClickItem.bind(this), this.isCurrentCreamColor.bind(this));
                this.reuseList.setDatas(arr);
                Timer.callLater(0.016, () => {
                    this.reuseList.scrollTo(0);
                }, this);
                this.onClickCreamColor(arr[0].id);
                this.showPartContainer();
                this.tryShowCreamGuide();
                if (!mgrGuide.isFinished(2121)) {
                    mgrGuide.startGuide(2121);
                }
            }
            exeCream() {
                if (!this.avatar || this.avatar.destroyed) {
                    return;
                }
                this.tryExecShineCreamGuide();
                let creamData = null;
                if (this.operatingCreamIndex >= 0) {
                    creamData = this.stageData.creamArr[this.operatingCreamIndex];
                }
                if (this.isContainVerticalCream() && this.bTouchBg && creamData) {
                }
                else {
                    this.cakeRotatedYValue -= ((this.bTouchBg && creamData) ? 6 : 1);
                    this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
                }
                if (!!creamData) {
                    switch (creamData.creamType) {
                        case CreamType.horzontal:
                            this.horizontalCreamScript.exeCream();
                            break;
                        case CreamType.vertical:
                            this.verticalCreamScript.exeCream();
                            break;
                        case CreamType.flowerHorzontal:
                            this.flowerHorzontalCreamScript.exeCream();
                            break;
                        case CreamType.flowerVertical:
                            this.flowerVerticalCreamScript.exeCream();
                            break;
                        default:
                            break;
                    }
                }
            }
            outCream() {
                if (this.naiyoudai) {
                    this.naiyoudai.active = false;
                }
                this.tryHideCreamGuide();
                Tools.unRegisterTouchHander(this.spriteTouch);
            }
            isContainVerticalCream() {
                let arr = this.stageData.creamArr;
                for (let k in arr) {
                    let creamData = arr[k];
                    if (!!creamData && (creamData.creamType == CreamType.vertical || creamData.creamType == CreamType.flowerVertical)) {
                        return true;
                    }
                }
                return false;
            }
            inDeco() {
                this.cameraFollow.fov = CAMERA_PRARAM_CAKE_MAKE.fov;
                this.cameraFollow.position = CAMERA_PRARAM_CAKE_MAKE.position;
                this.cameraFollow.endRotation = CAMERA_PRARAM_CAKE_MAKE.rotation;
                this.cameraFollow.lerpValue = CAMERA_PRARAM_CAKE_MAKE.lerpValue;
                if (this.bTouchBg) {
                    this.bTouchBg = false;
                }
                let arr = this.getPartDataByDbName("cake_deco_db", this.onClickItem.bind(this), this.isCurrentDeco.bind(this));
                this.reuseList.setDatas(arr);
                Timer.callLater(0.016, () => {
                    this.reuseList.scrollTo(0);
                }, this);
                this.showPartContainer();
                this.boliping.active = true;
                Tools.registerTouchHander(this.spriteTouch, this.onTouchSpriteBg.bind(this));
                if (!mgrGuide.isFinished(2131)) {
                    mgrGuide.startGuide(2131);
                }
            }
            exeDeco() {
                this.cakeRotatedYValue -= 1;
                this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
            }
            outDeco() {
                this.boliping.active = false;
                Tools.unRegisterTouchHander(this.spriteTouch);
            }
            inSticker() {
                this.cameraFollow.fov = CAMERA_PRARAM_CAKE_MAKE.fov;
                this.cameraFollow.position = CAMERA_PRARAM_CAKE_MAKE.position;
                this.cameraFollow.endRotation = CAMERA_PRARAM_CAKE_MAKE.rotation;
                this.cameraFollow.lerpValue = CAMERA_PRARAM_CAKE_MAKE.lerpValue;
                if (this.bTouchBg) {
                    this.bTouchBg = false;
                }
                let arr = this.getPartDataByDbName("cake_sticker_db", this.onClickItem.bind(this), this.isCurrentSticker.bind(this));
                this.reuseList.setDatas(arr);
                Timer.callLater(0.016, () => {
                    this.reuseList.scrollTo(0);
                }, this);
                this.showPartContainer();
                this.boliping.active = true;
                Tools.registerTouchHander(this.spriteTouch, this.onTouchSpriteBg.bind(this));
                if (!mgrGuide.isFinished(2141)) {
                    mgrGuide.startGuide(2141);
                }
            }
            exeSticker() {
                this.cakeRotatedYValue -= 1;
                this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
            }
            outSticker() {
                this.boliping.active = false;
                Tools.unRegisterTouchHander(this.spriteTouch);
            }
            cakeJumpToRole(targetPosition, callback) {
                let startPos = this.avatar.transform.position.clone();
                let oRot = Tools.getAngle(startPos.x, startPos.z);
                let tmpPos = new Laya.Vector3;
                let offsetHeight = 0.1;
                let targetScale = 0.75;
                let doLerpPosFunc = (percent) => {
                    Laya.Vector3.lerp(startPos, targetPosition, percent, tmpPos);
                    let offsetY = cc.Ease.expoOut((percent > 0.5 ? 1 - percent : percent) / 0.5) * offsetHeight;
                    tmpPos.y += offsetY;
                    let currScale = 1 - (1 - targetScale) * percent;
                    this.avatar.transform.localScale = new Laya.Vector3(currScale, currScale, currScale);
                    this.avatar.transform.position = tmpPos.clone();
                    if (percent >= 1.0) {
                        callback && callback();
                    }
                };
                let startTime = Tools.time();
                let dur = 0.5;
                let decoTimer = Timer.callLoop(0.016, (timer) => {
                    let passTime = Tools.time() - startTime;
                    if (passTime >= dur) {
                        doLerpPosFunc(1);
                        timer.stop();
                        return;
                    }
                    doLerpPosFunc(passTime / dur);
                }, this);
            }
            inGetShow() {
                if (mgrDebug.bShowDevButton) {
                    this.mapModel.active = false;
                    this.avatar.transform.rotationEuler = new Laya.Vector3;
                    this.cameraFollow.fov = 40;
                    this.cameraFollow.position = new Laya.Vector3(0, 0.4, 0.9);
                    this.cameraFollow.endRotation = CAMERA_PRARAM_CAKE_MAKE.rotation;
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                    let saveImageName = `preview${this.stageData.id >= 10 ? this.stageData.id : ("0" + this.stageData.id)}`;
                    Tools.cameraForSaveImg(this.cameraBack, saveImageName);
                    return;
                }
                this.buttonBack.__node.visible = false;
                let score = this.calcCustomMadeStageScore(this.stageData.id, this.usedPaintColorIdDict, this.usedCreamColorIdDict, this.usedDecoIdDict, this.usedStickerIdDict);
                this.bSuccess = score >= this.stageData.passScore ? true : false;
                let gotShowRotTimer = Timer.callLoop(0.016, () => {
                    let tmpRot = this.avatar.transform.rotationEuler.y % 360;
                    if (tmpRot <= -6 && tmpRot >= -354) {
                        this.cakeRotatedYValue -= 3;
                        this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
                    }
                    else {
                        gotShowRotTimer.stop();
                        gotShowRotTimer = null;
                        this.roleAvatar.registerLoadEndCallback(() => {
                            this.cameraFollow.fov = CAMERA_PRARAM_ROLE_IN.fov;
                            this.cameraFollow.position = CAMERA_PRARAM_ROLE_IN.position;
                            this.cameraFollow.endRotation = CAMERA_PRARAM_ROLE_IN.rotation;
                            this.cameraFollow.lerpValue = CAMERA_PRARAM_ROLE_IN.lerpValue;
                            let aniIdArr = ["dangao-dg_zjl"];
                            this.roleAvatar.playAnimation(aniIdArr, 0, () => {
                                this.roleAvatar.transform.position = new Laya.Vector3(this.roleAvatarPosRotDict[0].pos.x, this.roleAvatarPosRotDict[0].pos.y, this.roleAvatarPosRotDict[0].pos.z);
                                this.roleAvatar.transform.rotationEuler = this.roleAvatarPosRotDict[0].rot;
                            }, () => {
                                if (!this.nodeResource || this.nodeResource.destroyed) {
                                    return;
                                }
                                this.roleAvatar.playAnimation("dangao-dg_idle02", 0);
                                let targetNode = Tools.findNode("Bip001 L Hand", this.roleAvatar);
                                let targetPos = targetNode.transform.position.clone();
                                let callback = () => {
                                    this.roleAvatar.linkModel(this.avatar, "Bip001 L Hand");
                                    let wordArr = this.bSuccess ? this.GOOD_WORD_DESC_ARR : this.BAD_WORD_DESC_ARR;
                                    this.labelJudgeWord.text = `${Tools.randomGotOneArrayData(wordArr)}`;
                                    this.showJudgeWord(0.3);
                                    Timer.callLater(1, () => {
                                        if (!this.nodeResource || this.nodeResource.destroyed) {
                                            return;
                                        }
                                        this.hideJudgeWord();
                                        let cameraFollow = this.cameraBack.getComponent(CameraFollow);
                                        let oldPos = cameraFollow.position.clone();
                                        let oldFov = cameraFollow.fov;
                                        let oldRot = cameraFollow.endRotation.clone();
                                        cameraFollow.position = new Laya.Vector3(0, 0.4, 2);
                                        cameraFollow.fov = 30;
                                        cameraFollow.lerpValue = 1;
                                        cameraFollow.endRotation = new Laya.Vector3(-2.5);
                                        cameraFollow.onLateUpdate();
                                        Tools.takeAPhoto(512, 512, this.cameraBack, (tex2d) => {
                                            this.shareTex2d = tex2d;
                                            cameraFollow.position = oldPos;
                                            cameraFollow.fov = oldFov;
                                            cameraFollow.endRotation = oldRot;
                                            if (this.bSuccess) {
                                                mgrSound.play(421);
                                                let aniIdArr = ["dangao-dg_kx"];
                                                this.roleAvatar.playAnimation(aniIdArr, 0, null, () => {
                                                    this.bGetShowCompleted = true;
                                                }, false, true);
                                            }
                                            else {
                                                mgrSound.play(422);
                                                let aniIdArr = ["dangao-dg_sq"];
                                                this.roleAvatar.playAnimation(aniIdArr, 0, null, () => {
                                                    this.bGetShowCompleted = true;
                                                }, false);
                                                Timer.callLater(0.6, () => {
                                                    this.roleAvatar.unlinkModel(this.avatar, true);
                                                    this.avatar.removeSelf();
                                                    this.avatar.active = false;
                                                }, this);
                                            }
                                        }, Laya.RenderTextureFormat.R8G8B8A8);
                                    }, this);
                                };
                                this.cakeJumpToRole(targetPos, callback);
                            }, false, true);
                        });
                    }
                }, this);
                this.hidePartContainer();
                this.spriteTarget.visible = false;
                this.spriteStageTarget.visible = false;
                this.buttonSummit.__node.visible = false;
            }
            exeGetShow() {
                if (mgrDebug.bShowDevButton) {
                    return;
                }
                if (!!this.bGetShowCompleted && this.stManager.getCurrStateRanTime() > 1) {
                    this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.reward);
                }
            }
            outGetShow() {
            }
            inReward() {
                if (!this.bTouchBg) {
                    this.cakeRotatedYValue -= 1;
                    this.avatar.transform.rotationEuler = new Laya.Vector3(0, this.cakeRotatedYValue, 0);
                }
                this.add3DEffectAtFront("117_ui_loop_ray_02", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 3);
                this.add3DEffectAtFront("117_ui_loop_star_02", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 3);
                this.spriteTitleSuccess.visible = !!this.bSuccess;
                this.spriteTitleFaild.visible = !this.spriteTitleSuccess.visible;
                this.spriteTitle.visible = true;
                this.spriteTitle.scale(3, 3, true);
                cc.tween(this.spriteTitle).toScale(0.1, 1)
                    .call(() => {
                    if (!!this.bSuccess) {
                        mgrSound.play(312);
                    }
                    else {
                        mgrSound.play(313);
                    }
                })
                    .delay(0.5)
                    .call(() => {
                    let rewardColorPoint = 0;
                    if (this.bSuccess) {
                        rewardColorPoint = this.stageData.bestRewardColorPoint;
                    }
                    else {
                        rewardColorPoint = this.stageData.goodRewardColorPoint;
                    }
                    if (this.bSuccess) {
                        let gameWorldDailyData = mgrCfg.get_from_cake_daily_quest_config(mgrWorldDaily.getWorldDay()) || mgrCfg.get_from_cake_daily_quest_config(1);
                        mgrPlayer.addItemAmount(gameWorldDailyData.rewardItemId, gameWorldDailyData.rewardItemAmount, "蛋糕结算奖励");
                    }
                    this.oldColorPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_CAKE_COLOR);
                    this.currGotColorPoint = rewardColorPoint;
                    mgrPlayer.addItemAmount(Const.ITEM_ID_CAKE_COLOR, rewardColorPoint, "蛋糕结算奖励");
                    this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.palette);
                })
                    .start();
            }
            exeReward() {
            }
            outReward() {
            }
            inPalette() {
                let gotCoinFunc = () => {
                    let rewardRmb = !!this.bSuccess ? this.stageData.bestRewardRmbAmount : this.stageData.goodRewardRmbAmount;
                    let moonCakeAmount = !!this.bSuccess ? this.stageData.successMoonCakeAmount : this.stageData.failMoonCakeAmount;
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, rewardRmb, "蛋糕结算奖励");
                    mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, rewardRmb, null, {
                        fOnClose: () => {
                            let partId = mgrWorldDaily.getUnownedVipPart(DailyGameType.cake);
                            if (!!partId && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment) && (Tools.random(0, 100) <= mgrSdk.getCopNumberValueByKey("surprise_cake_ratio") || !!this.context.bVip)) {
                                mgrDirector.openDialog("vSurpriseRewardDialog", {
                                    bVip: !!this.context.bVip,
                                    partId,
                                    fOnClose: () => {
                                        if (mgrMidAutumn.isEnable() && !!moonCakeAmount) {
                                            mgrPlayer.addItemAmount(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, "蛋糕结算月饼奖励");
                                            mgrTip.addGotItemTip(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, null, {
                                                fOnClose: () => {
                                                    this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.finish);
                                                }
                                            });
                                        }
                                        else {
                                            this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.finish);
                                        }
                                    }
                                });
                            }
                            else {
                                if (mgrMidAutumn.isEnable() && !!moonCakeAmount) {
                                    mgrPlayer.addItemAmount(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, "蛋糕结算月饼奖励");
                                    mgrTip.addGotItemTip(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, null, {
                                        fOnClose: () => {
                                            this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.finish);
                                        }
                                    });
                                }
                                else {
                                    this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.finish);
                                }
                            }
                        }
                    });
                };
                if (!this.bSuccess) {
                    gotCoinFunc();
                }
                else {
                    let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.cake);
                    if (!rewardPartId) {
                        gotCoinFunc();
                        return;
                    }
                    mgrDirector.openDialog("vAmuseCakeResultDialog", {
                        colorItemId: Const.ITEM_ID_CAKE_COLOR,
                        oldColorPoint: this.oldColorPoint,
                        currGotColorPoint: this.currGotColorPoint,
                        dailyGameType: DailyGameType.cake,
                        bSuccess: this.bSuccess,
                        rewardPartId: rewardPartId,
                        fOnClose: () => {
                            gotCoinFunc();
                        }
                    });
                }
            }
            exePalette() {
            }
            outPalette() {
            }
            inFinish() {
                this.stageData.statisPointId && mgrSdk.statisOnStageEnd(`${this.stageData.statisPointId}`, this.bSuccess ? 1 : 0, `${this.stageData.id}`);
                mgrVideoRecorder.stopRecord();
                mgrTip.tryShowPhotoShare("vAmuseCakeMakeScene", this.shareTex2d, null, () => {
                    this.stManager.stopUpdate();
                    mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene", {
                        bSuccess: this.bSuccess,
                        dailyGameType: DailyGameType.cake,
                        bFromGameResult: true
                    });
                });
            }
            exeFinish() {
            }
            outFinish() {
            }
            calcCustomMadeStageScore(stageId, paintColorIdDict, creamColorIdDict, decoIdDict, stickerIdDict) {
                let stageData = mgrCfg.get_from_cake_stage_db(stageId);
                let tagWeights = stageData.tagWeights;
                let getMaxScoreByPartIdDict = (dict) => {
                    dict = dict || {};
                    let maxScore = 0;
                    let maxScoreId = 0;
                    for (let k in dict) {
                        const partId = parseInt(k);
                        if (!partId) {
                            continue;
                        }
                        let currScore = 0;
                        let partData = mgrCfg.get_from_cake_cream_color_db(partId) || mgrCfg.get_from_cake_paint_color_db(partId) || mgrCfg.get_from_cake_deco_db(partId) || mgrCfg.get_from_cake_sticker_db(partId);
                        for (let index = 0; index < 10; index++) {
                            const partTagScore = partData["score" + (index + 1)] || 0;
                            currScore += partTagScore * (tagWeights[index] || 0);
                        }
                        currScore = Math.floor(currScore);
                        if (currScore > maxScore) {
                            maxScore = currScore;
                            maxScoreId = partData.id;
                        }
                    }
                    return maxScore;
                };
                let score = getMaxScoreByPartIdDict(paintColorIdDict) +
                    getMaxScoreByPartIdDict(creamColorIdDict) +
                    getMaxScoreByPartIdDict(decoIdDict) +
                    getMaxScoreByPartIdDict(stickerIdDict);
                return Math.floor(score);
            }
            getPartDataByDbName(dbName, onClickFunc, isCurrentFunc) {
                let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial);
                if (bCanAd) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
                if (!!this.dbName2DatasDict[dbName]) {
                    return this.dbName2DatasDict[dbName];
                }
                let gotedPartIdArr = [];
                let lockedPartIdArr = [];
                let coinPartIdArr = [];
                let specialPartArr = [];
                let db = mgrCfg.getDb(dbName);
                for (let k in db) {
                    let v = db[k];
                    if (!!v.bDisableShowInRoom || (mgrPlayer.getItemAmount(v.id) <= 0 && !!v.bDisableShowWhenUnown)) {
                        continue;
                    }
                    let data = {
                        dbName: dbName,
                        guideOrder: 0,
                        __customOrderValue: 0,
                        id: v.id,
                        order: v.order,
                        fOnClick: onClickFunc,
                        fIsCurrent: isCurrentFunc,
                        fIsTry: this.isTrialingItem.bind(this),
                        fIsRecommend: this.isRecommend.bind(this),
                        fStaticsShow: () => {
                        },
                        bCanAd: bCanAd
                    };
                    if (this.isRecommend(v.id)) {
                        specialPartArr.push(data);
                    }
                    else {
                        if (mgrPlayer.getItemAmount(v.id) <= 0) {
                            let shopData = mgrCfg.get_from_shop_template_db(v.id);
                            if (!!shopData) {
                                coinPartIdArr.push(data);
                            }
                            else {
                                lockedPartIdArr.push(data);
                            }
                        }
                        else {
                            gotedPartIdArr.push(data);
                        }
                    }
                }
                let datas = [];
                let dataDict = {
                    [0]: gotedPartIdArr,
                    [1]: lockedPartIdArr,
                    [2]: coinPartIdArr
                };
                let count = Math.max(Math.max(gotedPartIdArr.length, lockedPartIdArr.length), coinPartIdArr.length);
                for (let i = 0; i < count; i++) {
                    let indexDataArr = i == 0 ? [0, 1, 2] : Tools.randomGotArrayDatas([0, 1, 2], 3);
                    for (let tmp in indexDataArr) {
                        let tmpDatas = dataDict[indexDataArr[tmp]];
                        if (tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                        if (indexDataArr[tmp] == 1 && Tools.random(100) > 50 && tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                    }
                }
                specialPartArr = Tools.randomGotArrayDatas(specialPartArr, specialPartArr.length);
                for (let i = 0; i < specialPartArr.length; i++) {
                    let index = (!!mgrGuide.isGuiding() || !mgrGuide.isFinished(2100)) ? 0 : Tools.random(2, 9);
                    datas.splice(index, 0, specialPartArr[i]);
                }
                let sortedPartId2OrderDict = mgrPart.getGameRoomListSortedId2OrderDictByType(DailyGameType.cake, dbName);
                if (!!sortedPartId2OrderDict && Tools.getObjSize(sortedPartId2OrderDict) > 0) {
                    for (let i = 0; i < datas.length; i++) {
                        let sortedOrder = parseInt(sortedPartId2OrderDict[datas[i].partId]);
                        datas[i].__customOrderValue = !!isNaN(sortedOrder) ? i : sortedOrder;
                    }
                }
                else {
                    let sortedPartId2OrderDict = {};
                    for (let i = 0; i < datas.length; i++) {
                        datas[i].__customOrderValue = i;
                        sortedPartId2OrderDict[datas[i].partId] = i;
                    }
                    mgrPart.setGameRoomListSortedId2OrderDictByType(DailyGameType.cake, dbName, sortedPartId2OrderDict);
                }
                datas = Tools.sortArrayByField(datas, ["-guideOrder", "__customOrderValue"]);
                this.dbName2DatasDict[dbName] = datas;
                return datas;
            }
            onClickTab(tab) {
                if (tab != this.TAB_SHAPE && this.stageData.bCanSelectShape) {
                    if (this.badCakeModel.active) {
                        mgrTip.alertPrompt1("提示", "需要切完糕体才能进行装饰~", "好的");
                        return;
                    }
                }
                let callback = () => {
                    switch (tab) {
                        case this.TAB_PAINT: {
                            this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.paintColor);
                            break;
                        }
                        case this.TAB_CRAEM: {
                            this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.cream);
                            break;
                        }
                        case this.TAB_DECO: {
                            this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.deco);
                            break;
                        }
                        case this.TAB_STICKER: {
                            this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.sticker);
                            break;
                        }
                        case this.TAB_SHAPE: {
                            if (this.currentTab == this.TAB_SHAPE) {
                                return;
                            }
                            this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.selectShape);
                            break;
                        }
                        default:
                            break;
                    }
                    this.onSelectTab(tab);
                    this.boxPartList.alpha = 0;
                    cc.tween(this.boxPartList, true).toAlpha(0.5, 1).start();
                };
                if (!!this.currentTab && this.currentTab == this.TAB_SHAPE && tab != this.TAB_SHAPE) {
                    this.reInitHandleCream(callback);
                    return;
                }
                else if (tab == this.TAB_SHAPE) {
                }
                callback();
            }
            isCurrentTab(tab) {
                return this.currentTab == tab ? true : false;
            }
            onSelectTab(tab) {
                this.currentTab = tab;
                this.sendMsg("MSG_REFRESH_TAB_SEL_STATUS", { tab: tab });
                this.refreshTabUsedStatus();
                this.refreshTargetScore();
            }
            isUsedTab(tab) {
                let tab2SelectIdDict = {
                    [this.TAB_PAINT]: this.usedPaintColorIdDict,
                    [this.TAB_CRAEM]: this.usedCreamColorIdDict,
                    [this.TAB_DECO]: this.usedDecoIdDict,
                    [this.TAB_STICKER]: this.usedStickerIdDict,
                    [this.TAB_SHAPE]: this.usedShapeIdDict,
                };
                return Tools.getObjSize(tab2SelectIdDict[tab]) > 0 ? true : false;
            }
            refreshTabUsedStatus() {
                let tab2SelectIdDict = {
                    [this.TAB_PAINT]: this.usedPaintColorIdDict,
                    [this.TAB_CRAEM]: this.usedCreamColorIdDict,
                    [this.TAB_DECO]: this.usedDecoIdDict,
                    [this.TAB_STICKER]: this.usedStickerIdDict,
                    [this.TAB_SHAPE]: this.usedShapeIdDict,
                };
                let bShowButtonSubmit = false;
                for (let i = 1; i <= 5; i++) {
                    this.sendMsg("MSG_REFRESH_TAB_USED_STATUS", { id: i });
                    if (!bShowButtonSubmit && i > 1 && Tools.getObjSize(tab2SelectIdDict[i]) > 0) {
                        bShowButtonSubmit = true;
                    }
                }
                if (bShowButtonSubmit && this.buttonSummit.__node.scaleX < 0.1) {
                    cc.tween(this.buttonSummit.__node).toScale(0.3, 1).start();
                }
            }
            refreshTargetScore(duration) {
                let score = this.calcCustomMadeStageScore(this.stageData.id, this.usedPaintColorIdDict, this.usedCreamColorIdDict, this.usedDecoIdDict, this.usedStickerIdDict);
                let maxScore = Math.ceil(this.stageData.passScore / (2 / 3));
                this.spriteStageRate01.visible = score < this.stageData.passScore ? true : false;
                this.spriteStageRate02.visible = (score >= this.stageData.passScore && score < maxScore) ? true : false;
                this.spriteStageRate03.visible = score >= maxScore ? true : false;
                this.spriteStageScoreGood.visible = !!this.spriteStageRate03.visible;
                this.spriteStageScoreBad.visible = !this.spriteStageScoreGood.visible;
                this.labelStagePower.text = `${score}`;
                if (!!this.lastRecordTargetScore) {
                    this.spriteStageScoreUpFlag.visible = !!score && this.lastRecordTargetScore < score ? true : false;
                    this.spriteStageScoreDownFlag.visible = !!score && this.lastRecordTargetScore > score ? true : false;
                    if (!!this.spriteStageScoreUpFlag.visible) {
                        this.add3DEffectAtFront("117_ui_once_up_01", this.spriteStageScoreUpFlag, 2);
                    }
                    else if (!!this.spriteStageScoreDownFlag.visible) {
                        this.add3DEffectAtFront("117_ui_once_down_01", this.spriteStageScoreDownFlag, 2);
                    }
                }
                this.lastRecordTargetScore = score;
                if (this.spriteStageRate03.visible) {
                    mgrEffect.shineNode(this.spriteStageScoreGood);
                }
                else {
                    mgrEffect.stopShineNode(this.spriteStageScoreGood);
                }
            }
            onTouchButtonBack() {
                if (mgrGuide.isGuiding() && mgrGuide.curExecutingGuideId == 2112) {
                    return;
                }
                else if (mgrGuide.isGuiding() && mgrGuide.curExecutingGuideId == 2122) {
                    return;
                }
                else if (mgrGuide.isGuiding() && mgrGuide.curExecutingGuideId == 2132) {
                    return;
                }
                else if (mgrGuide.isGuiding() && mgrGuide.curExecutingGuideId == 2142) {
                    return;
                }
                mgrDirector.warpSceneWidthEffect(`vWorldDailyQuestMainScene`, { fromSystemModel: SYSTEM_MODEL.amaze });
            }
            onTouchButtonSummit() {
                if (mgrGuide.isGuiding() && mgrGuide.curExecutingGuideId == 2112) {
                    return;
                }
                else if (mgrGuide.isGuiding() && mgrGuide.curExecutingGuideId == 2122) {
                    return;
                }
                else if (mgrGuide.isGuiding() && mgrGuide.curExecutingGuideId == 2132) {
                    return;
                }
                else if (mgrGuide.isGuiding() && mgrGuide.curExecutingGuideId == 2142) {
                    return;
                }
                let tab2SelectIdDict = {
                    [this.TAB_PAINT]: this.usedPaintColorIdDict,
                    [this.TAB_CRAEM]: this.usedCreamColorIdDict,
                    [this.TAB_DECO]: this.usedDecoIdDict,
                    [this.TAB_STICKER]: this.usedStickerIdDict,
                };
                let bSelected = false;
                for (let i = 1; i < 5; i++) {
                    if (Tools.getObjSize(tab2SelectIdDict[i]) > 0) {
                        bSelected = true;
                        break;
                    }
                }
                if (!bSelected) {
                    mgrTip.alertPrompt1("提示", "蛋糕还没有做好，不能给顾客哦~", "确定", () => { });
                    return;
                }
                let doExcFunc = () => {
                    this.stManager.setNextState(AMUSE_CAKE_MAKE_STATE.getShow);
                };
                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                    mgrTip.alertPrompt2("提示", `确定提交装扮吗?`, "再想想", "确定", null, () => {
                        doExcFunc();
                    });
                }
                else {
                    doExcFunc();
                }
            }
            onTouchButtonTab01() {
                this.onClickTab(1);
            }
            onTouchButtonTab02() {
                this.onClickTab(2);
            }
            onTouchButtonTab03() {
                this.onClickTab(3);
            }
            onTouchButtonTab04() {
                this.onClickTab(4);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseCakeMakeScene_trial) {
                    this.tryingPartIds.push(e.userData.partId);
                    this.reuseList.refresh();
                    let partId = e.userData.partId;
                    let cakeColorData = mgrCfg.get_from_cake_paint_color_db(partId);
                    let creamColorData = mgrCfg.get_from_cake_cream_color_db(partId);
                    let decoData = mgrCfg.get_from_cake_deco_db(partId);
                    let stickerData = mgrCfg.get_from_cake_sticker_db(partId);
                    let shapeData = mgrCfg.get_from_cake_shape_db(partId);
                    if (!!cakeColorData) {
                        this.onClickColor(partId);
                    }
                    else if (!!creamColorData) {
                        this.onClickCreamColor(partId);
                    }
                    else if (!!decoData) {
                        this.onClickDeco(partId);
                    }
                    else if (!!stickerData) {
                        this.onClickSticker(partId);
                    }
                    else if (!!shapeData) {
                        this.onClickShape(partId);
                    }
                }
            }
            onMsgShopBuySuccessed() {
            }
        }

        var AMUSE_CARD_FIGHT_STATE;
        (function (AMUSE_CARD_FIGHT_STATE) {
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["init"] = 1] = "init";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["openSkill"] = 2] = "openSkill";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["prepareTurnPlayer"] = 3] = "prepareTurnPlayer";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["turnPlayer"] = 4] = "turnPlayer";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["turnPlayerComplete"] = 5] = "turnPlayerComplete";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["prepareTurnEnemy"] = 6] = "prepareTurnEnemy";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["turnEnemy"] = 7] = "turnEnemy";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["turnEnemyPhysical"] = 8] = "turnEnemyPhysical";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["turnEnemyComplete"] = 9] = "turnEnemyComplete";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["turnMagic"] = 10] = "turnMagic";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["checkResult"] = 11] = "checkResult";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["reward"] = 12] = "reward";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["palette"] = 13] = "palette";
            AMUSE_CARD_FIGHT_STATE[AMUSE_CARD_FIGHT_STATE["finish"] = 14] = "finish";
        })(AMUSE_CARD_FIGHT_STATE || (AMUSE_CARD_FIGHT_STATE = {}));
        class vAmuseCardFightScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseCardFightScene";
                this.ATTACK_ADD_TAG_DICT = {
                    [1]: 2,
                    [2]: 3,
                    [3]: 1
                };
                this.CARD_FIGHT_SPEED = 1.6;
                this.PLAYER_TAG_ID_2_EFFNAME_DICT = {
                    [1]: [
                        { begin: "117_ui_once_cardbegain_01", end: "117_ui_once_cardhit_01", move: "117_ui_loop_cardattack_01", bMoveToTarget: true, bRot: false },
                        { begin: "117_ui_once_cardbegain_02", end: "117_ui_once_cardhit_02", move: "117_ui_loop_cardattack_02", bMoveToTarget: true, bRot: true }
                    ],
                    [2]: [
                        { begin: "117_ui_once_cardbegain_01", end: "117_ui_once_cardhit_01", move: "117_ui_loop_cardattack_01", bMoveToTarget: true, bRot: false },
                        { begin: "117_ui_once_cardbegain_02", end: "117_ui_once_cardhit_02", move: "117_ui_loop_cardattack_02", bMoveToTarget: true, bRot: true }
                    ],
                    [3]: [
                        { begin: "117_ui_once_cardbegain_01", end: "117_ui_once_cardhit_01", move: "117_ui_loop_cardattack_01", bMoveToTarget: true, bRot: false },
                        { begin: "117_ui_once_cardbegain_02", end: "117_ui_once_cardhit_02", move: "117_ui_loop_cardattack_02", bMoveToTarget: true, bRot: true }
                    ],
                    [4]: [
                        { begin: "117_ui_once_cardbegain_03", end: "117_ui_once_cardhit_03", move: "117_ui_loop_cardattack_03", bMoveToTarget: true, bRot: true },
                        { begin: "117_ui_once_cardbegain_04", end: "117_ui_once_cardhit_04", move: "117_ui_loop_cardattack_04", bMoveToTarget: true, bRot: true }
                    ],
                    [5]: [
                        { begin: "117_ui_once_cardbegain_03", end: "117_ui_once_cardhit_03", move: "117_ui_loop_cardattack_03", bMoveToTarget: true, bRot: true },
                        { begin: "117_ui_once_cardbegain_04", end: "117_ui_once_cardhit_04", move: "117_ui_loop_cardattack_04", bMoveToTarget: true, bRot: true }
                    ],
                    [6]: [
                        { begin: "117_ui_once_cardbegain_03", end: "117_ui_once_cardhit_03", move: "117_ui_loop_cardattack_03", bMoveToTarget: true, bRot: true },
                        { begin: "117_ui_once_cardbegain_04", end: "117_ui_once_cardhit_04", move: "117_ui_loop_cardattack_04", bMoveToTarget: true, bRot: true }
                    ],
                    [7]: [
                        { begin: "117_ui_once_cardbegain_05", end: "117_ui_once_cardhit_05", move: "117_ui_loop_cardattack_05", bMoveToTarget: true, bRot: true },
                        { begin: "117_ui_once_cardbegain_06", end: "117_ui_once_cardhit_06", move: "117_ui_loop_cardattack_06", bMoveToTarget: true, bRot: false }
                    ],
                    [8]: [
                        { begin: "117_ui_once_cardbegain_05", end: "117_ui_once_cardhit_05", move: "117_ui_loop_cardattack_05", bMoveToTarget: true, bRot: true },
                        { begin: "117_ui_once_cardbegain_06", end: "117_ui_once_cardhit_06", move: "117_ui_loop_cardattack_06", bMoveToTarget: true, bRot: false }
                    ],
                    [9]: [
                        { begin: "117_ui_once_cardbegain_05", end: "117_ui_once_cardhit_05", move: "117_ui_loop_cardattack_05", bMoveToTarget: true, bRot: true },
                        { begin: "117_ui_once_cardbegain_06", end: "117_ui_once_cardhit_06", move: "117_ui_loop_cardattack_06", bMoveToTarget: true, bRot: false }
                    ],
                };
                this.curMaxCardFightId = 0;
                this.tipArr = [];
                this.tipCount = 0;
                this.preInitData();
            }
            getPreLoadModelIds() {
                return [
                    "116_ui_once_bao_02",
                    "116_ui_once_bao_03",
                    "116_ui_once_bao_05",
                    "116_ui_once_bao_06",
                    "116_ui_once_bao_08",
                    "117_ui_once_bao_01",
                    "116_ui_once_bao_10",
                    "117_ui_once_recparticle_01",
                    "117_ui_once_recparticle_02",
                    "117_ui_once_begain_yellow",
                    "117_ui_loop_balltrail_yellow",
                    "117_ui_once_ballex_yellow",
                    "117_ui_once_begain_purple",
                    "117_ui_loop_balltrail_purple",
                    "117_ui_once_ballex_purple",
                    "117_ui_once_hit_03",
                ];
            }
            getPreLoadAnimationIds() {
                return [];
            }
            getPreLoadImagePaths() {
                let arr = [];
                return arr;
            }
            onOpened() {
                super.onOpened();
                mgrSound.play(10);
                this.buildUi();
                this.fillData();
                this.widget();
                this.stManager = new FSMObject;
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.openSkill, this.inOpenSkill.bind(this), this.exeOpenSkill.bind(this), this.outOpenSkill.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.prepareTurnPlayer, this.inPrepareTurnPlayer.bind(this), this.exePrepareTurnPlayer.bind(this), this.outPrepareTurnPlayer.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.turnPlayer, this.inTurnPlayer.bind(this), this.exeTurnPlayer.bind(this), this.outTurnPlayer.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.turnPlayerComplete, this.inTurnPlayerComplete.bind(this), this.exeTurnPlayerComplete.bind(this), this.outTurnPlayerComplete.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.prepareTurnEnemy, this.inPrepareTurnEnemy.bind(this), this.exePrepareTurnEnemy.bind(this), this.outPrepareTurnEnemy.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.turnEnemy, this.inTurnEnemy.bind(this), this.exeTurnEnemy.bind(this), this.outTurnEnemy.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.turnEnemyPhysical, this.inTurnEnemyPhysical.bind(this), this.exeTurnEnemyPhysical.bind(this), this.outTurnEnemyPhysical.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.turnEnemyComplete, this.inTurnEnemyComplete.bind(this), this.exeTurnEnemyComplete.bind(this), this.outTurnEnemyComplete.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.turnMagic, this.inTurnMagic.bind(this), this.exeTurnMagic.bind(this), this.outTurnMagic.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.checkResult, this.inCheckResult.bind(this), this.exeCheckResult.bind(this), this.outCheckResult.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.reward, this.inReward.bind(this), this.exeReward.bind(this), this.outReward.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.palette, this.inPalette.bind(this), this.exePalette.bind(this), this.outPalette.bind(this));
                this.stManager.registerState(AMUSE_CARD_FIGHT_STATE.finish, this.inFinish.bind(this), this.exeFinish.bind(this), this.outFinish.bind(this));
                this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.init);
                this.stManager.startUpdate(this);
                this.uiActionIn(() => {
                    let goNextStep = () => {
                        this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.openSkill);
                    };
                    if (this.playerCardPosInfo.length < Const.PLAYER_CARD_POS_COUNT && !!mgrGuide.isAllForceGuideFinished()) {
                        let arr = mgrCfg.getDbArr("amuse_card_npc_db", (data) => {
                            return !!data.bCanTrial;
                        });
                        let npcData = Tools.randomGotOneArrayData(arr);
                        if (!npcData) {
                            goNextStep();
                            return;
                        }
                        if (mgrCard.isCardInTempFightCardStandbying(npcData.cardId)) {
                            return;
                        }
                        mgrDirector.openDialog("vAmuseCardTrialDialog", {
                            npcId: npcData.id,
                            adEventId: AD_EVENT_ID.VIDEO.video_vAmuseCardFightScene_trial,
                            fOnAdResult: (bAded) => {
                                if (!!bAded) {
                                    mgrTip.showLoadingTip("_trial_card_loading");
                                    mgrLoader.Load2dRes(npcData.imgCardTexture, Laya.Loader.IMAGE, this, (res) => {
                                        mgrTip.hideLoadingTip("_trial_card_loading");
                                        for (let posIndex = 0; posIndex < Const.PLAYER_CARD_POS_COUNT; posIndex++) {
                                            let cardUiInfo = this.playerCardArr[posIndex];
                                            cardUiInfo.nodeRoot.alpha = 0;
                                        }
                                        this.playerCardPosInfo.push({
                                            roleId: npcData.id,
                                            tagId: npcData.roleTagId,
                                            styleId: npcData.cardStyle,
                                            textureCard: res,
                                            power: npcData.fightPower,
                                            hp: npcData.hp
                                        });
                                        let cardPosIndex = this.playerCardFightDataArr.length;
                                        this.playerCardFightDataArr.push({
                                            id: ++this.curMaxCardFightId,
                                            roleId: npcData.id,
                                            tagId: npcData.roleTagId,
                                            fightPower: npcData.fightPower,
                                            hp: npcData.hp,
                                            originHp: npcData.hp,
                                            cardPosIndex: cardPosIndex,
                                            textureCard: res,
                                            styleId: npcData.cardStyle,
                                            remainFreezeRound: 0,
                                        });
                                        this.refreshPlayerCardUi();
                                        let cardUiInfo = this.playerCardArr[cardPosIndex];
                                        for (let posIndex = 0; posIndex < Const.PLAYER_CARD_POS_COUNT; posIndex++) {
                                            let cardUiInfo = this.playerCardArr[posIndex];
                                            if (!cardUiInfo.nodeRoot.visible || posIndex == cardPosIndex) {
                                                continue;
                                            }
                                            cc.tween(cardUiInfo.nodeRoot).toAlpha(0.05, 1).start();
                                        }
                                        mgrEffect.playComebackAction([cardUiInfo.nodeRoot], 0, 500, 0.5, 0.6, () => {
                                            goNextStep();
                                        });
                                    });
                                }
                                else {
                                    goNextStep();
                                }
                            }
                        });
                    }
                    else {
                        goNextStep();
                    }
                });
                mgrVideoRecorder.startRecord();
            }
            onClosed() {
                super.onClosed();
                mgrCard.cleanTempFightCardPosInfoData();
                mgrCard.cleanTempTryingCardInfoData();
                mgrTip.hideLoadingTip("_trial_card_loading");
            }
            buildUi() {
                let arr = [];
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let spritePlayer = this["spritePlayerCard" + i];
                    let spriteCardBack = spritePlayer.getChildByName("spriteCardBack");
                    let spriteCard = spritePlayer.getChildByName("spriteCard");
                    let spriteCardFont = spritePlayer.getChildByName("spriteCardFont");
                    let spriteTagIcon = spritePlayer.getChildByName("spriteTagIcon");
                    let labelPower = spritePlayer.getChildByName("labelPower");
                    let spriteAdd = spritePlayer.getChildByName("spriteAdd");
                    let spriteLock = spritePlayer.getChildByName("spriteLock");
                    let spriteEff = spritePlayer.getChildByName("spriteEff");
                    let progressBar = this["progressBarPlayerHp" + i];
                    progressBar.barName = progressBar.__node.name;
                    progressBar.style = ULPROGRESSBAR_STYLE.hor;
                    progressBar.progress = 1;
                    spritePlayer["originPos"] = new Laya.Vector2(spritePlayer.x, spritePlayer.y);
                    let data = {
                        nodeRoot: spritePlayer,
                        spriteCardBack: spriteCardBack,
                        spriteCard: spriteCard,
                        spriteCardFont: spriteCardFont,
                        spriteTagIcon: spriteTagIcon,
                        labelPower: labelPower,
                        spriteAdd: spriteAdd,
                        spriteLock: spriteLock,
                        progressBar: progressBar,
                        nodeEff: spriteEff,
                    };
                    arr.push(data);
                }
                this.playerCardArr = arr;
                let arrEnemy = [];
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let spritePlayer = this["spriteEnemyCard" + i];
                    let spriteCardBack = spritePlayer.getChildByName("spriteCardBack");
                    let spriteCard = spritePlayer.getChildByName("spriteCard");
                    let spriteCardFont = spritePlayer.getChildByName("spriteCardFont");
                    let spriteTagIcon = spritePlayer.getChildByName("spriteTagIcon");
                    let labelPower = spritePlayer.getChildByName("labelPower");
                    let spriteEff = spritePlayer.getChildByName("spriteEff");
                    let progressBar = this["progressBarNpcHp" + i];
                    progressBar.barName = progressBar.__node.name;
                    progressBar.style = ULPROGRESSBAR_STYLE.hor;
                    progressBar.progress = 1;
                    spritePlayer["originPos"] = new Laya.Vector2(spritePlayer.x, spritePlayer.y);
                    let data = {
                        nodeRoot: spritePlayer,
                        spriteCardBack: spriteCardBack,
                        spriteCard: spriteCard,
                        spriteCardFont: spriteCardFont,
                        spriteTagIcon: spriteTagIcon,
                        labelPower: labelPower,
                        progressBar: progressBar,
                        nodeEff: spriteEff,
                    };
                    arrEnemy.push(data);
                }
                this.enemyCardArr = arrEnemy;
                this.spriteEnemyFightPowerContainer.visible = false;
                this.spritePlayerFightPowerContainer.visible = false;
                this.boxContainerMC["_originPos"] = new Laya.Vector2(this.boxContainerMC.x, this.boxContainerMC.y);
            }
            uiActionIn(callback) {
                if (!!mgrGuide.isAllForceGuideFinished()) {
                    let delayEnemy = 0.5;
                    for (let posIndex = 0; posIndex < this.enemyCardArr.length; posIndex++) {
                        let cardUiInfo = this.enemyCardArr[posIndex];
                        if (!cardUiInfo.nodeRoot.visible) {
                            continue;
                        }
                        let cardDataInfo = this.enemyCardPosInfo[posIndex];
                        if (!cardDataInfo) {
                            continue;
                        }
                        mgrEffect.playComebackAction([cardUiInfo.nodeRoot], 0, -500, posIndex * 0.1, 0.6);
                        this.add3DEffectAtFront("117_ui_once_recparticle_02", cardUiInfo.nodeRoot, posIndex * 0.1 + 0.6);
                        delayEnemy += 0.1;
                    }
                    let delayPlayer = 0.8;
                    for (let posIndex = 0; posIndex < this.playerCardArr.length; posIndex++) {
                        let cardUiInfo = this.playerCardArr[posIndex];
                        if (!cardUiInfo.nodeRoot.visible) {
                            continue;
                        }
                        mgrEffect.playComebackAction([cardUiInfo.nodeRoot], 0, 500, delayPlayer + posIndex * 0.1, 0.6);
                        this.add3DEffectAtFront("117_ui_once_recparticle_01", cardUiInfo.nodeRoot, delayPlayer + posIndex * 0.1 + 0.6);
                        Timer.callLater(delayPlayer + posIndex * 0.1, () => {
                            mgrSound.play(631);
                        }, this);
                        delayPlayer += 0.1;
                    }
                    Timer.callLater(Math.max(delayEnemy, delayPlayer + 0.5) + 2, () => {
                        callback && callback();
                    }, this);
                }
                else {
                    for (let posIndex = 1; posIndex < this.enemyCardArr.length; posIndex++) {
                        let cardUiInfo = this.enemyCardArr[posIndex];
                        if (!cardUiInfo.nodeRoot.visible) {
                            continue;
                        }
                        cardUiInfo.nodeRoot.alpha = 0;
                    }
                    for (let posIndex = 1; posIndex < this.playerCardArr.length; posIndex++) {
                        let cardUiInfo = this.playerCardArr[posIndex];
                        if (!cardUiInfo.nodeRoot.visible) {
                            continue;
                        }
                        cardUiInfo.nodeRoot.alpha = 0;
                    }
                    let cardUiInfoEnemy = this.enemyCardArr[0];
                    mgrEffect.playComebackAction([cardUiInfoEnemy.nodeRoot], 0, -500, 0, 0.6);
                    this.add3DEffectAtFront("117_ui_once_recparticle_02", cardUiInfoEnemy.nodeRoot, 0.6);
                    let cardUiInfoPlayer = this.playerCardArr[0];
                    mgrEffect.playComebackAction([cardUiInfoPlayer.nodeRoot], 0, 500, 0.5, 0.6, () => {
                        this.playMovie(() => {
                            let delayEnemy = 0.5;
                            for (let posIndex = 1; posIndex < this.enemyCardArr.length; posIndex++) {
                                let cardUiInfo = this.enemyCardArr[posIndex];
                                if (!cardUiInfo.nodeRoot.visible) {
                                    continue;
                                }
                                let cardDataInfo = this.enemyCardPosInfo[posIndex];
                                if (!cardDataInfo) {
                                    continue;
                                }
                                mgrEffect.playComebackAction([cardUiInfo.nodeRoot], 0, -500, (posIndex - 1) * 0.1, 0.6);
                                this.add3DEffectAtFront("117_ui_once_recparticle_02", cardUiInfo.nodeRoot, (posIndex - 1) * 0.1 + 0.6);
                                delayEnemy += 0.1;
                            }
                            let delayPlayer = 0.8;
                            for (let posIndex = 1; posIndex < this.playerCardArr.length; posIndex++) {
                                let cardUiInfo = this.playerCardArr[posIndex];
                                if (!cardUiInfo.nodeRoot.visible) {
                                    continue;
                                }
                                mgrEffect.playComebackAction([cardUiInfo.nodeRoot], 0, 500, delayPlayer + (posIndex - 1) * 0.1, 0.6);
                                this.add3DEffectAtFront("117_ui_once_recparticle_01", cardUiInfo.nodeRoot, delayPlayer + (posIndex - 1) * 0.1 + 0.6);
                                mgrSound.play(631);
                                delayPlayer += 0.1;
                            }
                            Timer.callLater(Math.max(delayEnemy, delayPlayer + 0.5), () => {
                                callback && callback();
                            }, this);
                        });
                    });
                    this.add3DEffectAtFront("117_ui_once_recparticle_01", cardUiInfoPlayer.nodeRoot, 0.5 + 0.6);
                }
                cc.tween(this.boxContainerMC)
                    .toAlpha(0.2, 1)
                    .call(() => {
                    mgrTip.hideLoadingTip("CARD_TEAM_SET_TO_FIGHT");
                })
                    .start();
            }
            preInitData() {
                if (this.context.stageId) {
                    this.stageData = mgrCfg.get_from_amaze_card_stage_db(this.context.stageId);
                }
                this.stageData = this.stageData || mgrCfg.get_from_amaze_card_stage_db(mgrCard.getStageProgress() + 1) || mgrCfg.get_from_amaze_card_stage_db(mgrCard.getStageProgress());
                this.stageData.statisPointId && mgrSdk.statisOnStageStart(`${this.stageData.statisPointId}`, `${this.stageData.id}`);
                this.enemyCardPosInfo = this.context.enemyCardPosInfo;
                this.playerCardPosInfo = this.context.playerCardPosInfo;
            }
            playMovie(callback) {
                let finishCallback = () => {
                    callback && callback();
                };
                if (this.stageData.fightStoryId != 0) {
                    mgrDirector.openDialog("vStoryDialog", {
                        storyId: this.stageData.fightStoryId,
                        bShowSkip: true,
                        skipCallback: finishCallback,
                        finishCallback: finishCallback,
                    });
                }
                else {
                    finishCallback();
                }
            }
            inInit() {
                this.spriteTitle.visible = false;
            }
            exeInit() {
            }
            outInit() {
            }
            inOpenSkill() {
                console.log("skill--- enter openSkill, doSkillCalc");
                let parseEnemyDataArr = (enemyFightDataArr) => {
                    let arr = [];
                    for (let i = 0; i < enemyFightDataArr.length; i++) {
                        let enemyFightData = enemyFightDataArr[i];
                        let template = {
                            id: enemyFightData.id,
                            npcId: enemyFightData.npcId,
                            tagId: enemyFightData.tagId,
                            fightPower: enemyFightData.fightPower,
                            hp: enemyFightData.hp,
                            originHp: enemyFightData.originHp,
                            cardPosIndex: enemyFightData.cardPosIndex,
                            textureCard: null,
                            styleId: null,
                            remainFreezeRound: enemyFightData.remainFreezeRound || 0,
                        };
                        arr.push(template);
                    }
                    return arr;
                };
                let parsePlayerDataArr = (playerFightDataArr) => {
                    let arr = [];
                    for (let i = 0; i < playerFightDataArr.length; i++) {
                        let playerFightData = playerFightDataArr[i];
                        let template = {
                            id: playerFightData.id,
                            npcId: playerFightData.roleId,
                            tagId: playerFightData.tagId,
                            fightPower: playerFightData.fightPower,
                            hp: playerFightData.hp,
                            originHp: playerFightData.originHp,
                            cardPosIndex: playerFightData.cardPosIndex,
                            textureCard: playerFightData.textureCard,
                            styleId: playerFightData.styleId,
                            remainFreezeRound: playerFightData.remainFreezeRound || 0
                        };
                        arr.push(template);
                    }
                    return arr;
                };
                let parseCardFightDataArrToEnemyFightData = (cardFightDataArr, enemyFightDataArr) => {
                    if (cardFightDataArr.length != enemyFightDataArr.length) {
                        console.warn("skill--- parseCardFightDataArrToEnemyFightData 战斗卡牌 【通用数据】转【敌人数据】 数组长度不一致", cardFightDataArr.length, enemyFightDataArr.length);
                    }
                    for (let i = 0; i < enemyFightDataArr.length; i++) {
                        if (i > cardFightDataArr.length - 1) {
                            break;
                        }
                        let enemyFightData = enemyFightDataArr[i];
                        let cardFightData = cardFightDataArr[i];
                        enemyFightData.cardPosIndex = cardFightData.cardPosIndex;
                        enemyFightData.fightPower = cardFightData.fightPower;
                        enemyFightData.hp = cardFightData.hp;
                        enemyFightData.originHp = cardFightData.originHp;
                        enemyFightData.tagId = cardFightData.tagId;
                        enemyFightData.remainFreezeRound = cardFightData.remainFreezeRound;
                    }
                };
                let parseCardFightDataArrToPlayerFightData = (cardFightDataArr, playerFightDataArr) => {
                    if (cardFightDataArr.length != playerFightDataArr.length) {
                        console.warn("skill--- parseCardFightDataArrToEnemyFightData 战斗卡牌 【通用数据】转【我方数据】 数组长度不一致", cardFightDataArr.length, playerFightDataArr.length);
                    }
                    for (let i = 0; i < playerFightDataArr.length; i++) {
                        if (i > cardFightDataArr.length - 1) {
                            break;
                        }
                        let playerFightData = playerFightDataArr[i];
                        let cardFightData = cardFightDataArr[i];
                        playerFightData.cardPosIndex = cardFightData.cardPosIndex;
                        playerFightData.fightPower = cardFightData.fightPower;
                        playerFightData.hp = cardFightData.hp;
                        playerFightData.originHp = cardFightData.originHp;
                        playerFightData.tagId = cardFightData.tagId;
                        playerFightData.textureCard = cardFightData.textureCard;
                        playerFightData.remainFreezeRound = cardFightData.remainFreezeRound;
                    }
                };
                let dataProcessArr1 = [];
                let dataProcessArr2 = [];
                let userArr = parseEnemyDataArr(this.enemyCardFightDataArr);
                let effectorArr = parsePlayerDataArr(this.playerCardFightDataArr);
                let enemyTeamSkillId = this.stageData.teamSkillId;
                if (enemyTeamSkillId) {
                    let calcRet = mgrCardFightSkill.calcSkillData(enemyTeamSkillId, userArr, effectorArr);
                    let effRenderNodeArr = [];
                    let effCardDataArr = [];
                    if (calcRet.changeData) {
                        for (let key in calcRet.changeData) {
                            let changeFieldDatas = calcRet.changeData[key];
                            let changeFields = [];
                            for (let i = 0; i < changeFieldDatas.length; i++) {
                                let changeFieldData = changeFieldDatas[i];
                                changeFields.push(changeFieldData.dataKey);
                            }
                            let cardId = parseInt(key);
                            let ui = this.getCardUiDataById(cardId);
                            effRenderNodeArr.push(ui.nodeEff);
                            effCardDataArr.push({
                                cardId: cardId,
                                changeFields: changeFields,
                            });
                        }
                    }
                    let renderFun = mgrCardFightSkill.factoryRenderSkill(effRenderNodeArr, effCardDataArr, this.spriteSkillScreenEffNode, this, enemyTeamSkillId);
                    dataProcessArr1.push({
                        data: calcRet,
                        render: renderFun
                    });
                }
                if (dataProcessArr1 && dataProcessArr1.length > 0) {
                    let dataProcess = dataProcessArr1[dataProcessArr1.length - 1];
                    userArr = dataProcess.data.effectorData;
                    effectorArr = dataProcess.data.userData;
                }
                else {
                    userArr = parsePlayerDataArr(this.playerCardFightDataArr);
                    effectorArr = parseEnemyDataArr(this.enemyCardFightDataArr);
                }
                let teamSkillInfo = mgrCardFightSkill.getCurTeamSkillInfo();
                if (teamSkillInfo) {
                    let calcRet = mgrCardFightSkill.calcSkillData(teamSkillInfo.id, userArr, effectorArr);
                    let effRenderNodeArr = [];
                    let effCardDataArr = [];
                    if (calcRet.changeData) {
                        for (let key in calcRet.changeData) {
                            let changeFieldDatas = calcRet.changeData[key];
                            let changeFields = [];
                            for (let i = 0; i < changeFieldDatas.length; i++) {
                                let changeFieldData = changeFieldDatas[i];
                                changeFields.push(changeFieldData.dataKey);
                            }
                            let cardId = parseInt(key);
                            let ui = this.getCardUiDataById(cardId);
                            effRenderNodeArr.push(ui.nodeEff);
                            effCardDataArr.push({
                                cardId: cardId,
                                changeFields: changeFields,
                            });
                        }
                    }
                    let renderFun = mgrCardFightSkill.factoryRenderSkill(effRenderNodeArr, effCardDataArr, this.spriteSkillScreenEffNode, this, teamSkillInfo.id);
                    dataProcessArr2.push({
                        data: calcRet,
                        render: renderFun
                    });
                }
                let getCardFightDataFromSkillCalcResultInfoById = (cardId, calcRet) => {
                    let cardData = null;
                    let fightDataArr1 = calcRet.userData;
                    let fightDataArr2 = calcRet.effectorData;
                    for (let i = 0; i < fightDataArr1.length; i++) {
                        let fightData = fightDataArr1[i];
                        if (fightData.id == cardId) {
                            cardData = fightData;
                            break;
                        }
                    }
                    if (cardData) {
                        return cardData;
                    }
                    for (let i = 0; i < fightDataArr2.length; i++) {
                        let fightData = fightDataArr2[i];
                        if (fightData.id == cardId) {
                            cardData = fightData;
                            break;
                        }
                    }
                    return cardData;
                };
                let renderSkillEff = (calcRet) => {
                    let cardId2ChangeData = calcRet.changeData;
                    let bDie = false;
                    if (!cardId2ChangeData) {
                        return;
                    }
                    console.log("skill--- 进入renderSkillEff--- ", cardId2ChangeData, calcRet);
                    for (let cardId in cardId2ChangeData) {
                        let changeDataArr = cardId2ChangeData[cardId];
                        let id = parseInt(cardId);
                        let cardData = this.getFightCardDataById(id);
                        let cardUiData = this.getCardUiDataById(id);
                        console.log("skill--- 准备刷新渲染--- ", cardId, changeDataArr);
                        if (!cardData) {
                            continue;
                        }
                        console.log("skill--- 刷新渲染--- ", cardId, changeDataArr);
                        for (let i = 0; i < changeDataArr.length; i++) {
                            let changeData = changeDataArr[i];
                            switch (changeData.dataKey) {
                                case "hp":
                                    let changedHp = changeData.dataValue;
                                    let afterHp = cardData.hp;
                                    let beforeHp = afterHp - changedHp;
                                    console.log("skill--- renderSkillData--- render hp", afterHp, beforeHp, changedHp, afterHp / cardData.originHp, cardData.originHp);
                                    mgrSound.play(Tools.random(666, 667));
                                    mgrEffect.shakeNodeXOnce(this.boxContainerMC);
                                    cardUiData.progressBar.progressTweenTo(0.8 / this.CARD_FIGHT_SPEED, afterHp / cardData.originHp);
                                    let bloodItem = new vAmuseCardFightBloodTip({ bSkill: true, amount: changedHp, byPos: new Laya.Vector2(30, -30) });
                                    bloodItem.pos(cardUiData.nodeRoot.x + 10, cardUiData.nodeRoot.y - 10);
                                    cardUiData.nodeRoot.parent.addChild(bloodItem);
                                    if (afterHp <= 0) {
                                        Timer.callLater(0.2, () => {
                                            cc.tween(cardUiData.nodeRoot).removeAllActions();
                                            cc.tween(cardUiData.nodeRoot, true).toAlpha(0.1, 0)
                                                .call(() => { this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnPlayerComplete); })
                                                .start();
                                            cardUiData.nodeEff.alpha = 0;
                                        });
                                        bDie = true;
                                    }
                                    break;
                                case "remainFreezeRound":
                                    let changedFreezeRound = changeData.dataValue;
                                    let afterFreezeRound = cardData.remainFreezeRound;
                                    let beforeFreezeRound = afterFreezeRound - changedFreezeRound;
                                    console.log("skill--- renderSkillData--- render freeze", changedFreezeRound, afterFreezeRound, beforeFreezeRound);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                };
                console.log("renderSkil-- enterRender --");
                let durTime = 0;
                for (let i = 0; i < dataProcessArr1.length; i++) {
                    let processData = dataProcessArr1[i];
                    let preCostTime = processData.data.durTime;
                    parseCardFightDataArrToEnemyFightData(processData.data.userData, this.enemyCardFightDataArr);
                    parseCardFightDataArrToPlayerFightData(processData.data.effectorData, this.playerCardFightDataArr);
                    console.log("skill--- renderSkillData--- 敌方技能效果刷新 enemyCardFightDataArr", this.enemyCardFightDataArr, processData.data.userData);
                    console.log("skill--- renderSkillData--- 敌方技能效果刷新 playerCardFightDataArr", this.playerCardFightDataArr, processData.data.effectorData);
                    console.log("renderSkil-- callLaterRender 敌方 --", durTime);
                    Timer.callLater(durTime, () => {
                        let costTime = processData.render();
                        Timer.callLater(costTime, () => {
                            renderSkillEff(processData.data);
                        });
                        console.log("renderSkil-- doRender addDurTime 敌方 , durTime, costTime", durTime, costTime);
                    });
                    durTime += preCostTime;
                }
                for (let i = 0; i < dataProcessArr2.length; i++) {
                    let processData = dataProcessArr2[i];
                    let preCostTime = processData.data.durTime;
                    parseCardFightDataArrToEnemyFightData(processData.data.effectorData, this.enemyCardFightDataArr);
                    parseCardFightDataArrToPlayerFightData(processData.data.userData, this.playerCardFightDataArr);
                    console.log("skill--- renderSkillData--- 我方技能效果刷新 enemyCardFightDataArr", this.playerCardFightDataArr, processData.data.userData);
                    console.log("skill--- renderSkillData--- 我方技能效果刷新 playerCardFightDataArr", this.enemyCardFightDataArr, processData.data.effectorData);
                    console.log("renderSkil-- callLaterRender 我方 --", durTime);
                    Timer.callLater(durTime, () => {
                        let costTime = processData.render();
                        Timer.callLater(costTime, () => {
                            renderSkillEff(processData.data);
                        });
                        console.log("renderSkil-- doRender addDurTime 我方 , durTime, costTime", durTime, costTime);
                    });
                    durTime += preCostTime;
                }
                Timer.callLater(durTime, () => {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.prepareTurnPlayer);
                    console.log("skill--- skill calculate complete, set next state");
                });
            }
            exeOpenSkill() {
            }
            outOpenSkill() {
            }
            inPrepareTurnPlayer() {
                this.currTurnAttackPosIndex = 5;
                this.currTurnAttackData = this.getPlayerFightCardDataAttack(this.currTurnAttackPosIndex);
                this.currTurnDefenceData = this.getEnemyFightCardDataDefence();
                if (!!this.currTurnAttackData) {
                    this.currTurnAttackPosIndex = this.currTurnAttackData.cardPosIndex - 1;
                }
                this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnPlayer);
            }
            exePrepareTurnPlayer() {
            }
            outPrepareTurnPlayer() {
            }
            inTurnPlayer() {
                let playerData = this.currTurnAttackData;
                let enemyData = this.currTurnDefenceData;
                if (!enemyData) {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnPlayerComplete);
                    return;
                }
                let doContent = () => {
                    let playerUiData = this.playerCardArr[playerData.cardPosIndex >= 5 ? 4 : playerData.cardPosIndex];
                    let enemyUiData = this.enemyCardArr[enemyData.cardPosIndex];
                    let enemyPos = enemyUiData.nodeRoot["originPos"];
                    let playerPos = playerUiData.nodeRoot["originPos"];
                    let oldZOrder = playerUiData.nodeRoot.zOrder;
                    playerUiData.nodeRoot.zOrder = 100;
                    let targetPos = new Laya.Vector2(enemyPos.x, enemyPos.y);
                    let centerPoint = new Laya.Point(targetPos.x + (playerPos.x - targetPos.x) / 2, targetPos.y + (playerPos.y - targetPos.y) / 2);
                    if (targetPos.x > playerPos.x) {
                        centerPoint.x += 100;
                    }
                    else {
                        centerPoint.x -= 100;
                    }
                    let oldScale = playerUiData.nodeRoot.scaleX;
                    let rot = Tools.getAngle(playerPos.x, playerPos.y - 20, targetPos.x, targetPos.y);
                    let tagId = playerData.tagId;
                    let effInfos = this.PLAYER_TAG_ID_2_EFFNAME_DICT[tagId] || this.PLAYER_TAG_ID_2_EFFNAME_DICT[1];
                    let effInfo = Tools.randomGotOneArrayData(effInfos);
                    cc.tween(playerUiData.nodeRoot)
                        .toPos(0.15, playerPos.x, playerPos.y - 20)
                        .delay(0.4 / this.CARD_FIGHT_SPEED)
                        .call(() => {
                        this.add3DEffectAtFront(effInfo.begin || "117_ui_once_begain_yellow", playerUiData.nodeRoot, 1 / this.CARD_FIGHT_SPEED, 1, null, this.CARD_FIGHT_SPEED);
                        mgrSound.play(Tools.random(661, 665));
                    })
                        .toScale(0.5 / this.CARD_FIGHT_SPEED, oldScale * 1.3).toScale(0.15 / this.CARD_FIGHT_SPEED, oldScale)
                        .call(() => {
                        let spriteHolder = new Laya.Sprite();
                        playerUiData.nodeRoot.parent.addChild(spriteHolder);
                        spriteHolder.pos(playerUiData.nodeRoot.x, playerUiData.nodeRoot.y);
                        let doFightMoveEff = (particleModelId, speed, rotVec3) => {
                            this.add3DEffectAtFront(particleModelId, spriteHolder, 0.6 / this.CARD_FIGHT_SPEED, 1, null, speed || this.CARD_FIGHT_SPEED, rotVec3);
                            cc.tween(spriteHolder)
                                .then(cc.bezierTo(0.6 / this.CARD_FIGHT_SPEED, [playerPos.x, playerPos.y, centerPoint.x, centerPoint.y, targetPos.x, targetPos.y], 3))
                                .call(() => {
                                if (particleModelId instanceof Laya.Sprite3D) {
                                    Timer.callLater(0.6 / this.CARD_FIGHT_SPEED, () => {
                                        mgrLoader.Pool.recoverModel(particleModelId);
                                    }, this);
                                }
                                this.add3DEffectAtFront(effInfo.end || "117_ui_once_ballex_yellow", spriteHolder, 2 / this.CARD_FIGHT_SPEED, 1, null, this.CARD_FIGHT_SPEED);
                                mgrEffect.shakeNodeXOnce(enemyUiData.nodeRoot);
                            })
                                .start();
                        };
                        let doFightStandEff = (particleModelId, speed, rotVec3) => {
                            this.add3DEffectAtFront(particleModelId, spriteHolder, 0.6 / this.CARD_FIGHT_SPEED, 1, null, speed || this.CARD_FIGHT_SPEED, rotVec3);
                            cc.tween(spriteHolder)
                                .delay(0.6 / this.CARD_FIGHT_SPEED)
                                .call(() => {
                                if (particleModelId instanceof Laya.Sprite3D) {
                                    Timer.callLater(0.6 / this.CARD_FIGHT_SPEED, () => {
                                        mgrLoader.Pool.recoverModel(particleModelId);
                                    }, this);
                                }
                                this.add3DEffectAtFront(effInfo.end || "117_ui_once_ballex_yellow", enemyUiData.nodeRoot, 1 / this.CARD_FIGHT_SPEED, 1, null, this.CARD_FIGHT_SPEED);
                                mgrEffect.shakeNodeXOnce(enemyUiData.nodeRoot);
                            })
                                .start();
                        };
                        if (effInfo.bMoveToTarget) {
                            doFightMoveEff(effInfo.move, null, effInfo.bRot ? new Laya.Vector3(0, 0, rot) : new Laya.Vector3);
                        }
                        else {
                            doFightStandEff(effInfo.move, null, effInfo.bRot ? new Laya.Vector3(0, 0, rot) : new Laya.Vector3);
                        }
                    })
                        .delay(0.4 / this.CARD_FIGHT_SPEED)
                        .call(() => {
                        mgrSound.play(Tools.random(666, 667));
                        mgrEffect.shakeNodeXOnce(this.boxContainerMC);
                        let bSkill = this.ATTACK_ADD_TAG_DICT[playerData.tagId] == enemyData.tagId ? true : false;
                        let currFightPower = Math.floor(!!bSkill ? playerData.fightPower * 1.2 : playerData.fightPower);
                        let lostHp = enemyData.hp <= currFightPower ? enemyData.hp : currFightPower;
                        enemyData.hp -= lostHp;
                        enemyUiData.progressBar.progressTweenTo(0.8 / this.CARD_FIGHT_SPEED, enemyData.hp / enemyData.originHp);
                        let bloodItem = new vAmuseCardFightBloodTip({ bSkill: bSkill, amount: lostHp, byPos: new Laya.Vector2(30, -30) });
                        bloodItem.pos(enemyUiData.nodeRoot.x + 10, enemyUiData.nodeRoot.y - 10);
                        enemyUiData.nodeRoot.parent.addChild(bloodItem);
                    })
                        .delay(1.2 / this.CARD_FIGHT_SPEED)
                        .call(() => {
                        if (enemyData.hp <= 0) {
                            cc.tween(enemyUiData.nodeRoot).removeAllActions();
                            cc.tween(enemyUiData.nodeRoot, true).toAlpha(0.1, 0).start();
                            cc.tween(enemyUiData.nodeEff).removeAllActions();
                            cc.tween(enemyUiData.nodeEff).toAlpha(0.1, 0).start();
                        }
                    })
                        .delay(0.3 / this.CARD_FIGHT_SPEED)
                        .toPos(0.2 / this.CARD_FIGHT_SPEED, playerPos.x, playerPos.y)
                        .call(() => {
                        playerUiData.nodeRoot.zOrder = oldZOrder;
                        this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnPlayerComplete);
                    })
                        .start();
                };
                let bFrozed = mgrCardFightSkill.isExistFrozenEff(playerData.id);
                console.log("解冻判断-- remainFreezeRound, bFrozed", playerData.remainFreezeRound, bFrozed);
                if (playerData.remainFreezeRound && playerData.remainFreezeRound > 0) {
                    playerData.remainFreezeRound = Math.max(0, playerData.remainFreezeRound - 1);
                    mgrTip.showMsgTip(`冻结！剩余冻结回合:${playerData.remainFreezeRound}`);
                    Timer.callLater(1, () => {
                        this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnPlayerComplete);
                    });
                    return;
                }
                else if (playerData.remainFreezeRound <= 0 && bFrozed) {
                    mgrTip.showMsgTip(`冰冻解除！`);
                    let ui = this.getCardUiDataById(playerData.id);
                    delete playerData.remainFreezeRound;
                    let fun = mgrCardFightSkill.factoryRelieveFroze(ui.nodeEff, this, playerData.id);
                    let costTime = fun();
                    Timer.callLater(costTime, () => {
                        doContent();
                    });
                    return;
                }
                doContent();
            }
            exeTurnPlayer() {
            }
            outTurnPlayer() {
            }
            inTurnPlayerComplete() {
                this.currTurnAttackData = this.getPlayerFightCardDataAttack(this.currTurnAttackPosIndex);
                this.currTurnDefenceData = this.getEnemyFightCardDataDefence();
                if (!!this.currTurnAttackData) {
                    this.currTurnAttackPosIndex = this.currTurnAttackData.cardPosIndex - 1;
                }
                if (!this.currTurnDefenceData) {
                    this.bSuccess = true;
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.reward);
                }
                else if (!this.currTurnAttackData) {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.prepareTurnEnemy);
                }
                else {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnPlayer);
                }
            }
            exeTurnPlayerComplete() {
            }
            outTurnPlayerComplete() {
            }
            inPrepareTurnEnemy() {
                this.currTurnAttackPosIndex = 0;
                this.currTurnAttackData = this.getEnemyFightCardDataAttack(this.currTurnAttackPosIndex);
                this.currTurnDefenceData = this.getPlayerFightCardDataDefence();
                if (!!this.currTurnAttackData) {
                    this.currTurnAttackPosIndex = this.currTurnAttackData.cardPosIndex + 1;
                }
                if (this.currTurnDefenceData.bPhysical) {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnEnemyPhysical);
                }
                else {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnEnemy);
                }
            }
            exePrepareTurnEnemy() {
            }
            outPrepareTurnEnemy() {
            }
            inTurnEnemy() {
                let playerData = this.currTurnDefenceData;
                let enemyData = this.currTurnAttackData;
                let doContent = () => {
                    let playerUiData = this.playerCardArr[playerData.cardPosIndex >= 5 ? 4 : playerData.cardPosIndex];
                    let enemyUiData = this.enemyCardArr[enemyData.cardPosIndex];
                    let enemyPos = enemyUiData.nodeRoot["originPos"];
                    let playerPos = playerUiData.nodeRoot["originPos"];
                    let oldZOrder = enemyUiData.nodeRoot.zOrder;
                    enemyUiData.nodeRoot.zOrder = 100;
                    let targetPos = new Laya.Vector2(playerPos.x, playerPos.y);
                    let centerPoint = new Laya.Point(enemyPos.x + (targetPos.x - enemyPos.x) / 2, enemyPos.y + (targetPos.y - enemyPos.y) / 2);
                    if (targetPos.x > enemyPos.x) {
                        centerPoint.x -= 100;
                    }
                    else {
                        centerPoint.x += 100;
                    }
                    cc.tween(enemyUiData.nodeRoot)
                        .toPos(0.15, enemyPos.x, enemyPos.y + 20)
                        .delay(0.4 / this.CARD_FIGHT_SPEED)
                        .call(() => {
                        mgrSound.play(Tools.random(668, 670));
                        this.add3DEffectAtFront("117_ui_once_begain_purple", enemyUiData.nodeRoot, 1 / this.CARD_FIGHT_SPEED, 1, null, this.CARD_FIGHT_SPEED);
                    })
                        .delay(0.75 / this.CARD_FIGHT_SPEED)
                        .call(() => {
                        let spriteHolder = new Laya.Sprite();
                        enemyUiData.nodeRoot.parent.addChild(spriteHolder);
                        spriteHolder.pos(enemyUiData.nodeRoot.x, enemyUiData.nodeRoot.y);
                        this.add3DEffectAtFront("117_ui_loop_balltrail_purple", spriteHolder, 0.6 / this.CARD_FIGHT_SPEED, 1, null, this.CARD_FIGHT_SPEED);
                        cc.tween(spriteHolder)
                            .then(cc.bezierTo(0.6 / this.CARD_FIGHT_SPEED, [enemyPos.x, enemyPos.y, centerPoint.x, centerPoint.y, targetPos.x, targetPos.y], 3))
                            .call(() => {
                            this.add3DEffectAtFront("117_ui_once_ballex_purple", spriteHolder, 2 / this.CARD_FIGHT_SPEED, 1, null, this.CARD_FIGHT_SPEED);
                            mgrEffect.shakeNodeXOnce(playerUiData.nodeRoot);
                        })
                            .start();
                    })
                        .delay(0.4 / this.CARD_FIGHT_SPEED)
                        .call(() => {
                        mgrSound.play(Tools.random(666, 667));
                        let bSkill = this.ATTACK_ADD_TAG_DICT[enemyData.tagId] == playerData.tagId ? true : false;
                        let currFightPower = Math.floor(!!bSkill ? enemyData.fightPower * 1.2 : enemyData.fightPower);
                        let lostHp = playerData.hp <= currFightPower ? playerData.hp : currFightPower;
                        playerData.hp -= lostHp;
                        playerUiData.progressBar.progressTweenTo(0.8 / this.CARD_FIGHT_SPEED, playerData.hp / playerData.originHp);
                        let bloodItem = new vAmuseCardFightBloodTip({ bSkill: bSkill, amount: lostHp, byPos: new Laya.Vector2(30, 30) });
                        bloodItem.pos(playerUiData.nodeRoot.x + 10, playerUiData.nodeRoot.y - 10);
                        playerUiData.nodeRoot.parent.addChild(bloodItem);
                    })
                        .delay(1.2 / this.CARD_FIGHT_SPEED)
                        .call(() => {
                        if (playerData.hp <= 0) {
                            cc.tween(playerUiData.nodeRoot).removeAllActions();
                            cc.tween(playerUiData.nodeRoot, true).toAlpha(0.1, 0).start();
                            cc.tween(playerUiData.nodeEff).removeAllActions();
                            cc.tween(playerUiData.nodeEff).toAlpha(0.1, 0).start();
                        }
                    })
                        .delay(0.3 / this.CARD_FIGHT_SPEED)
                        .toPos(0.2 / this.CARD_FIGHT_SPEED, enemyPos.x, enemyPos.y)
                        .call(() => {
                        enemyUiData.nodeRoot.zOrder = oldZOrder;
                        this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnEnemyComplete);
                    })
                        .start();
                };
                let bFrozed = mgrCardFightSkill.isExistFrozenEff(enemyData.id);
                console.log("解冻判断-- remainFreezeRound, bFrozed", enemyData.remainFreezeRound, bFrozed);
                if (enemyData.remainFreezeRound && enemyData.remainFreezeRound > 0) {
                    enemyData.remainFreezeRound = Math.max(0, enemyData.remainFreezeRound - 1);
                    mgrTip.showMsgTip(`冻结！剩余冻结回合:${enemyData.remainFreezeRound}`);
                    Timer.callLater(1, () => {
                        this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnEnemyComplete);
                    });
                    return;
                }
                else if (enemyData.remainFreezeRound <= 0 && bFrozed) {
                    mgrTip.showMsgTip(`冰冻解除！`);
                    let ui = this.getCardUiDataById(enemyData.id);
                    delete enemyData.remainFreezeRound;
                    let fun = mgrCardFightSkill.factoryRelieveFroze(ui.nodeEff, this, enemyData.id);
                    let costTime = fun();
                    Timer.callLater(costTime, () => {
                        doContent();
                    });
                    return;
                }
                doContent();
            }
            exeTurnEnemy() {
            }
            outTurnEnemy() {
            }
            inTurnEnemyPhysical() {
                let playerData = this.currTurnDefenceData;
                let enemyData = this.currTurnAttackData;
                let playerUiData = this.playerCardArr[playerData.cardPosIndex];
                let enemyUiData = this.enemyCardArr[enemyData.cardPosIndex];
                let enemyPos = enemyUiData.nodeRoot["originPos"];
                let playerPos = playerUiData.nodeRoot["originPos"];
                let oldZOrder = enemyUiData.nodeRoot.zOrder;
                enemyUiData.nodeRoot.zOrder = 100;
                cc.tween(enemyUiData.nodeRoot)
                    .toPos(0.2 / this.CARD_FIGHT_SPEED, enemyPos.x, enemyPos.y + 20)
                    .delay(0.6 / this.CARD_FIGHT_SPEED)
                    .toPos(0.2 / this.CARD_FIGHT_SPEED, playerPos.x - 10, playerPos.y - 50)
                    .call(() => {
                    let bSkill = this.ATTACK_ADD_TAG_DICT[enemyData.tagId] == playerData.tagId ? true : false;
                    let currFightPower = Math.floor(!!bSkill ? enemyData.fightPower * 1.2 : enemyData.fightPower);
                    let lostHp = playerData.hp <= currFightPower ? playerData.hp : currFightPower;
                    playerData.hp -= lostHp;
                    playerUiData.progressBar.progressTweenTo(0.8 / this.CARD_FIGHT_SPEED, playerData.hp / playerData.originHp);
                    let bloodItem = new vAmuseCardFightBloodTip({ bSkill: bSkill, amount: lostHp, byPos: new Laya.Vector2(30, 30) });
                    bloodItem.pos(playerUiData.nodeRoot.x + 10, playerUiData.nodeRoot.y - 10);
                    playerUiData.nodeRoot.parent.addChild(bloodItem);
                    this.add3DEffectAtFront("117_ui_once_hit_03", playerUiData.nodeRoot, 0.5);
                })
                    .delay(1.2 / this.CARD_FIGHT_SPEED)
                    .call(() => {
                    if (playerData.hp <= 0) {
                        cc.tween(playerUiData.nodeRoot).removeAllActions();
                        cc.tween(playerUiData.nodeRoot, true).toAlpha(0.1, 0).start();
                        cc.tween(playerUiData.nodeEff).removeAllActions();
                        cc.tween(playerUiData.nodeEff).toAlpha(0.1, 0).start();
                    }
                })
                    .delay(0.3 / this.CARD_FIGHT_SPEED)
                    .toPos(0.2 / this.CARD_FIGHT_SPEED, enemyPos.x, enemyPos.y)
                    .delay(0.3 / this.CARD_FIGHT_SPEED)
                    .call(() => {
                    enemyUiData.nodeRoot.zOrder = oldZOrder;
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnEnemyComplete);
                })
                    .start();
            }
            exeTurnEnemyPhysical() {
            }
            outTurnEnemyPhysical() {
            }
            inTurnEnemyComplete() {
                this.currTurnAttackData = this.getEnemyFightCardDataAttack(this.currTurnAttackPosIndex);
                this.currTurnDefenceData = this.getPlayerFightCardDataDefence();
                if (!!this.currTurnAttackData) {
                    this.currTurnAttackPosIndex = this.currTurnAttackData.cardPosIndex + 1;
                }
                if (!this.currTurnDefenceData) {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.reward);
                }
                else if (!this.currTurnAttackData) {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.prepareTurnPlayer);
                }
                else {
                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.turnEnemy);
                }
            }
            exeTurnEnemyComplete() {
            }
            outTurnEnemyComplete() {
            }
            inTurnMagic() {
            }
            exeTurnMagic() {
            }
            outTurnMagic() {
            }
            inCheckResult() {
            }
            exeCheckResult() {
            }
            outCheckResult() {
            }
            inReward() {
                let fOnMoreUnlockItemDialogClose = () => {
                    if (!this.visible) {
                        return;
                    }
                    console.log("fTryTipNewYearRewards-- open vGotNewRoleDialog", this.tipArr);
                    if (!this.tipArr || !this.tipArr.length) {
                        this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.palette);
                        return;
                    }
                    for (let j = 0; j < this.tipArr.length; j++) {
                        let tipData = this.tipArr[j];
                        console.log("fTryTipNewYearRewards-- pop tipArr", this.tipArr);
                        mgrTip.addGotItemTip(tipData.itemId, tipData.amount, null, {
                            fOnClose: () => {
                                this.tipCount--;
                                console.log("fTryTipNewYearRewards-- try set next state", this.tipCount);
                                if (this.tipCount <= 0) {
                                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.palette);
                                }
                            }
                        });
                    }
                };
                Timer.callLater(1, () => {
                    let fTryTipNewYearRewards = (data) => {
                        let newYearRewards = data.newYearRewards;
                        let result = false;
                        if (newYearRewards && newYearRewards.length > 0) {
                            for (let i = 0; i < newYearRewards.length; i++) {
                                let rewardData = newYearRewards[i];
                                if (rewardData.type == "roleUnlockItem") {
                                    let roleId = null;
                                    let roleDataArr = mgrCfg.getDbArr("role_db", (data2) => {
                                        if (data2.unlockItemId == rewardData.itemId) {
                                            return true;
                                        }
                                    });
                                    let newYearRoleId = mgrCard.getNewYearStageRewardConfig().roleId;
                                    if (roleDataArr) {
                                        for (let j = 0; j < roleDataArr.length; j++) {
                                            let roleData = roleDataArr[j];
                                            if (roleData.id == newYearRoleId) {
                                                roleId = roleData.id;
                                            }
                                        }
                                    }
                                    if (roleId) {
                                        mgrDirector.openDialog("vAdGetMoreUnlockItemDialog", {
                                            roleId: roleId,
                                            amount: rewardData.amount,
                                            stageId: this.context.stageId,
                                            labelBtnGiveUp: "确定",
                                            fOnCloseDialog: fOnMoreUnlockItemDialogClose
                                        });
                                        result = true;
                                    }
                                }
                                else {
                                    this.tipArr.push(rewardData);
                                    this.tipCount++;
                                    result = true;
                                    console.log("fTryTipNewYearRewards-- push into tipArr", rewardData, this.tipArr);
                                }
                            }
                        }
                        return result;
                    };
                    let doExcFunc = () => {
                        let data = mgrCard.finishStage(this.stageData.id, this.bSuccess);
                        if (!mgrGuide.isGuiding()) {
                            mgrCard.obtainRewardInSDK();
                        }
                        this.oldColorPoint = data.oldColorPoint;
                        this.currGotColorPoint = data.currGotColorPoint;
                        this.spriteTitleSuccess.visible = !!this.bSuccess;
                        this.spriteTitleFaild.visible = !this.spriteTitleSuccess.visible;
                        this.spriteTitle.visible = true;
                        this.spriteTitle.scale(3, 3, true);
                        cc.tween(this.spriteTitle).toScale(0.1, 1)
                            .call(() => {
                            if (!!this.bSuccess) {
                                mgrSound.play(312);
                            }
                            else {
                                mgrSound.play(313);
                            }
                        })
                            .delay(1)
                            .call(() => {
                            let alertResult = fTryTipNewYearRewards(data);
                            if (alertResult) {
                            }
                            else {
                                this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.palette);
                            }
                        })
                            .start();
                    };
                    if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                        mgrTip.alertPrompt1("提示", `战斗完成`, "确定", () => {
                            doExcFunc();
                        });
                    }
                    else {
                        doExcFunc();
                    }
                }, this);
            }
            exeReward() {
            }
            outReward() {
            }
            inPalette() {
                let gotCoinFunc = () => {
                    if (!mgrGuide.isAllForceGuideFinished()) {
                        this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.finish);
                        return;
                    }
                    let rewardRmb = Tools.random(5, 10);
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, rewardRmb, "卡牌战斗结算奖励");
                    mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, rewardRmb, null, {
                        fOnClose: () => {
                            let partId = mgrWorldDaily.getUnownedVipPart(DailyGameType.card);
                            if (this.bSuccess && !!partId && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment) && (Tools.random(0, 100) <= mgrSdk.getCopNumberValueByKey("surprise_card_ratio") || !!this.context.bVip)) {
                                mgrDirector.openDialog("vSurpriseRewardDialog", {
                                    bVip: !!this.context.bVip,
                                    partId,
                                    fOnClose: () => {
                                        this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.finish);
                                    }
                                });
                            }
                            else if (!this.bSuccess) {
                                mgrSdk.statisOnStageStart("30001");
                                mgrTip.alertPrompt2("提示", "太遗憾了！听说抽卡能获得高分卡挽救败局哦~", "算了", "去抽卡", () => {
                                    mgrSdk.statisOnStageEnd("30001", 1, "");
                                    this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.finish);
                                }, () => {
                                    mgrSdk.statisOnStageEnd("30001", 1, "");
                                    mgrSdk.statisCommonEvent(30002);
                                    mgrDirector.openDialog("vAmuseCardPreviewExtractDialog", {
                                        fOnClose: () => {
                                            this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.finish);
                                        }
                                    });
                                });
                            }
                            else {
                                this.stManager.setNextState(AMUSE_CARD_FIGHT_STATE.finish);
                            }
                        }
                    });
                };
                if (!this.bSuccess || this.currGotColorPoint <= 0) {
                    gotCoinFunc();
                }
                else {
                    let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.card);
                    if (!rewardPartId) {
                        gotCoinFunc();
                        return;
                    }
                    mgrDirector.openDialog("vAmuseCakeResultDialog", {
                        colorItemId: Const.ITEM_ID_CARD_FIGHT_PROGRESS_POINT,
                        oldColorPoint: this.oldColorPoint,
                        currGotColorPoint: this.currGotColorPoint,
                        dailyGameType: DailyGameType.card,
                        bSuccess: this.bSuccess,
                        rewardPartId: rewardPartId,
                        fOnClose: () => {
                            gotCoinFunc();
                        }
                    });
                }
            }
            exePalette() {
            }
            outPalette() {
            }
            inFinish() {
                this.stageData.statisPointId && mgrSdk.statisOnStageEnd(`${this.stageData.statisPointId}`, this.bSuccess ? 1 : 0, `${this.stageData.id}`);
                let callback = () => {
                    switch (this.stageData.type) {
                        case CARD_FIGHT_TYPE.dailyword:
                            mgrWorldDaily.markCardFighted();
                            if (mgrGuide.isAllForceGuideFinished()) {
                                mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene");
                            }
                            else {
                                mgrDirector.warpSceneWidthEffect("vHubScene");
                            }
                            break;
                        default:
                            mgrDirector.warpSceneWidthEffect(this.context.backSceneName || "vHubScene");
                            break;
                    }
                };
                mgrVideoRecorder.stopRecord();
                mgrTip.tryShowPhotoShare("vAmuseCardFightScene", "res/ui/stage_result_fm/sprite_content_bg06.jpg", null, () => {
                    callback();
                });
            }
            exeFinish() {
            }
            outFinish() {
            }
            playerAttackScreenEffect() {
            }
            enemyAttackScreenEffect() {
            }
            getCardUiDataById(cardId) {
                let uiData = null;
                let playerFightDataArr = this.playerCardFightDataArr;
                let enemyFightDataArr = this.enemyCardFightDataArr;
                for (let i = 0; i < playerFightDataArr.length; i++) {
                    let fightData = playerFightDataArr[i];
                    if (fightData.id == cardId) {
                        uiData = this.playerCardArr[fightData.cardPosIndex >= 5 ? 4 : fightData.cardPosIndex];
                        break;
                    }
                }
                if (uiData) {
                    return uiData;
                }
                for (let i = 0; i < enemyFightDataArr.length; i++) {
                    let fightData = enemyFightDataArr[i];
                    if (fightData.id == cardId) {
                        uiData = this.enemyCardArr[fightData.cardPosIndex];
                        break;
                    }
                }
                return uiData;
            }
            getFightCardDataById(cardId) {
                let cardData = null;
                let playerFightDataArr = this.playerCardFightDataArr;
                let enemyFightDataArr = this.enemyCardFightDataArr;
                for (let i = 0; i < playerFightDataArr.length; i++) {
                    let fightData = playerFightDataArr[i];
                    if (fightData.id == cardId) {
                        cardData = fightData;
                        break;
                    }
                }
                if (cardData) {
                    return cardData;
                }
                for (let i = 0; i < enemyFightDataArr.length; i++) {
                    let fightData = enemyFightDataArr[i];
                    if (fightData.id == cardId) {
                        cardData = fightData;
                        break;
                    }
                }
                return cardData;
            }
            getFightCardData() {
                let validPlayerArr = [];
                for (let k in this.playerCardFightDataArr) {
                    let data = this.playerCardFightDataArr[k];
                    if (data.hp > 0) {
                        validPlayerArr.push(data);
                    }
                }
                let validEnemyArr = [];
                for (let k in this.enemyCardFightDataArr) {
                    let data = this.enemyCardFightDataArr[k];
                    if (data.hp > 0) {
                        validEnemyArr.push(data);
                    }
                }
                let playerData = validPlayerArr.length > 0 ? validPlayerArr[Tools.random(0, validPlayerArr.length - 1)] : null;
                let enemyData = validEnemyArr.length > 0 ? validEnemyArr[Tools.random(0, validEnemyArr.length - 1)] : null;
                return { playerData: playerData, enemyData: enemyData };
            }
            getEnemyFightCardDataDefence() {
                let validEnemyArr = [];
                for (let k in this.enemyCardFightDataArr) {
                    let data = this.enemyCardFightDataArr[k];
                    if (data.hp > 0) {
                        validEnemyArr.push(data);
                    }
                }
                let enemyData = validEnemyArr.length > 0 ? validEnemyArr[Tools.random(0, validEnemyArr.length - 1)] : null;
                return enemyData;
            }
            getPlayerFightCardDataDefence() {
                let validPlayerArr = [];
                for (let k in this.playerCardFightDataArr) {
                    let data = this.playerCardFightDataArr[k];
                    if (data.hp > 0) {
                        validPlayerArr.push(data);
                    }
                }
                let playerData = validPlayerArr.length > 0 ? validPlayerArr[Tools.random(0, validPlayerArr.length - 1)] : null;
                return playerData;
            }
            getPlayerFightCardDataAttack(startCheckPosIndex) {
                for (let i = 5; i >= 0; i--) {
                    let posIndex = i;
                    if (startCheckPosIndex < posIndex) {
                        continue;
                    }
                    let data = this.playerCardFightDataArr[posIndex];
                    if (!data) {
                        continue;
                    }
                    if (data.hp > 0) {
                        return data;
                    }
                }
                return null;
            }
            getEnemyFightCardDataAttack(startCheckPosIndex) {
                for (let k in this.enemyCardFightDataArr) {
                    let posIndex = parseInt(k);
                    if (startCheckPosIndex > posIndex) {
                        continue;
                    }
                    let data = this.enemyCardFightDataArr[k];
                    if (data.hp > 0) {
                        return data;
                    }
                }
                return null;
            }
            fillData() {
                let enemyCardFightDataArr = [];
                let playerCardFightDataArr = [];
                for (let k in this.enemyCardPosInfo) {
                    let data = this.enemyCardPosInfo[k];
                    enemyCardFightDataArr.push({
                        id: ++this.curMaxCardFightId,
                        npcId: data.roleId,
                        tagId: data.tagId,
                        fightPower: data.power,
                        hp: data.hp,
                        originHp: (data.hp || 1),
                        cardPosIndex: parseInt(k),
                        bPhysical: !!parseInt(k) ? (Tools.random(100) > 50 ? true : false) : false,
                        remainFreezeRound: data.remainFreezeRound || 0,
                    });
                }
                this.enemyCardFightDataArr = enemyCardFightDataArr;
                for (let i = 0; i < this.playerCardPosInfo.length; i++) {
                    let data = this.playerCardPosInfo[i];
                    if (data["bDoubleNpc"]) {
                        playerCardFightDataArr.push({
                            id: ++this.curMaxCardFightId,
                            roleId: data.roleId,
                            tagId: data.tagId,
                            fightPower: data.power,
                            hp: data.hp,
                            originHp: (data.hp || 1),
                            cardPosIndex: i,
                            textureCard: data.textureCard,
                            styleId: data.styleId,
                            npcPicId: data["npcPicId"],
                            bDoubleNpc: data["bDoubleNpc"],
                            remainFreezeRound: data.remainFreezeRound || 0,
                        });
                    }
                    else {
                        playerCardFightDataArr.push({
                            id: ++this.curMaxCardFightId,
                            roleId: data.roleId,
                            tagId: data.tagId,
                            fightPower: data.power,
                            hp: data.hp,
                            originHp: (data.hp || 1),
                            cardPosIndex: i,
                            textureCard: data.textureCard,
                            styleId: data.styleId,
                            remainFreezeRound: data.remainFreezeRound || 0,
                        });
                    }
                }
                this.playerCardFightDataArr = playerCardFightDataArr;
                this.refreshEnemyCardUi();
                this.refreshPlayerCardUi();
            }
            refreshEnemyCardUi() {
                let setedCardCount = 0;
                let totalPower = 0;
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let cardDataInfo = this.enemyCardPosInfo[i];
                    this.adaptEnemyCardByPosIndex(i, cardDataInfo);
                    if (!!cardDataInfo) {
                        totalPower += cardDataInfo.power;
                        setedCardCount++;
                    }
                }
                this.labelEnemyTotalPower.text = `${totalPower}`;
                for (let posIndex = 0; posIndex < setedCardCount; posIndex++) {
                    let cardUiInfo = this.enemyCardArr[posIndex];
                    let holderName = `spriteEnemyCount${setedCardCount}Holder${posIndex}`;
                    let holder = this.boxContainerMC.getChildByName(holderName);
                    cardUiInfo.nodeRoot.pos(holder.x, holder.y, true);
                    cardUiInfo.nodeRoot.scale(holder.scaleX, holder.scaleX, true);
                    cardUiInfo.nodeRoot["originPos"] = new Laya.Vector2(cardUiInfo.nodeRoot.x, cardUiInfo.nodeRoot.y);
                }
            }
            refreshPlayerCardUi() {
                let setedCardCount = 0;
                let playerTotalPower = 0;
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let cardDataInfo = this.playerCardFightDataArr[i];
                    this.adaptPlayerCardByPosIndex(i, cardDataInfo);
                    if (!!cardDataInfo) {
                        playerTotalPower += cardDataInfo.fightPower;
                        setedCardCount++;
                    }
                }
                this.labelPlayerTotalPower.text = `${playerTotalPower}`;
                for (let posIndex = 0; posIndex < setedCardCount; posIndex++) {
                    let cardUiInfo = this.playerCardArr[posIndex];
                    let holderName = `spritePlayerCount${setedCardCount}Holder${posIndex}`;
                    let holder = this.boxContainerMC.getChildByName(holderName);
                    cardUiInfo.nodeRoot.pos(holder.x, holder.y, true);
                    cardUiInfo.nodeRoot.scale(holder.scaleX, holder.scaleX, true);
                    cardUiInfo.nodeRoot["originPos"] = new Laya.Vector2(cardUiInfo.nodeRoot.x, cardUiInfo.nodeRoot.y);
                }
            }
            widget() {
            }
            adaptEnemyCardByPosIndex(posIndex, cardDataInfo) {
                let bUnlocked = true;
                let cardUiInfo = this.enemyCardArr[posIndex];
                cardUiInfo.nodeRoot.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                if (!!cardDataInfo) {
                    let tagData = mgrCfg.get_from_part_tag_db(cardDataInfo.tagId);
                    let styleData = mgrCfg.get_from_amuse_card_style_db(cardDataInfo.styleId);
                    Tools.loadImg(cardUiInfo.spriteCard, cardDataInfo.texturePath);
                    Tools.loadImg(cardUiInfo.spriteCardBack, styleData.textureSmallBack);
                    Tools.loadImg(cardUiInfo.spriteCardFont, styleData.textureSmallFront);
                    Tools.loadImg(cardUiInfo.spriteTagIcon, tagData.icon);
                    cardUiInfo.labelPower.text = `${cardDataInfo.power}`;
                }
            }
            adaptPlayerCardByPosIndex(posIndex, cardDataInfo) {
                let cardUiInfo = this.playerCardArr[posIndex];
                if (!cardDataInfo) {
                    cardUiInfo.nodeRoot.visible = false;
                    return;
                }
                console.log("vAmuseCardFightScene.adaptPlayerCardByPosIndex.cardDataInfo=====", cardDataInfo);
                if (!cardDataInfo.roleId) {
                    let tagData = mgrCfg.get_from_part_tag_db(cardDataInfo.tagId);
                    let styleData = mgrCfg.get_from_amuse_card_style_db(!!cardDataInfo.styleId ? cardDataInfo.styleId : cardDataInfo.cardStyleId);
                    let npcData = mgrCfg.get_from_amuse_double_npc_card_role_pic_db(cardDataInfo.npcPicId);
                    Tools.loadImg(cardUiInfo.spriteCard, npcData.smallTextuer);
                    Tools.loadImg(cardUiInfo.spriteCardBack, styleData.textureSmallBack);
                    Tools.loadImg(cardUiInfo.spriteCardFont, styleData.textureSmallFront);
                    Tools.loadImg(cardUiInfo.spriteTagIcon, tagData.icon);
                    cardUiInfo.labelPower.text = `${cardDataInfo.fightPower}`;
                }
                else {
                    let tagData = mgrCfg.get_from_part_tag_db(cardDataInfo.tagId);
                    let styleData = mgrCfg.get_from_amuse_card_style_db(cardDataInfo.styleId);
                    cardUiInfo.spriteCard.texture = new Laya.Texture(cardDataInfo.textureCard);
                    Tools.loadImg(cardUiInfo.spriteCardBack, styleData.textureSmallBack);
                    Tools.loadImg(cardUiInfo.spriteCardFont, styleData.textureSmallFront);
                    Tools.loadImg(cardUiInfo.spriteTagIcon, tagData.icon);
                    cardUiInfo.labelPower.text = `${cardDataInfo.fightPower}`;
                }
            }
        }

        var AMUSE_CARD_PHOTO_MAKE_STATE;
        (function (AMUSE_CARD_PHOTO_MAKE_STATE) {
            AMUSE_CARD_PHOTO_MAKE_STATE[AMUSE_CARD_PHOTO_MAKE_STATE["init"] = 1] = "init";
            AMUSE_CARD_PHOTO_MAKE_STATE[AMUSE_CARD_PHOTO_MAKE_STATE["ani"] = 2] = "ani";
            AMUSE_CARD_PHOTO_MAKE_STATE[AMUSE_CARD_PHOTO_MAKE_STATE["shot"] = 3] = "shot";
            AMUSE_CARD_PHOTO_MAKE_STATE[AMUSE_CARD_PHOTO_MAKE_STATE["style"] = 4] = "style";
            AMUSE_CARD_PHOTO_MAKE_STATE[AMUSE_CARD_PHOTO_MAKE_STATE["showCard"] = 5] = "showCard";
            AMUSE_CARD_PHOTO_MAKE_STATE[AMUSE_CARD_PHOTO_MAKE_STATE["finish"] = 6] = "finish";
        })(AMUSE_CARD_PHOTO_MAKE_STATE || (AMUSE_CARD_PHOTO_MAKE_STATE = {}));
        class vAmuseCardPhotoMakeScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseCardPhotoMakeScene";
                this.exportNodeNames = [];
                this.CUSTOM_CAMERA_LAYER_VALUE = 20;
                this.TAB_ANI = 1;
                this.TAB_MASK = 2;
                this.AD_VIDEO_TRY_PVP_PHOTO_RECIPE = "video_vAmuseCardPhotoMakeScene_recipe";
                this.AD_VIDEO_TRY_PVP_PHOTO_MASK = "video_vAmuseCardPhotoMakeScene_mask";
                this.dbName2DatasDict = {};
                this.tryingPartIds = [];
                this.maskPower = 0;
                this.recipePower = 0;
                this.context.roleId = this.context.roleId || mgrRole.showingRoleId;
                this.context.partIds = this.context.partIds;
            }
            getPreLoadModelIds() {
                return ["huanzhuang_bg"];
            }
            onOpened() {
                super.onOpened();
                this.boxContainerMC.alpha = 0;
                mgrLoader.loadFont("card_power", this.labelShowingPower);
                this.initData();
                this.buildUi();
                this.widget();
                Tools.registerTouchHander(this.boxFrontEvent, () => { });
                this.stManager = new FSMObject;
                this.stManager.registerState(AMUSE_CARD_PHOTO_MAKE_STATE.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                this.stManager.registerState(AMUSE_CARD_PHOTO_MAKE_STATE.ani, this.inAni.bind(this), this.exeAni.bind(this), this.outAni.bind(this));
                this.stManager.registerState(AMUSE_CARD_PHOTO_MAKE_STATE.shot, this.inShot.bind(this), this.exeShot.bind(this), this.outShot.bind(this));
                this.stManager.registerState(AMUSE_CARD_PHOTO_MAKE_STATE.style, this.inStyle.bind(this), this.exeStyle.bind(this), this.outStyle.bind(this));
                this.stManager.registerState(AMUSE_CARD_PHOTO_MAKE_STATE.showCard, this.inShowCard.bind(this), this.exeShowCard.bind(this), this.outShowCard.bind(this));
                this.stManager.registerState(AMUSE_CARD_PHOTO_MAKE_STATE.finish, this.inFinish.bind(this), this.exeFinish.bind(this), this.outFinish.bind(this));
                this.stManager.startUpdate(this);
                this.stManager.setNextState(AMUSE_CARD_PHOTO_MAKE_STATE.init);
                this.playOutUi();
                this.playInUi();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                if (!mgrVideoRecorder.isRecording() && !this.context.bDisableStartVideoRecorder) {
                    mgrVideoRecorder.startRecord();
                }
            }
            onClosed() {
                this.imageShowingPhoto.source = null;
                if (this.cameraBack) {
                    this.cameraBack.renderTarget = null;
                }
                if (!!this.cardCameraRenderTexture) {
                    Laya.RenderTexture.recoverToPool(this.cardCameraRenderTexture);
                }
                super.onClosed();
            }
            initData() {
                this.selectedTab = this.TAB_ANI;
            }
            buildUi() {
                this.spriteBg.zOrder = -4;
                let mapBg = mgrLoader.Pool.getModel("huanzhuang_bg");
                mapBg.active = false;
                this.add3DEffectAtBack(mapBg);
                this.mapBg = mapBg;
                let topBar = new vTopBar({ bDisableGold: true, bDisableEnergy: true });
                this.spriteTopBarHolder.addChild(topBar);
                this.avatar = new RoleAvatar({ roleId: this.context.roleId, bDisableDynamic: true });
                this.avatar.setDisableRelateFaceBodyAni(true);
                this.add3DEffectAtBack(this.avatar, 0);
                let cameraFollow = this.cameraBack.getComponent(CameraFollow);
                cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                cameraFollow.fov = 30;
                cameraFollow.position = new Laya.Vector3(0, 1.45, 5.6);
                cameraFollow.endRotation = new Laya.Vector3(-9);
                cameraFollow.lerpValue = 1;
                cameraFollow.onLateUpdate();
                this.cardCameraRenderTexture = Laya.RenderTexture.createFromPool(this.imageShowingPhoto.width * 2, this.imageShowingPhoto.height * 2, Laya.RenderTextureFormat.R8G8B8A8);
                this.imageShowingPhoto.source = new Laya.Texture(this.cardCameraRenderTexture);
                this.reuseList = new ReuseList(5, 0, 7);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vAmuseCardPhotoMakeListItem);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(0);
                this.reuseList.setSpaceY(6);
                this.spriteName.visible = false;
            }
            widget() {
                mgrLayout.widgetBottomMC(this.boxBottom);
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetRightBottomMC(this.boxRightBottom);
                mgrLayout.widgetBottomMC(this.buttonSaveCard.__node);
                mgrLayout.widgetTopMC(this.spriteTitle);
                mgrLayout.widgetTopMC(this.spriteName);
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            playOutUi() {
            }
            playInUi() {
                if (!!this.buttonBack.__node.visible) {
                    mgrEffect.playComebackAction([this.buttonBack.__node], -150, 0, 1, 0.7);
                }
                mgrEffect.playComebackAction([this.buttonConfirm.__node], 200, 0, 1, 0.7);
                mgrEffect.playComebackAction([this.boxList], 0, 600, 0.5, 1.4, () => {
                    this.add3DEffectAtFront("117_ui_loop_bgparticle_01", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 });
                });
                this.boxList.mouseEnabled = false;
                Timer.callLater(1.2, () => {
                    this.boxFrontEvent.visible = false;
                    this.startGuide();
                    this.boxList.mouseEnabled = true;
                }, this);
            }
            startGuide() {
                if (!mgrGuide.isFinished(1710)) {
                    mgrGuide.startGuide(1710);
                }
            }
            inInit() {
                this.spriteShine.visible = false;
                this.boxShowingPhotoContainer.visible = false;
                this.spriteCameraBorder.scale(0, 0, true);
                this.buttonSaveCard.__node.scale(0, 0, true);
                this.boxBottom.scale(0, 0, true);
                this.buttonBack.__node.visible = !!mgrGuide.isAllForceGuideFinished();
                this.boxContainerMC.alpha = 1;
                this.stManager.setNextState(AMUSE_CARD_PHOTO_MAKE_STATE.ani);
            }
            exeInit() { }
            outInit() { }
            inAni() {
                mgrSound.play(405);
                this.labelTitle.text = "请选择一个动作";
                this.selectedTab = this.TAB_ANI;
                this.fillList();
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                Tools.loadImg(this.spriteShowingTagIcon, tagData.icon);
                let power = mgrCard.calculateRoleTagPartIdsPower(roleData.roleTagId, this.avatar.getPartIds());
                this.labelShowingPower.text = `${power}`;
                cc.tween(this.boxBottom).toScale(0.15, 1).start();
            }
            exeAni() { }
            outAni() { }
            inShot() {
                this.add3DEffectAtFront(MODEL_ID.effect.e_photo_glow, this.boxContainerMC);
                this.boxBottom.scale(0, 0, true);
                this.spriteCameraBorder.scale(1, 1, true);
                cc.tween(this.spriteCameraBorder).toScale(0.15, 1.2).toScale(0.3, 0.9).toScale(0.15, 1.1).toScale(0.15, 1)
                    .call(() => {
                    let cameraFollow = this.cameraBack.getComponent(CameraFollow);
                    let oldPos = cameraFollow.position.clone();
                    let oldFov = cameraFollow.fov;
                    let oldRot = cameraFollow.endRotation.clone();
                    cameraFollow.position = new Laya.Vector3(0, 1.2, 2);
                    cameraFollow.fov = 30;
                    cameraFollow.lerpValue = 1;
                    cameraFollow.endRotation = new Laya.Vector3(-2.5);
                    cameraFollow.onLateUpdate();
                    this.mapBg.active = true;
                    Tools.takeAPhoto(512, 512, this.cameraBack, (tex2d) => {
                        this.shareTex2d = tex2d;
                        this.mapBg.active = false;
                        mgrSound.play(120);
                        this.spriteCameraBorder.scale(0, 0, true);
                        this.stManager.setNextState(AMUSE_CARD_PHOTO_MAKE_STATE.style);
                    }, Laya.RenderTextureFormat.R8G8B8A8);
                }).start();
            }
            exeShot() { }
            outShot() { }
            inStyle() {
                this.labelTitle.text = "请选择卡面样式";
                mgrSound.play(407);
                this.cameraBack.removeLayer(this.CUSTOM_CAMERA_LAYER_VALUE);
                this.cameraBack.clearFlag = Laya.CameraClearFlags.SolidColor;
                this.cameraBack.clearColor = new Laya.Vector4(0, 0, 0, 0);
                this.cameraBack.layer = this.CUSTOM_CAMERA_LAYER_VALUE;
                this.cameraBack.cullingMask = 0;
                this.cameraBack.cullingMask = this.cameraBack.cullingMask | Math.pow(2, this.CUSTOM_CAMERA_LAYER_VALUE);
                this.cameraBack.renderTarget = this.cardCameraRenderTexture;
                let animationInfo = this.recipeData.centerAnimationInfo || [];
                let avatarX = animationInfo[4] || 0;
                let avatarY = animationInfo[5] || 0;
                let avatarZ = animationInfo[6] || 0;
                let cameraFollow = this.cameraBack.getComponent(CameraFollow);
                cameraFollow.position = new Laya.Vector3(avatarX, avatarY, avatarZ);
                this.boxShowingPhotoContainer.visible = true;
                this.selectedTab = this.TAB_MASK;
                this.fillList();
                cc.tween(this.boxBottom).toScale(0.15, 1).start();
                cc.tween(this.buttonConfirm.__node).toScale(0.15, 1)
                    .call(() => {
                    this.boxFrontEvent.visible = false;
                })
                    .start();
            }
            exeStyle() { }
            outStyle() { }
            inShowCard() {
                this.spriteName.visible = true;
                this.spriteTitle.visible = false;
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                this.labelName.text = roleData.name;
                this.boxBottom.scale(0, 0, true);
                this.spriteShine.visible = true;
                this.buttonSaveCard.__node.scale(1, 1, true);
                mgrSound.play(402);
                cc.tween(this.spriteShine).repeatForever(cc.tween().byRotation(6, 360)).start();
                cc.tween(this.boxShowingPhotoContainer)
                    .toScale(0.15, 1.2).toScale(0.15, 1)
                    .call(() => {
                    this.boxFrontEvent.visible = false;
                })
                    .start();
                this.add3DEffectAtMiddle("117_ui_loop_ray_01", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 3);
            }
            exeShowCard() { }
            outShowCard() { }
            inFinish() {
            }
            exeFinish() { }
            outFinish() { }
            fillList() {
                let adName = null;
                let dbName = null;
                if (this.selectedTab == this.TAB_ANI) {
                    dbName = "amuse_card_photo_recipe_db";
                    adName = this.AD_VIDEO_TRY_PVP_PHOTO_RECIPE;
                }
                else {
                    dbName = "amuse_card_style_db";
                    adName = this.AD_VIDEO_TRY_PVP_PHOTO_MASK;
                }
                let arr = this.getPartDataByDbName(dbName, this.selectedTab, adName);
                this.reuseList.setDatas(arr);
                this.reuseList.scrollTo(0);
                if (!this.context.player) {
                    this.doClickItem(arr[0].id);
                }
            }
            getPartDataByDbName(dbName, tab, adName) {
                let bCanAd = mgrAd.preCheckAdNoCd(adName, true);
                if (!!bCanAd) {
                    let adEventData = mgrCfg.get_from_ad_event_db(adName);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
                if (!!this.dbName2DatasDict[dbName]) {
                    return this.dbName2DatasDict[dbName];
                }
                let gotedPartIdArr = [];
                let lockedPartIdArr = [];
                let coinPartIdArr = [];
                let specialPartArr = [];
                let guideItemData = null;
                let db = mgrCfg.getDb(dbName);
                for (let k in db) {
                    let v = db[k];
                    if (!!v.bBoss || !!v.bDisableShowInRoom || (mgrPlayer.getItemAmount(v.id) <= 0 && !!v.bDisableShowWhenUnown)) {
                        continue;
                    }
                    let data = {
                        dbName: dbName,
                        adName: adName,
                        tab: tab,
                        __customOrderValue: 0,
                        id: v.id,
                        icon: v.icon,
                        fOnClick: this.onClickItem.bind(this),
                        fIsSelected: this.isSelected.bind(this),
                        fIsTry: this.isTry.bind(this),
                        fStaticsShow: () => {
                        },
                        bAd: bCanAd
                    };
                    if (v.id == 502 || v.id == 412) {
                        guideItemData = data;
                        continue;
                    }
                    if (mgrPlayer.getItemAmount(v.id) <= 0) {
                        let shopData = mgrCfg.get_from_shop_template_db(v.id);
                        if (!!shopData) {
                            coinPartIdArr.push(data);
                        }
                        else {
                            lockedPartIdArr.push(data);
                        }
                    }
                    else {
                        gotedPartIdArr.push(data);
                    }
                }
                let datas = [];
                let tmpData = Tools.randomRemoveArrayDatas(gotedPartIdArr, 1)[0];
                datas.push(tmpData);
                let dataDict = {
                    [0]: gotedPartIdArr,
                    [1]: lockedPartIdArr,
                    [2]: coinPartIdArr
                };
                let count = Math.max(Math.max(gotedPartIdArr.length, lockedPartIdArr.length), coinPartIdArr.length);
                for (let i = 0; i < count; i++) {
                    let indexDataArr = Tools.randomGotArrayDatas([0, 1, 2], 3);
                    for (let tmp in indexDataArr) {
                        let tmpDatas = dataDict[indexDataArr[tmp]];
                        if (tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                        if (indexDataArr[tmp] == 1 && Tools.random(100) > 50 && tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                    }
                }
                specialPartArr = Tools.randomGotArrayDatas(specialPartArr, specialPartArr.length);
                for (let i = 0; i < specialPartArr.length; i++) {
                    let index = Tools.random(2, 9);
                    datas.splice(index, 0, specialPartArr[i]);
                }
                if (!!guideItemData) {
                    datas.splice(1, 0, guideItemData);
                }
                let sortedPartId2OrderDict = mgrPart.getGameRoomListSortedId2OrderDictByType(DailyGameType.cardMade, dbName);
                if (!!sortedPartId2OrderDict && Tools.getObjSize(sortedPartId2OrderDict) > 0) {
                    for (let i = 0; i < datas.length; i++) {
                        let sortedOrder = parseInt(sortedPartId2OrderDict[datas[i].id]);
                        datas[i].__customOrderValue = !!isNaN(sortedOrder) ? i : sortedOrder;
                    }
                }
                else {
                    let sortedPartId2OrderDict = {};
                    for (let i = 0; i < datas.length; i++) {
                        datas[i].__customOrderValue = i;
                        sortedPartId2OrderDict[datas[i].id] = i;
                    }
                    mgrPart.setGameRoomListSortedId2OrderDictByType(DailyGameType.cardMade, dbName, sortedPartId2OrderDict);
                }
                datas = Tools.sortArrayByField(datas, ["__customOrderValue"]);
                this.dbName2DatasDict[dbName] = datas;
                return datas;
            }
            refreshPower() {
                let roleData = mgrCfg.get_from_role_db(this.context.roleId);
                let power = mgrCard.calculateRoleTagPartIdsPower(roleData.roleTagId, this.avatar.getPartIds());
                this.labelShowingPower.text = `${power + this.maskPower + this.recipePower}`;
                let star = mgrCard.calculateCardLevelStarByPower(power + this.maskPower + this.recipePower);
                let numChildren = this.spriteStarContainer.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let sprite = this.spriteStarContainer.getChildAt(i);
                    sprite.visible = star - 1 >= i ? true : false;
                }
            }
            isSelected(id) {
                if (this.selectedTab == this.TAB_ANI) {
                    return (!!this.recipeData && this.recipeData.id == id) ? true : false;
                }
                else {
                    return (!!this.styleData && this.styleData.id == id) ? true : false;
                }
            }
            isTry(id) {
                return this.tryingPartIds.indexOf(id) >= 0;
            }
            onClickItem(id, bAd = false) {
                this.tryPopClickItemTrial(id);
                this.doClickItem(id, bAd);
            }
            tryPopClickItemTrial(partId) {
                if (mgrGuide.isGuiding()) {
                    return;
                }
                if (mgrPlayer.getItemAmount(partId) <= 0 || mgrSdk.getCopNumberValueByKey("b_click_part_item_pop_trial") != 1) {
                    return;
                }
                let gap = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_gap") || 0;
                if (Tools.time() < (mgrPart.roomPopClickItemPartLastTime + gap)) {
                    return;
                }
                let popCount = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_count_per_stage") || 0;
                if (this.roomPopClickItemPartCount > popCount) {
                    return;
                }
                let adName = this.selectedTab == this.TAB_ANI ? this.AD_VIDEO_TRY_PVP_PHOTO_RECIPE : this.AD_VIDEO_TRY_PVP_PHOTO_MASK;
                if (!mgrAd.preCheckAdNoCd(adName, true)) {
                    return;
                }
                this.roomPopClickItemPartCount++;
                mgrPart.roomPopClickItemPartLastTime = Tools.time();
                let lockedPartIdArr = [];
                let dbName = this.selectedTab == this.TAB_ANI ? "amuse_card_photo_recipe_db" : "amuse_card_style_db";
                if (!dbName) {
                    return;
                }
                let dbData = mgrCfg.getDb(dbName);
                for (let k in dbData) {
                    let data = dbData[k];
                    let shopData = mgrCfg.get_from_shop_template_db(data.id);
                    if (!data.bBoss && mgrPlayer.getItemAmount(data.id) <= 0 && !shopData) {
                        lockedPartIdArr.push(data.id);
                    }
                }
                if (lockedPartIdArr.length == 0) {
                    return;
                }
                let partIdAd = Tools.randomGotOneArrayData(lockedPartIdArr);
                console.warn("---------phooto trial id=", partIdAd);
                mgrDirector.openDialog("vAdFreeTrialPartDialog", {
                    adEventId: adName,
                    partId: partIdAd,
                    adTriggerParams: {
                        id: partIdAd,
                    }
                });
            }
            doClickItem(id, bAd = false) {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCardPhotoMakeScene.clickGuide${id}` });
                if (this.selectedTab == this.TAB_ANI) {
                    if (bAd) {
                        mgrAd.triggerAdEvent(this.AD_VIDEO_TRY_PVP_PHOTO_RECIPE, { id }, true);
                    }
                    else {
                        if (mgrPlayer.getItemAmount(id) <= 0 && !this.isTry(id)) {
                            let shopData = mgrCfg.get_from_shop_template_db(id);
                            if (!!shopData) {
                                let doBuyFunc = () => {
                                    if (mgrShop.requestBuy(id, "制卡")) {
                                        Timer.callLoop(0.016, (timer) => {
                                            if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                                return;
                                            timer.stop();
                                            this.selectRecipe(id);
                                            this.reuseList.refresh();
                                        }, this);
                                    }
                                };
                                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                                    let partData = mgrCfg.get_from_item_template_db(id);
                                    let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                                    mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                        doBuyFunc();
                                    });
                                }
                                else {
                                    doBuyFunc();
                                }
                                return;
                            }
                        }
                        this.selectRecipe(id);
                    }
                }
                else {
                    if (bAd) {
                        mgrAd.triggerAdEvent(this.AD_VIDEO_TRY_PVP_PHOTO_MASK, { id }, true);
                    }
                    else {
                        if (mgrPlayer.getItemAmount(id) <= 0 && !this.isTry(id)) {
                            let shopData = mgrCfg.get_from_shop_template_db(id);
                            if (!!shopData) {
                                let doBuyFunc = () => {
                                    if (mgrShop.requestBuy(id, "制卡")) {
                                        Timer.callLoop(0.016, (timer) => {
                                            if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                                return;
                                            timer.stop();
                                            this.selectMask(id);
                                            this.reuseList.refresh();
                                        }, this);
                                    }
                                };
                                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                                    let partData = mgrCfg.get_from_item_template_db(id);
                                    let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                                    mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                        doBuyFunc();
                                    });
                                }
                                else {
                                    doBuyFunc();
                                }
                                return;
                            }
                        }
                        this.selectMask(id);
                    }
                }
                this.reuseList.refresh();
            }
            selectRecipe(recipeId) {
                if (!recipeId) {
                    return;
                }
                let soundIdArr = [413, 414, 415];
                mgrSound.play(soundIdArr[Tools.random(0, soundIdArr.length - 1)]);
                let recipeData = mgrCfg.get_from_amuse_card_photo_recipe_db(recipeId || 1);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!recipeData.statisPointId && mgrSdk.statisCommonEvent(recipeData.statisPointId);
                }
                this.recipePower = recipeData.addPower;
                this.refreshPower();
                this.recipeData = recipeData;
                this.refreshTeamAvatarCenter();
                this.add3DEffectAtFront("117_ui_once_flash_01", { x: mgrDirector.width / 2, y: mgrDirector.height * 0.35 }, 1);
            }
            selectMask(styleId) {
                if (!styleId) {
                    return;
                }
                let soundIdArr = [411, 412];
                mgrSound.play(soundIdArr[Tools.random(0, soundIdArr.length - 1)]);
                let styleData = mgrCfg.get_from_amuse_card_style_db(styleId || 1);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!styleData.statisPointId && mgrSdk.statisCommonEvent(styleData.statisPointId);
                }
                this.maskPower = styleData.addPower;
                this.refreshPower();
                this.styleData = styleData;
                Tools.loadImg(this.spriteShowingPhotoMask, this.styleData.textureFront);
                Tools.loadImg(this.spriteShowingPhotoBg, this.styleData.textureBack);
                this.add3DEffectAtFront("117_ui_once_flash_01", { x: mgrDirector.width / 2, y: mgrDirector.height * 0.35 }, 1);
            }
            refreshTeamAvatarCenter() {
                let animationInfo = this.recipeData.centerAnimationInfo || [];
                let bodyAniId = animationInfo[0];
                let faceAniId = animationInfo[1];
                let bodyNormalizedTime = animationInfo[2];
                let faceNormalizedTime = animationInfo[3];
                let setAniPosFunc = () => {
                    let bodyPlayed = false;
                    let facePlayed = false;
                    let tryRebackPos = () => {
                        this.avatar.transform.position = new Laya.Vector3;
                    };
                    this.avatar.playAnimation(bodyAniId, 0, () => {
                        let animatorState = this.avatar.baseBodyAnimator.getControllerLayer(0).getAnimatorState(bodyAniId);
                        if (!!animatorState) {
                            this.avatar.baseBodyAnimator.play(bodyAniId, 0, bodyNormalizedTime);
                        }
                        else {
                            console.warn("-------[ERROR]-cardphotomakescene-refreshTeamAvatarCenter---动画不存在");
                        }
                        bodyPlayed = true;
                        tryRebackPos();
                    });
                    this.avatar.playRoleFaceAnimation(faceAniId, 0, () => {
                        this.avatar.playToFaceNormalizedTime(faceAniId, faceNormalizedTime);
                        facePlayed = true;
                        tryRebackPos();
                    });
                };
                this.avatar.outForHide();
                this.avatar.fillByPartIds(this.context.partIds || mgrPart.getLastClothes(this.context.roleId));
                this.avatar.registerAllLoadEndCallback(() => {
                    Tools.setSprite3dLayer(this.avatar, this.CUSTOM_CAMERA_LAYER_VALUE);
                    this.avatar.timeScale = 0.000001;
                    this.avatar.hideShadow();
                    setAniPosFunc();
                });
                Tools.setSprite3dLayer(this.avatar, this.CUSTOM_CAMERA_LAYER_VALUE);
            }
            onClickTab(tabIndex) {
                this.selectedTab = tabIndex;
                this.fillList();
            }
            doSaveCard() {
                this.buttonSaveCard.__node.visible = false;
                Tools.takeAPhoto(Const.CARD_PHOTO_SIZE.width, Const.CARD_PHOTO_SIZE.height, this.cameraBack, (tex2d) => {
                    if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                        return;
                    }
                    let cardId = this.context.cardId;
                    let partIds = this.avatar.getPartIds(true);
                    let bContained = false;
                    let allCards = mgrCard.getAllPlayerCardInfo();
                    if (allCards && allCards.length > 0) {
                        for (let k in allCards) {
                            let dataCard = allCards[k];
                            if (dataCard && Tools.isEqualArr(dataCard.partIds, partIds) && dataCard.cardId != cardId) {
                                bContained = true;
                                break;
                            }
                        }
                    }
                    if (!bContained) {
                        let textureKey = mgrCard.getRoleCardTextureKeyNameByCardId(cardId);
                        mgrRole.savePhoto(textureKey, tex2d);
                        let styleId = (this.styleData && this.styleData.id) ? this.styleData.id : 1;
                        let power = mgrCard.calculateRolePartIdsPower(this.context.roleId, partIds);
                        power = power + this.maskPower + this.recipePower;
                        let hp = mgrCard.calculateRolePartIdsHp(this.context.roleId, partIds);
                        mgrCard.setPlayerCardInfo(cardId, this.context.roleId, styleId, textureKey, power, hp, partIds);
                        mgrTip.showMsgTip("卡片存入卡册成功");
                    }
                    else {
                        mgrTip.showMsgTip("相同装扮不存入卡册");
                    }
                    mgrVideoRecorder.stopRecord();
                    if (!!mgrGuide.isAllForceGuideFinished()) {
                        Timer.callLater(0.2, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                                return;
                            }
                            mgrTip.tryShowPhotoShare("vAmuseCardPhotoMakeScene", this.shareTex2d, null, () => {
                                let doExeFunc = () => {
                                    mgrDirector.warpSceneWidthEffect(this.context.backSceneName || "vHubScene", { nextDialogName: this.context.nextDialogName, bRemakeCardResult: this.context.bRemakeCardResult });
                                };
                                if (mgrSwitchOpen.checkOpenDialog("vAdPopMachineDialog")) {
                                    mgrDirector.openDialog("vAdPopMachineDialog", {
                                        fOnClose: () => {
                                            doExeFunc();
                                        }
                                    });
                                }
                                else {
                                    doExeFunc();
                                }
                            });
                        });
                    }
                    else {
                        this.gotoGuideCardFight();
                    }
                }, Laya.RenderTextureFormat.R8G8B8A8, Laya.TextureFormat.R8G8B8A8);
            }
            gotoGuideCardFight() {
                let enemyCardPosInfo = [];
                let playerCardPosInfo = [];
                let stageData = mgrCfg.get_from_amaze_card_stage_db(100);
                let npcIdArr = stageData.npcIdArr || [];
                if (npcIdArr && npcIdArr.length > 0) {
                    for (let i = 0; i < npcIdArr.length; i++) {
                        let npcId = npcIdArr[i] || 0;
                        let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                        enemyCardPosInfo[i] = { roleId: npcId, tagId: npcData.roleTagId, styleId: npcData.cardStyle, texturePath: npcData.imgCardTexture, power: npcData.fightPower, hp: npcData.hp };
                    }
                }
                let cardDataArr = mgrCard.getAllPlayerCardInfo();
                if (!!cardDataArr && cardDataArr.length > 0) {
                    let cardData = cardDataArr[0];
                    let texture = null;
                    let tex2dSaved = mgrRole.getPhotoTexture2D(cardData.cardTextureKeyName);
                    if (!!tex2dSaved) {
                        texture = new Laya.Texture(tex2dSaved);
                    }
                    else {
                    }
                    let roleData = mgrCfg.get_from_role_db(cardData.roleId);
                    playerCardPosInfo[0] = {
                        roleId: cardData.roleId,
                        tagId: roleData.roleTagId,
                        styleId: cardData.styleId,
                        textureCard: texture,
                        power: cardData.power,
                        hp: cardData.hp
                    };
                }
                let preloadPlayerCardImgArr = [];
                let guideNpcIdArr = [502, 503, 504, 505];
                for (let i = 0; i < guideNpcIdArr.length; i++) {
                    let npcId = guideNpcIdArr[i] || 0;
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    preloadPlayerCardImgArr.push(npcData.imgCardTexture);
                }
                mgrLoader.batchLoadResources(null, null, preloadPlayerCardImgArr, () => {
                    for (let i = 0; i < guideNpcIdArr.length; i++) {
                        let npcId = guideNpcIdArr[i] || 0;
                        let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                        playerCardPosInfo.push({
                            roleId: npcId,
                            tagId: npcData.roleTagId,
                            styleId: npcData.cardStyle,
                            textureCard: mgrLoader.get2dRes(npcData.imgCardTexture),
                            power: npcData.fightPower,
                            hp: npcData.hp
                        });
                    }
                    let params = {
                        backSceneName: "vHubScene",
                        stageId: stageData.id,
                        enemyCardPosInfo: enemyCardPosInfo,
                        playerCardPosInfo: playerCardPosInfo,
                    };
                    mgrDirector.warpSceneWidthEffect("vAmuseCardFightScene", params);
                });
            }
            onMsgAdEventSuccessd(e) {
                let userData = e.userData || {};
                if (e.adEventId == this.AD_VIDEO_TRY_PVP_PHOTO_RECIPE) {
                    let id = userData.id;
                    this.tryingPartIds.push(id);
                    mgrPlayer.addItemAmount(id, 1, "看视频得卡动作");
                    this.selectRecipe(id);
                    this.reuseList.refresh();
                }
                else if (e.adEventId == this.AD_VIDEO_TRY_PVP_PHOTO_MASK) {
                    let id = userData.id;
                    this.tryingPartIds.push(id);
                    mgrPlayer.addItemAmount(id, 1, "看视频得卡片");
                    this.selectMask(id);
                    this.reuseList.refresh();
                }
                else if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment) {
                    mgrPlayer.addItemAmount(userData.cardId, 1, "解锁卡册位置");
                    this.context.cardId = userData.cardId;
                    this.doSaveCard();
                }
            }
            onTouchButtonConfirm() {
                if (!this.avatar) {
                    mgrTip.showMsgTip("请稍等");
                    return;
                }
                this.boxFrontEvent.visible = true;
                this.buttonConfirm.clearTween();
                this.buttonConfirm.__node.scale(0, 0, true);
                let typeFlag = 1;
                let doExcFunc = () => {
                    if (this.stManager.getCurState() == AMUSE_CARD_PHOTO_MAKE_STATE.ani) {
                        if (mgrDebug.bShowDevButton) {
                            let cameraFollow = this.cameraBack.getComponent(CameraFollow);
                            cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                            cameraFollow.fov = 30;
                            cameraFollow.position = new Laya.Vector3(0, 1.45, 3.5);
                            cameraFollow.endRotation = new Laya.Vector3(-9);
                            cameraFollow.lerpValue = 1;
                            cameraFollow.onLateUpdate();
                            let saveImageName = `make_card`;
                            Tools.cameraForSaveImg(this.cameraBack, saveImageName);
                            Timer.callLater(1, () => {
                                this.boxFrontEvent.visible = false;
                                this.buttonConfirm.clearTween();
                                this.buttonConfirm.__node.scale(1, 1, true);
                            }, this);
                            return;
                        }
                        this.boxBottom.scale(0, 0, true);
                        this.buttonBack.__node.scale(0, 0, true);
                        this.stManager.setNextState(AMUSE_CARD_PHOTO_MAKE_STATE.shot);
                        typeFlag = 1;
                    }
                    else if (this.stManager.getCurState() == AMUSE_CARD_PHOTO_MAKE_STATE.style) {
                        this.boxBottom.scale(0, 0, true);
                        this.buttonBack.__node.scale(0, 0, true);
                        this.stManager.setNextState(AMUSE_CARD_PHOTO_MAKE_STATE.showCard);
                        typeFlag = 2;
                    }
                };
                let tipStr = this.stManager.getCurState() == AMUSE_CARD_PHOTO_MAKE_STATE.style ? "耶，好棒好棒！" : "真漂亮，进入下一步吧";
                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                    mgrTip.alertPrompt1("提示", tipStr, "确定", () => {
                        doExcFunc();
                    });
                }
                else {
                    doExcFunc();
                }
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCardPhotoMakeScene.clickButtonConfirm${typeFlag}` });
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(this.context.backSceneName);
            }
            onTouchButtonSaveCard() {
                if (this.stManager.getCurState() != AMUSE_CARD_PHOTO_MAKE_STATE.showCard) {
                    return;
                }
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCardPhotoMakeScene.clickButtonSaveCard` });
                if (!this.context.cardId) {
                    let emptyCardId = mgrCard.getMinEmptyDataCardId();
                    if (!emptyCardId) {
                        let lockedCardId = mgrCard.getMinLockedCardId();
                        if (!!lockedCardId) {
                            let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment);
                            if (!!bCanAd) {
                                mgrTip.alertPrompt2("提示", "已没有更多的卡槽，是否解锁新的卡槽？", "不了", "好的", null, () => {
                                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment);
                                    adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardAlbumDialog_fragment, { cardId: lockedCardId }, true);
                                });
                            }
                            else {
                                let coinAmount = Const.UNLOCK_ALBUM_CARD_COST;
                                let coinTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                                mgrTip.alertPrompt2("提示", `是否花费${coinAmount}${coinTemplate.name}【解锁卡槽】？`, "取消", "确定", null, () => {
                                    if (mgrShop.tryConsumeItem(Const.ITEM_ID_DIAMONDS, coinAmount, "解锁卡册位置")) {
                                        mgrPlayer.addItemAmount(lockedCardId, 1, "解锁卡册位置");
                                        this.context.cardId = lockedCardId;
                                        this.doSaveCard();
                                    }
                                });
                            }
                        }
                        else {
                            let arr = [];
                            mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                                arr.push(v.id);
                            });
                            this.context.cardId = Tools.randomGotOneArrayData(arr);
                            this.doSaveCard();
                        }
                    }
                    else {
                        this.context.cardId = emptyCardId;
                        this.doSaveCard();
                    }
                    return;
                }
                this.doSaveCard();
            }
        }

        class vAmuseCardStartNewYearStageScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseCardStartNewYearStageScene";
                this.stageNewYearArr = [];
            }
            onOpened() {
                super.onOpened();
                this.initData();
                mgrSound.play(8);
                this.buildUi();
                this.fillData();
                this.widget();
                this.uiActionIn(() => {
                    mgrDirector.openDialog(this.context.nextDialogName);
                });
                cc.tween(this.spriteRewardPreviewAction).repeatForever(cc.tween().by(1.6, { y: 8 }, cc.Ease.sineOut)
                    .by(1.6, { y: -8 }, cc.Ease.sineIn)
                    .by(1.6, { y: -8 }, cc.Ease.sineOut)
                    .by(1.6, { y: 8 }, cc.Ease.sineIn)).start();
                mgrTip.tryShowFullScreenMoreGameFixed("b_fsmgfs_card_fight");
            }
            onClosed() {
                super.onClosed();
            }
            initData() {
                let stageNewYearArr = mgrCfg.getDbArr("amaze_card_stage_db", (data) => {
                    if (data.type == CARD_FIGHT_TYPE.newYear) {
                        return true;
                    }
                });
                this.stageNewYearArr = Tools.sortArrayByField(stageNewYearArr, "id");
            }
            buildUi() {
                this.topBar = new vTopBar({ bDisableGold: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                this.reusePreviewList = new ReuseList(1, 0, 11);
                this.reusePreviewList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reusePreviewList);
                this.reusePreviewList.setItemClass(vCardNewYearPreviewItem);
                this.reusePreviewList.setVerticalMoveEnable(true);
            }
            uiActionIn(callback) {
                this.buttonBack.__node.scale(0, 0, true);
                this.buttonCardCollect.__node.scale(0, 0, true);
                this.buttonLotteryCard.__node.scale(0, 0, true);
                let uiFunc = () => {
                    let onTitleComedInCallback = () => {
                        Timer.callLater(0.1, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            let delay = 0;
                            Timer.callLater(delay, () => {
                                if (!this.nodeResource || this.nodeResource.destroyed) {
                                    return;
                                }
                                this.buttonCardCollect.__node.scale(1, 1, true);
                                this.buttonLotteryCard.__node.scale(1, 1, true);
                                cc.tween(this.buttonBack.__node).toScale(0.3, 1).start();
                            }, this);
                        }, this);
                    };
                    let onProgressBarComedInCallBack = () => {
                    };
                    onTitleComedInCallback();
                };
                let scaleGray = -100;
                Timer.callLater(0.1, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    Timer.callLoop(0.016, (timer) => {
                        scaleGray += 3;
                        scaleGray = scaleGray > 0 ? 0 : scaleGray;
                        if (scaleGray >= 0) {
                            timer.stop();
                            timer = null;
                            uiFunc();
                        }
                    }, this);
                }, this);
            }
            fillData() {
                let stageDataArr = mgrCfg.getDbArr("amaze_card_stage_db", (data) => {
                    return data.type == CARD_FIGHT_TYPE.newYear;
                });
                stageDataArr = Tools.sortArrayByField(stageDataArr, "id");
                for (const key in stageDataArr) {
                    let data = stageDataArr[key];
                    data["fOnClick"] = this.doClickStartNormal.bind(this, data.id);
                }
                this.reusePreviewList.setDatas(stageDataArr);
                this.fillNextReward();
            }
            fillNextReward() {
                let stageDataArr = this.stageNewYearArr;
                let newYearStageProgress = mgrCard.getNewYearStageProgress();
                let stageData = null;
                let rewardIcon = null;
                for (let i = 0; i < stageDataArr.length; i++) {
                    if (stageDataArr[i].id > newYearStageProgress) {
                        stageData = stageDataArr[i];
                        break;
                    }
                }
                if (stageData) {
                    let rewards = mgrCard.getNewYearStageFirstPassReward(stageData.id);
                    let partId = null;
                    for (let i = 0; i < rewards.length; i++) {
                        let data = rewards[i];
                        if (data.type == "part") {
                            partId = data.itemId;
                            break;
                        }
                    }
                    if (partId) {
                        let partData = mgrCfg.get_from_part_db(partId);
                        rewardIcon = partData.icon;
                        let bOwned = mgrPlayer.getItemAmount(partId) > 0;
                        if (bOwned) {
                            this.boxReward.visible = false;
                        }
                        else {
                            this.boxReward.visible = true;
                        }
                    }
                }
                if (rewardIcon) {
                    Tools.loadImg(this.spriteRewardPreviewAction, rewardIcon);
                }
                else {
                    this.boxReward.visible = false;
                }
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetLeftTopMC(this.buttonCardCollect.__node);
                mgrLayout.widgetLeftTopMC(this.buttonLotteryCard.__node);
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGame);
            }
            playMovie(storyId, callback) {
                let finishCallback = () => {
                    callback && callback();
                };
                mgrDirector.openDialog("vStoryDialog", {
                    storyId: storyId,
                    bShowSkip: true,
                    skipCallback: finishCallback,
                    finishCallback: finishCallback,
                });
            }
            gotoCardTeamSetView(id, bVip = false) {
                let stageId = id;
                let stageData = mgrCfg.get_from_amaze_card_stage_db(stageId);
                if (!stageData) {
                    return;
                }
                let stageNewYearProgress = mgrCard.getNewYearStageProgress();
                if (!stageNewYearProgress) {
                    let firstStage = this.stageNewYearArr[0];
                    if (stageId != firstStage.id) {
                        mgrTip.showMsgTip("完成上一关才能继续挑战~");
                        return;
                    }
                }
                else {
                    if (stageId > stageNewYearProgress + 1) {
                        mgrTip.showMsgTip("完成上一关才能继续挑战~");
                        return;
                    }
                }
                this.playMovie(stageData.storyId, () => {
                    mgrTip.showLoadingTip("CARD_TEAM_SET_TO_FIGHT", new Laya.Vector2, 0, true);
                    mgrDirector.open2DScene(`vAmuseCardTeamSetScene`, {
                        stageId: stageId,
                        bVip: bVip,
                        backSceneName: `vAmuseCardStartNewYearStageScene`
                    });
                });
            }
            doClickStartNormal(id) {
                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                    mgrTip.alertPrompt2("提示", "准备好挑战了吗？", "再想想", "确定", () => { }, () => {
                        this.gotoCardTeamSetView(id);
                    });
                }
                else {
                    this.gotoCardTeamSetView(id);
                }
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(this.context.backSceneName || "vHubScene");
            }
            onTouchButtonCardCollect() {
                mgrDirector.openDialog("vAmuseCardAlbumDialog");
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonLotteryCard() {
                mgrDirector.openDialog("vAmuseCardPreviewExtractDialog");
            }
            onTouchButtonMoreGameBox() {
                mgrSdk.opentChannelMoreGameBox();
            }
        }

        class vAmuseCardStartScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseCardStartScene";
                this.bSpecialDaily = false;
                this.bSpecialSimulate = false;
                this.preInitData();
            }
            getPreLoadModelIds() {
                return [
                    "117_ui_once_bat_01"
                ];
            }
            getPreLoadAnimationIds() {
                return [];
            }
            getPreLoadImagePaths() {
                let arr = [];
                let npcIdArr = this.stageData.npcIdArr || [];
                for (let k in npcIdArr) {
                    let npcId = npcIdArr[k];
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    if (!npcData.imgBody) {
                        continue;
                    }
                    arr.push(npcData.imgBody);
                    break;
                }
                return arr;
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag2"];
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelTotalPower);
                mgrLoader.loadFont("card_power", this.labelFightPower);
                mgrSound.play(8);
                this.buildUi();
                this.fillData();
                this.widget();
                this.uiActionIn(() => {
                    if (!this.context.bRemakeCardResult) {
                        this.playMovie();
                    }
                    else if (this.context.nextDialogName) {
                        mgrDirector.openDialog(this.context.nextDialogName);
                    }
                });
                cc.tween(this.spriteNodeReward).repeatForever(cc.tween().by(1.6, { y: 8 }, cc.Ease.sineOut)
                    .by(1.6, { y: -8 }, cc.Ease.sineIn)
                    .by(1.6, { y: -8 }, cc.Ease.sineOut)
                    .by(1.6, { y: 8 }, cc.Ease.sineIn)).start();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.buttonMoreGameBox.__node.visible = mgrAd.showMoreGameBox(2);
                mgrTip.tryShowFullScreenMoreGameFixed("b_fsmgfs_card_fight");
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.spriteSpecialItem.visible = false;
                this.buttonTriggerNativeBanner.__node.visible = false;
                Timer.callLoop(0.016, () => {
                    this.buttonTriggerNativeBanner.__node.visible = (mgrSdk.getCopNumberValueByKey("b_vAmuseCardStartScene_trigger_native_banner") == 1 && mgrBannerInt.isNativeBannerShowing()) ? true : false;
                }, this);
                this.topBar = new vTopBar({ bDisableGold: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                this.boxRoleContainer.visible = false;
                this.reusePreviewList = new ReuseList(1, 0, 11);
                this.reusePreviewList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reusePreviewList);
                this.reusePreviewList.setItemClass(vCardPreviewItem);
                this.reusePreviewList.setVerticalMoveEnable(true);
            }
            uiActionIn(callback) {
                this.buttonBack.__node.scale(0, 0, true);
                this.buttonRank.__node.scale(0, 0, true);
                this.buttonCardCollect.__node.scale(0, 0, true);
                this.buttonLotteryCard.__node.scale(0, 0, true);
                this.buttonMoreGameBox.__node.scale(0, 0, true);
                this.buttonStartNormal.__node.scale(0, 0, true);
                this.spriteAdButtonContainer.scale(0, 0, true);
                this.spriteAdButtonContainerVip.scale(0, 0, true);
                this.spritePreviewInfo.scale(0, 0, true);
                this.spritePreviewInfoSimulate.scale(0, 0, true);
                let uiFunc = () => {
                    if (!!this.spritePreviewInfo.visible) {
                        this.spritePreviewInfo.scale(1, 1, true);
                        this.spritePreviewInfoSimulate.scale(1, 1, true);
                        this.spriteFightPowerContainer.scale(0, 0, true);
                        this.spriteLvContainer.scale(0, 0, true);
                        this.spriteItem1.scale(0, 0, true);
                        this.spriteItem2.scale(0, 0, true);
                    }
                    else {
                        this.spritePreviewInfo.scale(1, 1, true);
                        this.spritePreviewInfoSimulate.scale(1, 1, true);
                        this.spriteFightPowerContainerSimulate.scale(0, 0, true);
                        this.spritePowerContainerSimulate.scale(0, 0, true);
                        this.spriteItem1Simulate.scale(0, 0, true);
                        this.spriteItem2Simulate.scale(0, 0, true);
                        this.spriteItem3Simulate.scale(0, 0, true);
                    }
                    let onTitleComedInCallback = () => {
                        Timer.callLater(0.1, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            let delay = 0;
                            if (!!this.buttonStartNormal.__node.visible) {
                                cc.tween(this.buttonStartNormal.__node).toScale(0.2, 1, cc.Ease.backOut).start();
                            }
                            else if (!!this.buttonStartNormal.__node.visible) {
                                this.spriteAdButtonContainer.scale(1, 1, true);
                                this.buttonGetAd.__node.scale(0, 0, true);
                                cc.tween(this.buttonGetAd.__node).delay(0).toScale(0.2, 1, cc.Ease.backOut).start();
                            }
                            else {
                                this.spriteAdButtonContainerVip.scale(1, 1, true);
                                this.buttonGiveUpVip.__node.scale(0, 0, true);
                                this.buttonStartAdVip.__node.scale(0, 0, true);
                                cc.tween(this.buttonGiveUpVip.__node).delay(0).toScale(0.2, 1, cc.Ease.backOut).start();
                                cc.tween(this.buttonStartAdVip.__node).delay(0.2 * 1).toScale(0.2, 1, cc.Ease.backOut).start();
                            }
                            if (this.buttonNewYear.__node.visible) {
                                cc.tween(this.buttonNewYear.__node).repeatForever(cc.tween()
                                    .by(0.1, { rotation: -10 })
                                    .by(0.2, { rotation: 20 })
                                    .by(0.1, { rotation: -10 })
                                    .delay(2)).start();
                            }
                            Timer.callLater(delay, () => {
                                if (!this.nodeResource || this.nodeResource.destroyed) {
                                    return;
                                }
                                this.buttonRank.__node.scale(1, 1, true);
                                this.buttonCardCollect.__node.scale(1, 1, true);
                                this.buttonLotteryCard.__node.scale(1, 1, true);
                                this.buttonMoreGameBox.__node.scale(1, 1, true);
                                mgrEffect.playComebackAction([this.buttonRank.__node, this.buttonCardCollect.__node, this.buttonLotteryCard.__node, this.buttonMoreGameBox], -200, 0, 0, 0.5);
                                cc.tween(this.buttonBack.__node).toScale(0.3, 1).start();
                                this.buttonStartNormal.__node.scale(1, 1, true);
                                this.spriteAdButtonContainer.scale(1, 1, true);
                                this.spriteAdButtonContainerVip.scale(1, 1, true);
                            }, this);
                        }, this);
                    };
                    if (!!this.spriteTitle.visible) {
                        mgrEffect.playComebackAction([this.spriteTitle], 0, -300, 0, 0.7, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            onTitleComedInCallback();
                        });
                    }
                    else {
                        onTitleComedInCallback();
                    }
                };
                let scaleGray = -100;
                mgrEffect.filterBCSH(this.spriteRoleBody, scaleGray, scaleGray, scaleGray, scaleGray);
                this.spriteRoleBody.alpha = 0.5;
                cc.tween(this.spriteRoleBody).toAlpha(0.3, 1).start();
                if (!!this.spritePreviewInfo.visible) {
                    let roleEffModel = mgrLoader.Pool.getModel("117_ui_once_bat_01");
                    this.add3DEffectAtFront(roleEffModel, this.spriteRoleBodyEffHolder);
                    cc.tween(this.spriteRoleBodyEffHolder)
                        .byPos(0.5, 0, -350)
                        .delay(1.5)
                        .call(() => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        mgrLoader.Pool.recoverModel(roleEffModel);
                    })
                        .start();
                }
                Timer.callLater(0.1, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    Timer.callLoop(0.016, (timer) => {
                        scaleGray += 3;
                        scaleGray = scaleGray > 0 ? 0 : scaleGray;
                        mgrEffect.filterBCSH(this.spriteRoleBody, scaleGray, scaleGray, scaleGray, scaleGray);
                        if (scaleGray >= 0) {
                            timer.stop();
                            timer = null;
                            uiFunc();
                        }
                    }, this);
                }, this);
            }
            preInitData() {
                this.normalStageInitData();
            }
            normalStageInitData() {
                this.stageData = mgrCfg.get_from_amaze_card_stage_db(mgrCard.getStageProgress() + 1) || mgrCfg.get_from_amaze_card_stage_db(mgrCard.getStageProgress());
                let power = 0;
                let npcIdArr = this.stageData.npcIdArr || [];
                for (let k in npcIdArr) {
                    let npcId = npcIdArr[k];
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    if (!npcData) {
                        continue;
                    }
                    power += npcData.fightPower;
                }
                this.npcTotalPower = power;
            }
            vipStageInitData() {
                let arr = mgrCfg.getDbArr("amaze_card_stage_db", (data) => {
                    return data.type == CARD_FIGHT_TYPE.simulatePlayer ? true : false;
                });
                this.stageData = Tools.randomGotOneArrayData(arr);
                let power = 0;
                let npcIdArr = this.stageData.npcIdArr || [];
                for (let k in npcIdArr) {
                    let npcId = npcIdArr[k];
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    if (!npcData) {
                        continue;
                    }
                    power += npcData.fightPower;
                }
                this.npcTotalPower = power;
            }
            randomVipStageData() {
                let arr = mgrCfg.getDbArr("amaze_card_stage_db", (data) => {
                    return data.type == CARD_FIGHT_TYPE.simulatePlayer ? true : false;
                });
                let stageData = Tools.randomGotOneArrayData(arr);
                let bossData = null;
                let npcIdArr = this.stageData.npcIdArr || [];
                for (let k in npcIdArr) {
                    let npcId = npcIdArr[k];
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    if (!npcData) {
                        continue;
                    }
                    bossData = npcData;
                }
                return [stageData, bossData];
            }
            fillData() {
                let npcId1 = this.stageData.npcIdArr[0];
                let npcData1 = mgrCfg.get_from_amuse_card_npc_db(npcId1);
                Tools.loadImg(this.spriteRoleBody, npcData1.imgBody);
                Tools.loadImg(this.spriteRoleShadow, npcData1.imgShadowBody);
                Tools.loadImg(this.spriteRoleName, npcData1.imgName);
                let tagTemplate = mgrCfg.get_from_part_tag_db(npcData1.roleTagId);
                Tools.loadImg(this.spriteRoleTagIcon, tagTemplate.icon);
                let worldDay = mgrWorldDaily.getWorldDay();
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                if (!mgrWorldDaily.isCardFightedDay(worldDay) && !!template.cardFightStageId && !!mgrCfg.get_from_amaze_card_stage_db(template.cardFightStageId)) {
                    this.warnCardStageData = mgrCfg.get_from_amaze_card_stage_db(template.cardFightStageId);
                    let bossNpcData = null;
                    let npcIdArr = this.warnCardStageData.npcIdArr || [];
                    for (let k in npcIdArr) {
                        let npcId = npcIdArr[k];
                        let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                        if (!npcData) {
                            continue;
                        }
                        bossNpcData = npcData;
                        break;
                    }
                    this.labelFightPower.text = `${bossNpcData.fightPower}`;
                    Tools.loadImg(this.spriteNpc, bossNpcData.imgCardTexture);
                    let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                    Tools.loadImg(this.spriteSpecialItemIcon1, itemTemplate.icon);
                    let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.card);
                    let partData = mgrCfg.get_from_item_template_db(rewardPartId);
                    if (!!partData && partData.type) {
                        let partTypeData = mgrCfg.get_from_item_type_db(partData.type);
                        Tools.loadImg(this.spriteSpecialItemIcon2, partTypeData.iconTcutShot);
                    }
                    this.bSpecialDaily = true;
                    this.spriteSpecialItem.visible = true;
                }
                else {
                    if (Tools.random(100) < 50 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardStartScene_vip)) {
                        this.stageSimulateData = this.randomVipStageData()[0];
                        let bossData = this.randomVipStageData()[1];
                        if (!!bossData) {
                            this.labelFightPower.text = `${bossData.fightPower}`;
                            Tools.loadImg(this.spriteNpc, bossData.imgCardTexture);
                            let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                            Tools.loadImg(this.spriteSpecialItemIcon1, itemTemplate.icon);
                            let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.card);
                            let partData = mgrCfg.get_from_item_template_db(rewardPartId);
                            if (!!partData && partData.type) {
                                let partTypeData = mgrCfg.get_from_item_type_db(partData.type);
                                Tools.loadImg(this.spriteSpecialItemIcon2, partTypeData.iconTcutShot);
                            }
                            this.bSpecialSimulate = true;
                            this.spriteSpecialItem.visible = true;
                        }
                    }
                }
                if (this.bSpecialDaily || this.bSpecialSimulate) {
                    this.boxList.height = 440;
                    this.boxList.y = 460;
                    this.reusePreviewList.size(this.boxList.width, this.boxList.height);
                }
                this.spritePreviewInfoSimulate.visible = false;
                this.spritePreviewInfo.visible = false;
                this.spriteAdButtonContainerVip.visible = false;
                this.buttonStartNormal.__node.visible = false;
                this.spriteAdButtonContainer.visible = false;
                this.spriteTitle.visible = false;
                if (this.stageData.type == CARD_FIGHT_TYPE.simulatePlayer) {
                    if (mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.card)) {
                        this.buttonGiveUpVip.__node.visible = false;
                        this.spriteAdFlag2.visible = false;
                    }
                    this.labelPlayerNameSimulate.text = `玩家:${npcData1.name}`;
                    this.labelTotalPowerSimulate.text = `${this.npcTotalPower}`;
                    let vipPartId = mgrWorldDaily.getUnownedVipPart(DailyGameType.card);
                    let partDataVip = mgrCfg.get_from_item_template_db(vipPartId);
                    if (!!partDataVip && partDataVip.type) {
                        Tools.loadImg(this.imageItemIcon1Simulate, partDataVip.icon, true, () => {
                            let deltaScale = 70 / this.imageItemIcon1Simulate.height;
                            this.imageItemIcon1Simulate.scale(deltaScale, deltaScale);
                        });
                        let typeData = mgrCfg.get_from_item_type_db(partDataVip.type);
                        this.labelItemAmount1Simulate.text = `+${typeData.name}`;
                    }
                    else {
                        this.spriteItem2.visible = false;
                    }
                    let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                    Tools.loadImg(this.spriteItemIcon2Simulate, itemTemplate.icon);
                    let rmbAmount = Tools.random(5, 10);
                    this.labelItemAmount2Simulate.text = `+${rmbAmount}`;
                    let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.card);
                    let partData = mgrCfg.get_from_item_template_db(rewardPartId);
                    if (!!partData && partData.type) {
                        let partTypeData = mgrCfg.get_from_item_type_db(partData.type);
                        Tools.loadImg(this.spriteItemIcon3Simulate, partTypeData.iconTcutShot);
                        this.labelItemAmount3Simulate.text = `+${this.stageData.successRewardColorPoint}`;
                    }
                    else {
                        this.spriteItem3Simulate.visible = false;
                    }
                }
                else {
                    this.labelTotalPower.text = `${this.npcTotalPower}`;
                    this.labelStageLv.text = `${this.stageData.level}`;
                    let itemTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                    Tools.loadImg(this.spriteItemIcon1, itemTemplate.icon);
                    let rmbAmount = Tools.random(5, 10);
                    this.labelItemAmount1.text = `+${rmbAmount}`;
                    let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.card);
                    let partData = mgrCfg.get_from_item_template_db(rewardPartId);
                    if (!!partData && partData.type) {
                        let partTypeData = mgrCfg.get_from_item_type_db(partData.type);
                        Tools.loadImg(this.spriteItemIcon2, partTypeData.iconTcutShot);
                        this.labelItemAmount2.text = `+${this.stageData.successRewardColorPoint}`;
                    }
                    else {
                        this.spriteItem2.visible = false;
                    }
                    let npcIdArr = this.stageData.npcIdArr || [];
                    for (let k in npcIdArr) {
                        let npcId = npcIdArr[k];
                        let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                        this.labelRoleTitle.text = `${npcData.name}`;
                        if (!npcData.imgName || npcData.imgName == "") {
                            continue;
                        }
                        Tools.loadImg(this.spriteRoleName, npcData.imgName);
                        break;
                    }
                }
                let datas = mgrCfg.getDbArr("amaze_card_stage_db", (data) => {
                    return data.type == CARD_FIGHT_TYPE.base;
                });
                let curStageProgress = mgrCard.getStageProgress() >= 90 ? 90 : mgrCard.getStageProgress();
                if (curStageProgress % 9 == 0 && mgrCard.isSuccessedStage(curStageProgress) && curStageProgress < 90) {
                    curStageProgress += 1;
                }
                let chapter = (Math.floor(curStageProgress / 9) + 1) > 10 ? 10 : (Math.floor(curStageProgress / 9) + 1);
                this.labelCurChapter.text = "第" + chapter.toString() + "章";
                if (mgrCard.getStageProgress() >= 90 && mgrCard.isSuccessedStage(90)) {
                    this.boxReward.visible = false;
                }
                let showDatas = datas.splice((chapter - 1) * 9, 9);
                let rewardId = mgrWorldDaily.getNextRewardPartId(DailyGameType.card);
                let rewardData = mgrCfg.get_from_amuse_card_style_db(rewardId);
                if (rewardData) {
                    Tools.loadImg(this.spriteRewardPreview2, rewardData.textureSmallFront);
                    Tools.loadImg(this.spriteRewardPreview, rewardData.textureSmallBack);
                }
                else {
                    let itemData = mgrCfg.get_from_item_template_db(rewardId);
                    if (itemData) {
                        Tools.loadImg(this.spriteRewardPreviewAction, itemData.icon);
                    }
                    else {
                        this.boxReward.visible = false;
                    }
                }
                for (const key in showDatas) {
                    let data = showDatas[key];
                    data["fOnClick"] = this.doClickStartNormal.bind(this, data.id);
                }
                this.reusePreviewList.setDatas(showDatas);
                this.reusePreviewList.setScroll(mgrCard.getStageProgress() % 9);
                this.reusePreviewList.scrollTo(mgrCard.getStageProgress() % 9);
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetBottomMC(this.spriteAdButtonContainer);
                mgrLayout.widgetLeftTopMC(this.buttonRank.__node);
                mgrLayout.widgetLeftTopMC(this.buttonCardCollect.__node);
                mgrLayout.widgetLeftTopMC(this.buttonLotteryCard.__node);
                mgrLayout.widgetLeftTopMC(this.buttonMoreGameBox.__node);
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGame);
            }
            playMovie(callback) {
                let finishCallback = () => {
                    callback && callback();
                };
                if (this.stageData.storyId != 0) {
                    mgrDirector.openDialog("vStoryDialog", {
                        storyId: this.stageData.storyId,
                        bShowSkip: true,
                        skipCallback: finishCallback,
                        finishCallback: finishCallback,
                    });
                }
                else {
                    finishCallback();
                }
            }
            activeAvatarOut(callback) {
            }
            gotoCardTeamSetView(bVip, id) {
                let stageData = mgrCfg.get_from_amaze_card_stage_db(id) || mgrCfg.get_from_amaze_card_stage_db(mgrCard.getStageProgress());
                if (stageData.id % 9 != 1 && stageData.id > mgrCard.getStageProgress() + 1) {
                    mgrTip.showMsgTip("完成上一关才能继续挑战~");
                    return;
                }
                this.playMovie(() => {
                    mgrTip.showLoadingTip("CARD_TEAM_SET_TO_FIGHT", new Laya.Vector2, 0, true);
                    mgrDirector.open2DScene(`vAmuseCardTeamSetScene`, {
                        stageId: stageData.id,
                        bVip: bVip,
                        backSceneName: `vAmuseCardStartScene`
                    });
                });
            }
            doClickStartNormal(id) {
                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                    mgrTip.alertPrompt2("提示", "准备好挑战了吗？", "再想想", "确定", () => { }, () => {
                        this.gotoCardTeamSetView(false, id);
                    });
                }
                else {
                    this.gotoCardTeamSetView(false, id);
                }
            }
            onTouchButtonAdAreaScreen() {
            }
            onTouchButtonGetAd() {
                this.gotoCardTeamSetView();
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(this.context.backSceneName || "vHubScene");
            }
            onTouchButtonRank() {
                mgrDirector.warpSceneWidthEffect(`vRankScene`, {
                    backSceneName: `vAmuseCardStartScene`,
                });
            }
            onTouchButtonCardCollect() {
                mgrDirector.openDialog("vAmuseCardAlbumDialog");
            }
            onTouchButtonAdAreaScreenVip() {
            }
            onTouchButtonGiveUpVip() {
                this.normalStageInitData();
                this.fillData();
                this.playMovie();
            }
            onTouchButtonStartAdVip() {
                if (!this.spriteAdFlag2.visible) {
                    this.gotoCardTeamSetView();
                }
                else {
                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardStartScene_vip, null, true);
                }
            }
            onTouchButtonStartNormal() {
            }
            onTouchButtonTriggerNativeBanner() {
                this.sendMsg("MSG_TRIGGER_NATIVE_BANNER");
            }
            onTouchButtonSpecialItem() {
                if (this.bSpecialDaily) {
                    mgrDirector.openDialog("vAmuseCardWorldDailyStartDialog", {
                        stageId: this.warnCardStageData.id,
                        bFromCard: true,
                    }, true);
                    return;
                }
                if (this.bSpecialSimulate) {
                    this.playMovie(() => {
                        mgrTip.showLoadingTip("CARD_TEAM_SET_TO_FIGHT", new Laya.Vector2, 0, true);
                        mgrDirector.open2DScene(`vAmuseCardTeamSetScene`, {
                            stageId: this.stageSimulateData.id,
                            bVip: true,
                            backSceneName: `vAmuseCardStartScene`,
                            bSpecial: true
                        });
                    });
                    return;
                }
            }
            onTouchButtonLotteryCard() {
                mgrDirector.openDialog("vAmuseCardPreviewExtractDialog");
            }
            onTouchButtonMoreGameBox() {
                mgrSdk.opentChannelMoreGameBox();
            }
            onTouchButtonNewYear() {
                mgrDirector.warpSceneWidthEffect(`vAmuseCardStartNewYearStageScene`, {
                    backSceneName: `vAmuseCardStartScene`
                });
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseCardStartScene_vip) {
                    this.gotoCardTeamSetView(true);
                }
            }
        }

        class vAmuseCardTeamSetScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseCardTeamSetScene";
                this.enemyCardPosInfo = [];
                this.playerCardPosInfo = [];
                this.preInitData();
            }
            getPreLoadModelIds() {
                return [];
            }
            getPreLoadAnimationIds() {
                return [];
            }
            getPreLoadImagePaths() {
                if (!this.stageData) {
                    return [];
                }
                let arr = [];
                let npcIdArr = this.stageData.npcIdArr || [];
                for (let k in npcIdArr) {
                    let npcId = npcIdArr[k];
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    if (!npcData.imgBody || npcData.imgBody == "") {
                        continue;
                    }
                    arr.push(npcData.imgBody);
                    break;
                }
                return arr;
            }
            getChannelAdFlagIconNames() {
                return ["spriteAdFlag", "spriteAdFlag1", "spriteAdFlag2", "spriteAdFlag3", "spriteAdFlag4", "spriteAdFlag5"];
            }
            onOpened() {
                super.onOpened();
                mgrVideoRecorder.stopRecord();
                mgrSound.play(9);
                this.buildUi();
                this.fillData();
                this.widget();
                this.uiActionUi();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.startGuide();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.labelCostEnergyCount.text = `${(this.context.bSpecial ? -3 : -1)}`;
                this.spriteBg.zOrder = -5;
                let arr = [];
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let nodeRoot = this["buttonPlayerCard" + i].__node;
                    let spriteCardBack = nodeRoot.getChildByName("spriteCardBack");
                    let spriteCard = nodeRoot.getChildByName("spriteCard");
                    let spriteCardFont = nodeRoot.getChildByName("spriteCardFont");
                    let spriteTagIcon = nodeRoot.getChildByName("spriteTagIcon");
                    let labelPower = nodeRoot.getChildByName("labelPower");
                    let spriteAdd = nodeRoot.getChildByName("spriteAdd");
                    let spriteLock = nodeRoot.getChildByName("spriteLock");
                    let spriteCard2 = nodeRoot.getChildByName("spriteCard2");
                    let data = {
                        nodeRoot: nodeRoot,
                        spriteCardBack: spriteCardBack,
                        spriteCard: spriteCard,
                        spriteCardFont: spriteCardFont,
                        spriteTagIcon: spriteTagIcon,
                        labelPower: labelPower,
                        spriteAdd: spriteAdd,
                        spriteLock: spriteLock,
                        spriteCard2: spriteCard2,
                    };
                    arr.push(data);
                }
                this.playerCardArr = arr;
                let arrEnemy = [];
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let nodeRoot = this["spriteEnemyCard" + i];
                    let spriteCardBack = nodeRoot.getChildByName("spriteCardBack");
                    let spriteCard = nodeRoot.getChildByName("spriteCard");
                    let spriteCardFont = nodeRoot.getChildByName("spriteCardFont");
                    let spriteTagIcon = nodeRoot.getChildByName("spriteTagIcon");
                    let labelPower = nodeRoot.getChildByName("labelPower");
                    let data = {
                        nodeRoot: nodeRoot,
                        spriteCardBack: spriteCardBack,
                        spriteCard: spriteCard,
                        spriteCardFont: spriteCardFont,
                        spriteTagIcon: spriteTagIcon,
                        labelPower: labelPower,
                    };
                    arrEnemy.push(data);
                }
                this.enemyCardArr = arrEnemy;
            }
            preInitData() {
                if (this.context.bPvp) {
                }
                else {
                    this.stageData = mgrCfg.get_from_amaze_card_stage_db(this.context.stageId) || mgrCfg.get_from_amaze_card_stage_db(mgrCard.getStageProgress() + 1) || mgrCfg.get_from_amaze_card_stage_db(mgrCard.getStageProgress());
                    this.context.stageId = this.stageData.id;
                }
            }
            fillData() {
                if (this.context.bPvp) {
                    this.enemyCardPosInfo = this.context.enemyCardPosInfo || [];
                }
                else {
                    let npcIdArr = this.stageData.npcIdArr || [];
                    if (npcIdArr && npcIdArr.length > 0) {
                        for (let i = 0; i < npcIdArr.length; i++) {
                            let npcId = npcIdArr[i] || 0;
                            let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                            this.enemyCardPosInfo[i] = { roleId: npcId, tagId: npcData.roleTagId, styleId: npcData.cardStyle, texturePath: npcData.imgCardTexture, power: npcData.fightPower, hp: npcData.hp };
                        }
                    }
                }
                this.refreshEnemyCardUi();
                this.refreshPlayerCardUi();
                if (this.context.bPvp || this.stageData.bAutoAllGo) {
                    this.onTouchButtonAllGo();
                }
                let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardTeamSetScene_unlock);
                for (let i = 1; i <= 5; i++) {
                    this["spriteAdFlag" + i].visible = !!bCanAd;
                }
            }
            refreshPlayerCardUi() {
                let totalPower = 0;
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let cardDataInfo = mgrCard.getTempFightCardPosInfoByPosIndex(i);
                    this.adaptPlayerCardByPosIndex(i, cardDataInfo);
                    if (!!cardDataInfo) {
                        if (cardDataInfo["bDoubleNpc"]) {
                            totalPower += cardDataInfo["fightPower"];
                        }
                        else {
                            totalPower += cardDataInfo.power;
                        }
                    }
                }
                this.labelPlayerTotalPower.text = `${totalPower}`;
            }
            refreshEnemyCardUi() {
                let setedCardCount = 0;
                let totalPower = 0;
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let cardDataInfo = this.enemyCardPosInfo[i];
                    this.adaptEnemyCardByPosIndex(i, cardDataInfo);
                    if (!!cardDataInfo) {
                        totalPower += cardDataInfo.power;
                        setedCardCount++;
                    }
                }
                this.labelEnemyTotalPower.text = `${totalPower}`;
                for (let posIndex = 0; posIndex < setedCardCount; posIndex++) {
                    let cardUiInfo = this.enemyCardArr[posIndex];
                    let holderName = `spriteEnemyCount${setedCardCount}Holder${posIndex}`;
                    let holder = this.boxContainerMC.getChildByName(holderName);
                    cardUiInfo.nodeRoot.pos(holder.x, holder.y, true);
                    cardUiInfo.nodeRoot.scale(holder.scaleX, holder.scaleY);
                    cardUiInfo.nodeRoot["originPos"] = new Laya.Vector2(cardUiInfo.nodeRoot.x, cardUiInfo.nodeRoot.y);
                }
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetLeftMC(this.spritePlayerFightPowerContainer);
                mgrLayout.widgetRightMC(this.spriteEnemyFightPowerContainer);
            }
            uiActionUi() {
                let callback = () => {
                    this.spritePlayerFightPowerContainer["_originPos"] = new Laya.Vector2(this.spritePlayerFightPowerContainer.x, this.spritePlayerFightPowerContainer.y);
                    this.spriteEnemyFightPowerContainer["_originPos"] = new Laya.Vector2(this.spriteEnemyFightPowerContainer.x, this.spriteEnemyFightPowerContainer.y);
                    this.spriteCenterBtn.scale(0, 0, true);
                    this.spriteVsContainer.scale(0, 0, true);
                    this.spritePlayerFightPowerContainer.pos(this.spritePlayerFightPowerContainer["_originPos"].x - 250, this.spritePlayerFightPowerContainer["_originPos"].y + 30);
                    this.spriteEnemyFightPowerContainer.pos(this.spriteEnemyFightPowerContainer["_originPos"].x + 250, this.spriteEnemyFightPowerContainer["_originPos"].y - 30);
                    for (let posIndex = 0; posIndex < this.enemyCardArr.length; posIndex++) {
                        let cardUiInfo = this.enemyCardArr[posIndex];
                        mgrEffect.playComebackAction([cardUiInfo.nodeRoot], 0, -400, posIndex * 0.1, 0.6);
                    }
                    let delay = 0.6 + (this.enemyCardArr.length - 1) * 0.1;
                    cc.tween(this.spritePlayerFightPowerContainer)
                        .delay(delay)
                        .toPos(0.15, this.spritePlayerFightPowerContainer["_originPos"].x, this.spritePlayerFightPowerContainer["_originPos"].y)
                        .start();
                    cc.tween(this.spriteEnemyFightPowerContainer)
                        .delay(delay)
                        .toPos(0.15, this.spriteEnemyFightPowerContainer["_originPos"].x, this.spriteEnemyFightPowerContainer["_originPos"].y)
                        .call(() => {
                        mgrSound.play(632);
                        cc.tween(this.spriteCenterBtn).toScale(0.2, 1).start();
                        this.add3DEffectAtMiddle("117_ui_once_flash_01", this.spriteCenterBtn);
                    })
                        .start();
                };
                callback && callback();
                cc.tween(this.boxContainerMC)
                    .toAlpha(0.2, 1)
                    .call(() => {
                    mgrTip.hideLoadingTip("CARD_TEAM_SET_TO_FIGHT");
                })
                    .start();
            }
            startGuide() {
                mgrGuide.registerGuideNode(`vAmuseCardTeamSetScene.buttonAllGo`, this.buttonAllGo.__node);
                mgrGuide.registerGuideNode(`vAmuseCardTeamSetScene.buttonStart`, this.buttonStart.__node);
                if (!mgrGuide.isFinished(802)) {
                    mgrGuide.startGuide(802);
                }
            }
            adaptEnemyCardByPosIndex(posIndex, cardDataInfo) {
                let bUnlocked = true;
                let cardUiInfo = this.enemyCardArr[posIndex];
                cardUiInfo.spriteCardBack.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.spriteCard.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.spriteCardFont.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.spriteTagIcon.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.labelPower.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                if (!!cardDataInfo) {
                    let tagData = mgrCfg.get_from_part_tag_db(cardDataInfo.tagId);
                    let styleData = mgrCfg.get_from_amuse_card_style_db(cardDataInfo.styleId);
                    Tools.loadImg(cardUiInfo.spriteCard, cardDataInfo.texturePath);
                    Tools.loadImg(cardUiInfo.spriteCardBack, styleData.textureSmallBack);
                    Tools.loadImg(cardUiInfo.spriteCardFont, styleData.textureSmallFront);
                    Tools.loadImg(cardUiInfo.spriteTagIcon, tagData.icon);
                    cardUiInfo.labelPower.text = `${cardDataInfo.power}`;
                }
            }
            adaptPlayerCardByPosIndex(posIndex, cardDataInfo) {
                let bUnlocked = mgrCard.isUnlockedPlayerCardPos(posIndex);
                let cardUiInfo = this.playerCardArr[posIndex];
                cardUiInfo.spriteCardBack.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.spriteCard.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.spriteCardFont.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.spriteTagIcon.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.labelPower.alpha = (!!bUnlocked && !!cardDataInfo) ? 1 : 0;
                cardUiInfo.spriteAdd.alpha = (!!bUnlocked && !cardDataInfo) ? 1 : 0;
                cardUiInfo.spriteLock.alpha = !!bUnlocked ? 0 : 1;
                console.log("vAmuseCardTeamSetScene.adaptPlayerCardByPosIndex.cardDataInfo========", cardDataInfo);
                if (!!cardDataInfo) {
                    if (cardDataInfo.bDoubleNpc) {
                        let tagData = mgrCfg.get_from_part_tag_db(cardDataInfo.roleTagId);
                        let styleData = mgrCfg.get_from_amuse_card_style_db(!!cardDataInfo.styleId ? cardDataInfo.styleId : cardDataInfo.cardStyleId);
                        let npcData = mgrCfg.get_from_amuse_double_npc_card_role_pic_db(cardDataInfo.npcPicId);
                        cardUiInfo.spriteCard2.visible = true;
                        cardUiInfo.spriteCard.visible = false;
                        Tools.loadImg(cardUiInfo.spriteCard2, npcData.smallTextuer);
                        Tools.loadImg(cardUiInfo.spriteCardBack, styleData.textureSmallBack);
                        Tools.loadImg(cardUiInfo.spriteCardFont, styleData.textureSmallFront);
                        Tools.loadImg(cardUiInfo.spriteTagIcon, tagData.icon);
                        cardUiInfo.labelPower.text = `${cardDataInfo.fightPower}`;
                    }
                    else {
                        cardUiInfo.spriteCard.visible = true;
                        cardUiInfo.spriteCard2.visible = false;
                        let roleData = mgrCfg.get_from_role_db(cardDataInfo.roleId);
                        let tagData = mgrCfg.get_from_part_tag_db(roleData.roleTagId);
                        let styleData = mgrCfg.get_from_amuse_card_style_db(cardDataInfo.styleId);
                        cardUiInfo.spriteCard.texture = new Laya.Texture(cardDataInfo.textureCard);
                        Tools.loadImg(cardUiInfo.spriteCardBack, styleData.textureSmallBack);
                        Tools.loadImg(cardUiInfo.spriteCardFont, styleData.textureSmallFront);
                        Tools.loadImg(cardUiInfo.spriteTagIcon, tagData.icon);
                        cardUiInfo.labelPower.text = `${cardDataInfo.power}`;
                    }
                }
                if (!bUnlocked) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAmuseCardTeamSetScene_unlock);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
            }
            onClickPlayerCard(posIndex) {
                let bUnlocked = mgrCard.isUnlockedPlayerCardPos(posIndex);
                if (!bUnlocked) {
                    if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardTeamSetScene_unlock)) {
                        mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCardTeamSetScene_unlock, { posIndex: posIndex }, true);
                    }
                    else {
                        mgrTip.alertPrompt2("提示", `是否花费${posIndex * 100}【解锁位置】？`, "不了", "是的", () => {
                        }, () => {
                            if (mgrShop.tryConsumeItem(Const.ITEM_ID_DIAMONDS, posIndex * 100, "解锁卡牌位置")) {
                                this.doUnlockHandler(posIndex);
                            }
                        });
                    }
                    return;
                }
                let count = 0;
                mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                    if (mgrPlayer.getItemAmount(v.id) <= 0) {
                        return;
                    }
                    let cardInfo = mgrCard.getPlayerCardInfo(v.id);
                    if (!cardInfo || !!mgrCard.isCardInTempFightCardStandbying(v.id)) {
                        return;
                    }
                    count++;
                });
                let node = this["buttonPlayerCard" + posIndex].__node;
                let worldPos = node.localToGlobal(new Laya.Point(node.pivotX, node.pivotY));
                mgrDirector.openDialog("vAmuseCardFightSelectDialog", {
                    posIndex: posIndex,
                    worldPos: worldPos,
                    fOnChanged: () => {
                        mgrSound.play(634);
                        this.refreshPlayerCardUi();
                        cc.tween(node).toScale(0.1, 1.2).toScale(0.1, 1).start();
                    }
                });
            }
            doUnlockHandler(posIndex) {
                mgrCard.unlockPlayerCardPos(posIndex);
                this.adaptPlayerCardByPosIndex(posIndex, null);
                let cardUiInfo = this.playerCardArr[posIndex];
                this.add3DEffectAtFront("117_ui_once_flash_01", cardUiInfo.nodeRoot);
                mgrTip.showMsgTip("解锁成功");
            }
            onTouchButtonAdAreaScreen() {
            }
            onTouchButtonGetNormal() {
            }
            onTouchButtonGetAd() {
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(this.context.backSceneName || "vHubScene");
            }
            onTouchButtonRank() {
            }
            onTouchButtonAllGo() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCardTeamSetScene.clickButtonAllGo` });
                mgrSound.play(633);
                let arr = [];
                mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                    if (mgrPlayer.getItemAmount(v.id) <= 0) {
                        return;
                    }
                    let cardInfo = mgrCard.getPlayerCardInfo(v.id);
                    if (!cardInfo) {
                        return;
                    }
                    let texture = null;
                    let tex2dSaved = mgrRole.getPhotoTexture2D(cardInfo.cardTextureKeyName);
                    if (!!tex2dSaved) {
                        texture = new Laya.Texture(tex2dSaved);
                    }
                    else {
                        return;
                    }
                    arr.push({ cardId: v.id, roleId: cardInfo.roleId, styleId: cardInfo.styleId, textureCard: texture, power: cardInfo.power || 0, hp: cardInfo.hp });
                });
                mgrCard.cleanTempFightCardPosInfoData();
                let doubleNpcCards = mgrDoubleNpcCard.getOwnedDoubleNpcCard();
                for (let i = 0; i < doubleNpcCards.length; i++) {
                    const cardData = doubleNpcCards[i];
                    let npcData = mgrCfg.get_from_amuse_double_npc_card_role_pic_db(cardData.npcPicId);
                    arr.push({ cardId: cardData.cardId, roleId: "", bDoubleNpc: true, npcPicId: cardData.npcPicId, styleId: cardData.cardStyleId, roleTagId: cardData.roleTagId, textureCard: npcData.texture, power: cardData.fightPower || 0, fightPower: cardData.fightPower || 0, hp: cardData.hp });
                }
                arr = Tools.sortArrayByField(arr, ["-power", "-hp"]);
                let tryingCardInfo = mgrCard.getTryingCardInfo();
                for (let k in tryingCardInfo) {
                    let cardData = tryingCardInfo[k];
                    arr.unshift({ cardId: cardData.cardId, roleId: cardData.roleId, styleId: cardData.styleId, textureCard: cardData.textureCard, power: cardData.power || 0, hp: cardData.hp });
                }
                let posArr = mgrCard.getUnlockedPlayerCardPosArr();
                for (let i = 0; i < posArr.length; i++) {
                    let roleData = arr[i];
                    if (!roleData) {
                        break;
                    }
                    let posIndex = posArr[i];
                    mgrCard.setTempFightCardDataByPosIndex(posIndex, roleData);
                    let node = this["buttonPlayerCard" + posIndex].__node;
                    cc.tween(node).toScale(0.1, 1.2).toScale(0.1, 1).start();
                }
                this.refreshPlayerCardUi();
                let count = 0;
                mgrCfg.forDb_from_amuse_player_make_card_db((k, v) => {
                    if (mgrPlayer.getItemAmount(v.id) <= 0) {
                        return;
                    }
                    let cardInfo = mgrCard.getPlayerCardInfo(v.id);
                    if (!cardInfo || !!mgrCard.isCardInTempFightCardStandbying(v.id)) {
                        return;
                    }
                    count++;
                });
                let bPosAll = true;
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let cardDataInfo = mgrCard.getTempFightCardPosInfoByPosIndex(i);
                    if (!cardDataInfo) {
                        bPosAll = false;
                        break;
                    }
                }
                if (!count && !bPosAll) {
                    mgrTip.showMsgTip("没有更多的角色卡啦");
                    return;
                }
            }
            onTouchButtonStart() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vAmuseCardTeamSetScene.clickButtonStart` });
                let dict = mgrCard.getTempFightCardPosInfoDict();
                if (!Tools.getObjSize(dict)) {
                    mgrTip.showMsgTip("还没有设置好的呢");
                    return;
                }
                for (let i = 0; i < Const.PLAYER_CARD_POS_COUNT; i++) {
                    let cardData = mgrCard.getTempFightCardPosInfoByPosIndex(i);
                    if (!cardData) {
                        continue;
                    }
                    if (cardData["bDoubleNpc"]) {
                        let npcData = mgrCfg.get_from_amuse_double_npc_card_role_pic_db(cardData["npcPicId"]);
                        this.playerCardPosInfo.push({
                            roleId: cardData.roleId,
                            tagId: cardData["roleTagId"],
                            styleId: !!cardData["cardStyleId"] ? cardData["cardStyleId"] : cardData["styleId"],
                            textureCard: npcData.texture,
                            power: cardData["fightPower"],
                            hp: cardData.hp,
                            npcPicId: cardData["npcPicId"],
                            bDoubleNpc: cardData["bDoubleNpc"],
                        });
                    }
                    else {
                        let roleData = mgrCfg.get_from_role_db(cardData.roleId);
                        this.playerCardPosInfo.push({
                            roleId: cardData.roleId,
                            tagId: roleData.roleTagId,
                            styleId: cardData.styleId,
                            textureCard: cardData.textureCard,
                            power: cardData.power,
                            hp: cardData.hp
                        });
                    }
                }
                let rewardSurprisePartId = mgrWorldDaily.getUnownedVipPart(DailyGameType.card);
                let params = {
                    bVip: this.context.bVip,
                    backSceneName: this.context.backSceneName,
                    bPvp: this.context.bPvp,
                    stageId: this.context.stageId,
                    enemyCardPosInfo: this.enemyCardPosInfo,
                    rewardSurprisePartId: rewardSurprisePartId,
                    playerCardPosInfo: this.playerCardPosInfo,
                };
                let count = 1;
                if (this.context.bSpecial) {
                    count = 3;
                }
                let bRet = mgrShop.tryConsumeItem(Const.ITEM_ID_ENERGY, count, "卡牌战斗");
                if (bRet) {
                    mgrTip.addGotItemTip(Const.ITEM_ID_ENERGY, -count);
                    mgrTip.showLoadingTip("CARD_TEAM_SET_TO_FIGHT", new Laya.Vector2, 0, true);
                    mgrDirector.open2DScene("vAmuseCardFightScene", params);
                }
                mgrCard.curSelectCard = [];
            }
            onTouchButtonPlayerCard0() {
                this.onClickPlayerCard(0);
            }
            onTouchButtonPlayerCard1() {
                this.onClickPlayerCard(1);
            }
            onTouchButtonPlayerCard2() {
                this.onClickPlayerCard(2);
            }
            onTouchButtonPlayerCard3() {
                this.onClickPlayerCard(3);
            }
            onTouchButtonPlayerCard4() {
                this.onClickPlayerCard(4);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseCardTeamSetScene_unlock) {
                    let posIndex = e.userData.posIndex;
                    this.doUnlockHandler(posIndex);
                }
            }
        }

        var AMUSE_CLOTH_CROSSING_STATE;
        (function (AMUSE_CLOTH_CROSSING_STATE) {
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["init"] = 1] = "init";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["waitStart"] = 2] = "waitStart";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["turnReady"] = 3] = "turnReady";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["avatarComing"] = 4] = "avatarComing";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["avatarMoving"] = 5] = "avatarMoving";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["selectAni"] = 6] = "selectAni";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["playerShow"] = 7] = "playerShow";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["enemyShow"] = 8] = "enemyShow";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["changeCloth"] = 9] = "changeCloth";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["toSeat"] = 10] = "toSeat";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["nextTurnReady"] = 11] = "nextTurnReady";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["restartCurrTurn"] = 12] = "restartCurrTurn";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["checkResultSuccess"] = 13] = "checkResultSuccess";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["reward"] = 14] = "reward";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["palette"] = 15] = "palette";
            AMUSE_CLOTH_CROSSING_STATE[AMUSE_CLOTH_CROSSING_STATE["finish"] = 16] = "finish";
        })(AMUSE_CLOTH_CROSSING_STATE || (AMUSE_CLOTH_CROSSING_STATE = {}));
        class vAmuseClothCrossingScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseClothCrossingScene";
                this.exportNodeNames = [];
                this.avatar = null;
                this.avatarPosCameraDict = {
                    [0]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(0, 0, 0)
                        },
                        cameraData: {
                            fov: 60,
                            pos: new Laya.Vector3(0, 1.31, 2.45),
                            rot: new Laya.Vector3(-9, 0, 0),
                        }
                    },
                    [1]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(0, 0, 0)
                        },
                        cameraData: {
                            fov: 60,
                            pos: new Laya.Vector3(0, 2.81, 3.25),
                            rot: new Laya.Vector3(-27, 0, 0),
                        }
                    },
                    [4]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(0, 0, 0)
                        },
                        cameraData: {
                            fov: 60,
                            pos: new Laya.Vector3(6.6, 4.26, 0),
                            rot: new Laya.Vector3(-27, 90, 0),
                        }
                    },
                    [5]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(0, 0, 0)
                        },
                        cameraData: {
                            fov: 45,
                            pos: new Laya.Vector3(4.15, 1.26, 0),
                            rot: new Laya.Vector3(-7, 90, 0),
                        }
                    },
                };
                this.targetPercentage = 0;
                this.PREFAB_ROAD_LINE_NAME = "lu01";
                this.PREFAB_ROAD_CROSS_NAME = "lu06";
                this.PREFAB_ROAD_SEAT_NAME = "lu08";
                this.PREFAB_COIN_NAME = "mlb";
                this.PREFAB_ROAD_LINE_LEN = 4;
                this.PREFAB_ROAD_CROSS_LEN = 8;
                this.PREFAB_ROAD_SEAT_LEN = 4;
                this.pointNodeArr = [];
                this.MOVE_FPS = 1;
                this.ROAD_WH = 2;
                this.touchBgBeginAvatarPosX = 0;
                this.lastTouchResultMapAvatarPositionX = 0;
                this.crossArr2RoadModelDict = [];
                this.currCrossPathRoadIndex = 0;
                this.PART_TYPE_2_Y_OFFSET_DICT = {
                    [PartType.hair]: -0.5,
                    [PartType.headDec]: -2,
                    [PartType.shoe]: 0.5
                };
                this.PART_TYPE_2_SCALE_DICT = {
                    [PartType.hair]: 1,
                    [PartType.headDec]: 2,
                    [PartType.shoe]: 1,
                    [PartType.sock]: 1,
                };
                this.LANDING_POS_X_OFFSET = 0.4;
                this.playerGotScore = 0;
                this.enemyGotScore = 0;
                this.dressedPartIdDict = {};
                this.cameraFarPlaneTargetZ = 0;
                this.lastCameraFarPlaneTargetZ = 0;
                this.mlbNodeArr = [];
                this.gotMlbCount = 0;
                this.finishFlyEndPosZ = 0;
                this.ANGEL_CHANGE_PARTID_ARR = [
                    [12042, 12060], [21042, 21003], [13328, 13329], [16014, 16026]
                ];
                this.EVIL_CHANGE_PARTID_ARR = [
                    [12058, 12059], [21041, 21012], [13330, 13331], [16225, 16226]
                ];
                this.bSuccess = false;
                this.preInitData();
            }
            getPreLoadModelIds() {
                let preloadModelIdArr = [
                    "baozuo",
                    "tiankonghe",
                    "e_explode",
                    "e_daoju_wudi",
                    "tailuo",
                    "117_e_once_flash_01",
                    "117_e_loop_angel_01",
                    "117_e_loop_devil_01",
                    "117_e_loop_cry_01",
                    "117_e_loop_ringglow_01",
                ];
                preloadModelIdArr.push(this.PREFAB_COIN_NAME);
                preloadModelIdArr.push(this.PREFAB_ROAD_LINE_NAME);
                preloadModelIdArr.push(this.PREFAB_ROAD_CROSS_NAME);
                preloadModelIdArr.push(this.PREFAB_ROAD_SEAT_NAME);
                let modelDict = {};
                let count = this.stageData.roadPartIds.length;
                for (let i = 0; i < count; i++) {
                    let partDatas = this.stageData.roadPartIds[i];
                    for (let index = 0; index < partDatas.length; index++) {
                        let partData = mgrCfg.get_from_part_db(partDatas[index]);
                        modelDict[partData.modelId] = true;
                    }
                }
                for (let k in modelDict) {
                    preloadModelIdArr.push(k);
                }
                let enemyRoleData = mgrCfg.get_from_role_db(this.context.enemyRoleId);
                if (!!enemyRoleData) {
                    for (let k in enemyRoleData.centerPartIds) {
                        let pid = enemyRoleData.centerPartIds[k];
                        let partData = mgrCfg.get_from_part_db(pid);
                        if (partData.type == PartType.face || partData.type == PartType.hair || partData.type == PartType.cloth) {
                            preloadModelIdArr.push(partData.modelId);
                        }
                    }
                }
                return preloadModelIdArr;
            }
            getPreLoadAnimationIds() {
                return [
                    "paoku_idle-paoku_idle",
                    "paoku_move-paoku_run",
                    "paoku_move-paoku_fly",
                    "paoku_walk-paoku_walk",
                    "paoku_kuqi-paoku_kuqi",
                    "tailuo_paoku-tailuo_paoku",
                    "zjm_bixin-zjm_bixin01",
                    "zjm_bixin-zjm_bixin02",
                    "zjm_maimeng-zjm_maimeng"
                ];
            }
            getPreLoadImagePaths() {
                return [];
            }
            preInitData() {
                let stageId = this.context.stageId || 1;
                this.stageData = mgrCfg.get_from_amaze_cloth_crossing_stage_db(stageId);
                this.stageData.statisPointId && mgrSdk.statisOnStageStart(`${this.stageData.statisPointId}`, `${stageId}`);
            }
            onOpened() {
                super.onOpened();
                mgrLoader.loadFont("card_power", this.labelScore1);
                mgrLoader.loadFont("card_power", this.labelScore2);
                mgrLoader.loadFont("card_power", this.labelScore3);
                this.widget();
                mgrSound.play(9);
                this.spritePlayerFightPowerContainer.alpha = 0;
                this.spriteEnemyFightPowerContainer.alpha = 0;
                this.spriteTitle.visible = false;
                this.buildScene(() => {
                    this.cameraBack.useOcclusionCulling = false;
                    this.progressBarAni.barName = this.progressBarAni.owner.name;
                    this.progressBarAni.style = ULPROGRESSBAR_STYLE.hor;
                    this.progressBarAni.progress = 1;
                    this.progressBarRan.barName = this.progressBarRan.owner.name;
                    this.progressBarRan.style = ULPROGRESSBAR_STYLE.hor;
                    this.progressBarRan.progress = 1;
                    this.cameraBack.farPlane = 500;
                    this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                    this.cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                    let param = this.avatarPosCameraDict[0].cameraData;
                    this.cameraFollow.position = param.pos.clone();
                    this.cameraFollow.endRotation = param.rot.clone();
                    this.cameraFollow.fov = param.fov;
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                    this.stManager = new FSMObject;
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.waitStart, this.inWaitStart.bind(this), this.exeWaitStart.bind(this), this.outWaitStart.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.turnReady, this.inTurnReady.bind(this), this.exeTurnReady.bind(this), this.outTurnReady.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.avatarComing, this.inAvatarComing.bind(this), this.exeAvatarComing.bind(this), this.outAvatarComing.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.avatarMoving, this.inAvatarMoving.bind(this), this.exeAvatarMoving.bind(this), this.outAvatarMoving.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.selectAni, this.inSelectAni.bind(this), this.exeSelectAni.bind(this), this.outSelectAni.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.playerShow, this.inPlayerShow.bind(this), this.exePlayerShow.bind(this), this.outPlayerShow.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.enemyShow, this.inEnemyShow.bind(this), this.exeEnemyShow.bind(this), this.outEnemyShow.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.changeCloth, this.inChangeCloth.bind(this), this.exeChangeCloth.bind(this), this.outChangeCloth.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.toSeat, this.inToSeat.bind(this), this.exeToSeat.bind(this), this.outToSeat.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.nextTurnReady, this.inNextTurnReady.bind(this), this.exeNextTurnReady.bind(this), this.outNextTurnReady.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.restartCurrTurn, this.inRestartCurrTurn.bind(this), this.exeRestartCurrTurn.bind(this), this.outRestartCurrTurn.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.checkResultSuccess, this.inCheckResultSuccess.bind(this), this.exeCheckResultSuccess.bind(this), this.outCheckResultSuccess.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.reward, this.inReward.bind(this), this.exeReward.bind(this), this.outReward.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.palette, this.inPalette.bind(this), this.exePalette.bind(this), this.outPalette.bind(this));
                    this.stManager.registerState(AMUSE_CLOTH_CROSSING_STATE.finish, this.inFinish.bind(this), this.exeFinish.bind(this), this.outFinish.bind(this));
                    this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.init);
                    this.stManager.startUpdate(this, this.onTimerLoop.bind(this));
                    this.registerListeners({
                        MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                    });
                });
            }
            onTimerLoop() {
                if (!!this.cameraFarPlaneTargetZ) {
                    if (!Laya.Scene3DShaderDeclaration[`SHADERDEFINE_FARPLANEWORLDPOSITIONZ`]) {
                        Laya.Scene3DShaderDeclaration[`SHADERDEFINE_FARPLANEWORLDPOSITIONZ`] = Laya.Shader3D.getDefineByName(`FARPLANEWORLDPOSITIONZ`);
                    }
                    if (!this.lastCameraFarPlaneTargetZ) {
                        this.cameraBack.scene._shaderValues.addDefine(Laya.Scene3DShaderDeclaration[`SHADERDEFINE_FARPLANEWORLDPOSITIONZ`]);
                        this.lastCameraFarPlaneTargetZ = this.cameraFarPlaneTargetZ;
                    }
                    else {
                        this.lastCameraFarPlaneTargetZ = Math.max(this.lastCameraFarPlaneTargetZ - 0.1 * (this.stageData.moveFps || 1), this.cameraFarPlaneTargetZ - 0.1);
                    }
                    if (!this.customPid) {
                        this.customPid = Laya.Shader3D.propertyNameToID(`u_FarPlaneWorldPositionZ`);
                    }
                    this.cameraBack.scene._shaderValues.setNumber(this.customPid, this.lastCameraFarPlaneTargetZ);
                }
                if (!this.seatRoadNode || this.seatRoadNode.destroyed || !this.spriteTarget.visible) {
                    return;
                }
                let seatNode = this.seatRoadNode.getChildByName("seat");
                this.progressBarRan.progress = Math.abs(this.mapAvatarNode.transform.position.z) / Math.abs(seatNode.transform.position.z);
                let w = this.spriteRanCurrFlag.parent.width;
                this.spriteRanCurrFlag.x = Math.min(w, w * this.progressBarRan.progress);
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
                mgrLayout.widgetTopMC(this.spriteTarget);
                mgrLayout.widgetBottomMC(this.spriteScoreContainer);
                mgrLayout.widgetBottomMC(this.spriteAniContainer);
                mgrLayout.widgetLeftTopMC(this.spritePlayerFightPowerContainer);
                mgrLayout.widgetRightTopMC(this.spriteEnemyFightPowerContainer);
                mgrLayout.widgetLeftTopMC(this.spriteLeftTop);
            }
            buildScene(callback) {
                let mapSky = mgrLoader.Pool.getModel("tiankonghe");
                this.add3DEffectAtBack(mapSky, 0);
                mapSky.transform.position = new Laya.Vector3(0, 0, 0);
                this.mapSky = mapSky;
                this.mapStage = new Laya.Sprite3D;
                this.add3DEffectAtBack(this.mapStage);
                this.mapAvatarNode = new Laya.Sprite3D;
                this.add3DEffectAtBack(this.mapAvatarNode);
                this.spriteRule.visible = false;
                this.genStageMap();
                callback && callback();
            }
            genStageMap() {
                let count = this.stageData.roadPartIds.length;
                for (let i = 1; i <= 2; i++) {
                    let startNode = mgrLoader.Pool.getModel(this.PREFAB_ROAD_LINE_NAME);
                    mgrMaterial.setCustomMaterial(startNode, startNode.name);
                    startNode.transform.localPositionZ = this.PREFAB_ROAD_LINE_LEN * i;
                    this.mapStage.addChild(startNode);
                }
                let startZ = 0;
                for (let i = 0; i < count; i++) {
                    let partDatas = this.stageData.roadPartIds[i];
                    let pointNode = new Laya.Sprite3D;
                    pointNode.transform.localPositionZ = startZ;
                    this.mapStage.addChild(pointNode);
                    this.pointNodeArr.push(pointNode);
                    pointNode["_roadLen"] = (this.PREFAB_ROAD_LINE_LEN + this.PREFAB_ROAD_LINE_LEN + this.PREFAB_ROAD_CROSS_LEN);
                    startZ -= pointNode["_roadLen"];
                    let startNode = mgrLoader.Pool.getModel(this.PREFAB_ROAD_LINE_NAME);
                    mgrMaterial.setCustomMaterial(startNode, startNode.name);
                    pointNode.addChild(startNode);
                    let lineNode = mgrLoader.Pool.getModel(this.PREFAB_ROAD_LINE_NAME);
                    mgrMaterial.setCustomMaterial(lineNode, lineNode.name);
                    lineNode.transform.localPositionZ = -this.PREFAB_ROAD_LINE_LEN;
                    pointNode.addChild(lineNode);
                    let crossNode = mgrLoader.Pool.getModel(this.PREFAB_ROAD_CROSS_NAME);
                    mgrMaterial.setCustomMaterial(crossNode, crossNode.name);
                    crossNode.transform.localPositionZ = -this.PREFAB_ROAD_LINE_LEN * 2;
                    crossNode.name = "cross_node";
                    pointNode.addChild(crossNode);
                    if (i != 0) {
                        for (let i = 0; i < 15; i++) {
                            let mlbNode = mgrLoader.Pool.getModel(this.PREFAB_COIN_NAME);
                            mgrMaterial.setCustomMaterial(mlbNode, mlbNode.name);
                            mlbNode.transform.localPosition = new Laya.Vector3((i % 3 - 1) * 0.6, 0.5, -this.PREFAB_ROAD_LINE_LEN - (Math.floor(i / 3) * 0.7));
                            pointNode.addChild(mlbNode);
                            cc.tween(mlbNode.transform)
                                .repeatForever(cc.tween().to(0.05, { localRotationEulerY: 40 }).to(0.05, { localRotationEulerY: 0 }).to(0.05, { localRotationEulerY: -40 }).to(0.05, { localRotationEulerY: 0 }))
                                .start();
                            this.mlbNodeArr.push(mlbNode);
                        }
                    }
                    this.crossArr2RoadModelDict[i] = {};
                    for (let index = 0; index < 3; index++) {
                        let pathNode = crossNode.getChildByName("path" + (index + 1));
                        let pathPartNode = pathNode.getChildByName("part");
                        if (!!pathPartNode) {
                            let partId = partDatas[index];
                            let partData = mgrCfg.get_from_part_db(partId);
                            if (!partData || !partData.modelId) {
                                continue;
                            }
                            let scale = this.PART_TYPE_2_SCALE_DICT[partData.type] || 1;
                            let offsetY = this.PART_TYPE_2_Y_OFFSET_DICT[partData.type] || 0;
                            let model = mgrLoader.Pool.getModel(partData.modelId);
                            model.transform.setWorldLossyScale(new Laya.Vector3(scale, scale, scale));
                            model.transform.localPosition = new Laya.Vector3(0, offsetY, 0);
                            pathPartNode.addChild(model);
                            mgrMaterial.setCustomMaterial(model, partData.modelId, partData.modelMaterialNo);
                            this.crossArr2RoadModelDict[i][index + 1] = { partId: partId, model: model };
                        }
                    }
                    pointNode.active = i == 0 ? true : false;
                }
                let lastRoadContainer = new Laya.Sprite3D;
                this.mapStage.addChild(lastRoadContainer);
                let lineNode = mgrLoader.Pool.getModel(this.PREFAB_ROAD_LINE_NAME);
                mgrMaterial.setCustomMaterial(lineNode, lineNode.name);
                lineNode.transform.localPositionZ = startZ;
                lastRoadContainer.addChild(lineNode);
                startZ -= this.PREFAB_ROAD_LINE_LEN;
                this.finishFlyEndPosZ = startZ;
                let lineNode2 = mgrLoader.Pool.getModel(this.PREFAB_ROAD_LINE_NAME);
                mgrMaterial.setCustomMaterial(lineNode2, lineNode2.name);
                lineNode2.transform.localPositionZ = startZ;
                lastRoadContainer.addChild(lineNode2);
                startZ -= this.PREFAB_ROAD_LINE_LEN;
                this.enemyShowPosZ = lineNode.transform.position.z;
                this.startRotateCameraPosZ = startZ + this.PREFAB_ROAD_LINE_LEN / 2;
                let seatRoadNode = mgrLoader.Pool.getModel(this.PREFAB_ROAD_SEAT_NAME);
                mgrMaterial.setCustomMaterial(seatRoadNode, seatRoadNode.name);
                seatRoadNode.transform.localPositionZ = startZ;
                lastRoadContainer.addChild(seatRoadNode);
                startZ -= this.PREFAB_ROAD_SEAT_LEN;
                let lineNode3 = mgrLoader.Pool.getModel(this.PREFAB_ROAD_LINE_NAME);
                mgrMaterial.setCustomMaterial(lineNode3, lineNode3.name);
                lineNode3.transform.localPositionZ = startZ;
                lastRoadContainer.addChild(lineNode3);
                startZ -= this.PREFAB_ROAD_LINE_LEN;
                let lineNode4 = mgrLoader.Pool.getModel(this.PREFAB_ROAD_LINE_NAME);
                mgrMaterial.setCustomMaterial(lineNode4, lineNode4.name);
                lineNode4.transform.localPositionZ = startZ;
                lastRoadContainer.addChild(lineNode4);
                startZ -= this.PREFAB_ROAD_LINE_LEN;
                lastRoadContainer.active = false;
                this.lastRoadContainer = lastRoadContainer;
                this.seatRoadNode = seatRoadNode;
            }
            tryInitSeat() {
                if (!!this.baozuoModel) {
                    return;
                }
                let baozuoModel = mgrLoader.Pool.getModel("baozuo");
                mgrMaterial.setCustomMaterial(baozuoModel, "baozuo");
                baozuoModel.transform.localRotationEulerY = 90;
                let seatNode = this.seatRoadNode.getChildByName("seat");
                if (!!seatNode) {
                    seatNode.addChild(baozuoModel);
                }
                this.baozuoModel = baozuoModel;
            }
            resetDataOnStart() {
                this.MOVE_FPS = this.stageData.moveFps;
                this.currPointNodeIndex = -1;
                this.baseRoadX = 0;
                this.bTouchBg = false;
                this.lastTouchBgPos = null;
                this.touchBgBeginPos = null;
                this.touchBgBeginAvatarPosX = 0;
                this.lastTouchResultMapAvatarPositionX = 0;
            }
            cleanModels() {
                if (!!this.baozuoModel && this.baozuoModel.destroyed) {
                    cc.tween(this.baozuoModel.transform).removeAllActions();
                    mgrLoader.Pool.recoverModel(this.baozuoModel);
                    this.baozuoModel = null;
                }
                if (!!this.crossArr2RoadModelDict) {
                    for (let k in this.crossArr2RoadModelDict) {
                        let arr = this.crossArr2RoadModelDict[k];
                        for (let kk in arr) {
                            let data = arr[kk];
                            if (data.model && !data.model.destroyed) {
                                cc.tween(data.model).removeAllActions();
                                mgrLoader.Pool.recoverModel(data.model);
                            }
                        }
                    }
                    this.crossArr2RoadModelDict = {};
                }
                if (!!this.mlbNodeArr) {
                    for (let k in this.mlbNodeArr) {
                        let node = this.mlbNodeArr[k];
                        if (!!node && !node.destroyed) {
                            cc.tween(node.transform).removeAllActions();
                            mgrLoader.Pool.recoverModel(node);
                        }
                    }
                }
                if (!!this.pointNodeArr) {
                    for (let k in this.pointNodeArr) {
                        let node = this.pointNodeArr[k];
                        let numChildren = node.numChildren;
                        for (let i = numChildren; i >= 0; i--) {
                            let model = node.getChildAt(i);
                            if (model && !model.destroyed) {
                                cc.tween(model).removeAllActions();
                                mgrLoader.Pool.recoverModel(model);
                            }
                        }
                    }
                    this.pointNodeArr = [];
                }
                if (!!this.flyEffectNode && !this.flyEffectNode.destroyed) {
                    cc.tween(this.flyEffectNode).removeAllActions();
                    mgrLoader.Pool.recoverModel(this.flyEffectNode);
                    this.flyEffectNode = null;
                }
                if (!!this.avatar && !this.avatar.destroyed) {
                    this.avatar.destroy();
                    this.avatar = null;
                }
                if (!!this.mapAvatarNode && !this.mapAvatarNode.destroyed) {
                    let numChildren = this.mapAvatarNode.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let child = this.mapAvatarNode.getChildAt(i);
                        cc.tween(child).removeAllActions();
                        mgrLoader.Pool.recoverModel(child);
                    }
                    this.mapAvatarNode.destroy();
                    this.mapAvatarNode = null;
                }
                if (!!this.mapStage && !this.mapStage.destroyed) {
                    let numChildren = this.mapStage.numChildren;
                    for (let i = numChildren - 1; i >= 0; i--) {
                        let node = this.mapStage.getChildAt(i);
                        mgrLoader.Pool.recoverModel(node);
                    }
                    this.mapStage.destroy();
                    this.mapStage = null;
                }
                if (!!this.avatarEnemy && !this.avatarEnemy.destroyed) {
                    this.avatarEnemy.destroy();
                    this.avatarEnemy = null;
                }
            }
            onTouchSpriteBg(e) {
                if (this.stManager.getCurState() == AMUSE_CLOTH_CROSSING_STATE.waitStart) {
                    if (!this.bTouchedOnce) {
                        this.boxGuideStart.visible = false;
                        this.bTouchedOnce = true;
                        this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.turnReady);
                    }
                    return;
                }
                if (this.stManager.getCurState() != AMUSE_CLOTH_CROSSING_STATE.avatarMoving) {
                    return;
                }
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.touchBgBeginPos = new Laya.Vector2(e.pos.x, e.pos.y);
                    this.touchBgBeginAvatarPosX = this.mapAvatarNode.transform.localPositionX - this.baseRoadX;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                    this.lastTouchBgPos = null;
                    this.touchBgBeginPos = null;
                }
                if (!this.touchBgBeginPos) {
                    this.touchBgBeginPos = null;
                    this.lastTouchBgPos = null;
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    this.lastTouchBgPos = e.pos;
                }
            }
            inInit() {
                this.resetDataOnStart();
                this.spriteAniContainer.visible = false;
                this.spriteScoreContainer.visible = false;
                this.successScoreArr = [Tools.random(2) + 8, 10, Tools.random(2) + 8];
                this.faildScoreArr = [Tools.random(3) + 5, 6, Tools.random(3) + 5];
                this.successTotalScore = 0;
                this.faildTotalScore = 0;
                for (let k in this.successScoreArr) {
                    this.successTotalScore += this.successScoreArr[k];
                }
                for (let k in this.faildScoreArr) {
                    this.faildTotalScore += this.faildScoreArr[k];
                }
                this.labelTarget.text = this.stageData.stageDesc || "";
                let roleId = mgrRole.showingRoleId;
                let initPartIds = [13000, 16000];
                let roleData = mgrCfg.get_from_role_db(roleId);
                for (let k in roleData.centerPartIds) {
                    let partData = mgrCfg.get_from_part_db(roleData.centerPartIds[k]);
                    if (partData.type == PartType.hair || partData.type == PartType.face) {
                        initPartIds.push(partData.id);
                    }
                }
                let usePartIds = null;
                let onResPreloadedFunc = () => {
                    if (!this.avatar) {
                        this.avatar = new RoleAvatar({ roleId: roleId });
                    }
                    this.avatar.fillByPartIds(usePartIds);
                    this.mapAvatarNode.addChild(this.avatar);
                    this.avatar.registerLoadEndCallback(() => {
                        mgrTip.hideLoadingTip("cloth_crossing_loading");
                        this.avatar.playDefaultIdleAnimation();
                        this.avatar.transform.localPosition = new Laya.Vector3(0, 0.1, 0);
                        this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.waitStart);
                    });
                };
                let onSkinConfirmFunc = (skinPartIds) => {
                    let targetPartIdDict = {};
                    for (let k in this.stageData.targetPartIds) {
                        let pid = this.stageData.targetPartIds[k];
                        targetPartIdDict[pid] = true;
                    }
                    let fixPartTypeDict = {};
                    for (let k in skinPartIds) {
                        let pid = skinPartIds[k];
                        if (targetPartIdDict[pid]) {
                            this.dressedPartIdDict[pid] = true;
                            let partData = mgrCfg.get_from_part_db(pid);
                            fixPartTypeDict[partData.type] = true;
                        }
                    }
                    this.fixPartTypeDict = fixPartTypeDict;
                    let modelIds = [];
                    let partIds = skinPartIds || initPartIds;
                    usePartIds = partIds;
                    for (let k in partIds) {
                        let partData = mgrCfg.get_from_part_db(partIds[k]);
                        if (!partData || !partData.modelId) {
                            continue;
                        }
                        modelIds.push(partData.modelId);
                    }
                    mgrTip.showLoadingTip("cloth_crossing_loading", null, 0, true, "正在装饰跑道");
                    mgrLoader.batchLoadResources(modelIds, null, null, () => {
                        onResPreloadedFunc();
                    });
                };
                if (this.stageData.id > 3 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseClothCrossingScene_trial_role)) {
                    let skinIds = this.stageData.trialSkinIds;
                    let skinId = Tools.randomGotOneArrayData(skinIds);
                    let skinData = mgrCfg.get_from_amaze_cloth_crossing_skin_db(skinId);
                    console.log("-------------------trial skinId=", skinId);
                    mgrDirector.openDialog("vAmusePenRoleTrialDialog", {
                        adEventId: AD_EVENT_ID.VIDEO.video_vAmuseClothCrossingScene_trial_role,
                        skinId: skinId,
                        previewImg: skinData.previewImg,
                        fOnAdResult: (bAded) => {
                            if (!!bAded) {
                                onSkinConfirmFunc(skinData.partIds);
                            }
                            else {
                                onSkinConfirmFunc(null);
                            }
                        }
                    });
                }
                else {
                    onSkinConfirmFunc(null);
                }
            }
            exeInit() { }
            outInit() { }
            inWaitStart() {
                Tools.registerTouchHander(this.boxBackPanel, this.onTouchSpriteBg.bind(this));
            }
            exeWaitStart() { }
            outWaitStart() { }
            inTurnReady() {
                this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.avatarComing);
            }
            exeTurnReady() { }
            outTurnReady() { }
            inAvatarComing() {
                mgrVideoRecorder.startRecord();
                let param = this.avatarPosCameraDict[1].cameraData;
                this.cameraFollow.position = param.pos.clone();
                this.cameraFollow.endRotation = param.rot.clone();
                this.cameraFollow.fov = param.fov;
                this.cameraFollow.lerpValue = 0.1;
                this.avatar.playAnimation("paoku_move-paoku_run", 0, null, null, true);
            }
            exeAvatarComing() {
                this.avatar.transform.localRotationEulerY += 6;
                if (this.avatar.transform.localRotationEulerY >= 180) {
                    this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.avatarMoving);
                }
            }
            outAvatarComing() { }
            inAvatarMoving() {
                this.avatar.transform.localRotationEulerY = 180;
            }
            exeAvatarMoving(deltaTime) {
                this.forwardAvatar(deltaTime);
                this.tryChangeCurrentPointNodeIndex();
                this.checkMlb();
                this.checkFinishFly();
                this.checkEnemyShow();
                this.checkAvatarPos();
                this.checkFinishRotateCamera();
            }
            outAvatarMoving() {
                this.avatar.timeScale = 1;
                this.avatar.transform.localRotationEulerX = 0;
            }
            getCurrentCrossRoadNode() {
                let count = this.pointNodeArr.length;
                for (let i = 0; i < count; i++) {
                    let pointNode = this.pointNodeArr[i];
                    let crossNode = pointNode.getChildByName("cross_node");
                    if (!crossNode) {
                        continue;
                    }
                    if (this.mapAvatarNode.transform.position.z < crossNode.transform.position.z && this.mapAvatarNode.transform.position.z >= (crossNode.transform.position.z - this.PREFAB_ROAD_CROSS_LEN)) {
                        return { index: i, node: crossNode };
                    }
                }
            }
            getCurrentCrossRoadPathPointByIndex(index) {
                let crossNodeData = this.getCurrentCrossRoadNode();
                if (!crossNodeData) {
                    return;
                }
                let crossNode = crossNodeData.node;
                let pathNode = crossNode.getChildByName("path" + index);
                if (!pathNode) {
                    return;
                }
                let pathPoints = [];
                let numChildren = pathNode.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let node = pathNode.getChildAt(i);
                    if (node.name == "part") {
                        continue;
                    }
                    pathPoints.push(node.transform.position);
                }
                return pathPoints;
            }
            forwardAvatar(deltaTime) {
                let dis = Math.min(deltaTime * this.MOVE_FPS, 0.03 * this.MOVE_FPS);
                this.mapAvatarNode.transform.localPositionZ -= dis;
                let crossNodeData = this.getCurrentCrossRoadNode();
                if (!crossNodeData || !crossNodeData.node) {
                    if (!this.avatarEnemyNode) {
                        if (this.bTouchBg && this.lastTouchBgPos && this.touchBgBeginPos) {
                            let tmpx = (this.lastTouchBgPos.x - this.touchBgBeginPos.x) / (mgrDirector.width * 0.6) * this.ROAD_WH + (this.touchBgBeginAvatarPosX);
                            this.lastTouchResultMapAvatarPositionX = ul.clamp(tmpx, -this.ROAD_WH / 2, this.ROAD_WH / 2);
                        }
                        this.mapAvatarNode.transform.localPositionX = this.lastTouchResultMapAvatarPositionX + this.baseRoadX;
                    }
                    else {
                        this.mapAvatarNode.transform.localPositionX = this.baseRoadX;
                    }
                    this.mapAvatarNode.transform.localRotationEulerY = 0;
                    this.currCrossPathPoints = null;
                }
                else {
                    if (!this.currCrossPathPoints) {
                        let index = 2;
                        let roadCheckOffsetX = this.ROAD_WH / 3 / 2;
                        let offsetX = this.mapAvatarNode.transform.position.x - crossNodeData.node.transform.position.x;
                        if (offsetX > roadCheckOffsetX) {
                            index = 3;
                        }
                        else if (offsetX > -roadCheckOffsetX) {
                            index = 2;
                        }
                        else {
                            index = 1;
                        }
                        this.currCrossPathRoadIndex = index;
                        this.currCrossPathPoints = this.getCurrentCrossRoadPathPointByIndex(index);
                        let nextPointNode = this.pointNodeArr[crossNodeData.index + 1];
                        if (!!nextPointNode) {
                            nextPointNode.active = true;
                            nextPointNode.transform.localPositionX = this.currCrossPathPoints[this.currCrossPathPoints.length - 1].x;
                            this.cameraFarPlaneTargetZ = nextPointNode.transform.position.z - nextPointNode["_roadLen"];
                        }
                        else {
                            this.cameraFarPlaneTargetZ = -500;
                            this.lastRoadContainer.transform.localPositionX = this.currCrossPathPoints[this.currCrossPathPoints.length - 1].x;
                            this.lastRoadContainer.active = true;
                            this.tryInitSeat();
                        }
                    }
                    let prePos = null;
                    let nextPos = null;
                    let posAvatar = this.mapAvatarNode.transform.position;
                    for (let i = 0; i < this.currCrossPathPoints.length; i++) {
                        let pos = this.currCrossPathPoints[i];
                        if (posAvatar.z >= pos.z) {
                            prePos = this.currCrossPathPoints[i - 1];
                            nextPos = pos;
                            break;
                        }
                    }
                    if (!prePos && !!nextPos) {
                        this.mapAvatarNode.transform.localPositionX += (nextPos.x - this.mapAvatarNode.transform.localPositionX) * Math.min(1, 0.1 * this.MOVE_FPS);
                    }
                    else if (!!prePos && !!nextPos) {
                        let ratio = Math.abs(this.mapAvatarNode.transform.position.z - prePos.z) / Math.abs(prePos.z - nextPos.z);
                        let targetX = prePos.x + (nextPos.x - prePos.x) * ratio;
                        this.mapAvatarNode.transform.localPositionX += (targetX - this.mapAvatarNode.transform.localPositionX) * Math.min(1, 0.3 * this.MOVE_FPS);
                        let rot = Tools.getAngle(prePos.x, prePos.z, nextPos.x, nextPos.z);
                        this.mapAvatarNode.transform.localRotationEulerY += (rot - this.mapAvatarNode.transform.localRotationEulerY) / (Math.abs(rot - this.mapAvatarNode.transform.localRotationEulerY) || 1) * 0.25 * this.MOVE_FPS;
                    }
                    else {
                        console.warn("-----------------something wrong");
                    }
                    this.lastTouchResultMapAvatarPositionX = 0;
                    this.baseRoadX = this.mapAvatarNode.transform.localPositionX;
                    let partModelData = this.crossArr2RoadModelDict[crossNodeData.index][this.currCrossPathRoadIndex];
                    if (!!partModelData && !partModelData.bHitedModel) {
                        let model = partModelData.model;
                        if (!!model &&
                            Math.abs(model.transform.position.x - this.mapAvatarNode.transform.position.x) < 1 &&
                            Math.abs(model.transform.position.z - this.mapAvatarNode.transform.position.z) < 0.6) {
                            partModelData.bHitedModel = true;
                            let partData = mgrCfg.get_from_part_db(partModelData.partId);
                            if (!this.bFlying && partData && partData.type == PartType.backDeco) {
                                this.avatar.playAnimation("paoku_move-paoku_fly", 0, null, null, true, true);
                                this.bFlying = true;
                                let effectNode = mgrLoader.Pool.getModel("e_daoju_wudi");
                                effectNode.transform.localPositionY = 1.2;
                                this.mapAvatarNode.addChild(effectNode);
                                this.flyEffectNode = effectNode;
                            }
                            if (this.fixPartTypeDict[partData.type]) {
                                cc.tween(partModelData.model.transform).to(0.3, { localPositionY: 6, localPositionX: Tools.random(1, 5) * Tools.random(100) < 50 ? 1 : -1 })
                                    .call(() => {
                                    if (!!this.nodeResource && !this.nodeResource.destroyed) {
                                        delete partModelData.model;
                                        mgrLoader.Pool.recoverModel(model);
                                    }
                                })
                                    .start();
                                mgrSound.play(113);
                                let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                                this.add3DEffectAtBack(effExplodeModel, 1);
                                effExplodeModel.transform.position = this.mapAvatarNode.transform.position;
                                effExplodeModel.transform.setWorldLossyScale(new Laya.Vector3(0.3, 0.3, 0.3));
                            }
                            else {
                                delete partModelData.model;
                                mgrLoader.Pool.recoverModel(model);
                                this.avatar.fillByPartIds([partModelData.partId]);
                                this.dressedPartIdDict[partModelData.partId] = partModelData.partId;
                                mgrSound.play(167);
                                let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                                this.add3DEffectAtBack(effExplodeModel, 1);
                                effExplodeModel.transform.position = this.mapAvatarNode.transform.position;
                                effExplodeModel.transform.setWorldLossyScale(new Laya.Vector3(0.7, 0.7, 0.7));
                            }
                        }
                    }
                }
                if (!!this.currCrossPathPoints) {
                    this.mapSky.transform.position = this.mapAvatarNode.transform.position;
                }
                else {
                    this.mapSky.transform.position = new Laya.Vector3(this.baseRoadX, this.mapAvatarNode.transform.position.y, this.mapAvatarNode.transform.position.z);
                }
                if (!this.bStartedFinishRotateCamera) {
                    let param = this.avatarPosCameraDict[1].cameraData;
                    if (!!this.currCrossPathPoints) {
                        this.cameraFollow.position = new Laya.Vector3(param.pos.x + this.mapAvatarNode.transform.position.x, param.pos.y, param.pos.z + this.mapAvatarNode.transform.position.z);
                    }
                    else {
                        this.cameraFollow.position = new Laya.Vector3(this.baseRoadX, param.pos.y, param.pos.z + this.mapAvatarNode.transform.position.z);
                    }
                }
                else {
                }
            }
            tryChangeCurrentPointNodeIndex() {
                let count = this.pointNodeArr.length;
                for (let i = count - 1; i >= 0; i--) {
                    let pointNode = this.pointNodeArr[i];
                    if (pointNode.transform.position.z >= this.mapAvatarNode.transform.position.z) {
                        this.currPointNodeIndex = i;
                        pointNode.active = true;
                        this.cameraFarPlaneTargetZ = Math.min(pointNode.transform.position.z - pointNode["_roadLen"], this.cameraFarPlaneTargetZ);
                        break;
                    }
                }
            }
            checkMlb() {
                if (!this.mlbNodeArr) {
                    return;
                }
                let avatarPos = this.mapAvatarNode.transform.position;
                for (let k in this.mlbNodeArr) {
                    let model = this.mlbNodeArr[k];
                    if (!model.active || Math.abs(model.transform.position.z - avatarPos.z) > 0.5) {
                        continue;
                    }
                    if (Math.abs(model.transform.position.x - avatarPos.x) >= 0.5) {
                        continue;
                    }
                    let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                    this.add3DEffectAtBack(effExplodeModel, 1);
                    effExplodeModel.transform.setWorldLossyScale(new Laya.Vector3(0.2, 0.2, 0.2));
                    effExplodeModel.transform.position = this.mapAvatarNode.transform.position;
                    mgrSound.play(111);
                    cc.tween(model.transform).removeAllActions();
                    model.active = false;
                    this.gotMlbCount++;
                }
            }
            checkEnemyShow() {
                if (this.mapAvatarNode.transform.position.z < this.enemyShowPosZ && !this.avatarEnemyNode) {
                    let playerDressCount = 0;
                    let targetCount = this.stageData.targetPartIds.length || 1;
                    let targetPartIdDict = {};
                    for (let k in this.stageData.targetPartIds) {
                        let tmpId = this.stageData.targetPartIds[k];
                        targetPartIdDict[tmpId] = true;
                        if (this.dressedPartIdDict[tmpId]) {
                            playerDressCount++;
                        }
                    }
                    this.playerGotScore = playerDressCount * this.stageData.rightDressGotScore + (targetCount - playerDressCount) * this.stageData.wrongDressGotScore;
                    let bPlayerScoreHigher = this.playerGotScore < this.stageData.successScore ? false : true;
                    let enemyPartIds = [];
                    for (let k in this.stageData.roadPartIds) {
                        let partIds = this.stageData.roadPartIds[k];
                        for (let tmp in partIds) {
                            let tmpPartId = partIds[tmp];
                            if (!bPlayerScoreHigher) {
                                if (!!targetPartIdDict[tmpPartId]) {
                                    enemyPartIds.push(tmpPartId);
                                    break;
                                }
                            }
                            else {
                                if (!targetPartIdDict[tmpPartId]) {
                                    enemyPartIds.push(tmpPartId);
                                    break;
                                }
                            }
                        }
                    }
                    this.avatarEnemyNode = new Laya.Sprite3D;
                    this.add3DEffectAtBack(this.avatarEnemyNode);
                    let enemyRoleId = this.context.enemyRoleId || this.avatar.getRoleId();
                    enemyPartIds = mgrPart.getReplacedRoleCenterParts(enemyRoleId, enemyPartIds);
                    this.avatarEnemy = new RoleAvatar({ roleId: enemyRoleId });
                    this.avatarEnemy.fillByPartIds(enemyPartIds);
                    this.avatarEnemyNode.addChild(this.avatarEnemy);
                    this.avatarEnemy.transform.localPosition = new Laya.Vector3(0, 0.1, 0);
                    this.avatarEnemy.registerAllLoadEndCallback(() => {
                        this.avatarEnemy.playAnimation("paoku_walk-paoku_walk", 0, null, null, true, true);
                    });
                }
            }
            checkFinishRotateCamera() {
                if (this.mapAvatarNode.transform.position.z < this.startRotateCameraPosZ && !this.bStartedFinishRotateCamera) {
                    this.bStartedFinishRotateCamera = true;
                    let centerNode = this.seatRoadNode.getChildByName("center");
                    this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                    let param = this.avatarPosCameraDict[4].cameraData;
                    this.cameraFollow.position = new Laya.Vector3(param.pos.x + centerNode.transform.position.x, param.pos.y + centerNode.transform.position.y, param.pos.z + centerNode.transform.position.z);
                    this.cameraFollow.endRotation = param.rot.clone();
                    this.cameraFollow.fov = param.fov;
                    this.cameraFollow.lerpValue = 0.02;
                    Timer.callLater(3.5, () => {
                        this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                        let param = this.avatarPosCameraDict[5].cameraData;
                        this.cameraFollow.position = new Laya.Vector3(param.pos.x + centerNode.transform.position.x, param.pos.y + centerNode.transform.position.y, param.pos.z + centerNode.transform.position.z);
                        this.cameraFollow.endRotation = param.rot.clone();
                        this.cameraFollow.fov = param.fov;
                        this.cameraFollow.lerpValue = 0.03;
                    }, this);
                }
            }
            checkFinishFly() {
                if (this.mapAvatarNode.transform.position.z < this.finishFlyEndPosZ && this.bFlying) {
                    if (!!this.flyEffectNode) {
                        mgrLoader.Pool.recoverModel(this.flyEffectNode);
                        this.flyEffectNode = null;
                    }
                    this.spriteTarget.visible = false;
                    this.bFlying = false;
                    this.avatar.playAnimation("paoku_walk-paoku_walk", 0, null, null, true, true);
                    this.MOVE_FPS = 1;
                }
            }
            checkAvatarPos() {
                let centerNode = this.seatRoadNode.getChildByName("center");
                if (this.avatarEnemyNode) {
                    let avatarPos = this.mapAvatarNode.transform.position;
                    let centerPos = centerNode.transform.position;
                    this.avatarEnemyNode.transform.position = new Laya.Vector3(avatarPos.x, avatarPos.y, centerPos.z - Math.abs(avatarPos.z - centerPos.z));
                }
                let playerArrivedZ = centerNode.transform.position.z + this.LANDING_POS_X_OFFSET;
                if (Math.abs(this.mapAvatarNode.transform.position.z - playerArrivedZ) < 0.1 || this.mapAvatarNode.transform.position.z <= playerArrivedZ) {
                    cc.tween(this.avatar.transform, true).to(0.3, { localRotationEulerY: 90 }).start();
                    this.avatar.playDefaultIdleAnimation();
                    cc.tween(this.avatarEnemy.transform, true).to(0.3, { localRotationEulerY: 90 }).start();
                    this.avatarEnemy.playDefaultIdleAnimation();
                    this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.selectAni);
                }
            }
            inSelectAni() {
                this.spriteTarget.visible = false;
                this.buttonBack.__node.visible = false;
                mgrTip.hideJumpOtherGameBannerVertical(this);
                let adFlagIconPath = Const.AD_FLAG_ICON_PATH_DICT[mgrSdk.getCopNumberValueByKey("ad_flag_style") || 0];
                let adEventId = AD_EVENT_ID.VIDEO.video_vAmuseClothCrossingScene_trial_ani;
                let bCanAd = mgrAd.preCheckAdNoCd(adEventId, true);
                let adEventData = mgrCfg.get_from_ad_event_db(adEventId);
                adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                this.spriteAniContainer.visible = true;
                mgrBannerInt.closeBannerOnce();
                let itemArr = [this.buttonAni1.__node, this.buttonAni2.__node, this.buttonAni3.__node];
                for (let k in itemArr) {
                    let node = itemArr[k];
                    node.scale(0, 0);
                    cc.tween(node).toScale(0.1, 1, cc.Ease.backOut).start();
                    let spriteAd = node.getChildByName("spriteAdFlag");
                    if (!!spriteAd) {
                        spriteAd.visible = !!bCanAd;
                        Tools.loadImg(spriteAd, adFlagIconPath);
                    }
                }
                mgrSound.play(116);
                mgrCfg.forDb_from_amuse_cloth_crossing_photo_recipe_db((k, v) => {
                    let icon = this["spritePhotoIcon" + v.id];
                    let labelName = this["labelPhotoName" + v.id];
                    Tools.loadImg(icon, v.icon, true);
                    labelName.text = v.name;
                });
            }
            exeSelectAni() {
                let ranTime = this.stManager.getCurrStateRanTime() || 0;
                this.progressBarAni.progress = Math.max(0, 1 - ranTime / 3);
                if (this.progressBarAni.progress <= 0.01) {
                    this.doClickAni(1);
                }
            }
            outSelectAni() { }
            inPlayerShow() {
                let avatarPlayerPos = this.mapAvatarNode.transform.localPosition.clone();
                let showNode = this.seatRoadNode.getChildByName("show");
                let offsetPosAvatar = new Laya.Vector3;
                Laya.Vector3.subtract(showNode.transform.position, this.mapAvatarNode.transform.position, offsetPosAvatar);
                this.avatar.playAnimation("paoku_walk-paoku_walk", 0, null, null, true, true);
                cc.tween(this.mapAvatarNode.transform, true)
                    .to(1, { localPositionX: avatarPlayerPos.x + offsetPosAvatar.x, localPositionY: avatarPlayerPos.y, localPositionZ: avatarPlayerPos.z + offsetPosAvatar.z })
                    .call(() => {
                    cc.tween(this.avatar.transform, true).to(0.3, { localRotationEulerY: 90 }).start();
                })
                    .delay(0.3)
                    .call(() => {
                    this.avatar.playAnimation(this.playerShowAniName, 0, null, () => {
                        this.showScoreContainer();
                        this.refreshScoreUiData();
                    }, false);
                })
                    .start();
            }
            exePlayerShow() { }
            outPlayerShow() { }
            showScoreContainer() {
                this.spriteScoreContainer.visible = true;
                let itemArr = [this.spriteScore1, this.spriteScore2, this.spriteScore3];
                let datas = Tools.randomGotArrayDatas([0, 1, 2], 3);
                for (let k in itemArr) {
                    let node = itemArr[k];
                    let index = datas[k];
                    let nodeEffect = node;
                    nodeEffect["_originPos"] = nodeEffect["_originPos"] || new Laya.Vector2(nodeEffect.x, nodeEffect.y);
                    nodeEffect.x = nodeEffect["_originPos"].x + 0;
                    nodeEffect.y = nodeEffect["_originPos"].y + 350;
                    nodeEffect.visible = true;
                    cc.tween(nodeEffect)
                        .delay(index * 0.2)
                        .call(() => {
                        mgrSound.play(153);
                        nodeEffect.alpha = 1;
                    })
                        .toPos(0.5, nodeEffect["_originPos"].x, nodeEffect["_originPos"].y, cc.Ease.elasticOut)
                        .start();
                }
                Timer.callLater(1.5, () => {
                    this.onShowedScore();
                }, this);
            }
            refreshScoreUiData() {
                let scoreArr = null;
                if (this.stManager.getCurState() == AMUSE_CLOTH_CROSSING_STATE.playerShow) {
                    scoreArr = this.bSuccess ? Tools.randomGotArrayDatas(this.successScoreArr, 3) : Tools.randomGotArrayDatas(this.faildScoreArr, 3);
                }
                else {
                    scoreArr = !this.bSuccess ? Tools.randomGotArrayDatas(this.successScoreArr, 3) : Tools.randomGotArrayDatas(this.faildScoreArr, 3);
                }
                for (let i = 1; i <= 3; i++) {
                    this["labelScore" + i].text = `${scoreArr[i - 1]}`;
                }
            }
            inEnemyShow() {
                let avatarPlayerPos = this.avatarEnemyNode.transform.localPosition.clone();
                let showNode = this.seatRoadNode.getChildByName("show");
                let offsetPosAvatar = new Laya.Vector3;
                Laya.Vector3.subtract(showNode.transform.position, this.avatarEnemyNode.transform.position, offsetPosAvatar);
                this.avatarEnemy.registerLoadEndCallback(() => {
                    this.avatarEnemy.playAnimation("paoku_walk-paoku_walk", 0.1, null, null, true, true);
                });
                cc.tween(this.avatarEnemyNode.transform, true)
                    .to(1, { localPositionX: avatarPlayerPos.x + offsetPosAvatar.x, localPositionY: avatarPlayerPos.y, localPositionZ: avatarPlayerPos.z + offsetPosAvatar.z })
                    .call(() => {
                    cc.tween(this.avatarEnemy.transform, true).to(0.3, { localRotationEulerY: 90 }).start();
                })
                    .delay(0.3)
                    .call(() => {
                    this.avatarEnemy.playDefaultIdleAnimation();
                    this.showScoreContainer();
                    this.refreshScoreUiData();
                })
                    .start();
            }
            exeEnemyShow() { }
            outEnemyShow() { }
            inCheckResultSuccess() {
                this.bSuccess = this.playerGotScore < this.stageData.successScore ? false : true;
                this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.playerShow);
            }
            exeCheckResultSuccess() { }
            outCheckResultSuccess() { }
            inChangeCloth() {
                let seatNode = this.seatRoadNode.getChildByName("seat");
                let tailuo = mgrLoader.Pool.getModel("tailuo");
                tailuo.transform.localPosition = new Laya.Vector3;
                tailuo.transform.localRotationEuler = new Laya.Vector3;
                tailuo.transform.localRotationEulerY = 90;
                mgrMaterial.setCustomMaterial(tailuo, "tailuo");
                this.add3DEffectAtBack(tailuo);
                tailuo.transform.position = new Laya.Vector3(seatNode.transform.position.x + 2.5, 0.01, seatNode.transform.position.z);
                let animator = tailuo.getComponent(Laya.Animator);
                this.tailuoModel = tailuo;
                mgrMaterial.playAnimation(animator, "tailuo_paoku-tailuo_paoku", 0, () => {
                    Timer.callLater(1.6, () => {
                        let avatarNode = this.bSuccess ? this.mapAvatarNode : this.avatarEnemyNode;
                        let avatar = this.bSuccess ? this.avatar : this.avatarEnemy;
                        let effAtted = mgrLoader.Pool.getModel("117_e_once_flash_01");
                        effAtted.transform.position = new Laya.Vector3(avatar.transform.position.x, avatar.transform.position.y + 1, avatar.transform.position.z);
                        this.mapStage.addChild(effAtted);
                        let bodyEffName = this.stageData.bSuccessChangeAngel ? "117_e_loop_angel_01" : "117_e_loop_devil_01";
                        let bodyEffModel = mgrLoader.Pool.getModel(bodyEffName);
                        avatarNode.addChild(bodyEffModel);
                        let usePartIds = [];
                        let partIds = this.stageData.bSuccessChangeAngel ? this.ANGEL_CHANGE_PARTID_ARR : this.EVIL_CHANGE_PARTID_ARR;
                        for (let k in partIds) {
                            let tmpPartIds = partIds[k];
                            usePartIds.push(Tools.randomGotOneArrayData(tmpPartIds));
                        }
                        mgrTip.showLoadingTip("cloth_crossing_loading");
                        avatar.fillByPartIds(usePartIds);
                        avatar.registerAllLoadEndCallback(() => {
                            mgrTip.hideLoadingTip("cloth_crossing_loading");
                            let aniIds = [
                                "zjm_bixin-zjm_bixin01",
                                "zjm_bixin-zjm_bixin02",
                                "zjm_maimeng-zjm_maimeng"
                            ];
                            avatar.playAnimation(Tools.randomGotOneArrayData(aniIds));
                            Timer.callLater(0.8, () => {
                                this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.toSeat);
                            }, this);
                        });
                    }, this);
                });
            }
            exeChangeCloth() { }
            outChangeCloth() { }
            inToSeat() {
                if (!!this.tailuoModel) {
                    this.tailuoModel.destroy();
                    this.tailuoModel = null;
                }
                let callback = () => {
                    let avatar = this.bSuccess ? this.avatar : this.avatarEnemy;
                    let avatarFaild = this.bSuccess ? this.avatarEnemy : this.avatar;
                    let avatarNodeSuccess = this.bSuccess ? this.mapAvatarNode : this.avatarEnemyNode;
                    avatarFaild.registerLoadEndCallback(() => {
                        avatarFaild.playAnimation("paoku_kuqi-paoku_kuqi", 0.1, null, null, true, true);
                    });
                    let effCray = mgrLoader.Pool.getModel("117_e_loop_cry_01");
                    if (!!effCray) {
                        avatarFaild.linkMode2EffectHead(effCray);
                        effCray.transform.position = new Laya.Vector3(effCray.transform.position.x - 0.11, effCray.transform.position.y - 0.2, effCray.transform.position.z - 0.05);
                        effCray.transform.localRotationEulerY = 90;
                        this.avatarCrayEff = effCray;
                    }
                    let avatarPlayerPos = avatarNodeSuccess.transform.localPosition.clone();
                    let showNode = this.seatRoadNode.getChildByName("seat_player");
                    let offsetPosAvatar = new Laya.Vector3;
                    Laya.Vector3.subtract(showNode.transform.position, avatarNodeSuccess.transform.position, offsetPosAvatar);
                    avatar.transform.localRotationEulerY = -90;
                    avatar.registerLoadEndCallback(() => {
                        avatar.playAnimation("paoku_walk-paoku_walk", 0, null, null, true, true);
                    });
                    let walkTimer = Timer.callLoop(0.8, () => {
                        mgrSound.play(166);
                    }, this);
                    this.bAutoSyncCameraForSeat = true;
                    cc.tween(avatarNodeSuccess.transform, true)
                        .to(1, { localPositionX: avatarPlayerPos.x + offsetPosAvatar.x, localPositionY: avatarPlayerPos.y, localPositionZ: avatarPlayerPos.z + offsetPosAvatar.z })
                        .to(0.3, { localPositionY: 0.1 })
                        .call(() => {
                        cc.tween(avatar.transform, true).to(0.3, { localRotationEulerY: 90 }).start();
                    })
                        .delay(0.3)
                        .call(() => {
                        walkTimer.stop();
                        walkTimer = null;
                        this.bAutoSyncCameraForSeat = false;
                        avatar.transform.localRotationEulerY = 90;
                        avatar.hideShadow();
                        avatar.playDefaultIdleAnimation();
                        avatar.registerLoadEndCallback(() => {
                            avatar.playAnimation(["paoku_shengli-paoku_zuoxia", "paoku_shengli-paoku_shengli"], 0, null, null, true, true);
                        });
                        mgrSound.play(Tools.randomGotOneArrayData([126, 127]));
                        Timer.callLater(0.5, () => {
                            mgrSound.play(149);
                            this.add3DEffectAtFront("e_yanhua_05", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 });
                        }, this);
                        Timer.callLater(2, () => {
                            this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.reward);
                        }, this);
                    })
                        .start();
                };
                Timer.callLater(0.2, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    callback();
                }, this);
            }
            exeToSeat() {
                if (this.bAutoSyncCameraForSeat) {
                    let avatarNodeSuccess = this.bSuccess ? this.mapAvatarNode : this.avatarEnemyNode;
                    this.mapSky.transform.position = this.mapAvatarNode.transform.position;
                    let centerNode = this.seatRoadNode.getChildByName("center");
                    let param = this.avatarPosCameraDict[5].cameraData;
                    this.cameraFollow.position = new Laya.Vector3(param.pos.x + avatarNodeSuccess.transform.position.x - 1, param.pos.y + centerNode.transform.position.y, param.pos.z + centerNode.transform.position.z);
                }
            }
            outToSeat() { }
            inNextTurnReady() { }
            exeNextTurnReady() { }
            outNextTurnReady() { }
            inRestartCurrTurn() { }
            exeRestartCurrTurn() { }
            outRestartCurrTurn() { }
            inReward() {
                let avatarFaild = this.bSuccess ? this.avatarEnemy : this.avatar;
                this.spritePlayerFightPowerContainer.alpha = 0;
                this.spriteEnemyFightPowerContainer.alpha = 0;
                this.spriteTitleSuccess.visible = !!this.bSuccess;
                this.spriteTitleFaild.visible = !this.spriteTitleSuccess.visible;
                this.spriteTitle.visible = true;
                this.spriteTitle.scale(3, 3, true);
                cc.tween(this.spriteTitle).toScale(0.1, 1)
                    .call(() => {
                    if (!!this.bSuccess) {
                        mgrSound.play(312);
                    }
                    else {
                        mgrSound.play(313);
                    }
                    avatarFaild.registerLoadEndCallback(() => {
                        avatarFaild.playAnimation("paoku_kuqi-paoku_kuqi", 0.1, null, null, true, true);
                    });
                })
                    .delay(0.5)
                    .call(() => {
                    Tools.takeAPhoto(512, 512, this.cameraBack, (tex2d) => {
                        avatarFaild.registerLoadEndCallback(() => {
                            avatarFaild.playAnimation("paoku_kuqi-paoku_kuqi", 0.1, null, null, true, true);
                        });
                        this.shareTex2d = tex2d;
                        let rewardColorPoint = 0;
                        if (this.bSuccess) {
                            rewardColorPoint = this.stageData.bestRewardColorPoint;
                        }
                        else {
                            rewardColorPoint = this.stageData.goodRewardColorPoint;
                        }
                        if (this.bSuccess) {
                            let gameWorldDailyData = mgrCfg.get_from_cloth_crossing_daily_quest_config(mgrWorldDaily.getWorldDay()) || mgrCfg.get_from_cloth_crossing_daily_quest_config(1);
                            mgrPlayer.addItemAmount(gameWorldDailyData.rewardItemId, gameWorldDailyData.rewardItemAmount, "女神挑战赛结算奖励");
                        }
                        this.oldColorPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_CLOTH_CROSSING_COLOR);
                        this.currGotColorPoint = rewardColorPoint;
                        mgrPlayer.addItemAmount(Const.ITEM_ID_CLOTH_CROSSING_COLOR, rewardColorPoint, "女神挑战赛结算奖励");
                        this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.palette);
                    }, Laya.RenderTextureFormat.R8G8B8A8);
                })
                    .start();
            }
            exeReward() { }
            outReward() { }
            trySaveCard(callback) {
                if (!this.bSuccess) {
                    callback && callback();
                    return;
                }
                let partIds = this.avatar.getPartIds(true);
                let bContained = false;
                let allCards = mgrCard.getAllPlayerCardInfo();
                if (allCards && allCards.length > 0) {
                    for (let k in allCards) {
                        let dataCard = allCards[k];
                        if (dataCard && Tools.isEqualArr(dataCard.partIds, partIds)) {
                            bContained = true;
                            break;
                        }
                    }
                }
                if (!!bContained) {
                    callback && callback();
                    return;
                }
                Tools.takeAPhoto(Const.CARD_PHOTO_SIZE.width * 3, Const.CARD_PHOTO_SIZE.height * 3, this.cameraBack, (tex2d) => {
                    let showTex2d = tex2d;
                    Tools.takeAPhoto(Const.CARD_PHOTO_SIZE.width, Const.CARD_PHOTO_SIZE.height, this.cameraBack, (tex2d) => {
                        let roleId = this.avatar.getRoleId();
                        let styleId = Tools.randomGotOneArrayData(this.stageData.successCardStyles);
                        let styleData = mgrCfg.get_from_amuse_card_style_db(styleId);
                        let power = mgrCard.calculateRolePartIdsPower(roleId, partIds);
                        power = power + styleData.addPower;
                        let hp = mgrCard.calculateRolePartIdsHp(roleId, partIds);
                        mgrDirector.openDialog("vAmuseClothCrossingCardSaveDialog", {
                            tex2d: showTex2d,
                            roleId: roleId,
                            styleId: styleId,
                            power: power,
                            fOnAdResult: (bDoSave, cardId) => {
                                if (!!bDoSave) {
                                    let textureKey = mgrCard.getRoleCardTextureKeyNameByCardId(cardId);
                                    mgrRole.savePhoto(textureKey, tex2d);
                                    mgrCard.setPlayerCardInfo(cardId, roleId, styleId, textureKey, power, hp, partIds);
                                    callback && callback();
                                }
                                else {
                                    callback && callback();
                                }
                            }
                        });
                    }, Laya.RenderTextureFormat.R8G8B8A8, Laya.TextureFormat.R8G8B8A8);
                }, Laya.RenderTextureFormat.R8G8B8A8, Laya.TextureFormat.R8G8B8A8);
            }
            inPalette() {
                let gotCoinFunc = () => {
                    let rewardRmb = !!this.bSuccess ? this.stageData.bestRewardRmbAmount : this.stageData.goodRewardRmbAmount;
                    let moonCakeAmount = !!this.bSuccess ? this.stageData.successMoonCakeAmount : this.stageData.failMoonCakeAmount;
                    rewardRmb += this.gotMlbCount;
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, rewardRmb, "女神挑战赛结算奖励");
                    mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, rewardRmb, null, {
                        fOnClose: () => {
                            let partId = mgrWorldDaily.getUnownedVipPart(DailyGameType.clothcrossing);
                            if (!!partId && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment) && (Tools.random(0, 100) <= mgrSdk.getCopNumberValueByKey("surprise_crossing_ratio"))) {
                                mgrDirector.openDialog("vSurpriseRewardDialog", {
                                    bVip: false,
                                    partId,
                                    fOnClose: () => {
                                        if (mgrMidAutumn.isEnable() && !!moonCakeAmount) {
                                            mgrPlayer.addItemAmount(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, "蛋糕结算月饼奖励");
                                            mgrTip.addGotItemTip(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, null, {
                                                fOnClose: () => {
                                                    this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.finish);
                                                }
                                            });
                                        }
                                        else {
                                            this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.finish);
                                        }
                                    }
                                });
                            }
                            else {
                                if (mgrMidAutumn.isEnable() && !!moonCakeAmount) {
                                    mgrPlayer.addItemAmount(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, "蛋糕结算月饼奖励");
                                    mgrTip.addGotItemTip(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, null, {
                                        fOnClose: () => {
                                            this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.finish);
                                        }
                                    });
                                }
                                else {
                                    this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.finish);
                                }
                            }
                        }
                    });
                };
                if (!this.bSuccess) {
                    gotCoinFunc();
                }
                else {
                    let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.clothcrossing);
                    if (!rewardPartId) {
                        gotCoinFunc();
                        return;
                    }
                    mgrDirector.openDialog("vAmuseCakeResultDialog", {
                        colorItemId: Const.ITEM_ID_CLOTH_CROSSING_COLOR,
                        oldColorPoint: this.oldColorPoint,
                        currGotColorPoint: this.currGotColorPoint,
                        dailyGameType: DailyGameType.clothcrossing,
                        bSuccess: this.bSuccess,
                        rewardPartId: rewardPartId,
                        fOnClose: () => {
                            gotCoinFunc();
                        }
                    });
                }
            }
            exePalette() { }
            outPalette() { }
            inFinish() {
                let callback = () => {
                    this.stageData.statisPointId && mgrSdk.statisOnStageEnd(`${this.stageData.statisPointId}`, this.bSuccess ? 1 : 0, `${this.stageData.id}`);
                    mgrVideoRecorder.stopRecord();
                    mgrTip.tryShowPhotoShare("vAmuseClothCrossingScene", this.shareTex2d, null, () => {
                        this.stManager.stopUpdate();
                        mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene", {
                            bSuccess: this.bSuccess,
                            dailyGameType: DailyGameType.clothcrossing,
                            bFromGameResult: true
                        });
                    });
                };
                this.trySaveCard(callback);
            }
            exeFinish() { }
            outFinish() { }
            onClickAni(index) {
                let template = mgrCfg.get_from_amuse_cloth_crossing_photo_recipe_db(index);
                if (template.bAd && mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vAmuseClothCrossingScene_trial_ani)) {
                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseClothCrossingScene_trial_ani, { index: index }, true);
                }
                else {
                    this.doClickAni(index);
                }
            }
            doClickAni(index) {
                this.spriteAniContainer.visible = false;
                let template = mgrCfg.get_from_amuse_cloth_crossing_photo_recipe_db(index);
                this.playerShowAniName = template.aniName;
                this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.checkResultSuccess);
            }
            onShowedScore() {
                this.spriteScoreContainer.visible = false;
                let bPlayerShowing = this.stManager.getCurState() == AMUSE_CLOTH_CROSSING_STATE.playerShow ? true : false;
                let avatar = bPlayerShowing ? this.avatar : this.avatarEnemy;
                let avatarNode = bPlayerShowing ? this.mapAvatarNode : this.avatarEnemyNode;
                if (bPlayerShowing) {
                    mgrSound.play(this.bSuccess ? 127 : 139);
                }
                else {
                    mgrSound.play(!this.bSuccess ? 127 : 139);
                }
                let offsetX = bPlayerShowing ? this.LANDING_POS_X_OFFSET : -this.LANDING_POS_X_OFFSET;
                let centerNode = this.seatRoadNode.getChildByName("center");
                let avatarPlayerPos = avatarNode.transform.localPosition.clone();
                let offsetPosAvatar = new Laya.Vector3;
                Laya.Vector3.subtract(centerNode.transform.position, avatarNode.transform.position, offsetPosAvatar);
                avatar.registerLoadEndCallback(() => {
                    avatar.playAnimation("paoku_walk-paoku_walk", 0, null, null, true, true);
                });
                avatar.transform.localRotationEulerY = -90;
                cc.tween(avatarNode.transform, true)
                    .to(1, { localPositionX: avatarPlayerPos.x + offsetPosAvatar.x, localPositionY: avatarPlayerPos.y, localPositionZ: avatarPlayerPos.z + offsetPosAvatar.z + offsetX })
                    .to(0.3, { localPositionY: 0.1 })
                    .call(() => {
                    cc.tween(avatar.transform, true).to(0.3, { localRotationEulerY: 90 }).start();
                })
                    .delay(0.4)
                    .call(() => {
                    avatar.playDefaultIdleAnimation();
                    avatar.transform.localRotationEulerY = 90;
                    if (bPlayerShowing) {
                        this.labelPlayerTotalPower.text = `${this.bSuccess ? this.successTotalScore : this.faildTotalScore}`;
                        cc.tween(this.spritePlayerFightPowerContainer).toAlpha(0.1, 1).start();
                        this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.enemyShow);
                    }
                    else {
                        this.labelEnemyTotalPower.text = `${!this.bSuccess ? this.successTotalScore : this.faildTotalScore}`;
                        cc.tween(this.spriteEnemyFightPowerContainer).toAlpha(0.1, 1).start();
                        this.stManager.setNextState(AMUSE_CLOTH_CROSSING_STATE.changeCloth);
                    }
                })
                    .start();
            }
            onClosed() {
                if (!!this.cameraBack) {
                    this.cameraBack.useOcclusionCulling = false;
                    let define = Laya.Scene3DShaderDeclaration[`SHADERDEFINE_FARPLANEWORLDPOSITIONZ`];
                    if (!!this.cameraBack.scene && !!this.cameraBack.scene._shaderValues && !!define) {
                        this.cameraBack.scene._shaderValues.removeDefine(define);
                    }
                }
                this.cleanModels();
                super.onClosed();
                mgrTip.hideLoadingTip("cloth_crossing_loading");
                mgrTip.hideLoadingTip("cloth_crossing_fly_prepare");
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene");
            }
            onTouchButtonAni1() {
                this.onClickAni(1);
            }
            onTouchButtonAni2() {
                this.onClickAni(2);
            }
            onTouchButtonAni3() {
                this.onClickAni(3);
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vAmuseClothCrossingScene_trial_ani) {
                    this.playerGotScore += this.stageData.videoAddScore;
                    this.doClickAni(e.userData.index);
                }
            }
        }

        var AMUSE_FASHION_PEN_STATE;
        (function (AMUSE_FASHION_PEN_STATE) {
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["init"] = 1] = "init";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["modeSelect"] = 2] = "modeSelect";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["waitStart"] = 3] = "waitStart";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["backCount"] = 4] = "backCount";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["turnReady"] = 5] = "turnReady";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["avatarComing"] = 6] = "avatarComing";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["avatarMoving"] = 7] = "avatarMoving";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["nextTurnReady"] = 8] = "nextTurnReady";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["hitWallDie"] = 9] = "hitWallDie";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["prickDie"] = 10] = "prickDie";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["singleBarDie"] = 11] = "singleBarDie";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["doubleBarDie"] = 12] = "doubleBarDie";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["dieComplete"] = 13] = "dieComplete";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["restartCurrTurn"] = 14] = "restartCurrTurn";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["arrivedDest"] = 15] = "arrivedDest";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["arrivedShow"] = 16] = "arrivedShow";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["fillColor"] = 17] = "fillColor";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["palette"] = 18] = "palette";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["judged"] = 19] = "judged";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["judgedShow"] = 20] = "judgedShow";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["success"] = 21] = "success";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["reward"] = 22] = "reward";
            AMUSE_FASHION_PEN_STATE[AMUSE_FASHION_PEN_STATE["finish"] = 23] = "finish";
        })(AMUSE_FASHION_PEN_STATE || (AMUSE_FASHION_PEN_STATE = {}));
        class vAmuseFashionPenScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseFashionPenScene";
                this.exportNodeNames = [];
                this.DIE_ANIMATION_ID_ARR = [
                    FASHION_SHOW_MOV.movLose01,
                    FASHION_SHOW_MOV.movLose02,
                    FASHION_SHOW_MOV.movLose03,
                ];
                this.DIE_ANIMATION_ID_BEST_LEFT = FASHION_SHOW_MOV.movLose05;
                this.DIE_ANIMATION_ID_BEST_RIGHT = FASHION_SHOW_MOV.movLose04;
                this.SINGLE_BAR_ANIMATION_ID_ARR = FASHION_SHOW_MOV.movLose01;
                this.avatarPosCameraDict = {
                    [0]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(-15, 0, 0)
                        },
                        cameraData: {
                            fov: 60,
                            pos: new Laya.Vector3(0, 1.06, 2),
                            rot: new Laya.Vector3(-5, 0, 0),
                        }
                    },
                    [1]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(-15, 0, 0)
                        },
                        cameraData: {
                            fov: 70,
                            pos: new Laya.Vector3(0, 3.26, 2.6),
                            rot: new Laya.Vector3(-32, 0, 0),
                        }
                    },
                    [3]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(0, 0, 0)
                        },
                        cameraData: {
                            fov: 54,
                            pos: new Laya.Vector3(0.06 - 0, 2.59 - 1.59, -36.65 - (-38.14)),
                            rot: new Laya.Vector3(-8, 0, 0),
                        }
                    },
                    [4]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(0, 0, 0)
                        },
                        cameraData: {
                            fov: 54,
                            pos: new Laya.Vector3(-0.4, 1.45, 0.18),
                            rot: new Laya.Vector3(-5, -173, 0),
                        }
                    },
                    [5]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(0, 0, 0)
                        },
                        cameraData: {
                            fov: 54,
                            pos: new Laya.Vector3(-1.79 - (-2), 2.63 - 1.59, -36.59 - (-37.82)),
                            rot: new Laya.Vector3(0, 9, 0),
                        }
                    },
                    [6]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(0, 0, 0)
                        },
                        cameraData: {
                            fov: 54,
                            pos: new Laya.Vector3(1.64 - (2), 2.73 - 1.59, -36.54 - (-37.82)),
                            rot: new Laya.Vector3(-6, -15, 0),
                        }
                    },
                };
                this.MOVE_END_CAMERA_DATA = {
                    fov: 49,
                    pos: new Laya.Vector3(0, 1.25, 7.88),
                    rot: new Laya.Vector3(-8, -1, 0)
                };
                this.VIDEO_AMAZE_FSHOE_UNLOCK_SUPER_MODE = "video_amaze_fshoe_unlock_super_mode";
                this.avatar = null;
                this.wallRowNodesArr = [];
                this.wallGlassRowNodesArr = [];
                this.wallAnimatorRowNodesArr = [];
                this.goldRowNodesArr = [];
                this.diamondRowNodesArr = [];
                this.shoeRowNodesArr = [];
                this.ladderRowNodesArr = [];
                this.prickRowNodesArr = [];
                this.singleBarRowNodesArr = [];
                this.doubleBarRowNodesArr = [];
                this.elevatorRowNodesArr = [];
                this.baseRoadRowNodesArr = [];
                this.baseRoadXCheckNodesArr = [];
                this.propsType1NodesArr = [];
                this.propsType2NodesArr = [];
                this.propsType3NodesArr = [];
                this.propsType4NodesArr = [];
                this.propsType5NodesArr = [];
                this.invincibleNodesArr = [];
                this.PEN_COLOR_SIZE_Z = 4;
                this.ROAD_LINE_COUNT = 33;
                this.ROAD_COLOR_LINE_COUNT = 21;
                this.ROAD_ROW_COUNT = 10;
                this.BOX_WH = 0.1;
                this.COLLIDE_WALL_Z_DIS = 0.5;
                this.WALL_GLASS_CHECK_DIS = 4;
                this.ANIMATION_BOX_PLAY_CHECK_DIS = 2;
                this.avatarGotShoeBoxArr = [];
                this.ladderStep = 0;
                this.MOVE_FPS = 1;
                this.MOVE_FPS_DIRECTION = 2;
                this.PER_BOX_DOWN_TIME = 0.4;
                this.avatarDirectionType = 0;
                this.AVATAR_DIRECTION_STAY = 0;
                this.AVATAR_DIRECTION_LEFT = -1;
                this.AVATAR_DIRECTION_RIGHT = 1;
                this.cameraWithAvatarZDiffDis = 0;
                this.AVATAR_TEACHER_ROLE_ID = 114;
                this.AVATAR_TEACHER_ROLE_ID2 = 116;
                this.elevatorChangeInfo = [];
                this.EFFECT_MODEL_ID_TEACHER_AN = "e_pingwei_an";
                this.TOUCH_MAX_DISTANCE = 200;
                this.PROPS_INDEX_2_EFFECT_NAME_DICT = {
                    [1]: "e_daoju_yinfu_glow",
                    [2]: "e_daoju_rose_glow",
                    [3]: "e_daoju_huaban_glow",
                    [4]: "e_daoju_star_glow",
                    [5]: "e_daoju_snow_glow",
                };
                this.roleEffectDict = {};
                this.touchBgBeginAvatarPosX = 0;
                this.touchBgBeginAvatarRotEulerZ = 0;
                this.BAR_TYPE_NONE = 0;
                this.BAR_TYPE_SINGLE = 1;
                this.BAR_TYPE_DOUBLE = 2;
                this.SINGLE_DIE_ROTATION = 30;
                this.SINGLE_BAR_OBLIQUE_ROTATION_PER_FRAME = 0.3;
                this.singleBarMapAvatarRotZ = 0;
                this.currBarFinishPositionZ = 0;
                this.currBarType = 0;
                this.currSingleBarObliqueFlag = 1;
                this.STAGE_MODE_NONE = 0;
                this.STAGE_MODE_COMMON = 1;
                this.STAGE_MODE_SUPER = 2;
                this.addedWallForReplacedArr = [];
                this.addedPrickForReplacedArr = [];
                this.elevatorPositionY = 0;
                this.currSingleBarX = 0;
                this.INVINCIBLE_FPS_RATIO = 3;
                this.CAMERA_INVINCIBLE_POSITION_OFFSET = new Laya.Vector3(0, -0.6, -1.5);
                this.penColorModelDict = {};
                this.roadIndex2PenColorIndexDict = {};
                this.baseRoadPosition = new Laya.Vector3;
                this.checkPenOverRoadX = 0;
                this.lastTouchResultMapAvatarPositionX = 0;
            }
            getPreLoadModelIds() {
                let preloadModelId = [
                    "pen_stage_sky",
                    "bi",
                    "fashion_shoe_stage_splash",
                    "e_daoju_wudi",
                    "e_explode",
                    "e_daoju_ex",
                    "e_huadong_smoke",
                    "pen_color",
                    "e_yanhua_ningxueyan",
                    "e_yanhua_09",
                    "jiesuanhe",
                    "boli_parts"
                ];
                for (let k in this.PROPS_INDEX_2_EFFECT_NAME_DICT) {
                    preloadModelId.push(this.PROPS_INDEX_2_EFFECT_NAME_DICT[k]);
                }
                if (this.EFFECT_MODEL_ID_TEACHER_AN && this.EFFECT_MODEL_ID_TEACHER_AN != "") {
                    preloadModelId.push(this.EFFECT_MODEL_ID_TEACHER_AN);
                }
                return preloadModelId;
            }
            getPreLoadAnimationIds() {
                return [
                    "paoku_idle-paoku_idle",
                    "paoku_move-paoku_fly",
                    "paoku_move-paoku_run",
                    "paoku_move-paoku_zhuang",
                    "paoku_shibai-paoku_shibai",
                    "paoku_shifa-paoku_shifa",
                ];
            }
            getPreLoadImagePaths() {
                return [
                    "res/ui/amuse_cake_result/sprite_palette.png"
                ];
            }
            onOpened() {
                super.onOpened();
                mgrSound.play(5);
                if (mgrGuide.isFinished(2900)) {
                    mgrSound.play(689);
                }
                this.boxGameContainer.visible = false;
                this.buttonBack.__node.visible = false;
                this.spriteTitle.visible = false;
                this.buildScene(() => {
                    this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                    this.cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                    let param = this.avatarPosCameraDict[0].cameraData;
                    this.cameraFollow.position = param.pos.clone();
                    this.cameraFollow.endRotation = param.rot.clone();
                    this.cameraFollow.fov = param.fov;
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                    this.widget();
                    this.stManager = new FSMObject;
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.waitStart, this.inWaitStart.bind(this), this.exeWaitStart.bind(this), this.outWaitStart.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.modeSelect, this.inModeSelect.bind(this), this.exeModeSelect.bind(this), this.outModeSelect.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.backCount, this.inBackCount.bind(this), this.exeBackCount.bind(this), this.outBackCount.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.turnReady, this.inTurnReady.bind(this), this.exeTurnReady.bind(this), this.outTurnReady.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.avatarComing, this.inAvatarComing.bind(this), this.exeAvatarComing.bind(this), this.outAvatarComing.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.avatarMoving, this.inAvatarMoving.bind(this), this.exeAvatarMoving.bind(this), this.outAvatarMoving.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.nextTurnReady, this.inNextTurnReady.bind(this), this.exeNextTurnReady.bind(this), this.outNextTurnReady.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.hitWallDie, this.inHitWallDie.bind(this), this.exeHitWallDie.bind(this), this.outHitWallDie.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.prickDie, this.inPrickDie.bind(this), this.exePrickDie.bind(this), this.outPrickDie.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.singleBarDie, this.inSingleBarDie.bind(this), this.exeSingleBarDie.bind(this), this.outSingleBarDie.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.doubleBarDie, this.inDoubleBarDie.bind(this), this.exeDoubleBarDie.bind(this), this.outDoubleBarDie.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.dieComplete, this.inDieComplete.bind(this), this.exeDieComplete.bind(this), this.outDieComplete.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.restartCurrTurn, this.inRestartCurrTurn.bind(this), this.exeRestartCurrTurn.bind(this), this.outRestartCurrTurn.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.arrivedDest, this.inArrivedDest.bind(this), this.exeArrivedDest.bind(this), this.outArrivedDest.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.fillColor, this.inFillColor.bind(this), this.exeFillColor.bind(this), this.outFillColor.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.palette, this.inPalette.bind(this), this.exePalette.bind(this), this.outPalette.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.judgedShow, this.inJudgedShow.bind(this), this.exeJudgedShow.bind(this), this.outJudgedShow.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.arrivedShow, this.inArrivedShow.bind(this), this.exeArrivedShow.bind(this), this.outArrivedShow.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.judged, this.inJudged.bind(this), this.exeJudged.bind(this), this.outJudged.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.success, this.inSuccess.bind(this), this.exeSuccess.bind(this), this.outSuccess.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.reward, this.inReward.bind(this), this.exeReward.bind(this), this.outReward.bind(this));
                    this.stManager.registerState(AMUSE_FASHION_PEN_STATE.finish, this.inFinish.bind(this), this.exeFinish.bind(this), this.outFinish.bind(this));
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.init);
                    this.stManager.startUpdate(this, this.onTimerLoop.bind(this));
                    this.registerListeners({});
                });
            }
            changeStageFog(bFog) {
                if (!this.mapFog) {
                    return;
                }
                this.mapFog.active = !!bFog;
                this.mapFog.transform.localPositionZ = -2;
            }
            modeUiActionIn() {
                this.boxGameContainer.visible = false;
                this.buttonBack.__node.visible = false;
                this.buttonBack.__node.visible = true;
                cc.tween(this.buttonBack.__node).toScale(0.2, 1, cc.Ease.backOut).start();
            }
            gameUiActionIn() {
                this.boxGameContainer.visible = true;
                this.buttonBack.__node.visible = false;
                this.buttonBack.__node.visible = true;
                cc.tween(this.buttonBack.__node).toScale(0.2, 1, cc.Ease.backOut).start();
            }
            onClosed() {
                this.cameraBack.useOcclusionCulling = true;
                mgrTip.hideLoadingTip("vAmuseTShowAvatarComing");
                this.cleanStageMapNode();
                if (this.avatar) {
                    this.avatar.destroy();
                }
                this.avatar = null;
                super.onClosed();
                mgrVideoRecorder.stopRecord();
            }
            onTimerLoop() {
                if (!this.mapSky && this.mapSky.destroyed) {
                    return;
                }
                this.singleBarHandler();
                this.doubleBarHandler();
                this.elevatorHandler();
                this.penColorHandler();
            }
            tryResetBarData() {
                this.currBarType = this.BAR_TYPE_NONE;
                this.currBarFinishPositionZ = 0;
                this.singleBarMapAvatarRotZ = 0;
                this.touchBgBeginAvatarRotEulerZ = 0;
                this.touchBgBeginPos = this.lastTouchBgPos;
                if (this.mapAvatarNode && !this.mapAvatarNode.destroyed) {
                    this.touchBgBeginAvatarPosX = this.mapAvatarNode.transform.localPositionX - this.baseRoadPosition.x;
                }
                this.doubleBarRoadLineArr = [];
                if (this.effHudongSmokeDoubleBar1) {
                    mgrLoader.Pool.recoverModel(this.effHudongSmokeDoubleBar1);
                    this.effHudongSmokeDoubleBar1 = null;
                }
                if (this.effHudongSmokeDoubleBar2) {
                    mgrLoader.Pool.recoverModel(this.effHudongSmokeDoubleBar2);
                    this.effHudongSmokeDoubleBar2 = null;
                }
            }
            singleBarHandler() {
                if (this.stManager.getCurState() != AMUSE_FASHION_PEN_STATE.avatarMoving || this.currBarType != this.BAR_TYPE_SINGLE || !this.mapAvatarNode || this.mapAvatarNode.destroyed) {
                    return;
                }
                if (this.mapAvatarNode.transform.position.z <= this.currBarFinishPositionZ) {
                    this.tryResetBarData();
                    if (!this.bInvincible) {
                        this.avatar.playAnimation(this.getAvatarRealAnimationId(this.avatar.context.roleId, FASHION_SHOW_MOV.movWalk), 0, null, null, true, true);
                    }
                    if (this.mapAvatarNode && !this.mapAvatarNode.destroyed) {
                        cc.tween(this.mapAvatarNode.transform).to(0.1, { localRotationEulerZ: 0 }).start();
                    }
                    if (!!this.avatar && !this.avatar.destroyed) {
                    }
                    return;
                }
                if (this.bInvincible) {
                    this.singleBarMapAvatarRotZ = 0;
                    this.touchBgBeginAvatarRotEulerZ = 0;
                    this.mapAvatarNode.transform.localPositionX = this.currSingleBarX || 0;
                    return;
                }
                if (!!this.mapAvatarNode.transform.localRotationEulerZ) {
                    this.currSingleBarObliqueFlag = this.mapAvatarNode.transform.localRotationEulerZ > 0 ? 1 : -1;
                }
                let addValue = this.currSingleBarObliqueFlag * this.SINGLE_BAR_OBLIQUE_ROTATION_PER_FRAME;
                this.singleBarMapAvatarRotZ = addValue;
                this.touchBgBeginAvatarRotEulerZ += addValue;
                if (Math.abs(this.mapAvatarNode.transform.localRotationEulerZ) > this.SINGLE_DIE_ROTATION) {
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.singleBarDie);
                }
            }
            doubleBarHandler() {
                if (this.stManager.getCurState() != AMUSE_FASHION_PEN_STATE.avatarMoving || this.currBarType != this.BAR_TYPE_DOUBLE || !this.mapAvatarNode || this.mapAvatarNode.destroyed) {
                    return;
                }
                if (this.mapAvatarNode.transform.position.z <= this.currBarFinishPositionZ) {
                    this.tryResetBarData();
                    if (!this.bInvincible) {
                        this.avatar.playAnimation(this.getAvatarRealAnimationId(this.avatar.context.roleId, FASHION_SHOW_MOV.movWalk), 0, null, null, true, true);
                    }
                    if (this.mapAvatarNode && !this.mapAvatarNode.destroyed) {
                        cc.tween(this.mapAvatarNode.transform).to(0.1, { localRotationEulerZ: 0 }).start();
                    }
                    if (!!this.avatar && !this.avatar.destroyed) {
                    }
                    return;
                }
                if (!this.doubleBarRoadLineArr) {
                    return;
                }
                let leftRoleLine = this.doubleBarRoadLineArr[0];
                let rightRoleLine = this.doubleBarRoadLineArr[1];
                let avatarPos = this.mapAvatarNode.transform.position;
                if (this.effHudongSmokeDoubleBar1 && !this.effHudongSmokeDoubleBar1.destroyed) {
                    this.effHudongSmokeDoubleBar1.transform.position = new Laya.Vector3(this.effHudongSmokeDoubleBar1.transform.position.x, avatarPos.y, avatarPos.z);
                }
                if (this.effHudongSmokeDoubleBar2 && !this.effHudongSmokeDoubleBar2.destroyed) {
                    this.effHudongSmokeDoubleBar2.transform.position = new Laya.Vector3(this.effHudongSmokeDoubleBar2.transform.position.x, avatarPos.y, avatarPos.z);
                }
                if (this.bInvincible) {
                    this.mapAvatarNode.transform.localPositionX = leftRoleLine + (rightRoleLine - leftRoleLine) / 2;
                    return;
                }
                let playerX = this.mapAvatarNode.transform.position.x;
                if (playerX > rightRoleLine || playerX < leftRoleLine) {
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.doubleBarDie);
                    return;
                }
            }
            elevatorHandler() {
                if (this.stManager.getCurState() != AMUSE_FASHION_PEN_STATE.avatarMoving || !this.elevatorChangeInfo || this.elevatorChangeInfo.length == 0 || !this.mapAvatarNode || this.mapAvatarNode.destroyed) {
                    return;
                }
                let elevatorBeginPos = this.elevatorChangeInfo[0];
                let elevatorEndPos = this.elevatorChangeInfo[1];
                let elevatorTotalDisZ = Math.abs(elevatorEndPos.z - elevatorBeginPos.z);
                let elevatorMovedDisZ = Math.abs(this.mapAvatarNode.transform.localPositionZ - elevatorBeginPos.z);
                let elevatorMovedPercent = elevatorMovedDisZ / (elevatorTotalDisZ || 1);
                this.elevatorPositionY = elevatorBeginPos.y + (elevatorEndPos.y - elevatorBeginPos.y) * elevatorMovedPercent;
                if (elevatorMovedPercent >= 1) {
                    this.elevatorChangeInfo = [];
                }
            }
            penColorHandler() {
                if (this.stManager.getCurState() != AMUSE_FASHION_PEN_STATE.avatarComing &&
                    this.stManager.getCurState() != AMUSE_FASHION_PEN_STATE.avatarMoving) {
                    return;
                }
                let currAvatarPos = this.mapAvatarNode.transform.position;
                let lastAvatarPosX = this.lastHandedPenInfo.avatarPos.x;
                let lastAvatarPosZ = this.lastHandedPenInfo.avatarPos.z;
                let endAvatarPosZ = currAvatarPos.z;
                for (let key in this.penColorModelDict) {
                    let config = this.penColorModelDict[key];
                    if (!config || !config.creamArr || config.creamArr.length == 0) {
                        continue;
                    }
                    let roadIndex = config.roadIndex;
                    let reuseMaxIndex = -1;
                    let creamArr = config.creamArr;
                    let penModelX = 0;
                    let penModel = null;
                    if (!!config.bUsing) {
                        for (let i = 0; i < this.avatarGotShoeBoxArr.length; i++) {
                            let tmpData = this.avatarGotShoeBoxArr[i];
                            if (tmpData.rowIndex != 0) {
                                continue;
                            }
                            if (tmpData.roadIndex == roadIndex) {
                                penModel = tmpData.penModel;
                                penModelX = penModel.transform.localPositionX + currAvatarPos.x;
                                break;
                            }
                        }
                    }
                    for (let index = 0; index < creamArr.length; index++) {
                        let creamData = creamArr[index];
                        let creamModelPosZ = creamData.model.transform.position.z;
                        if (currAvatarPos.z < creamModelPosZ && currAvatarPos.z > (creamModelPosZ - this.PEN_COLOR_SIZE_Z * 1.5)) {
                            let tmpPenInnerZ = currAvatarPos.z - creamModelPosZ;
                            let tmpLastPenInnerZ = lastAvatarPosZ - creamModelPosZ;
                            let showingPositionArr = creamData.showingPositionArr;
                            for (let i = 0; i < creamData.positionArr.length; i++) {
                                let originMeshPos = creamData.positionArr[i];
                                let shoingMeshPos = showingPositionArr[i];
                                let usePos = null;
                                if (penModel) {
                                    usePos = new Laya.Vector3(penModelX + originMeshPos.x, originMeshPos.y + this.ladderStep * this.BOX_WH + this.baseRoadPosition.y, shoingMeshPos.z);
                                }
                                usePos = usePos || new Laya.Vector3(this.baseRoadPosition.x);
                                if (originMeshPos.z <= tmpPenInnerZ) {
                                    if (Math.abs(tmpPenInnerZ - originMeshPos.z) < 0.01) {
                                        showingPositionArr[i] = usePos;
                                    }
                                    else {
                                        showingPositionArr[i].x = penModelX;
                                    }
                                }
                                else if (originMeshPos.z > tmpPenInnerZ && originMeshPos.z < tmpLastPenInnerZ) {
                                    showingPositionArr[i] = usePos;
                                }
                            }
                            creamData.showingPositionArr = showingPositionArr;
                            creamData.meshData["_setVerticeElementData"](showingPositionArr, Laya.VertexMesh.MESH_POSITION0);
                        }
                        else if (creamModelPosZ > endAvatarPosZ && Math.abs(creamModelPosZ - endAvatarPosZ) > this.PEN_COLOR_SIZE_Z * 2) {
                            reuseMaxIndex = Math.max(reuseMaxIndex, index);
                        }
                    }
                    if (reuseMaxIndex >= 0) {
                        let lastModelData = creamArr[creamArr.length - 1];
                        let deleteDataArr = creamArr.splice(0, reuseMaxIndex + 1);
                        for (let i = 0; i < deleteDataArr.length; i++) {
                            let modelData = deleteDataArr[i];
                            modelData.model.transform.position = new Laya.Vector3(0, lastModelData.model.transform.position.y, lastModelData.model.transform.position.z - (i + 1) * this.PEN_COLOR_SIZE_Z);
                            let showingPositionArr = [];
                            for (let i = 0; i < modelData.positionArr.length; i++) {
                                let tmpPos = modelData.positionArr[i];
                                showingPositionArr.push(new Laya.Vector3(penModelX, tmpPos.y, tmpPos.z));
                            }
                            modelData.showingPositionArr = showingPositionArr;
                            modelData.meshData["_setVerticeElementData"](showingPositionArr, Laya.VertexMesh.MESH_POSITION0);
                            creamArr.push(modelData);
                        }
                    }
                }
                this.lastHandedPenInfo = {
                    avatarPos: new Laya.Vector3(currAvatarPos.x, currAvatarPos.y, endAvatarPosZ)
                };
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
            }
            preinitData() {
                let stageId = this.context.stageId;
                if (!stageId) {
                    stageId = mgrAmaze.getCompletedPenStageId() + 1;
                }
                let data = mgrCfg.get_from_amaze_pen_stage_db(stageId);
                if (!data) {
                    data = mgrCfg.get_from_amaze_pen_stage_db(Tools.random(1, mgrAmaze.getCompletedPenStageId(AmusePenMode.common))) || mgrCfg.get_from_amaze_pen_stage_db(mgrAmaze.getCompletedPenStageId(AmusePenMode.common));
                }
                console.warn("-----pen stageId=", data.id);
                this.stageData = data;
                this.MOVE_FPS = this.stageData.moveFps || this.MOVE_FPS;
            }
            refreshUi() {
                this.refreshStageUi();
            }
            refreshStageUi() {
                let stageId = null;
                stageId = mgrAmaze.getPenShowingStageId() + 1;
            }
            buildScene(callback) {
                let mapSky = mgrLoader.Pool.getModel("pen_stage_sky");
                this.add3DEffectAtBack(mapSky, 0);
                this.mapSky = mapSky;
                this.cameraBack.useOcclusionCulling = false;
                callback && callback();
            }
            cleanReplacedWall() {
                let arr = this.addedWallForReplacedArr || [];
                let count = arr.length;
                for (let i = (count - 1); i >= 0; i--) {
                    let tmp = arr[i];
                    mgrLoader.Pool.recoverModel(tmp);
                }
                this.addedWallForReplacedArr = [];
            }
            cleanReplacedPrick() {
                let arr = this.addedPrickForReplacedArr || [];
                let count = arr.length;
                for (let i = (count - 1); i >= 0; i--) {
                    let tmp = arr[i];
                    mgrLoader.Pool.recoverModel(tmp);
                }
                this.addedPrickForReplacedArr = [];
            }
            cleanStageMapNode(bOnlyRestart) {
                if (!!this.wallRowBaseNodesArr) {
                    for (let i = 0; i < this.wallRowBaseNodesArr.length; i++) {
                        let row = this.wallRowBaseNodesArr[i];
                        if (row.name == "autoRotationY") {
                            cc.tween(row.transform).removeAllActions();
                            row.transform.localRotationEuler = new Laya.Vector3;
                        }
                    }
                }
                let wallArr = [this.wallRowNodesArr];
                for (let i = 0; i < wallArr.length; i++) {
                    let wallRowNodesArr = wallArr[i];
                    let countContainer = wallRowNodesArr.length;
                    for (let i = 0; i < countContainer; i++) {
                        let tmpBox = wallRowNodesArr[i];
                        cc.tween(tmpBox.transform).removeAllActions();
                        tmpBox.transform.localPosition = tmpBox["_originLocationPosition"] || tmpBox.transform.localPosition;
                        tmpBox.transform.localRotationEuler = tmpBox.transform.localRotationEuler;
                        tmpBox.transform.localScale = tmpBox["_originLocationScale"] || tmpBox.transform.localScale;
                    }
                }
                if (this.penColorModelDict) {
                    for (let key in this.penColorModelDict) {
                        let config = this.penColorModelDict[key];
                        if (!config || !config.creamArr || config.creamArr.length == 0) {
                            continue;
                        }
                        let creamArr = config.creamArr;
                        for (let index = 0; index < creamArr.length; index++) {
                            let creamData = creamArr[index];
                            creamData.meshData["_setVerticeElementData"](creamData.positionArr, Laya.VertexMesh.MESH_POSITION0);
                            mgrLoader.Pool.recoverModel(creamData.model);
                        }
                    }
                    this.penColorModelDict = {};
                }
                if (this.roleEffectDict) {
                    for (let k in this.roleEffectDict) {
                        let eff = this.roleEffectDict[k];
                        mgrLoader.Pool.recoverModel(eff);
                    }
                    this.roleEffectDict = {};
                }
                if (this.mapStage) {
                    for (let i = 1; i <= 5; i++) {
                        let propsTypeNodes = this.mapStage.getChildByName(`propsType${i}Nodes`);
                        if (!propsTypeNodes) {
                            continue;
                        }
                        let propsName = this.PROPS_INDEX_2_EFFECT_NAME_DICT[i];
                        let numChildren = propsTypeNodes.numChildren;
                        for (let j = 0; j < numChildren; j++) {
                            let tmpNode = propsTypeNodes.getChildAt(j);
                            let customEffectNode = tmpNode.getChildByName(propsName);
                            if (customEffectNode) {
                                mgrLoader.Pool.recoverModel(customEffectNode);
                            }
                        }
                    }
                }
                if (this.effHudongSmokeDoubleBar1) {
                    mgrLoader.Pool.recoverModel(this.effHudongSmokeDoubleBar1);
                    this.effHudongSmokeDoubleBar1 = null;
                }
                if (this.effHudongSmokeDoubleBar2) {
                    mgrLoader.Pool.recoverModel(this.effHudongSmokeDoubleBar2);
                    this.effHudongSmokeDoubleBar2 = null;
                }
                if (this.eDaojuWudiModel) {
                    mgrLoader.Pool.recoverModel(this.eDaojuWudiModel);
                    this.eDaojuWudiModel = null;
                }
                if (this.eMapEffectOnStartStand) {
                    mgrLoader.Pool.recoverModel(this.eMapEffectOnStartStand);
                    this.eMapEffectOnStartStand = null;
                }
                if (this.avatar && this.avatar["huangGuanModel"]) {
                    this.avatar.unlinkModel(this.avatar["huangGuanModel"]);
                    delete this.avatar["huangGuanModel"];
                }
                if (this.avatarGotShoeBoxArr) {
                    let count = this.avatarGotShoeBoxArr.length;
                    for (let i = (count - 1); i >= 0; i--) {
                        let data = this.avatarGotShoeBoxArr[i];
                        let penModel = data.penModel;
                        mgrLoader.Pool.recoverModel(penModel);
                        this.avatarGotShoeBoxArr.splice(i, 1);
                    }
                }
                if (this.mapTmpNodeContainer) {
                    let numChildren = this.mapTmpNodeContainer.numChildren;
                    for (let i = (numChildren - 1); i >= 0; i--) {
                        let tmp = this.mapTmpNodeContainer.getChildAt(i);
                        mgrLoader.Pool.recoverModel(tmp);
                    }
                    this.mapTmpNodeContainer.destroy();
                    this.mapTmpNodeContainer = null;
                }
                if (!bOnlyRestart) {
                    if (this.avatar) {
                        this.avatar.destroy();
                        this.avatar = null;
                    }
                    if (this.mapAvatarNode) {
                        let numChildren = this.mapAvatarNode.numChildren;
                        for (let i = (numChildren - 1); i >= 0; i--) {
                            let tmp = this.mapAvatarNode.getChildAt(i);
                            mgrLoader.Pool.recoverModel(tmp);
                        }
                        this.mapAvatarNode.destroy();
                        this.mapAvatarNode = null;
                    }
                    this.finishNodeHolder = null;
                    this.successNodeHolder = null;
                    this.wallRowNodesArr = [];
                    this.wallGlassRowNodesArr = [];
                    this.wallAnimatorRowNodesArr = [];
                    this.goldRowNodesArr = [];
                    this.diamondRowNodesArr = [];
                    this.shoeRowNodesArr = [];
                    this.ladderRowNodesArr = [];
                    this.prickRowNodesArr = [];
                    this.singleBarRowNodesArr = [];
                    this.doubleBarRowNodesArr = [];
                    this.elevatorRowNodesArr = [];
                    this.baseRoadRowNodesArr = [];
                    this.baseRoadXCheckNodesArr = [];
                    this.propsType1NodesArr = [];
                    this.propsType2NodesArr = [];
                    this.propsType3NodesArr = [];
                    this.propsType4NodesArr = [];
                    this.propsType5NodesArr = [];
                    this.invincibleNodesArr = [];
                    this.wallRowBaseNodesArr = [];
                    this.replaceWallModelId = null;
                    this.replacePrickModelId = null;
                    this.bAvatarMovingReadyed = false;
                    this.lastTouchResultMapAvatarPositionX = 0;
                    this.cleanReplacedWall();
                    this.cleanReplacedPrick();
                    if (this.mapStage) {
                        mgrLoader.Pool.recoverModel(this.mapStage);
                        this.mapStage = null;
                    }
                }
                else {
                    this.mapAvatarNode.transform.localPosition = new Laya.Vector3;
                    this.mapAvatarNode.transform.localRotationEuler = new Laya.Vector3;
                    this.avatar.transform.localPosition = new Laya.Vector3;
                }
                this.elevatorChangeInfo = [];
                this.elevatorPositionY = 0;
                this.ladderStep = 0;
                this.collideredWallNode = null;
                this.touchBgBeginAvatarPosX = 0;
                this.touchBgBeginAvatarRotEulerZ = 0;
                this.lastTouchBgPos = null;
                this.avatarGotShoeBoxArr = [];
                this.avatarDirectionType = 0;
                this.cameraWithAvatarZDiffDis = 0;
                this.disableAdatPlayerYEndTime = 0;
                this.bInvincible = false;
                this.tryResetBarData();
                if (this.mapSky) {
                    this.mapSky.transform.position = new Laya.Vector3(0, 0, 0);
                }
                if (this.mapFog) {
                    this.mapFog.transform.position = new Laya.Vector3(0, 0, 1000);
                }
                if (this.cameraFollow) {
                    let param = this.avatarPosCameraDict[0].cameraData;
                    this.cameraFollow.position = param.pos.clone();
                    this.cameraFollow.endRotation = param.rot.clone();
                    this.cameraFollow.fov = param.fov;
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                }
            }
            genStageMap(callback) {
                this.cleanStageMapNode();
                mgrTip.showLoadingTip("fashionshoe_load_stage_map");
                this.add3DEffectAtBack(this.stageData.stageModelId, 0, (model) => {
                    mgrTip.hideLoadingTip("fashionshoe_load_stage_map");
                    this.mapStage = model;
                    this.changeStageFog(!!this.stageData.bFog);
                    this.initLoadedStageMapModel();
                    callback && callback();
                });
            }
            initLoadedStageMapModel() {
                let model = this.mapStage;
                let avatarNode = model.getChildByName("avatarNode");
                let wallNodes = model.getChildByName("wallNodes");
                let wallGlassNodes = model.getChildByName("wallGlassNodes");
                let wallAnimatorNodes = model.getChildByName("wallAnimatorNodes");
                let goldNodes = model.getChildByName("goldNodes");
                let diamondNodes = model.getChildByName("diamondNodes");
                let shoeNodes = model.getChildByName("shoeNodes");
                let ladderNodes = model.getChildByName("ladderNodes");
                let prickNodes = model.getChildByName("prickNodes");
                let singleBarNodes = model.getChildByName("singleBarNodes");
                let doubleBarNodes = model.getChildByName("doubleBarNodes");
                let elevatorNodes = model.getChildByName("elevatorNodes");
                let invincibleNodes = model.getChildByName(`invincibleNodes`);
                let mapNode = model.getChildByName("map");
                let finishNode = mapNode.getChildByName("finishNode");
                let successNode = mapNode.getChildByName("successNode");
                let baseRoadNodes = mapNode.getChildByName("baseRoadNodes");
                this.finishNodeHolder = finishNode;
                this.successNodeHolder = successNode;
                this.mapAvatarNode = new Laya.Sprite3D;
                this.mapAvatarNode.transform.position = avatarNode.transform.position;
                this.add3DEffectAtBack(this.mapAvatarNode, 0);
                this.mapTmpNodeContainer = new Laya.Sprite3D;
                this.add3DEffectAtBack(this.mapTmpNodeContainer, 0);
                let numChildren = 0;
                for (let i = 1; i <= 5; i++) {
                    let arr = this[`propsType${i}NodesArr`];
                    let propsTypeNodes = model.getChildByName(`propsType${i}Nodes`);
                    if (!propsTypeNodes) {
                        continue;
                    }
                    numChildren = propsTypeNodes.numChildren;
                    for (let j = 0; j < numChildren; j++) {
                        let tmpNode = propsTypeNodes.getChildAt(j);
                        tmpNode.active = true;
                        arr.push(tmpNode);
                    }
                }
                if (!!invincibleNodes) {
                    numChildren = invincibleNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = invincibleNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            this.invincibleNodesArr.push(tmpNode);
                        }
                    }
                }
                if (!!wallNodes) {
                    numChildren = wallNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = wallNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            this.wallRowNodesArr.push(tmpNode);
                        }
                        this.wallRowBaseNodesArr.push(rowNode);
                    }
                }
                if (!!wallGlassNodes) {
                    numChildren = wallGlassNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = wallGlassNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            this.wallGlassRowNodesArr.push(tmpNode);
                        }
                    }
                }
                if (!!wallAnimatorNodes) {
                    numChildren = wallAnimatorNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = wallAnimatorNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            let animator = tmpNode.getComponent(Laya.Animator);
                            if (!!animator) {
                                animator.speed = 1;
                                animator.play("idle");
                            }
                        }
                        this.wallAnimatorRowNodesArr.push(rowNode);
                    }
                }
                if (!!goldNodes) {
                    numChildren = goldNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = goldNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                        }
                        this.goldRowNodesArr.push(rowNode);
                    }
                }
                if (!!diamondNodes) {
                    numChildren = diamondNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = diamondNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                        }
                        this.diamondRowNodesArr.push(rowNode);
                    }
                }
                if (!!shoeNodes) {
                    numChildren = shoeNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = shoeNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            this.shoeRowNodesArr.push(tmpNode);
                        }
                    }
                }
                if (!!ladderNodes) {
                    numChildren = ladderNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = ladderNodes.getChildAt(i);
                        this.ladderRowNodesArr.push(rowNode);
                    }
                }
                if (!!prickNodes) {
                    numChildren = prickNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = prickNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                        }
                        this.prickRowNodesArr.push(rowNode);
                    }
                }
                if (!!singleBarNodes) {
                    numChildren = singleBarNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = singleBarNodes.getChildAt(i);
                        this.singleBarRowNodesArr.push(rowNode);
                    }
                }
                if (!!doubleBarNodes) {
                    numChildren = doubleBarNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = doubleBarNodes.getChildAt(i);
                        this.doubleBarRowNodesArr.push(rowNode);
                    }
                }
                if (!!elevatorNodes) {
                    numChildren = elevatorNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = elevatorNodes.getChildAt(i);
                        this.elevatorRowNodesArr.push(rowNode);
                    }
                }
                if (!!baseRoadNodes) {
                    numChildren = baseRoadNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let roadModel = baseRoadNodes.getChildAt(i);
                        let numChildren2 = roadModel.numChildren;
                        for (let j = 0; j < numChildren2; j++) {
                            let rowNode = roadModel.getChildAt(j);
                            rowNode.active = false;
                            if (rowNode.name == "_XCheckBase") {
                                let numChildren3 = rowNode.numChildren;
                                for (let tmp = 0; tmp < numChildren3; tmp++) {
                                    let tmpNode = rowNode.getChildAt(tmp);
                                    this.baseRoadXCheckNodesArr.push(tmpNode);
                                }
                                continue;
                            }
                            this.baseRoadRowNodesArr.push(rowNode);
                        }
                    }
                }
                this.changeRoadDir();
                this.adaptMapMaterial();
                this.restoreNodeStatus();
            }
            changeRoadDir() {
                let model = this.mapStage;
                let mapNode = model.getChildByName("map");
                let changeXTo2 = mapNode.getChildByName("changeXTo2");
                if (!changeXTo2) {
                    return;
                }
                changeXTo2.active = false;
                let creamModel = new Laya.MeshSprite3D(changeXTo2.meshFilter.sharedMesh.clone(), changeXTo2.name);
                let materialArr = [];
                let materialCount = changeXTo2.meshRenderer.sharedMaterials.length;
                for (let matIndex = 0; matIndex < materialCount; matIndex++) {
                    let oldMat = changeXTo2.meshRenderer.sharedMaterials[matIndex];
                    let mat = new Laya.UnlitMaterial();
                    mat.albedoTexture = oldMat.albedoTexture;
                    materialArr.push(mat);
                }
                creamModel.meshRenderer.sharedMaterials = materialArr;
                creamModel.transform.position = changeXTo2.transform.position.clone();
                creamModel.transform.rotationEuler = changeXTo2.transform.rotationEuler.clone();
                changeXTo2.parent.addChild(creamModel);
                let modelData = this.getModelMeshData(creamModel);
                let positionArr = modelData.positionArr;
                let len = 4;
                let offsetX = 2;
                let handledPosArr = [];
                for (let i = 0; i < positionArr.length; i++) {
                    let posModel = positionArr[i];
                    let tmpValue = cc.Ease.expoOut(posModel.y / len) * offsetX;
                    handledPosArr.push(new Laya.Vector3(posModel.x - tmpValue, posModel.y, posModel.z));
                }
                modelData.meshData["_setVerticeElementData"](Tools.deepCopy(handledPosArr), Laya.VertexMesh.MESH_POSITION0);
            }
            adaptMapMaterial() {
            }
            restoreNodeStatus() {
                let model = this.mapStage;
                let avatarNode = model.getChildByName("avatarNode");
                let wallNodes = model.getChildByName("wallNodes");
                let wallGlassNodes = model.getChildByName("wallGlassNodes");
                let wallAnimatorNodes = model.getChildByName("wallAnimatorNodes");
                let goldNodes = model.getChildByName("goldNodes");
                let diamondNodes = model.getChildByName("diamondNodes");
                let shoeNodes = model.getChildByName("shoeNodes");
                let ladderNodes = model.getChildByName("ladderNodes");
                let prickNodes = model.getChildByName("prickNodes");
                let singleBarNodes = model.getChildByName("singleBarNodes");
                let doubleBarNodes = model.getChildByName("doubleBarNodes");
                let elevatorNodes = model.getChildByName("elevatorNodes");
                let invincibleNodes = model.getChildByName(`invincibleNodes`);
                let numChildren = 0;
                for (let i = 1; i <= 5; i++) {
                    let propsTypeNodes = model.getChildByName(`propsType${i}Nodes`);
                    if (!propsTypeNodes) {
                        continue;
                    }
                    numChildren = propsTypeNodes.numChildren;
                    for (let j = 0; j < numChildren; j++) {
                        let tmpNode = propsTypeNodes.getChildAt(j);
                        tmpNode.active = true;
                        tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                        if (tmpNode["_originPos"]) {
                            tmpNode.transform.localPosition = tmpNode["_originPos"].clone();
                        }
                        if (tmpNode["_originRot"]) {
                            tmpNode.transform.localRotationEuler = tmpNode["_originRot"].clone();
                        }
                        delete tmpNode["_originPos"];
                        delete tmpNode["_originRot"];
                        delete tmpNode["_bHited"];
                    }
                }
                if (!!invincibleNodes) {
                    numChildren = invincibleNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = invincibleNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                            delete tmpNode["_bHited"];
                        }
                        delete rowNode["_bHited"];
                    }
                }
                if (!!wallNodes) {
                    numChildren = wallNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = wallNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                            if (tmpNode["_originPos"]) {
                                tmpNode.transform.localPosition = tmpNode["_originPos"].clone();
                            }
                            if (tmpNode["_originRot"]) {
                                tmpNode.transform.localRotationEuler = tmpNode["_originRot"].clone();
                            }
                            delete tmpNode["_originPos"];
                            delete tmpNode["_originRot"];
                            delete tmpNode["_relationCustomReplaceBox"];
                            delete tmpNode["_bHited"];
                        }
                        delete rowNode["_bHited"];
                    }
                }
                if (!!wallGlassNodes) {
                    numChildren = wallGlassNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = wallGlassNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                            if (tmpNode["_originPos"]) {
                                tmpNode.transform.localPosition = tmpNode["_originPos"].clone();
                            }
                            if (tmpNode["_originRot"]) {
                                tmpNode.transform.localRotationEuler = tmpNode["_originRot"].clone();
                            }
                            delete tmpNode["_originPos"];
                            delete tmpNode["_originRot"];
                            delete tmpNode["_relationCustomReplaceBox"];
                            delete tmpNode["_bIgnored"];
                            delete tmpNode["_bHited"];
                        }
                        delete rowNode["_bHited"];
                    }
                }
                if (!!wallAnimatorNodes) {
                    numChildren = wallAnimatorNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = wallAnimatorNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                            if (tmpNode["_originPos"]) {
                                tmpNode.transform.localPosition = tmpNode["_originPos"].clone();
                            }
                            if (tmpNode["_originRot"]) {
                                tmpNode.transform.localRotationEuler = tmpNode["_originRot"].clone();
                            }
                            delete tmpNode["_originPos"];
                            delete tmpNode["_originRot"];
                            delete tmpNode["_relationCustomReplaceBox"];
                            delete tmpNode["_bIgnored"];
                            delete tmpNode["_bPlayed"];
                            delete tmpNode["_bHited"];
                        }
                        delete rowNode["_bHited"];
                    }
                }
                if (!!goldNodes) {
                    numChildren = goldNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = goldNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                        }
                        delete rowNode["_bHited"];
                    }
                }
                if (!!diamondNodes) {
                    numChildren = diamondNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = diamondNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                        }
                        delete rowNode["_bHited"];
                    }
                }
                if (!!shoeNodes) {
                    numChildren = shoeNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = shoeNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                            if (tmpNode["_originPos"]) {
                                tmpNode.transform.localPosition = tmpNode["_originPos"].clone();
                            }
                            if (tmpNode["_originRot"]) {
                                tmpNode.transform.localRotationEuler = tmpNode["_originRot"].clone();
                            }
                            delete tmpNode["_originPos"];
                            delete tmpNode["_originRot"];
                            delete tmpNode["_bHited"];
                        }
                        delete rowNode["_bHited"];
                    }
                }
                if (!!ladderNodes) {
                    numChildren = ladderNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = ladderNodes.getChildAt(i);
                        delete rowNode["_bHited"];
                    }
                }
                if (!!prickNodes) {
                    numChildren = prickNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = prickNodes.getChildAt(i);
                        let rowChildCount = rowNode.numChildren;
                        for (let tmp = 0; tmp < rowChildCount; tmp++) {
                            let tmpNode = rowNode.getChildAt(tmp);
                            tmpNode.active = true;
                            tmpNode["_roadLine"] = this.calculateRoadLineByPosX(tmpNode.transform.localPositionX);
                            delete tmpNode["_relationCustomReplaceBox"];
                        }
                        delete rowNode["_bHited"];
                    }
                }
                if (!!singleBarNodes) {
                    numChildren = singleBarNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = singleBarNodes.getChildAt(i);
                        delete rowNode["_bHited"];
                    }
                }
                if (!!doubleBarNodes) {
                    numChildren = doubleBarNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = doubleBarNodes.getChildAt(i);
                        delete rowNode["_bHited"];
                    }
                }
                if (!!elevatorNodes) {
                    numChildren = elevatorNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let rowNode = elevatorNodes.getChildAt(i);
                        delete rowNode["_bHited"];
                    }
                }
            }
            adaptXieTaiColor() {
                for (let k in this.shoeRowNodesArr) {
                    let tmpNode = this.shoeRowNodesArr[k];
                    let color = null;
                    let colorIdNode = tmpNode.getChildAt(0);
                    if (!!colorIdNode) {
                        let colorData = mgrCfg.get_from_world_color_db(colorIdNode.name);
                        if (!!colorData) {
                            color = new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255);
                        }
                    }
                    if (!color) {
                        let length = Tools.getObjSize(mgrCfg.getDb("world_color_db"));
                        let colorData = mgrCfg.get_from_world_color_db(Tools.random(1, length));
                        if (!!colorData) {
                            color = new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255);
                        }
                    }
                    color = color || new Laya.Color(Tools.random(255) / 255, Tools.random(255) / 255, Tools.random(255) / 255);
                    this.setXieTaiColor(tmpNode, color);
                }
                for (let k in this.wallRowNodesArr) {
                    let tmpNode = this.wallRowNodesArr[k];
                    let renderer = Tools.getMeshRender(tmpNode);
                    if (renderer) {
                        let modelId = tmpNode.name.substring(0, tmpNode.name.indexOf(" ") <= 0 ? tmpNode.name.length : tmpNode.name.indexOf(" "));
                        mgrMaterial.__setCustomMaterial(renderer, modelId, 0, modelId);
                    }
                }
            }
            setXieTaiColor(model, color) {
                let doSetFunc = (render) => {
                    if (!render) {
                        return;
                    }
                    mgrMaterial.__setCustomMaterial(render, "bi", 0, "bi");
                    for (let i = 0; i < render.sharedMaterials.length; i++) {
                        const oldMaterial = render.sharedMaterials[i];
                        if (oldMaterial.name == "bi_1") {
                            oldMaterial.albedoColor = new Laya.Vector4(color.r, color.g, color.b, 1);
                        }
                        else if (oldMaterial.name == "bi_2") {
                            oldMaterial.albedoColor = new Laya.Vector4(color.r * 0.9, color.g * 0.9, color.b * 0.9, 1);
                        }
                    }
                };
                let rendererNode = Tools.getMeshRender(model);
                if (!!rendererNode) {
                    doSetFunc(rendererNode);
                }
                else {
                    for (let i = 0; i < model.numChildren; i++) {
                        let child = model.getChildAt(i);
                        let renderer = Tools.getMeshRender(child);
                        doSetFunc(renderer);
                    }
                }
            }
            calculateRoadLineByPosX(posX) {
                let xAbs = Math.abs(posX);
                for (let i = this.ROAD_LINE_COUNT; i >= 0; i--) {
                    let minX = i * this.BOX_WH - this.BOX_WH / 2;
                    let maxX = i * this.BOX_WH + this.BOX_WH / 2;
                    if (xAbs >= minX && xAbs <= maxX) {
                        return posX >= 0 ? i : -i;
                    }
                }
                return NaN;
            }
            inInit() {
                this.staticsMethodCall("inInit");
                cc.tween(this.spriteRule).delay(2.5).toPos(0.3, this.spriteRule.x, this.spriteRule.y - mgrDirector.height / 2, cc.Ease.backIn).start();
                this.context.roleId = this.context.roleId || 102;
                this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.modeSelect);
            }
            exeInit() { }
            outInit() { }
            inWaitStart() {
            }
            exeWaitStart() { }
            outWaitStart() { }
            inModeSelect() {
                this.cleanStageMapNode();
                mgrTip.showLoadingTip("fashionshoe_model_select_load_splash_map");
                this.add3DEffectAtBack("fashion_shoe_stage_splash", 0, (model) => {
                    mgrTip.hideLoadingTip("fashionshoe_model_select_load_splash_map");
                    this.mapStage = model;
                    this.changeStageFog(false);
                    this.modeUiActionIn();
                    this.onSelectStageMode();
                });
            }
            exeModeSelect() { }
            outModeSelect() { }
            inBackCount() {
                Tools.registerTouchHander(this.boxBackPanel, this.onTouchSpriteBg.bind(this));
            }
            exeBackCount() { }
            outBackCount() {
                Tools.unRegisterTouchHander(this.boxBackPanel);
            }
            inTurnReady() {
                this.bPlayed = true;
                this.addAvatarShoe(new Laya.Color(Tools.random(255) / 255, Tools.random(255) / 255, Tools.random(255) / 255, 1));
                this.addAvatarShoe(new Laya.Color(Tools.random(255) / 255, Tools.random(255) / 255, Tools.random(255) / 255, 1));
                this.addAvatarShoe(new Laya.Color(Tools.random(255) / 255, Tools.random(255) / 255, Tools.random(255) / 255, 1));
                mgrSound.play(652);
                this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.avatarComing);
            }
            exeTurnReady() { }
            outTurnReady() { }
            inAvatarComing() {
                mgrVideoRecorder.startRecord();
                this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.avatarMoving);
            }
            exeAvatarComing() {
            }
            outAvatarComing() {
            }
            inAvatarMoving() {
                if (!!this.bReadyRevival) {
                    this.bReadyRevival = false;
                    this.bAvatarMovingReadyed = true;
                    Tools.registerTouchHander(this.boxBackPanel, this.onTouchSpriteBg.bind(this));
                    return;
                }
                if (this.stageData) {
                    this.staticsMethodCall("inAvatarMoving", this.stageData.id);
                }
                if (this.eMapEffectOnStartStand) {
                    mgrLoader.Pool.recoverModel(this.eMapEffectOnStartStand);
                    this.eMapEffectOnStartStand = null;
                }
                Tools.registerTouchHander(this.boxBackPanel, this.onTouchSpriteBg.bind(this));
                this.avatar.playAnimation(this.getAvatarRealAnimationId(this.avatar.context.roleId, FASHION_SHOW_MOV.movWalk), 0, () => {
                    this.resetPlayerAndBoxPos();
                }, null, true);
                let avatarPosCameraDict = this.avatarPosCameraDict[1];
                let param = avatarPosCameraDict.cameraData;
                let bInitedCamera = false;
                this.cameraWithAvatarZDiffDis = param.pos.z - this.mapAvatarNode.transform.position.z;
                this.avatar.registerLoadEndCallback(() => {
                    let doLerpPosFunc = (percent) => {
                        this.avatar.transform.localRotationEulerY = 180 * percent;
                        if (percent >= 0.6 && !bInitedCamera) {
                            bInitedCamera = true;
                            this.cameraFollow.position = param.pos.clone();
                            this.cameraFollow.endRotation = param.rot.clone();
                            this.cameraFollow.fov = param.fov;
                            this.cameraFollow.lerpValue = 0.03;
                        }
                        if (percent == 1) {
                            this.flagMoveReadyFunc();
                        }
                    };
                    let startTime = Tools.time();
                    let dur = 0.5;
                    Timer.callLoop(0.016, (timer) => {
                        if (!this.nodeResource || this.nodeResource.destroyed || this.stManager.getCurState() != AMUSE_FASHION_PEN_STATE.avatarMoving) {
                            timer.stop();
                            return;
                        }
                        let passTime = Tools.time() - startTime;
                        if (passTime >= dur) {
                            doLerpPosFunc(1);
                            timer.stop();
                            return;
                        }
                        doLerpPosFunc(passTime / dur);
                    }, this);
                });
            }
            flagMoveReadyFunc() {
                this.sendMsg("MSG_GUIDE_EVENT", { id: "vAmuseFashionPenScene.boxGuideStart.guideClick" });
                this.avatar.resume();
                this.bAvatarMovingReadyed = true;
            }
            exeAvatarMoving(deltaTime) {
                if (this.bPaused || !this.bAvatarMovingReadyed) {
                    return;
                }
                this.doAvatarMovingLerp(deltaTime);
                if (this.collideredWallNode) {
                    if (this.collideredWallNode.transform.position.z > this.mapAvatarNode.transform.position.z && Math.abs(this.mapAvatarNode.transform.position.z - this.collideredWallNode.transform.position.z) > this.COLLIDE_WALL_Z_DIS) {
                        this.collideredWallNode = null;
                    }
                    return;
                }
                this.tryAddPropsEffect();
                this.tryAddRoadEffect();
                this.checkShoeBoxCollider();
                this.checkWallBoxCollider();
                this.checkWallGlassBoxCollider();
                this.checkAnimationBoxPlay();
                this.checkAvatarGotShoeOver();
                this.checkSingleBarCollider();
                this.checkDoubleBarCollider();
                this.checkPropsCollider();
                this.checkElevatorCollider();
                this.checkBaseRoadCollider();
                this.resetPlayerAndBoxPos();
                this.checkArrivedDestination();
                this.checkInvincibleCollider();
            }
            outAvatarMoving() {
                this.bAvatarMovingReadyed = false;
                Tools.unRegisterTouchHander(this.boxBackPanel);
            }
            tryAddRoadEffect() {
                return;
            }
            tryAddPropsEffect() {
                if (this.mapAvatarNode.transform.position.z < this.successNodeHolder.transform.position.z) {
                    return;
                }
                for (let i = 1; i <= 5; i++) {
                    let arr = this[`propsType${i}NodesArr`];
                    if (!arr || arr.length == 0) {
                        continue;
                    }
                    let numChildren = arr.length;
                    for (let j = 0; j < numChildren; j++) {
                        let tmpNode = arr[j];
                        if (Math.abs(this.mapAvatarNode.transform.position.z - tmpNode.transform.position.z) > 10) {
                            continue;
                        }
                        let customEffectNode = tmpNode.getChildByName(this.PROPS_INDEX_2_EFFECT_NAME_DICT[i]);
                        if (customEffectNode) {
                            continue;
                        }
                        let effect = mgrLoader.Pool.getModel(this.PROPS_INDEX_2_EFFECT_NAME_DICT[i]);
                        tmpNode.addChild(effect);
                    }
                }
            }
            checkArrivedDestination() {
                if (!this.finishNodeHolder) {
                    return;
                }
                if (this.mapAvatarNode.transform.position.z < this.finishNodeHolder.transform.position.z) {
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.arrivedDest);
                }
            }
            checkPropsCollider() {
                let checkFunc = (nodeArr, hitFunc) => {
                    let countContainer = nodeArr.length;
                    for (let i = 0; i < countContainer; i++) {
                        let pNode = nodeArr[i];
                        if (pNode["_bHited"] || (!this.bInvincible && (Math.abs(this.mapAvatarNode.transform.position.z - pNode.transform.position.z) >= 0.5 ||
                            Math.abs(this.mapAvatarNode.transform.position.x - pNode.transform.position.x) >= 0.5 / 2))) {
                            continue;
                        }
                        pNode["_bHited"] = true;
                        let pos = pNode.transform.localPosition.clone();
                        let rot = pNode.transform.localRotationEuler.clone();
                        pNode["_originPos"] = pNode["_originPos"] || pos;
                        pNode["_originRot"] = pNode["_originRot"] || rot;
                        cc.tween(pNode.transform).to(0.1, {
                            localPositionX: this.mapAvatarNode.transform.localPositionX
                        })
                            .call(() => {
                            if (!this.nodeResource || this.nodeResource.destroyed || this.stManager.getCurState() != AMUSE_FASHION_PEN_STATE.avatarMoving) {
                                return;
                            }
                            pNode.active = false;
                            hitFunc && hitFunc(pNode.transform.position);
                        })
                            .start();
                    }
                };
                checkFunc(this.propsType1NodesArr, this.onHitedPropsType1Handler.bind(this));
                checkFunc(this.propsType2NodesArr, this.onHitedPropsType2Handler.bind(this));
                checkFunc(this.propsType3NodesArr, this.onHitedPropsType3Handler.bind(this));
                checkFunc(this.propsType4NodesArr, this.onHitedPropsType4Handler.bind(this));
                checkFunc(this.propsType5NodesArr, this.onHitedPropsType5Handler.bind(this));
            }
            onHitedPropsType1Handler(position) {
                this.add3DEffectAtAavtarBip01("e_daoju_yinfu", 3);
                mgrSound.play(141);
            }
            onHitedPropsType2Handler(position) {
                this.add3DEffectAtAavtarBip01("e_daoju_rose", 3);
                mgrSound.play(142);
            }
            onHitedPropsType3Handler(position) {
                this.add3DEffectAtAavtarBip01("e_daoju_huaban", 3);
                mgrSound.play(143);
            }
            onHitedPropsType4Handler(position) {
                this.add3DEffectAtAavtarBip01("e_daoju_star", 3);
                mgrSound.play(144);
            }
            onHitedPropsType5Handler(position) {
                this.add3DEffectAtAavtarBip01("e_daoju_snow", 3);
                mgrSound.play(145);
            }
            add3DEffectAtAavtarBip01(modelId, duration = 3) {
                let addFunc = (mode) => {
                    mode.transform.localPositionY = 1;
                    mode.transform.localRotationEulerX = -90;
                    this.avatar.addChild(mode);
                    duration > 0 && Timer.callLater(duration, () => {
                        mgrLoader.Pool.recoverModel(mode);
                    }, this);
                };
                if (modelId instanceof Laya.Sprite3D) {
                    addFunc(modelId);
                    return;
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    if (!this.scene3DBack)
                        return;
                    if (!this.avatar || this.avatar.destroyed) {
                        return;
                    }
                    let mode = mgrLoader.Pool.getModel(modelId);
                    addFunc(mode);
                }, this, 1);
            }
            checkInvincibleCollider() {
                if (this.bInvincible) {
                    return;
                }
                let countContainer = this.invincibleNodesArr.length;
                for (let i = 0; i < countContainer; i++) {
                    let pNode = this.invincibleNodesArr[i];
                    if (Math.abs(this.mapAvatarNode.transform.position.z - pNode.transform.position.z) >= 0.5 ||
                        Math.abs(this.mapAvatarNode.transform.position.x - pNode.transform.position.x) >= 0.5 / 2 ||
                        pNode["_bHited"]) {
                        continue;
                    }
                    pNode["_bHited"] = true;
                    pNode.active = false;
                    if (!mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseFashionPenScene_super)) {
                        return;
                    }
                    this.bPaused = true;
                    mgrDirector.openDialog("vAmusePenSuperDialog1", {
                        adEventId: AD_EVENT_ID.VIDEO.video_vAmuseFashionPenScene_super,
                        fOnAdResult: (bAded) => {
                            this.bPaused = false;
                            if (!bAded) {
                                return;
                            }
                            this.beginPenSuper();
                        }
                    });
                    break;
                }
            }
            beginPenSuper() {
                this.avatar.playAnimation("paoku_move-paoku_fly", 0, null, null, true, true);
                let model = mgrLoader.Pool.getModel("e_daoju_wudi");
                this.add3DEffectAtAavtarBip01(model, 0);
                this.eDaojuWudiModel = model;
                this.bInvincible = true;
                this.MOVE_FPS *= this.INVINCIBLE_FPS_RATIO;
                this.disableAdatPlayerYEndTime = Tools.time();
                this.avatar.timeScale = this.INVINCIBLE_FPS_RATIO / 2;
                this.bTouchBg = false;
                this.avatar.playAnimation("paoku_move-paoku_fly", 0, null, null, true, true);
            }
            checkWallBoxCollider() {
                let playerRoadLine = this.calculateRoadLineByPosX(this.mapAvatarNode.transform.localPositionX - this.baseRoadPosition.x);
                let gotRoadIndexDict = this.getAvatarGotShoeRoadIndexDict();
                let wallArr = [this.wallRowNodesArr, this.wallGlassRowNodesArr];
                for (let i = 0; i < wallArr.length; i++) {
                    let wallRowNodesArr = wallArr[i];
                    let wallRoadLineDict = {};
                    let currColisionedNodeArr = [];
                    let countContainer = wallRowNodesArr.length;
                    for (let i = 0; i < countContainer; i++) {
                        let tmpBox = wallRowNodesArr[i];
                        if (Math.abs(this.mapAvatarNode.transform.position.z - tmpBox.transform.position.z) > this.COLLIDE_WALL_Z_DIS || tmpBox["_bHited"]) {
                            continue;
                        }
                        tmpBox["_bHited"] = true;
                        let hitedRoadIndexDict = this.isHitedValidBox(tmpBox, gotRoadIndexDict);
                        if (Tools.getObjSize(hitedRoadIndexDict) > 0) {
                            currColisionedNodeArr.push(tmpBox);
                            for (let k in hitedRoadIndexDict) {
                                wallRoadLineDict[k] = true;
                            }
                        }
                    }
                    if (currColisionedNodeArr.length <= 0) {
                        continue;
                    }
                    if (this.bInvincible) {
                        let posAvatar = this.mapAvatarNode.transform.position;
                        let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                        this.add3DEffectAtBack(effExplodeModel, 1);
                        effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, posAvatar.y, posAvatar.z);
                        for (let i = 0; i < currColisionedNodeArr.length; i++) {
                            let obstacleBox = currColisionedNodeArr[i];
                            let pos = obstacleBox.transform.localPosition.clone();
                            let rot = obstacleBox.transform.localRotationEuler.clone();
                            obstacleBox["_originPos"] = obstacleBox["_originPos"] || pos;
                            obstacleBox["_originRot"] = obstacleBox["_originRot"] || rot;
                            let yFlag = Tools.random(100) > 50 ? 1 : -1;
                            if (obstacleBox["_roadLine"] > playerRoadLine) {
                                cc.tween(obstacleBox.transform)
                                    .to(0.2, {
                                    localPositionX: (pos.x + 5),
                                    localPositionY: pos.y + 5 * yFlag,
                                    localPositionZ: (pos.z - 5),
                                    localRotationEulerX: rot.x + Tools.random(0, 360),
                                    localRotationEulerY: rot.y + Tools.random(0, 360),
                                    localRotationEulerZ: rot.z + Tools.random(0, 360),
                                })
                                    .start();
                            }
                            else if (obstacleBox["_roadLine"] < playerRoadLine) {
                                cc.tween(obstacleBox.transform)
                                    .to(0.2, {
                                    localPositionX: (pos.x - 5),
                                    localPositionY: pos.y + 5 * yFlag,
                                    localPositionZ: (pos.z - 5),
                                    localRotationEulerX: rot.x + Tools.random(0, 360),
                                    localRotationEulerY: rot.y + Tools.random(0, 360),
                                    localRotationEulerZ: rot.z + Tools.random(0, 360),
                                })
                                    .start();
                            }
                            else {
                                let xFlag = Tools.random(100) > 50 ? 1 : -1;
                                cc.tween(obstacleBox.transform)
                                    .to(0.2, {
                                    localPositionX: (pos.x + 5 * xFlag),
                                    localPositionY: pos.y + 5 * yFlag,
                                    localPositionZ: (pos.z - 5),
                                    localRotationEulerX: rot.x + Tools.random(0, 360),
                                    localRotationEulerY: rot.y + Tools.random(0, 360),
                                    localRotationEulerZ: rot.z + Tools.random(0, 360),
                                })
                                    .start();
                            }
                        }
                        let soundArr = [146, 147, 148];
                        mgrSound.play(Tools.randomGotOneArrayData(soundArr));
                        this.disableAdatPlayerYEndTime = Tools.time() + 1 / (this.MOVE_FPS || 1) * this.BOX_WH;
                        this.collideredWallNode = currColisionedNodeArr[0];
                        return;
                    }
                    let len = this.avatarGotShoeBoxArr.length;
                    if (len == 0) {
                        mgrTip.showMsgTip("失败啦");
                        this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.hitWallDie);
                        return;
                    }
                    let removedShoeModelArr = [];
                    for (let tmp = (len - 1); tmp >= 0; tmp--) {
                        let data = this.avatarGotShoeBoxArr[tmp];
                        let penModel = data.penModel;
                        if (wallRoadLineDict[data.roadIndex]) {
                            this.avatarGotShoeBoxArr.splice(tmp, 1);
                            let oldPos = penModel.transform.position.clone();
                            penModel.removeSelf();
                            removedShoeModelArr.push(penModel);
                            this.add3DEffectAtBack(penModel, 0);
                            penModel.transform.position = oldPos;
                            if (data.rowIndex == 0) {
                                let penColorIndex = this.roadIndex2PenColorIndexDict[data.roadIndex];
                                let penColorInfo = this.penColorModelDict[penColorIndex];
                                penColorInfo.roadIndex = 0;
                                penColorInfo.bUsing = false;
                                delete this.roadIndex2PenColorIndexDict[data.roadIndex];
                            }
                        }
                    }
                    for (let tmp = 0; tmp < removedShoeModelArr.length; tmp++) {
                        let model = removedShoeModelArr[tmp];
                        let rot = Tools.random(50) * (Tools.random(100) > 50 ? 1 : -1);
                        let rightLocalRotationEulerZ = model.transform.localRotationEulerZ + rot;
                        cc.tween(model.transform).to(this.PER_BOX_DOWN_TIME, {
                            localRotationEulerX: -90,
                            localRotationEulerZ: rightLocalRotationEulerZ,
                            localPositionY: 0.06,
                        }).delay(2).call(() => {
                            mgrLoader.Pool.recoverModel(model);
                        }).start();
                    }
                    let soundArr = [146, 147, 148];
                    mgrSound.play(Tools.randomGotOneArrayData(soundArr));
                    this.disableAdatPlayerYEndTime = Tools.time() + 1 / (this.MOVE_FPS || 1) * this.BOX_WH;
                    Timer.callLater(0.4 * 1 / (this.MOVE_FPS || 1), () => {
                        this.adaptGotShoeRoadIndex();
                    }, this);
                    return;
                }
            }
            checkWallGlassBoxCollider() {
                if (!this.avatarGotShoeBoxArr.length) {
                    return;
                }
                let row2PenDataDict = {};
                for (let i = 0; i < this.avatarGotShoeBoxArr.length; i++) {
                    let penData = this.avatarGotShoeBoxArr[i];
                    row2PenDataDict[penData.rowIndex] = row2PenDataDict[penData.rowIndex] || [];
                    row2PenDataDict[penData.rowIndex].push(penData);
                }
                let getPenFunc = () => {
                    for (let i = 100; i >= 0; i--) {
                        if (!row2PenDataDict[i] || row2PenDataDict[i].length == 0) {
                            continue;
                        }
                        let datas = row2PenDataDict[i];
                        let index = Tools.random(datas.length - 1);
                        let penData = datas[index];
                        datas.splice(index, 1);
                        for (let tmp = this.avatarGotShoeBoxArr.length - 1; tmp >= 0; tmp--) {
                            let tmpPenData = this.avatarGotShoeBoxArr[tmp];
                            if (tmpPenData.penModel.id == penData.penModel.id) {
                                this.avatarGotShoeBoxArr.splice(tmp, 1);
                                break;
                            }
                        }
                        if (penData.rowIndex == 0) {
                            let penColorIndex = this.roadIndex2PenColorIndexDict[penData.roadIndex];
                            let penColorInfo = this.penColorModelDict[penColorIndex];
                            penColorInfo.roadIndex = 0;
                            penColorInfo.bUsing = false;
                            delete this.roadIndex2PenColorIndexDict[penData.roadIndex];
                        }
                        return penData;
                    }
                    return null;
                };
                let currColisionedNodeArr = [];
                let wallRoadLineDict = {};
                let countContainer = this.wallGlassRowNodesArr.length;
                for (let i = 0; i < countContainer; i++) {
                    let tmpBox = this.wallGlassRowNodesArr[i];
                    if (!!tmpBox["_bHited"] || this.mapAvatarNode.transform.position.z <= tmpBox.transform.position.z || (this.mapAvatarNode.transform.position.z - tmpBox.transform.position.z) > this.WALL_GLASS_CHECK_DIS) {
                        continue;
                    }
                    currColisionedNodeArr.push(tmpBox);
                }
                if (currColisionedNodeArr.length > 0) {
                    let bFighted = false;
                    for (let k in currColisionedNodeArr) {
                        let tmpBox = currColisionedNodeArr[k];
                        let penData = getPenFunc();
                        if (!penData) {
                            return;
                        }
                        tmpBox["_bHited"] = true;
                        bFighted = true;
                        let position = penData.penModel.transform.position.clone();
                        let diffPos = new Laya.Vector3;
                        Laya.Vector3.subtract(tmpBox.transform.position, penData.penModel.transform.position, diffPos);
                        penData.penModel.removeSelf();
                        this.mapTmpNodeContainer.addChild(penData.penModel);
                        penData.penModel.transform.position = position;
                        penData.penModel.transform.lookAt(tmpBox.transform.position, new Laya.Vector3);
                        let localPositon = penData.penModel.transform.localPosition.clone();
                        cc.tween(penData.penModel.transform)
                            .to(0.2 / this.MOVE_FPS, { localRotationEulerX: 90, localPositionY: localPositon.y + 0.4 })
                            .to(0.4 / this.MOVE_FPS, { localPositionX: (localPositon.x + diffPos.x), localPositionY: (localPositon.y + diffPos.y) + 1, localPositionZ: (localPositon.z + diffPos.z) })
                            .call(() => {
                            let eff = mgrLoader.Pool.getModel("e_yanhua_09");
                            eff.transform.position = tmpBox.transform.position.clone();
                            this.add3DEffectAtBack(eff);
                        })
                            .delay(0.01)
                            .call(() => {
                            let tmpBoxParts = mgrLoader.Pool.getModel("boli_parts");
                            this.add3DEffectAtBack(tmpBoxParts, 0);
                            tmpBoxParts.transform.position = tmpBox.transform.position.clone();
                            tmpBox.active = false;
                            let numChildren = tmpBoxParts.numChildren;
                            let leftNameDict = {
                                ["boli_parts09"]: true,
                                ["boli_parts02"]: true,
                                ["boli_parts10"]: true,
                                ["boli_parts15"]: true,
                                ["boli_parts14"]: true,
                                ["boli_parts07"]: true,
                                ["boli_parts03"]: true,
                                ["boli_parts17"]: true
                            };
                            let rightNameDict = {
                                ["boli_parts19"]: true,
                                ["boli_parts13"]: true,
                                ["boli_parts16"]: true,
                                ["boli_parts06"]: true,
                                ["boli_parts18"]: true,
                                ["boli_parts05"]: true
                            };
                            for (let indexTmp = 0; indexTmp < numChildren; indexTmp++) {
                                let childTmp = tmpBoxParts.getChildAt(indexTmp);
                                let pos = childTmp.transform.localPosition.clone();
                                let rot = childTmp.transform.localRotationEuler.clone();
                                let yFlag = Tools.random(100) > 50 ? 1 : -1;
                                if (rightNameDict[childTmp.name]) {
                                    cc.tween(childTmp.transform)
                                        .to(0.4, {
                                        localPositionX: (pos.x + 7),
                                        localPositionY: pos.y + 7 * yFlag,
                                        localPositionZ: (pos.z - 7),
                                        localRotationEulerX: rot.x + Tools.random(0, 360),
                                        localRotationEulerY: rot.y + Tools.random(0, 360),
                                        localRotationEulerZ: rot.z + Tools.random(0, 360),
                                    })
                                        .call(() => {
                                        childTmp.transform.localPosition = pos;
                                        childTmp.transform.localRotationEuler = rot;
                                        childTmp.active = false;
                                    })
                                        .start();
                                }
                                else if (leftNameDict[childTmp.name]) {
                                    cc.tween(childTmp.transform)
                                        .to(0.4, {
                                        localPositionX: (pos.x - 7),
                                        localPositionY: pos.y + 7 * yFlag,
                                        localPositionZ: (pos.z - 7),
                                        localRotationEulerX: rot.x + Tools.random(0, 360),
                                        localRotationEulerY: rot.y + Tools.random(0, 360),
                                        localRotationEulerZ: rot.z + Tools.random(0, 360),
                                    })
                                        .call(() => {
                                        childTmp.transform.localPosition = pos;
                                        childTmp.transform.localRotationEuler = rot;
                                        childTmp.active = false;
                                    })
                                        .start();
                                }
                                else {
                                    let xFlag = Tools.random(100) > 50 ? 1 : -1;
                                    cc.tween(childTmp.transform)
                                        .to(0.4, {
                                        localPositionX: (pos.x + 7 * xFlag),
                                        localPositionY: pos.y + 7 * yFlag,
                                        localPositionZ: (pos.z - 7),
                                        localRotationEulerX: rot.x + Tools.random(0, 360),
                                        localRotationEulerY: rot.y + Tools.random(0, 360),
                                        localRotationEulerZ: rot.z + Tools.random(0, 360),
                                    })
                                        .call(() => {
                                        childTmp.transform.localPosition = pos;
                                        childTmp.transform.localRotationEuler = rot;
                                        childTmp.active = false;
                                    })
                                        .start();
                                }
                            }
                            Timer.callLater(0.45, () => {
                                for (let indexTmp = 0; indexTmp < numChildren; indexTmp++) {
                                    let childTmp = tmpBoxParts.getChildAt(indexTmp);
                                    childTmp.active = true;
                                }
                                mgrLoader.Pool.recoverModel(tmpBoxParts);
                            }, this);
                            mgrLoader.Pool.recoverModel(penData.penModel);
                        })
                            .start();
                    }
                    if (bFighted) {
                        this.adaptGotShoeRoadIndex();
                    }
                }
            }
            checkAnimationBoxPlay() {
                let countContainer = this.wallAnimatorRowNodesArr.length;
                for (let i = 0; i < countContainer; i++) {
                    let pNode = this.wallAnimatorRowNodesArr[i];
                    if (Math.abs(this.mapAvatarNode.transform.position.z - pNode.transform.position.z) > this.ANIMATION_BOX_PLAY_CHECK_DIS) {
                        continue;
                    }
                    let numChildren = pNode.numChildren;
                    for (let tmp = 0; tmp < numChildren; tmp++) {
                        let obstacleBox = pNode.getChildAt(tmp);
                        if (!!obstacleBox["_bPlayed"]) {
                            return;
                        }
                        obstacleBox["_bPlayed"] = true;
                        let animator = obstacleBox.getComponent(Laya.Animator);
                        if (!!animator) {
                            animator.speed = this.MOVE_FPS / 1;
                            animator.play("comein");
                        }
                    }
                }
            }
            checkAvatarGotShoeOver() {
                if (!this.avatarGotShoeBoxArr.length) {
                    return;
                }
                let maxX = Math.max(Math.floor(this.ROAD_LINE_COUNT / 2) * this.BOX_WH, this.checkPenOverRoadX);
                for (let i = this.avatarGotShoeBoxArr.length - 1; i >= 0; i--) {
                    let penData = this.avatarGotShoeBoxArr[i];
                    let localX = penData.penModel.transform.position.x - this.baseRoadPosition.x;
                    let penX = Math.abs(localX);
                    if (penX <= maxX) {
                        continue;
                    }
                    this.avatarGotShoeBoxArr.splice(i, 1);
                    if (penData.rowIndex == 0) {
                        let penColorIndex = this.roadIndex2PenColorIndexDict[penData.roadIndex];
                        let penColorInfo = this.penColorModelDict[penColorIndex];
                        penColorInfo.roadIndex = 0;
                        penColorInfo.bUsing = false;
                        delete this.roadIndex2PenColorIndexDict[penData.roadIndex];
                    }
                    cc.tween(penData.penModel.transform)
                        .to(0.4, { localRotationEulerZ: localX < 0 ? 180 : -180 })
                        .call(() => {
                        mgrLoader.Pool.recoverModel(penData.penModel);
                    })
                        .start();
                }
            }
            checkSingleBarCollider() {
                if (this.currBarType) {
                    return;
                }
                let countContainer = this.singleBarRowNodesArr.length;
                for (let i = 0; i < countContainer; i++) {
                    let pNode = this.singleBarRowNodesArr[i];
                    if (this.mapAvatarNode.transform.position.z > pNode.transform.position.z || pNode["_bHited"]) {
                        continue;
                    }
                    pNode["_bHited"] = true;
                    let firstNode = pNode.getChildAt(0);
                    if (this.bInvincible) {
                        this.mapAvatarNode.transform.localPositionX = firstNode.transform.localPositionX;
                    }
                    if (Math.abs(firstNode.transform.position.x - this.mapAvatarNode.transform.position.x) > this.BOX_WH * 0.6) {
                        this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.singleBarDie);
                        return;
                    }
                    let singleBarLength = pNode.transform.localScaleZ * this.BOX_WH;
                    if (!singleBarLength) {
                        continue;
                    }
                    if (!!this.avatar && !this.avatar.destroyed) {
                    }
                    this.tryResetBarData();
                    this.currBarFinishPositionZ = this.mapAvatarNode.transform.position.z - singleBarLength;
                    this.currSingleBarX = firstNode.transform.localPositionX;
                    this.currBarType = this.BAR_TYPE_SINGLE;
                    this.currSingleBarObliqueFlag = Tools.random(100) > 50 ? 1 : -1;
                    this.touchBgBeginPos = this.lastTouchBgPos;
                    if (this.bInvincible) {
                        return;
                    }
                    this.avatar.playAnimation(this.getAvatarRealAnimationId(this.avatar.context.roleId, FASHION_SHOW_MOV.movSBMove01), 0, null, null, true, true);
                    break;
                }
            }
            checkDoubleBarCollider() {
                let countContainer = this.doubleBarRowNodesArr.length;
                for (let i = 0; i < countContainer; i++) {
                    let pNode = this.doubleBarRowNodesArr[i];
                    if (this.mapAvatarNode.transform.position.z > pNode.transform.position.z || pNode["_bHited"]) {
                        continue;
                    }
                    pNode["_bHited"] = true;
                    let singleBarLength = pNode.transform.localScaleZ * this.BOX_WH;
                    if (!singleBarLength) {
                        continue;
                    }
                    let doubleBarRoadLineArr = !!this.doubleBarRoadLineArr ? [this.doubleBarRoadLineArr[0] || -10, this.doubleBarRoadLineArr[1] || 10] : [-10, 10];
                    if (!!this.avatar && !this.avatar.destroyed) {
                    }
                    this.tryResetBarData();
                    this.currBarFinishPositionZ = this.mapAvatarNode.transform.position.z - singleBarLength;
                    this.currBarType = this.BAR_TYPE_DOUBLE;
                    let bar1 = pNode.getChildAt(0);
                    let bar2 = pNode.getChildAt(1);
                    let barRoadLine1 = bar1.transform.position.x;
                    let barRoadLine2 = bar2.transform.position.x;
                    let leftRoadLine = Math.min(barRoadLine1, barRoadLine2);
                    let rightRoadLine = Math.max(barRoadLine1, barRoadLine2);
                    this.doubleBarRoadLineArr = [leftRoadLine, rightRoadLine];
                    let model = mgrLoader.Pool.getModel("e_huadong_smoke");
                    this.mapAvatarNode.parent.addChild(model);
                    this.effHudongSmokeDoubleBar1 = model;
                    let model2 = mgrLoader.Pool.getModel("e_huadong_smoke");
                    this.mapAvatarNode.parent.addChild(model2);
                    this.effHudongSmokeDoubleBar2 = model2;
                    this.effHudongSmokeDoubleBar1.transform.position = bar1.transform.position.clone();
                    this.effHudongSmokeDoubleBar2.transform.position = bar2.transform.position.clone();
                    if (this.bInvincible) {
                        return;
                    }
                    this.avatar.playAnimation(this.getAvatarRealAnimationId(this.avatar.context.roleId, FASHION_SHOW_MOV.movDBMove01), 0, null, null, true, true);
                    break;
                }
            }
            checkElevatorCollider() {
                let countContainer = this.elevatorRowNodesArr.length;
                for (let i = 0; i < countContainer; i++) {
                    let pNode = this.elevatorRowNodesArr[i];
                    if (this.mapAvatarNode.transform.position.z > pNode.transform.position.z || pNode["_bHited"]) {
                        continue;
                    }
                    pNode["_bHited"] = true;
                    let beginPos = pNode.transform.position;
                    let targetPos = pNode.getChildByName("end").transform.position;
                    let diffY = targetPos.y - beginPos.y;
                    if (this.elevatorChangeInfo && this.elevatorChangeInfo.length >= 3) {
                        let lastTargetPos = this.elevatorChangeInfo[2];
                        this.elevatorPositionY += (beginPos.y - lastTargetPos.y);
                    }
                    this.elevatorChangeInfo = [
                        new Laya.Vector3(0, this.elevatorPositionY, this.mapAvatarNode.transform.localPositionZ),
                        new Laya.Vector3(0, this.elevatorPositionY + diffY, targetPos.z),
                        targetPos.clone()
                    ];
                    break;
                }
            }
            checkBaseRoadCollider() {
                if (this.baseRoadRowNodesArr.length > 0) {
                    let baseRoadNodeFront = null;
                    let baseRoadNodeBack = null;
                    let maxZ = -999999;
                    let minZ = 999999;
                    for (let i = 0; i < this.baseRoadRowNodesArr.length; i++) {
                        let node = this.baseRoadRowNodesArr[i];
                        if (this.mapAvatarNode.transform.position.z <= node.transform.position.z && node.transform.position.z < minZ) {
                            minZ = node.transform.position.z;
                            baseRoadNodeBack = node;
                        }
                        if (this.mapAvatarNode.transform.position.z >= node.transform.position.z && node.transform.position.z > maxZ) {
                            maxZ = node.transform.position.z;
                            baseRoadNodeFront = node;
                        }
                    }
                    if (!baseRoadNodeFront && !!baseRoadNodeBack) {
                        this.baseRoadPosition = baseRoadNodeBack.transform.localPosition.clone();
                    }
                    else if (!!baseRoadNodeFront && !!baseRoadNodeBack) {
                        let disTotal = baseRoadNodeFront.transform.position.z - baseRoadNodeBack.transform.position.z;
                        let dis1 = this.mapAvatarNode.transform.position.z - baseRoadNodeBack.transform.position.z;
                        let ratio = dis1 / (disTotal || 1);
                        Laya.Vector3.lerp(baseRoadNodeBack.transform.position, baseRoadNodeFront.transform.position, ratio, this.baseRoadPosition);
                    }
                }
                if (this.baseRoadXCheckNodesArr.length > 0) {
                    let tmpNode = null;
                    let disZ = 999999;
                    for (let i = 0; i < this.baseRoadXCheckNodesArr.length; i++) {
                        let node = this.baseRoadXCheckNodesArr[i];
                        let tmpDis = Math.abs(this.mapAvatarNode.transform.position.z - node.transform.position.z);
                        if (this.mapAvatarNode.transform.position.z > node.transform.position.z &&
                            tmpDis < this.COLLIDE_WALL_Z_DIS && tmpDis < disZ) {
                            disZ = tmpDis;
                            tmpNode = node;
                        }
                    }
                    if (!!tmpNode) {
                        this.checkPenOverRoadX = Math.abs(tmpNode.transform.position.x - this.baseRoadPosition.x);
                    }
                }
            }
            getAvatarGotShoeRoadIndexDict() {
                let gotRoadIndexDict = {};
                gotRoadIndexDict = {
                    [0]: true,
                    [-1]: true,
                    [1]: true,
                };
                let len = this.avatarGotShoeBoxArr.length;
                for (let tmp = (len - 1); tmp >= 0; tmp--) {
                    let data = this.avatarGotShoeBoxArr[tmp];
                    if (data.rowIndex != 0) {
                        continue;
                    }
                    let penModel = data.penModel;
                    let nodeRoadLine = this.calculateRoadLineByPosX(penModel.transform.localPositionX);
                    gotRoadIndexDict[nodeRoadLine] = true;
                }
                return gotRoadIndexDict;
            }
            isHitedValidBox(tmpBox, avatarShoeRoadIndexDict) {
                let tmpBoxRoadLineDict = {};
                let nodeSize1 = tmpBox.getChildByName("size1");
                let nodeSize2 = tmpBox.getChildByName("size2");
                if (!nodeSize1 || !nodeSize2) {
                    let tmpRoadIndex = this.calculateRoadLineByPosX(this.mapAvatarNode.transform.position.x - tmpBox.transform.position.x);
                    tmpBoxRoadLineDict[tmpRoadIndex] = true;
                }
                else {
                    let leftX = Math.min(nodeSize1.transform.position.x - this.mapAvatarNode.transform.position.x, nodeSize2.transform.position.x - this.mapAvatarNode.transform.position.x);
                    let rightX = Math.max(nodeSize1.transform.position.x - this.mapAvatarNode.transform.position.x, nodeSize2.transform.position.x - this.mapAvatarNode.transform.position.x);
                    let leftRoadLine = this.calculateRoadLineByPosX(leftX);
                    let rightRoadLine = this.calculateRoadLineByPosX(rightX);
                    for (let j = leftRoadLine; j <= rightRoadLine; j++) {
                        tmpBoxRoadLineDict[j] = true;
                    }
                }
                let hitedRoadIndexDict = {};
                for (let k in tmpBoxRoadLineDict) {
                    if (avatarShoeRoadIndexDict[k]) {
                        hitedRoadIndexDict[k] = true;
                    }
                }
                return hitedRoadIndexDict;
            }
            checkShoeBoxCollider() {
                let playerRoadLine = this.calculateRoadLineByPosX(this.mapAvatarNode.transform.localPositionX - this.baseRoadPosition.x);
                let gotRoadIndexDict = this.getAvatarGotShoeRoadIndexDict();
                let currColisionedNodeArr = [];
                let countContainer = this.shoeRowNodesArr.length;
                for (let i = 0; i < countContainer; i++) {
                    let tmpBox = this.shoeRowNodesArr[i];
                    if (Math.abs(this.mapAvatarNode.transform.position.z - tmpBox.transform.position.z) > this.BOX_WH || tmpBox["_bHited"]) {
                        continue;
                    }
                    tmpBox["_bHited"] = true;
                    let bColisioned = Tools.getObjSize(this.isHitedValidBox(tmpBox, gotRoadIndexDict)) > 0 ? true : false;
                    if (bColisioned) {
                        currColisionedNodeArr.push(tmpBox);
                    }
                }
                if (currColisionedNodeArr.length > 0) {
                    for (let i in currColisionedNodeArr) {
                        let tmpBox = currColisionedNodeArr[i];
                        tmpBox.active = false;
                        let color = null;
                        let colorIdNode = tmpBox.getChildAt(0);
                        if (!!colorIdNode) {
                            let colorData = mgrCfg.get_from_world_color_db(colorIdNode.name);
                            if (!!colorData) {
                                color = new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255);
                            }
                        }
                        if (!color) {
                            let length = Tools.getObjSize(mgrCfg.getDb("world_color_db"));
                            let colorData = mgrCfg.get_from_world_color_db(Tools.random(1, length));
                            if (!!colorData) {
                                color = new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255);
                            }
                        }
                        color = color || new Laya.Color(Tools.random(255) / 255, Tools.random(255) / 255, Tools.random(255) / 255);
                        this.addAvatarShoe(color);
                    }
                    mgrSound.play(137);
                }
            }
            adaptGotShoeRoadIndex() {
                if (!this.avatarGotShoeBoxArr.length) {
                    return;
                }
                let usingRoadIndexDict = {};
                for (let i = 0; i < this.avatarGotShoeBoxArr.length; i++) {
                    let data = this.avatarGotShoeBoxArr[i];
                    if (data.rowIndex != 0) {
                        continue;
                    }
                    usingRoadIndexDict[data.roadIndex] = true;
                }
                let bContinuity = true;
                let bFinded = false;
                for (let i = (Math.floor(this.ROAD_COLOR_LINE_COUNT / 2) - 1); i >= 0; i--) {
                    if (!bFinded) {
                        if (usingRoadIndexDict[i] || usingRoadIndexDict[-i]) {
                            bFinded = true;
                            continue;
                        }
                    }
                    else {
                        if ((!usingRoadIndexDict[i] && !usingRoadIndexDict[-i]) || (usingRoadIndexDict[i] && !usingRoadIndexDict[-i]) || (!usingRoadIndexDict[i] && usingRoadIndexDict[-i])) {
                            bContinuity = false;
                            break;
                        }
                    }
                }
                if (bContinuity) {
                    return;
                }
                let roadIndex2TargetDict = {};
                let usedRoadIndexDict = {};
                let maxRoadIndex = Math.floor(this.ROAD_COLOR_LINE_COUNT / 2);
                let genNewRoadIndexFunc = (checkRoadIndex) => {
                    if (!!usingRoadIndexDict[checkRoadIndex]) {
                        usedRoadIndexDict[checkRoadIndex] = true;
                        return;
                    }
                    let targetIndex = 9999999;
                    let findIndex = maxRoadIndex;
                    while (findIndex >= 0 && findIndex > Math.abs(checkRoadIndex)) {
                        if (!usedRoadIndexDict[findIndex] && usingRoadIndexDict[findIndex]) {
                            targetIndex = findIndex;
                            break;
                        }
                        else if (!usedRoadIndexDict[-findIndex] && usingRoadIndexDict[-findIndex]) {
                            targetIndex = -findIndex;
                            break;
                        }
                        findIndex -= 1;
                    }
                    if (targetIndex == 9999999 || Math.abs(targetIndex) <= checkRoadIndex) {
                        return;
                    }
                    roadIndex2TargetDict[targetIndex] = checkRoadIndex;
                    usedRoadIndexDict[targetIndex] = true;
                    usedRoadIndexDict[checkRoadIndex] = true;
                };
                for (let i = 0; i <= maxRoadIndex; i++) {
                    genNewRoadIndexFunc(i);
                    if (i != 0) {
                        genNewRoadIndexFunc(-i);
                    }
                }
                console.log("----roadIndex2TargetDict=", roadIndex2TargetDict);
                for (let i = 0; i < this.avatarGotShoeBoxArr.length; i++) {
                    let data = this.avatarGotShoeBoxArr[i];
                    let oldRoadIndex = data.roadIndex;
                    let targetRoadIndex = parseInt(roadIndex2TargetDict[oldRoadIndex]);
                    cc.tween(data.penModel.transform)
                        .to(0.3 * 1 / (this.MOVE_FPS || 1), { localPositionX: 0 })
                        .to(0.3 * 1 / (this.MOVE_FPS || 1), { localPositionX: this.BOX_WH * (isNaN(targetRoadIndex) ? oldRoadIndex : targetRoadIndex) })
                        .start();
                    if (isNaN(targetRoadIndex)) {
                        continue;
                    }
                    if (data.rowIndex == 0) {
                        let penColorIndex = this.roadIndex2PenColorIndexDict[oldRoadIndex];
                        let penColorInfo = this.penColorModelDict[penColorIndex];
                        penColorInfo.roadIndex = targetRoadIndex;
                        delete this.roadIndex2PenColorIndexDict[oldRoadIndex];
                        this.roadIndex2PenColorIndexDict[targetRoadIndex] = penColorIndex;
                    }
                    data.roadIndex = targetRoadIndex;
                }
            }
            addAvatarShoe(color) {
                let getValidRoadIndexFunc = () => {
                    if (!this.avatarGotShoeBoxArr.length) {
                        return { rowIndex: 0, roadIndex: 0 };
                    }
                    for (let rowIndex = 0; rowIndex < this.ROAD_ROW_COUNT; rowIndex++) {
                        let leftRoadIndexDict = {};
                        let rightRoadIndexDict = {};
                        for (let k in this.avatarGotShoeBoxArr) {
                            let data = this.avatarGotShoeBoxArr[k];
                            if (data.rowIndex != rowIndex) {
                                continue;
                            }
                            let roadIndex = data.roadIndex;
                            if (roadIndex < 0) {
                                leftRoadIndexDict[roadIndex] = true;
                            }
                            else {
                                rightRoadIndexDict[roadIndex] = true;
                            }
                        }
                        let leftCount = Tools.getObjSize(leftRoadIndexDict);
                        let rightCount = Tools.getObjSize(rightRoadIndexDict);
                        if (leftCount >= Math.floor(this.ROAD_COLOR_LINE_COUNT / 2) && rightCount >= (Math.floor(this.ROAD_COLOR_LINE_COUNT / 2) + 1)) {
                            continue;
                        }
                        let bFirstLeft = leftCount < rightCount ? true : false;
                        for (let tmpIndex = 1; tmpIndex <= (Math.floor(this.ROAD_COLOR_LINE_COUNT / 2) - 1); tmpIndex++) {
                            if (bFirstLeft) {
                                if (!leftRoadIndexDict[-tmpIndex] && leftCount < Math.floor(this.ROAD_COLOR_LINE_COUNT / 2)) {
                                    return { rowIndex: rowIndex, roadIndex: -tmpIndex };
                                }
                            }
                            else {
                                if (!rightRoadIndexDict[tmpIndex] && rightCount < (Math.floor(this.ROAD_COLOR_LINE_COUNT / 2) + 1)) {
                                    return { rowIndex: rowIndex, roadIndex: tmpIndex };
                                }
                            }
                        }
                    }
                };
                let indexInfo = getValidRoadIndexFunc();
                let tmpY = cc.Ease.expoIn(Math.abs(indexInfo.roadIndex) / Math.floor(this.ROAD_COLOR_LINE_COUNT / 2)) * this.BOX_WH * indexInfo.rowIndex;
                let penModel = mgrLoader.Pool.getModel("bi");
                penModel.transform.localPosition = new Laya.Vector3((indexInfo.roadIndex) * this.BOX_WH, tmpY, -(indexInfo.rowIndex) * this.BOX_WH);
                penModel.transform.setWorldLossyScale(new Laya.Vector3(0.85, 0.85, 0.85));
                this.mapAvatarNode.addChild(penModel);
                this.setXieTaiColor(penModel, color);
                this.avatarGotShoeBoxArr.push({ penModel: penModel, rowIndex: indexInfo.rowIndex, roadIndex: indexInfo.roadIndex });
                if (indexInfo.rowIndex == 0 && !this.roadIndex2PenColorIndexDict[indexInfo.roadIndex]) {
                    let unusedPenColorIndex = this.getUnusedPenColorIndex();
                    let penColorData = this.penColorModelDict[unusedPenColorIndex];
                    penColorData.bUsing = true;
                    penColorData.roadIndex = indexInfo.roadIndex;
                    let creamArr = penColorData.creamArr;
                    for (let index = 0; index < creamArr.length; index++) {
                        let creamData = creamArr[index];
                        Tools.setModelAlbedoColor(creamData.model, color);
                    }
                    this.roadIndex2PenColorIndexDict[indexInfo.roadIndex] = unusedPenColorIndex;
                }
            }
            getUnusedPenColorIndex() {
                for (let k in this.penColorModelDict) {
                    let data = this.penColorModelDict[k];
                    if (!data.bUsing) {
                        return k;
                    }
                }
            }
            resetPlayerAndBoxPos() {
                if (this.disableAdatPlayerYEndTime && Tools.time() < this.disableAdatPlayerYEndTime) {
                    return;
                }
                if (this.avatarGotShoeBoxArr.length > 0) {
                    let maxRow = 0;
                    for (let i = 0; i < this.avatarGotShoeBoxArr.length; i++) {
                        let data = this.avatarGotShoeBoxArr[i];
                        if (data.rowIndex <= maxRow) {
                            continue;
                        }
                        maxRow = data.rowIndex;
                    }
                    this.avatar.transform.localPositionZ = -0.5 - maxRow * this.BOX_WH;
                }
                this.mapAvatarNode.transform.localPositionY = this.ladderStep * this.BOX_WH + this.elevatorPositionY + this.baseRoadPosition.y;
                if (this.stManager.getCurrStateRanTime() >= 2) {
                    let param = this.avatarPosCameraDict[1].cameraData;
                    this.cameraFollow.position.y = param.pos.y + this.ladderStep * this.BOX_WH + this.elevatorPositionY;
                    if (this.bInvincible && Math.abs(this.successNodeHolder.transform.position.z - this.mapAvatarNode.transform.position.z) > 5) {
                        this.cameraFollow.position.y += this.CAMERA_INVINCIBLE_POSITION_OFFSET.y;
                    }
                }
            }
            doAvatarMovingLerp(deltaTime) {
                try {
                    if (this.lastTouchBgPos && this.touchBgBeginPos) {
                        let roadWidth = this.BOX_WH * this.ROAD_LINE_COUNT;
                        let tmpx = (this.lastTouchBgPos.x - this.touchBgBeginPos.x) / (mgrDirector.width * 0.6) * (roadWidth) + (this.touchBgBeginAvatarPosX);
                        this.lastTouchResultMapAvatarPositionX = ul.clamp(tmpx, -roadWidth / 2, roadWidth / 2);
                    }
                    this.mapAvatarNode.transform.localPositionX = this.lastTouchResultMapAvatarPositionX + this.baseRoadPosition.x;
                    let deltaDis = 0;
                    if (this.currBarType == this.BAR_TYPE_SINGLE) {
                        deltaDis = ul.clamp(deltaTime * this.MOVE_FPS / 2, 0, this.BOX_WH / 2);
                    }
                    else {
                        deltaDis = ul.clamp(deltaTime * this.MOVE_FPS, 0, this.BOX_WH / 2);
                        if (this.mapAvatarNode.transform.localRotationEulerZ != 0) {
                            this.mapAvatarNode.transform.localRotationEulerZ -= (this.mapAvatarNode.transform.localRotationEulerZ * 0.1);
                        }
                    }
                    this.mapAvatarNode.transform.localPositionZ -= (deltaDis);
                    this.cameraFollow.lerpValue = 0.05;
                    let cameraOffsetZByShoe = ul.clamp(this.avatarGotShoeBoxArr.length, 0, 5) * this.BOX_WH;
                    let cameraOffsetRotByShoe = ul.clamp(this.avatarGotShoeBoxArr.length, 0, 5) * 3;
                    this.cameraFollow.position.z = this.mapAvatarNode.transform.localPositionZ + this.cameraWithAvatarZDiffDis + cameraOffsetZByShoe;
                    if (this.bInvincible && Math.abs(this.successNodeHolder.transform.position.z - this.mapAvatarNode.transform.position.z) > 5) {
                        this.cameraFollow.position.z += this.CAMERA_INVINCIBLE_POSITION_OFFSET.z;
                    }
                    this.cameraFollow.position.x = this.baseRoadPosition.x;
                    let param = this.avatarPosCameraDict[1].cameraData;
                    this.cameraFollow.endRotation.x = param.rot.x + cameraOffsetRotByShoe;
                    this.mapSky.transform.localPositionZ -= (deltaDis);
                    if (!!this.mapFog) {
                        if (this.mapAvatarNode.transform.position.z > (this.successNodeHolder.transform.position.z + 6)) {
                            this.mapFog.transform.localPositionZ = this.mapSky.transform.localPositionZ - 2;
                        }
                        else {
                            this.mapFog.transform.position = new Laya.Vector3(0, 0, 1000);
                        }
                    }
                }
                catch (error) {
                    console.log("-------avtarMoving lerp Error");
                }
            }
            inJudged() {
            }
            exeJudged() { }
            outJudged() { }
            inNextTurnReady() {
                mgrDirector.warpSceneWidthEffect(`vWorldDailyQuestMainScene`);
            }
            exeNextTurnReady() {
            }
            outNextTurnReady() {
            }
            inHitWallDie() {
                this.buttonBack.__node.visible = false;
                let soundIdArr = [697, 698];
                let soundId = soundIdArr[this.avatarGotShoeBoxArr.length <= 3 ? 0 : 1];
                mgrSound.play(soundId);
                this.avatar.playAnimation("paoku_shibai-paoku_shibai", 0, null, () => {
                    mgrDirector.openDialog("vAmusePenRevivalDialog", {
                        adEventId: AD_EVENT_ID.VIDEO.video_vAmuseFashionPenScene_super,
                        fOnAdResult: (bAded) => {
                            this.bPaused = false;
                            if (!bAded) {
                                this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.dieComplete);
                                return;
                            }
                            this.bReadyRevival = true;
                            this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.avatarMoving);
                            this.beginPenSuper();
                        }
                    });
                });
            }
            exeHitWallDie() {
            }
            outHitWallDie() {
            }
            inPrickDie() {
                this.buttonBack.__node.visible = false;
                let soundId = 691;
                mgrSound.play(soundId);
                let position = this.mapAvatarNode.transform.position.clone();
                let baseY = 0;
                let downYDiss = this.avatar.transform.localPositionY - baseY;
                let playerRoadLine = this.calculateRoadLineByPosX(this.mapAvatarNode.transform.localPositionX - this.baseRoadPosition.x);
                let animationId = null;
                if (playerRoadLine == -2 || playerRoadLine == 2) {
                    animationId = playerRoadLine == -2 ? this.DIE_ANIMATION_ID_BEST_LEFT : this.DIE_ANIMATION_ID_BEST_RIGHT;
                }
                else {
                    animationId = Tools.randomGotOneArrayData(this.DIE_ANIMATION_ID_ARR);
                }
                this.avatar.playAnimation(this.getAvatarRealAnimationId(this.avatar.context.roleId, animationId), 0, () => {
                    Timer.callLater(0.6, () => {
                        let doLerpPosFunc = (percent) => {
                            this.avatar.transform.localPositionY = baseY + downYDiss * (1 - percent);
                        };
                        let startTime = Tools.time();
                        let dur = 0.6;
                        Timer.callLoop(0.016, (timer) => {
                            let passTime = Tools.time() - startTime;
                            if (passTime >= dur) {
                                doLerpPosFunc(1);
                                timer.stop();
                                return;
                            }
                            doLerpPosFunc(passTime / dur);
                        }, this);
                    }, this);
                }, () => {
                    Timer.callLater(1, () => {
                        this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.dieComplete);
                    }, this);
                }, false, true);
            }
            exePrickDie() {
            }
            outPrickDie() {
            }
            inSingleBarDie() {
                this.buttonBack.__node.visible = false;
                let soundId = 691;
                mgrSound.play(soundId);
                let position = this.mapAvatarNode.transform.position.clone();
                let baseY = 0;
                let downYDiss = this.avatar.transform.localPositionY - baseY;
                let starRot = this.mapAvatarNode.transform.localRotationEulerZ;
                let movName = null;
                if (starRot > 0) {
                    movName = FASHION_SHOW_MOV.movSBDie03;
                }
                else if (starRot < 0) {
                    movName = FASHION_SHOW_MOV.movSBDie02;
                }
                else {
                    movName = FASHION_SHOW_MOV.movSBDie01;
                }
                let animationId = this.getAvatarRealAnimationId(this.avatar.context.roleId, movName);
                this.avatar.playAnimation(animationId, 0.1, () => {
                    this.avatar.hideShadow();
                    let doLerpPosFunc = (percent) => {
                        this.avatar.transform.localPositionY = baseY + downYDiss * (1 - percent);
                        this.mapAvatarNode.transform.localRotationEulerZ = starRot * (1 - percent);
                    };
                    let startTime = Tools.time();
                    let dur = 0.3;
                    Timer.callLoop(0.016, (timer) => {
                        let passTime = Tools.time() - startTime;
                        if (passTime >= dur) {
                            doLerpPosFunc(1);
                            timer.stop();
                            return;
                        }
                        doLerpPosFunc(passTime / dur);
                    }, this);
                }, () => {
                    Timer.callLater(1, () => {
                        this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.dieComplete);
                    }, this);
                }, false, true);
            }
            exeSingleBarDie() {
            }
            outSingleBarDie() {
            }
            inDoubleBarDie() {
                if (this.effHudongSmokeDoubleBar1) {
                    mgrLoader.Pool.recoverModel(this.effHudongSmokeDoubleBar1);
                    this.effHudongSmokeDoubleBar1 = null;
                }
                if (this.effHudongSmokeDoubleBar2) {
                    mgrLoader.Pool.recoverModel(this.effHudongSmokeDoubleBar2);
                    this.effHudongSmokeDoubleBar2 = null;
                }
                this.buttonBack.__node.visible = false;
                let soundId = 691;
                mgrSound.play(soundId);
                let position = this.mapAvatarNode.transform.position.clone();
                let baseY = 0;
                let downYDiss = this.avatar.transform.localPositionY - baseY;
                let leftRoleLine = this.doubleBarRoadLineArr[0];
                let rightRoleLine = this.doubleBarRoadLineArr[1];
                let playerRoadLine = this.calculateRoadLineByPosX(this.mapAvatarNode.transform.localPositionX - this.baseRoadPosition.x);
                let movName = null;
                if (playerRoadLine > rightRoleLine) {
                    movName = FASHION_SHOW_MOV.movSBDie03;
                }
                else {
                    movName = FASHION_SHOW_MOV.movSBDie02;
                }
                let animationId = this.getAvatarRealAnimationId(this.avatar.context.roleId, movName);
                this.avatar.playAnimation(animationId, 0.1, () => {
                    this.avatar.hideShadow();
                    let doLerpPosFunc = (percent) => {
                        this.avatar.transform.localPositionY = baseY + downYDiss * (1 - percent);
                    };
                    let startTime = Tools.time();
                    let dur = 0.3;
                    Timer.callLoop(0.016, (timer) => {
                        let passTime = Tools.time() - startTime;
                        if (passTime >= dur) {
                            doLerpPosFunc(1);
                            timer.stop();
                            return;
                        }
                        doLerpPosFunc(passTime / dur);
                    }, this);
                }, () => {
                    Timer.callLater(1, () => {
                        this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.dieComplete);
                    }, this);
                }, false, true);
            }
            exeDoubleBarDie() {
            }
            outDoubleBarDie() {
            }
            inDieComplete() {
                this.buttonBack.__node.visible = false;
                this.bSuccess = false;
                this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.reward);
            }
            exeDieComplete() {
            }
            outDieComplete() {
            }
            inRestartCurrTurn() {
                this.buttonBack.__node.visible = true;
                this.cleanStageMapNode(true);
                this.restoreNodeStatus();
                Timer.callLater(0.3, () => {
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.avatarComing);
                }, this);
            }
            exeRestartCurrTurn() {
            }
            outRestartCurrTurn() {
            }
            inArrivedDest() {
                if (this.stageData) {
                    this.staticsMethodCall("inArrivedDest", this.stageData.id);
                }
                if (!this.avatar || this.avatar.destroyed) {
                    return;
                }
                this.avatar.timeScale = 1;
                this.restoreNodeStatus();
                let rewardColorPoint = 0;
                this.bSuccess = true;
                this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.fillColor);
            }
            exeArrivedDest() {
            }
            outArrivedDest() {
            }
            inFillColor() {
                if (this.avatarGotShoeBoxArr.length == 0) {
                    this.jiesuanheModel.active = false;
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.reward);
                    return;
                }
                let targetPosition = this.jiesuanheModel.transform.position.clone();
                for (let k in this.avatarGotShoeBoxArr) {
                    let penData = this.avatarGotShoeBoxArr[k];
                    let position = penData.penModel.transform.position;
                    let diffPos = new Laya.Vector3;
                    Laya.Vector3.subtract(targetPosition, penData.penModel.transform.position, diffPos);
                    penData.penModel.removeSelf();
                    this.mapTmpNodeContainer.addChild(penData.penModel);
                    penData.penModel.transform.position = position;
                    penData.penModel.transform.lookAt(targetPosition, new Laya.Vector3);
                    let localPositon = penData.penModel.transform.localPosition.clone();
                    cc.tween(penData.penModel.transform)
                        .delay(Tools.random())
                        .to(0.2, { localRotationEulerX: 90, localPositionY: localPositon.y + 0.4 })
                        .to(0.4, { localPositionX: (localPositon.x + diffPos.x), localPositionY: (localPositon.y + diffPos.y) + 1, localPositionZ: (localPositon.z + diffPos.z) })
                        .call(() => {
                        let eff = mgrLoader.Pool.getModel("e_yanhua_09");
                        eff.transform.position = targetPosition.clone();
                        this.add3DEffectAtBack(eff);
                        mgrLoader.Pool.recoverModel(penData.penModel);
                    })
                        .start();
                }
                this.avatar.playAnimation("paoku_shifa-paoku_shifa", 0, null, null, true, true);
                Timer.callLater(2, () => {
                    this.avatar.playAnimation("paoku_idle-paoku_idle");
                    this.jiesuanheModel.active = false;
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.reward);
                }, this);
            }
            exeFillColor() {
            }
            outFillColor() {
            }
            inPalette() {
                mgrDirector.openDialog("vAmuseCakeResultDialog", {
                    colorItemId: Const.ITEM_ID_PARKOUR_COLOR,
                    oldColorPoint: this.oldColorPoint,
                    currGotColorPoint: this.currGotColorPoint,
                    dailyGameType: DailyGameType.pen,
                    bSuccess: this.bSuccess,
                    rewardPartId: mgrWorldDaily.getNextRewardPartId(DailyGameType.pen),
                    fOnClose: () => {
                        let rewardRmb = !!this.bSuccess ? this.stageData.bestRewardRmbAmount : this.stageData.goodRewardRmbAmount;
                        mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, rewardRmb, "潮笔结算奖励");
                        mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, rewardRmb, null, {
                            fOnClose: () => {
                                if (!!this.context.rewardSurprisePartId && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment)) {
                                    mgrDirector.openDialog("vSurpriseRewardDialog", {
                                        partId: this.context.rewardSurprisePartId,
                                        fOnClose: () => {
                                            this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.finish);
                                        }
                                    });
                                }
                                else {
                                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.finish);
                                }
                            }
                        });
                    }
                });
            }
            exePalette() {
            }
            outPalette() {
            }
            inJudgedShow() {
            }
            exeJudgedShow() {
                if (this.stManager.getCurrStateRanTime() >= 3) {
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.success);
                }
            }
            outJudgedShow() {
                let lightCameraFollow = this.directitonLight.getComponent(CameraFollow);
                lightCameraFollow.endRotation = this.getBackSceneLightRotation();
            }
            inArrivedShow() {
                if (this.stageData) {
                    this.staticsMethodCall("inArrivedShow", this.stageData.id);
                }
                let oldZ = this.mapAvatarNode.transform.localPositionZ;
                let doLerpPosFunc = (percent) => {
                    this.avatar.transform.localRotationEulerY = 180 * (1 - percent);
                    this.mapAvatarNode.transform.localPositionZ = oldZ + 0.3 * percent;
                    if (percent == 1) {
                        this.avatar.playAnimation(this.getAvatarRealAnimationIdArr(this.avatar.context.roleId, [FASHION_SHOW_MOV.movShow01, FASHION_SHOW_MOV.movShow02, FASHION_SHOW_MOV.movShow01]), 0.1, null, null, true);
                        Timer.callLater(3, () => {
                            this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.success);
                        }, this);
                    }
                };
                let startTime = Tools.time();
                let dur = 0.5;
                Timer.callLoop(0.016, (timer) => {
                    let passTime = Tools.time() - startTime;
                    if (passTime >= dur) {
                        doLerpPosFunc(1);
                        timer.stop();
                        return;
                    }
                    doLerpPosFunc(passTime / dur);
                }, this);
            }
            exeArrivedShow() {
            }
            outArrivedShow() {
            }
            inSuccess() {
                this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.reward);
            }
            exeSuccess() {
            }
            outSuccess() {
            }
            inReward() {
                this.spriteTitleSuccess.visible = !!this.bSuccess;
                this.spriteTitleFaild.visible = !this.spriteTitleSuccess.visible;
                this.spriteTitle.visible = true;
                this.spriteTitle.scale(3, 3, true);
                cc.tween(this.spriteTitle).toScale(0.1, 1)
                    .delay(0.5)
                    .call(() => {
                    let rewardColorPoint = 0;
                    if (this.bSuccess) {
                        rewardColorPoint = this.stageData.bestRewardColorPoint;
                    }
                    else {
                        rewardColorPoint = this.stageData.goodRewardColorPoint;
                    }
                    if (this.bSuccess) {
                        let gameWorldDailyData = mgrCfg.get_from_pen_daily_quest_config(mgrWorldDaily.getWorldDay()) || mgrCfg.get_from_pen_daily_quest_config(1);
                        mgrPlayer.addItemAmount(gameWorldDailyData.rewardItemId, gameWorldDailyData.rewardItemAmount, "潮笔结算奖励");
                    }
                    this.oldColorPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_PARKOUR_COLOR);
                    this.currGotColorPoint = rewardColorPoint;
                    mgrPlayer.addItemAmount(Const.ITEM_ID_PARKOUR_COLOR, rewardColorPoint, "潮笔结算奖励");
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.palette);
                })
                    .start();
            }
            exeReward() {
            }
            outReward() { }
            inFinish() {
                mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene");
            }
            exeFinish() { }
            outFinish() { }
            getAvatarRealAnimationIdArr(roleId, fashionShowMovArr) {
                let arr = [];
                let roleData = mgrCfg.get_from_amaze_pen_select_role_db(roleId);
                for (let i = 0; i < fashionShowMovArr.length; i++) {
                    let name = roleData[fashionShowMovArr[i]];
                    if (!name || name == "") {
                        console.log("---arr-对应的角色没有此动作", roleId, fashionShowMovArr[i]);
                        continue;
                    }
                    arr.push(name);
                }
                return arr;
            }
            getAvatarRealAnimationId(roleId, fashionShowMov) {
                let roleData = mgrCfg.get_from_amaze_pen_select_role_db(roleId);
                let name = roleData[fashionShowMov];
                if (!name || name == "") {
                    console.log("----对应的角色没有此动作", roleId, fashionShowMov);
                    return;
                }
                return name;
            }
            getModelMeshData(model) {
                let meshData;
                let positionArr = [];
                let vertices;
                let indices;
                let normals = [];
                let render = null;
                let getDataFunc = (model) => {
                    render = Tools.getMeshRender(model);
                    if (render) {
                        let meshFilter = model["_meshFilter"];
                        if (meshFilter) {
                            meshData = meshFilter.sharedMesh;
                            meshData.getPositions(positionArr);
                            vertices = meshData.getVertices();
                            indices = meshData.getIndices();
                            meshData.getNormals(normals);
                        }
                    }
                };
                getDataFunc(model);
                if (!meshData) {
                    let numChildren = model.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let node = model.getChildAt(i);
                        getDataFunc(node);
                        if (meshData) {
                            break;
                        }
                    }
                }
                return {
                    model: model,
                    render: render,
                    meshData: meshData,
                    positionArr: positionArr,
                    localPositionY: model.transform.localPositionY,
                    showingPositionArr: null,
                    handledPosArr: null,
                    handledRPosArr: null,
                    vertices: vertices,
                    indices: indices,
                    normals: normals,
                    creamCakeR: 0
                };
            }
            onTouchSpriteBg(e) {
                if (this.stManager.getCurState() == AMUSE_FASHION_PEN_STATE.backCount) {
                    if (!this.bTouchOnce) {
                        this.boxGuideStart.visible = false;
                        this.bTouchOnce = true;
                        this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.turnReady);
                    }
                    return;
                }
                if (this.stManager.getCurState() != AMUSE_FASHION_PEN_STATE.avatarMoving) {
                    return;
                }
                if (this.bInvincible && !!this.currBarType) {
                    return;
                }
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.touchBgBeginPos = new Laya.Vector2(e.pos.x, e.pos.y);
                    this.touchBgBeginAvatarPosX = this.mapAvatarNode.transform.localPositionX - this.baseRoadPosition.x;
                    this.touchBgBeginAvatarRotEulerZ = this.mapAvatarNode.transform.localRotationEulerZ;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                    this.avatarDirectionType = this.AVATAR_DIRECTION_STAY;
                    this.lastTouchBgPos = null;
                    this.touchBgBeginPos = null;
                }
                if (!this.touchBgBeginPos) {
                    this.touchBgBeginPos = null;
                    this.lastTouchBgPos = null;
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    this.lastTouchBgPos = e.pos;
                }
            }
            changeRoleAvatar(roleId, callback) {
                if (this.avatar && this.avatar.context.roleId != roleId) {
                    if (this.avatarGotShoeBoxArr) {
                        let count = this.avatarGotShoeBoxArr.length;
                        for (let i = (count - 1); i >= 0; i--) {
                            let data = this.avatarGotShoeBoxArr[i];
                            mgrLoader.Pool.recoverModel(data.penModel);
                            this.avatarGotShoeBoxArr.splice(i, 1);
                        }
                    }
                    this.avatar.destroy();
                    this.avatar = null;
                }
                if (!this.avatar) {
                    let penRoleData = mgrCfg.get_from_amaze_pen_select_role_db(roleId);
                    this.avatar = new RoleAvatar({ roleId: roleId, bDisableLoadShadow: true });
                    this.avatar.fillByPartIds(penRoleData.partIds);
                    this.mapAvatarNode.addChild(this.avatar);
                    if (callback) {
                        this.avatar.registerLoadEndCallback(callback);
                    }
                }
                else if (callback) {
                    callback();
                }
            }
            onRoleSelected(roleId) {
                let id = roleId;
                let data = mgrCfg.get_from_amaze_pen_select_role_db(id);
                if (!data) {
                    mgrTip.showMsgTip("咦，奇怪");
                    return;
                }
                this.refreshUi();
                this.adaptXieTaiColor();
                this.changeRoleAvatar(roleId);
                let modelId = "pen_color";
                let templateModel = mgrLoader.Pool.getModel(modelId);
                for (let roadIndex = 1; roadIndex <= this.ROAD_COLOR_LINE_COUNT; roadIndex++) {
                    let startPos = this.mapAvatarNode.transform.position;
                    this.lastHandedPenInfo = {
                        avatarPos: new Laya.Vector3(startPos.x, startPos.y, startPos.z)
                    };
                    let creamArr = [];
                    for (let index = 0; index < 3; index++) {
                        let creamModel = new Laya.MeshSprite3D(templateModel.meshFilter.sharedMesh.clone(), templateModel.name);
                        let materialArr = [];
                        let materialCount = templateModel.meshRenderer.sharedMaterials.length;
                        for (let matIndex = 0; matIndex < materialCount; matIndex++) {
                            let mat = new Laya.UnlitMaterial();
                            mat.albedoColor = new Laya.Vector4(Tools.random(255) / 255, Tools.random(255) / 255, Tools.random(255) / 255, 1);
                            materialArr.push(mat);
                        }
                        creamModel.meshRenderer.sharedMaterials = materialArr;
                        creamModel["__modelId"] = modelId;
                        creamModel.transform.position = new Laya.Vector3(0, startPos.y, startPos.z - index * this.PEN_COLOR_SIZE_Z);
                        this.add3DEffectAtBack(creamModel, 0);
                        let modelData = this.getModelMeshData(creamModel);
                        let showingPositionArr = [];
                        for (let i = 0; i < modelData.positionArr.length; i++) {
                            let tmpPos = modelData.positionArr[i];
                            showingPositionArr.push(new Laya.Vector3(0, tmpPos.y, tmpPos.z));
                        }
                        modelData.showingPositionArr = showingPositionArr;
                        modelData.meshData["_setVerticeElementData"](showingPositionArr, Laya.VertexMesh.MESH_POSITION0);
                        creamArr.push(modelData);
                    }
                    this.penColorModelDict[roadIndex] = { creamArr: creamArr, roadIndex: 0, bUsing: false };
                }
                mgrLoader.Pool.recoverModel(templateModel);
                let jiesuanheModel = mgrLoader.Pool.getModel("jiesuanhe");
                this.finishNodeHolder.parent.addChild(jiesuanheModel);
                this.jiesuanheModel = jiesuanheModel;
                this.jiesuanheModel.transform.rotationEuler = new Laya.Vector3(40, 0, 0);
                this.jiesuanheModel.transform.position = new Laya.Vector3(this.finishNodeHolder.transform.position.x, this.finishNodeHolder.transform.position.y + 2, this.finishNodeHolder.transform.position.z - 4);
                mgrTip.showLoadingTip("amuse_fashion_shoe_load_avatar");
                this.avatar.registerLoadEndCallback(() => {
                    mgrTip.hideLoadingTip("amuse_fashion_shoe_load_avatar");
                    let changeCallback = () => {
                        this.avatar.transform.position = new Laya.Vector3;
                        this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.backCount);
                    };
                    let bCustomFashionShoeStage = mgrSdk.getCopNumberValueByKey("b_fashion_shoe_custom_stage") != 1 ? false : true;
                    if (!!bCustomFashionShoeStage) {
                        mgrDirector.openDialog("vAmuseFashionShoeMapChangeDialog", { fOnClose: changeCallback });
                    }
                    else {
                        changeCallback();
                    }
                });
                let wallArr = [this.wallRowNodesArr];
                for (let i = 0; i < wallArr.length; i++) {
                    let wallRowNodesArr = wallArr[i];
                    let countContainer = wallRowNodesArr.length;
                    for (let i = 0; i < countContainer; i++) {
                        let tmpBox = wallRowNodesArr[i];
                        if (!!tmpBox.getChildByName("autoRoll")) {
                            let oldPosY = tmpBox.transform.localPositionY;
                            let oldScaleY = tmpBox.transform.localScaleY;
                            tmpBox["_originLocationPosition"] = tmpBox.transform.localPosition.clone();
                            tmpBox["_originLocationScale"] = tmpBox.transform.localScale.clone();
                            cc.tween(tmpBox.transform)
                                .repeatForever(cc.tween()
                                .to(0.2, { localPositionY: oldPosY + 0.5 + Tools.random() * 0.3 })
                                .to(0.2, { localPositionY: oldPosY })
                                .to(0.05, { localPositionY: oldPosY - 0.1, localScaleY: oldScaleY * 0.5 })
                                .delay(0.02)
                                .to(0.05, { localPositionY: oldPosY, localScaleY: oldScaleY }))
                                .start();
                        }
                    }
                }
                if (!!this.wallRowBaseNodesArr) {
                    for (let i = 0; i < this.wallRowBaseNodesArr.length; i++) {
                        let row = this.wallRowBaseNodesArr[i];
                        if (row.name == "autoRotationY") {
                            cc.tween(row.transform)
                                .repeatForever(cc.tween().by(2, { localRotationEulerY: 180 }))
                                .start();
                            let numChildren = row.numChildren;
                            for (let j = 0; j < numChildren; j++) {
                                let rowChild = row.getChildAt(j);
                                cc.tween(rowChild.transform)
                                    .repeatForever(cc.tween().by(0.5, { localRotationEulerX: rowChild.transform.localPositionX > 0 ? -180 : 180 }))
                                    .start();
                            }
                        }
                    }
                }
            }
            onSelectStageMode() {
                console.log("查看当前状态", this.stManager.getCurState());
                this.preinitData();
                this.genStageMap(() => {
                    this.stManager.setNextState(AMUSE_FASHION_PEN_STATE.waitStart);
                    this.preinitData();
                    this.genStageMap(() => {
                        this.onRoleSelected(this.context.roleId);
                    });
                });
                this.gameUiActionIn();
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(`vWorldDailyQuestMainScene`);
            }
            onTouchButtonRoleStyle() {
                mgrDirector.openDialog("vAmusePenChooseDialog", {
                    fOnConfirm: (roleId) => {
                    }
                });
            }
        }

        var AMUSE_PARKOUR_SHOE_STATE;
        (function (AMUSE_PARKOUR_SHOE_STATE) {
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["init"] = 1] = "init";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["waitStart"] = 2] = "waitStart";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["turnReady"] = 3] = "turnReady";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["avatarComing"] = 4] = "avatarComing";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["avatarMoving"] = 5] = "avatarMoving";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["nextTurnReady"] = 6] = "nextTurnReady";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["restartCurrTurn"] = 7] = "restartCurrTurn";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["addFlyShoe"] = 8] = "addFlyShoe";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["recoverCenter"] = 9] = "recoverCenter";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["success"] = 10] = "success";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["reward"] = 11] = "reward";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["palette"] = 12] = "palette";
            AMUSE_PARKOUR_SHOE_STATE[AMUSE_PARKOUR_SHOE_STATE["finish"] = 13] = "finish";
        })(AMUSE_PARKOUR_SHOE_STATE || (AMUSE_PARKOUR_SHOE_STATE = {}));
        class vAmuseParkourScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vAmuseParkourScene";
                this.exportNodeNames = [];
                this.avatar = null;
                this.avatarPosCameraDict = {
                    [0]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(-15, 0, 0)
                        },
                        cameraData: {
                            fov: 60,
                            pos: new Laya.Vector3(0, 1.06, 2),
                            rot: new Laya.Vector3(-5, 0, 0),
                        }
                    },
                    [1]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(-15, 0, 0)
                        },
                        cameraData: {
                            fov: 70,
                            pos: new Laya.Vector3(0, 3.26, -0.65),
                            rot: new Laya.Vector3(-32, 0, 0),
                        }
                    },
                    [2]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(-7, 0, 0)
                        },
                        cameraData: {
                            fov: 45,
                            pos: new Laya.Vector3(0.3, 1.31, -30),
                            rot: new Laya.Vector3(-7, 0, 0),
                        }
                    },
                    [3]: {
                        avatarData: {
                            pos: new Laya.Vector3(0, 0, 0),
                            rot: new Laya.Vector3(-7, 0, 0)
                        },
                        cameraData: {
                            fov: 45,
                            pos: new Laya.Vector3(1.0, 2.66, -41.4),
                            rot: new Laya.Vector3(-22, 15, 0),
                        }
                    },
                };
                this.targetPercentage = 0;
                this.ROAD_TYPE_2_IMG_DICT = {
                    [0]: "res/material/parkour_road/map12_01.png",
                    [1]: "res/material/parkour_road/map12_01.png",
                    [2]: "res/material/parkour_road/map12_02.png",
                    [3]: "res/material/parkour_road/map12_03.png",
                    [4]: "res/material/parkour_road/map12_04.png",
                };
                this.colorPoorNodesArr = [];
                this.partClothNodesArr = [];
                this.partHairNodesArr = [];
                this.partShoeNodesArr = [];
                this.hairSprayNodesArr = [];
                this.mlbNodeArr = [];
                this.partModels = [];
                this.pengguanModelsArr = [];
                this.successPosZ = 0;
                this.cameraWithAvatarZDiffDis = 0;
                this.bPaused = false;
                this.cameraWithAvatarOffsetPosInRecover = new Laya.Vector3(0, 0, 3.357);
                this.bSuccess = false;
                this.clothColorId = 0;
                this.clothGridId = 0;
                this.clothShineId = 0;
                this.hairColorId = 0;
                this.hairGridId = 0;
                this.hairShineId = 0;
                this.coloredLog = {};
                this.SINK_HIGHT = 1.3;
                this.curSinkHeight = 0;
                this.bLockHorizontalMove = false;
                this.curDressClothPartId = 0;
                this.curDressShoePartId = 0;
                this.shoedLog = {};
                this.clothedLog = {};
                this.hairedLog = {};
                this.curDressHairPartId = 0;
                this.bTriggeredSuper = true;
                this.INVINCIBLE_FPS_RATIO = 3;
                this.bInvincible = false;
                this.lastTouchResultMapAvatarPositionX = 0;
                this.MOVE_FPS = 1;
                this.ROAD_WH = 2;
                this.baseRoadPosition = new Laya.Vector3;
                this.touchBgBeginAvatarPosX = 0;
                this.bTriggeredForzen = true;
                this.bTriggeredMagneted = true;
                this.bMagneted = false;
                this.preInitData();
            }
            getPreLoadModelIds() {
                let preloadModelIdArr = [
                    "penping_design",
                    "baozuo",
                    "tiankonghe",
                    "117_ui_loop_spraysmoke_01",
                    "e_explode",
                    "e_daoju_wudi",
                    "eff_ui_chaoxie_spglow",
                    "zhuangshi01",
                    "zhuangshi06",
                    "117_e_loop_cointrail",
                    "117_e_loop_snow",
                    "mlb"
                ];
                preloadModelIdArr.push(this.stageData.stageModelId);
                return preloadModelIdArr;
            }
            getPreLoadAnimationIds() {
                return [
                    "paoku_idle-paoku_idle",
                    "paoku_move-paoku_fly",
                    "paoku_walk-paoku_walk",
                ];
            }
            getPreLoadImagePaths() {
                let imgArr = [this.stageData.targetPreviewImg];
                let roadPaint = this.ROAD_TYPE_2_IMG_DICT[this.stageData.roadType] || this.ROAD_TYPE_2_IMG_DICT[0];
                imgArr.push(roadPaint);
                return imgArr;
            }
            preInitData() {
                let stageId = this.context.stageId || 1;
                this.stageData = mgrCfg.get_from_amaze_parkour_stage_db(stageId);
                this.stageData.statisPointId && mgrSdk.statisOnStageStart(`${this.stageData.statisPointId}`, `${stageId}`);
            }
            onOpened() {
                super.onOpened();
                this.widget();
                Tools.registerTouchHander(this.spritePreivewMask, () => {
                    this.hidePreivew();
                });
                mgrSound.play(7);
                this.spriteTitle.visible = false;
                this.buildScene(() => {
                    this.cameraBack.farPlane = 500;
                    this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                    this.cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                    let param = this.avatarPosCameraDict[0].cameraData;
                    this.cameraFollow.position = param.pos.clone();
                    this.cameraFollow.endRotation = param.rot.clone();
                    this.cameraFollow.fov = param.fov;
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                    this.stManager = new FSMObject;
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.waitStart, this.inWaitStart.bind(this), this.exeWaitStart.bind(this), this.outWaitStart.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.turnReady, this.inTurnReady.bind(this), this.exeTurnReady.bind(this), this.outTurnReady.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.avatarComing, this.inAvatarComing.bind(this), this.exeAvatarComing.bind(this), this.outAvatarComing.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.avatarMoving, this.inAvatarMoving.bind(this), this.exeAvatarMoving.bind(this), this.outAvatarMoving.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.nextTurnReady, this.inNextTurnReady.bind(this), this.exeNextTurnReady.bind(this), this.outNextTurnReady.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.restartCurrTurn, this.inRestartCurrTurn.bind(this), this.exeRestartCurrTurn.bind(this), this.outRestartCurrTurn.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.addFlyShoe, this.inAddFlyShoe.bind(this), this.exeAddFlyShoe.bind(this), this.outAddFlyShoe.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.success, this.inSuccess.bind(this), this.exeSuccess.bind(this), this.outSuccess.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.recoverCenter, this.inRecoverCenter.bind(this), this.exeRecoverCenter.bind(this), this.outRecoverCenter.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.reward, this.inReward.bind(this), this.exeReward.bind(this), this.outReward.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.palette, this.inPalette.bind(this), this.exePalette.bind(this), this.outPalette.bind(this));
                    this.stManager.registerState(AMUSE_PARKOUR_SHOE_STATE.finish, this.inFinish.bind(this), this.exeFinish.bind(this), this.outFinish.bind(this));
                    this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.init);
                    this.stManager.startUpdate(this, this.onTimerLoop.bind(this));
                    this.topBar = new vTopBar({ bDisableEnergy: true });
                    this.spriteTopBarHolder.addChild(this.topBar);
                    this.registerListeners({});
                });
            }
            onTimerLoop() {
            }
            widget() {
                mgrLayout.widgetRightTopMC(this.boxRightTop);
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftTopMC(this.boxLeftTop);
                mgrLayout.centerNodeBaseContent(this.spritePreviewContainer);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            buildScene(callback) {
                let mapSky = mgrLoader.Pool.getModel("tiankonghe");
                this.add3DEffectAtBack(mapSky, 0);
                mapSky.transform.position = new Laya.Vector3(0, 0, 0);
                this.mapSky = mapSky;
                Tools.loadImg(this.spritePreviewClothes, this.stageData.targetPreviewImg);
                this.add3DEffectAtBack(this.stageData.stageModelId, 0, (model) => {
                    this.mapStage = model;
                    callback && callback();
                });
                this.spriteRule.visible = false;
                this.labelScorePercentage.visible = false;
            }
            initLoadedStageMapModel() {
                let model = this.mapStage;
                let avatarNode = model.getChildByName("avatarNode");
                this.mapAvatarNode = new Laya.Sprite3D;
                this.mapAvatarNode.transform.position = avatarNode.transform.position;
                this.add3DEffectAtBack(this.mapAvatarNode, 0);
                let numChildren = 0;
                let mapNode = model.getChildByName("map");
                if (!!mapNode) {
                    numChildren = mapNode.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let luNode = mapNode.getChildAt(i);
                        let preName = luNode.name.substr(0, 4);
                        let renderer = Tools.getMeshRender(luNode);
                        if (renderer) {
                            for (let i = 0; i < renderer.sharedMaterials.length; i++) {
                                let mat = renderer.sharedMaterials[i];
                                let roadPaint = this.ROAD_TYPE_2_IMG_DICT[this.stageData.roadType] || this.ROAD_TYPE_2_IMG_DICT[0];
                                let texture = mgrLoader.get2dRes(roadPaint);
                                let text2d = texture.bitmap;
                                if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                    text2d.wrapModeU = Laya.WarpMode.Repeat;
                                    text2d.wrapModeV = Laya.WarpMode.Repeat;
                                    text2d.filterMode = Laya.FilterMode.Bilinear;
                                    text2d.generateMipmap();
                                }
                                mat.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                mat.albedoTexture = text2d;
                            }
                            let modelId = preName;
                            if (preName == "lu01" || "lu02" || "lu03" || "lu04" || "lu05") {
                                mgrMaterial.__setCustomMaterial(renderer, modelId, 0, modelId);
                            }
                        }
                        let colorPoorNode = luNode.getChildByName("colorPoor");
                        if (colorPoorNode && colorPoorNode.numChildren > 0) {
                            for (let tmp = 0; tmp < colorPoorNode.numChildren; tmp++) {
                                let tmpNode = colorPoorNode.getChildAt(tmp);
                                this.colorPoorNodesArr.push(tmpNode);
                            }
                            if (colorPoorNode.numChildren == 1) {
                                let colorNode = colorPoorNode.getChildAt(0);
                                let colorId = parseInt(colorNode.name);
                                let gridNode = colorNode.getChildByName("gridNode");
                                let shineNode = colorNode.getChildByName("shineNode");
                                let gridId = 0;
                                let shineId = 0;
                                if (gridNode && gridNode.numChildren > 0) {
                                    gridId = parseInt(gridNode.getChildAt(0).name);
                                }
                                if (shineNode && shineNode.numChildren > 0) {
                                    shineId = parseInt(shineNode.getChildAt(0).name);
                                }
                                this.renderingColorPool(colorId, luNode, 0, gridId, shineId);
                            }
                            else if (colorPoorNode.numChildren == 2) {
                                let rightColorNode = colorPoorNode.getChildAt(0);
                                let rightColorId = parseInt(rightColorNode.name);
                                let leftColorNode = colorPoorNode.getChildAt(1);
                                let leftColorId = parseInt(leftColorNode.name);
                                let rightGridNode = rightColorNode.getChildByName("gridNode");
                                let rightShineNode = rightColorNode.getChildByName("shineNode");
                                let rightGridId = 0;
                                let rightShineId = 0;
                                if (rightGridNode && rightGridNode.numChildren > 0) {
                                    rightGridId = parseInt(rightGridNode.getChildAt(0).name);
                                }
                                if (rightShineNode && rightShineNode.numChildren > 0) {
                                    rightShineId = parseInt(rightShineNode.getChildAt(0).name);
                                }
                                let leftGridNode = leftColorNode.getChildByName("gridNode");
                                let leftShineNode = leftColorNode.getChildByName("shineNode");
                                let leftGridId = 0;
                                let leftShineId = 0;
                                if (leftGridNode && leftGridNode.numChildren > 0) {
                                    leftGridId = parseInt(leftGridNode.getChildAt(0).name);
                                }
                                if (leftShineNode && leftShineNode.numChildren > 0) {
                                    leftShineId = parseInt(leftShineNode.getChildAt(0).name);
                                }
                                this.renderingColorPool(rightColorId, luNode, 1, rightGridId, rightShineId);
                                this.renderingColorPool(leftColorId, luNode, 2, leftGridId, leftShineId);
                            }
                        }
                    }
                }
                let partShoeNodes = model.getChildByName("partShoeNodes");
                if (!!partShoeNodes) {
                    numChildren = partShoeNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let clothPaNode = partShoeNodes.getChildAt(i);
                        let partId = parseInt(clothPaNode.name);
                        let partData = mgrCfg.get_from_part_db(partId);
                        mgrLoader.loadModeWithModeId(partData.modelId, () => {
                            mgrLoader.markPartResLoaded(partId);
                            let model = mgrLoader.Pool.getModel(partData.modelId);
                            let animator = model.getComponent(Laya.Animator);
                            if (!animator) {
                                animator = model.addComponent(Laya.Animator);
                            }
                            animator.speed = 0.00001;
                            mgrMaterial.setCustomMaterial(model, partData.modelId, 0, true);
                            clothPaNode.addChild(model);
                        }, this, 1);
                        this.partShoeNodesArr.push(clothPaNode);
                    }
                }
                let partClothNodes = model.getChildByName("partClothNodes");
                if (!!partClothNodes) {
                    numChildren = partClothNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let clothPaNode = partClothNodes.getChildAt(i);
                        let partId = parseInt(clothPaNode.name);
                        let partData = mgrCfg.get_from_part_db(partId);
                        mgrLoader.loadModeWithModeId(partData.modelId, () => {
                            mgrLoader.markPartResLoaded(partId);
                            let model = mgrLoader.Pool.getModel(partData.modelId);
                            let animator = model.getComponent(Laya.Animator);
                            if (!animator) {
                                animator = model.addComponent(Laya.Animator);
                            }
                            animator.speed = 0.00001;
                            mgrMaterial.setCustomMaterial(model, partData.modelId, 0, true);
                            let gridNode = clothPaNode.getChildByName("gridNode");
                            let gridData = null;
                            if (gridNode && gridNode.numChildren > 0 && parseInt(gridNode.getChildAt(0).name) > 0) {
                                gridData = mgrCfg.get_from_design_grid_db(parseInt(gridNode.getChildAt(0).name));
                            }
                            let shineNode = clothPaNode.getChildByName("shineNode");
                            let shineData = null;
                            if (shineNode && shineNode.numChildren > 0 && parseInt(shineNode.getChildAt(0).name) > 0) {
                                shineData = mgrCfg.get_from_design_shine_db(parseInt(shineNode.getChildAt(0).name));
                            }
                            let colorNode = clothPaNode.getChildByName("colorNode");
                            let colorData = null;
                            if (colorNode && colorNode.numChildren > 0 && parseInt(colorNode.getChildAt(0).name) > 0) {
                                colorData = mgrCfg.get_from_design_part_color_db(parseInt(colorNode.getChildAt(0).name));
                            }
                            this.designPartModel(model, colorData, gridData, shineData);
                            this.partModels.push(model);
                            clothPaNode.addChild(model);
                        }, this, 1);
                        this.partClothNodesArr.push(clothPaNode);
                    }
                }
                let partHairNodes = model.getChildByName("partHairNodes");
                if (!!partHairNodes) {
                    numChildren = partHairNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let hairPaNode = partHairNodes.getChildAt(i);
                        let partId = parseInt(hairPaNode.name);
                        let partData = mgrCfg.get_from_part_db(partId);
                        mgrLoader.loadModeWithModeId(partData.modelId, () => {
                            mgrLoader.markPartResLoaded(partId);
                            let model = mgrLoader.Pool.getModel(partData.modelId);
                            let animator = model.getComponent(Laya.Animator);
                            if (!animator) {
                                animator = model.addComponent(Laya.Animator);
                            }
                            animator.speed = 0.00001;
                            mgrMaterial.setCustomMaterial(model, partData.modelId, 0, true);
                            let gridNode = hairPaNode.getChildByName("gridNode");
                            let gridData = null;
                            if (gridNode && gridNode.numChildren > 0 && parseInt(gridNode.getChildAt(0).name) > 0) {
                                gridData = mgrCfg.get_from_design_grid_db(parseInt(gridNode.getChildAt(0).name));
                            }
                            let shineNode = hairPaNode.getChildByName("shineNode");
                            let shineData = null;
                            if (shineNode && shineNode.numChildren > 0 && parseInt(shineNode.getChildAt(0).name) > 0) {
                                shineData = mgrCfg.get_from_design_shine_db(parseInt(shineNode.getChildAt(0).name));
                            }
                            let colorNode = hairPaNode.getChildByName("colorNode");
                            let colorData = null;
                            if (colorNode && colorNode.numChildren > 0 && parseInt(colorNode.getChildAt(0).name) > 0) {
                                colorData = mgrCfg.get_from_design_part_color_db(parseInt(colorNode.getChildAt(0).name));
                            }
                            this.designPartModel(model, colorData, gridData, shineData);
                            this.partModels.push(model);
                            hairPaNode.addChild(model);
                        }, this, 1);
                        this.partHairNodesArr.push(hairPaNode);
                    }
                }
                let hairSprayNodes = model.getChildByName("hairSprayNodes");
                if (!!hairSprayNodes) {
                    numChildren = hairSprayNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let hairSpayPaNode = hairSprayNodes.getChildAt(i);
                        let penguanModel = mgrLoader.Pool.getModel("penping_design");
                        mgrMaterial.setCustomMaterial(penguanModel, "penping_design");
                        penguanModel.transform.setWorldLossyScale(new Laya.Vector3(2, 2, 2));
                        if (hairSpayPaNode.transform.position.x < 0) {
                            penguanModel.transform.localRotationEulerY = -60;
                        }
                        else {
                            penguanModel.transform.localRotationEulerY = 60;
                        }
                        let penguanEffNode = Tools.findNode("guadian_eff", penguanModel);
                        let penguanEffModel = mgrLoader.Pool.getModel("117_ui_loop_spraysmoke_01");
                        penguanEffModel.transform.setWorldLossyScale(new Laya.Vector3(1.2, 1.2, 1.2));
                        penguanEffNode.addChild(penguanEffModel);
                        penguanEffModel.transform.localRotationEulerY = -90;
                        let colorId = parseInt(hairSpayPaNode.name);
                        this.changePenguanColor(penguanEffModel, colorId);
                        this.pengguanModelsArr.push(penguanEffModel);
                        this.partModels.push(penguanModel);
                        hairSpayPaNode.addChild(penguanModel);
                        this.hairSprayNodesArr.push(hairSpayPaNode);
                    }
                }
                let mlbNodes = model.getChildByName("mlbNodes");
                if (!!mlbNodes) {
                    numChildren = mlbNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let mlbNode = mlbNodes.getChildAt(i);
                        this.mlbNodeArr.push(mlbNode);
                    }
                }
                let superRunNode = model.getChildByName("superRunNode");
                if (!!superRunNode) {
                    this.superRunNode = superRunNode;
                }
                let endNodes = model.getChildByName("endNodes");
                if (!!endNodes) {
                    this.successPosZ = endNodes.transform.position.z;
                    this.endNodes = endNodes;
                }
                let successNode = endNodes.getChildByName("successNode");
                if (!!successNode) {
                    this.successPosZ = successNode.transform.position.z;
                }
                let endPosSeatNode = endNodes.getChildByName("endPosSeatNode");
                if (!!endPosSeatNode) {
                    this.endPosSeatNode = endPosSeatNode;
                    let jiesuanheModel = mgrLoader.Pool.getModel("baozuo");
                    mgrMaterial.setCustomMaterial(jiesuanheModel, "baozuo");
                    this.partModels.push(jiesuanheModel);
                    this.endPosSeatNode.addChild(jiesuanheModel);
                }
                let recoverCenterPos = endNodes.getChildByName("recoverCenterPos");
                if (!!recoverCenterPos) {
                    this.recoverCenterPos = recoverCenterPos;
                }
                let frozenNode = model.getChildByName("frozenNode");
                if (!!frozenNode) {
                    this.frozenNode = frozenNode;
                }
                let magnetNode = model.getChildByName("magnetNode");
                if (!!magnetNode) {
                    this.magnetNode = magnetNode;
                }
            }
            designPartModel(model, colorData, gridData, shineData) {
                let emptyColorId = 4086;
                let emptyColorPaint = mgrCfg.get_from_design_part_color_db(emptyColorId).paint;
                let emptyGridId = 4299;
                let emptyGridPaint = mgrCfg.get_from_design_grid_db(emptyGridId).paint;
                let emptyShineId = 4199;
                let emptyShinePaint = mgrCfg.get_from_design_shine_db(emptyShineId).paint;
                for (let i = 0; i < model.numChildren; i++) {
                    let child = model.getChildAt(i);
                    let renderer = Tools.getMeshRender(child);
                    if (renderer) {
                        for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                            let material = renderer.sharedMaterials[j];
                            if (material.PlayerCustomChangeFlag < 0.5) {
                                continue;
                            }
                            Tools.loadMaterialTexture(Const.SKIN_CONTROL_GRID_SHINE_PATH, material, "controlDetailTexture");
                            material.albedoColor = new Laya.Vector4(0.88, 0.88, 0.88, 1.0);
                            material.albedoTexture = null;
                            material.AlbedoTillingX = 1.0;
                            material.AlbedoTillingY = 1.0;
                            Tools.loadMaterialTexture(emptyColorPaint, material, "albedoTexture");
                            Tools.loadMaterialTexture(emptyGridPaint, material, "gridTexture");
                            Tools.loadMaterialTexture(emptyShinePaint, material, "shineTexture");
                            material.gridTextureScale = 1.0;
                            material.shineTextureScale = 1.0;
                        }
                    }
                }
                if (!!gridData) {
                    mgrLoader.Load2dRes(gridData.paint, Laya.Loader.IMAGE, this, (res) => {
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    material.gridTextureScale = gridData.tillingOffset[0] || 1;
                                    Tools.loadMaterialTexture(gridData.paint, material, "gridTexture");
                                }
                            }
                        }
                    });
                }
                if (!!shineData) {
                    mgrLoader.Load2dRes(shineData.paint, Laya.Loader.IMAGE, this, (res) => {
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    material.shineTextureScale = shineData.tillingOffset[0] || 1;
                                    Tools.loadMaterialTexture(shineData.paint, material, "shineTexture");
                                }
                            }
                        }
                    });
                }
                if (!!colorData) {
                    let callback = () => {
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    let texture = null;
                                    if (colorData.paint == "") {
                                        texture = Tools.createPureColorTexture(new Laya.Color(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1));
                                    }
                                    else {
                                        texture = mgrLoader.get2dRes(colorData.paint);
                                    }
                                    let tex2d = texture.bitmap;
                                    if (tex2d.wrapModeU != Laya.WarpMode.Repeat) {
                                        tex2d.wrapModeU = Laya.WarpMode.Repeat;
                                        tex2d.wrapModeV = Laya.WarpMode.Repeat;
                                        tex2d.filterMode = Laya.FilterMode.Bilinear;
                                        tex2d.generateMipmap();
                                    }
                                    material.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                    material.albedoTexture = tex2d;
                                    material.AlbedoTillingX = colorData.tillingOffset[0] || 1;
                                    material.AlbedoTillingY = colorData.tillingOffset[1] || 1;
                                }
                            }
                        }
                    };
                    if (colorData.paint == "") {
                        callback();
                    }
                    else {
                        mgrLoader.batchLoadResources([], [], [colorData.paint], () => {
                            callback();
                        });
                    }
                }
            }
            renderingColorPool(colorId, node, type, gridId, shineId) {
                let colorData = mgrCfg.get_from_design_part_color_db(colorId);
                let gridData = mgrCfg.get_from_design_grid_db(gridId);
                let shineData = mgrCfg.get_from_design_shine_db(shineId);
                let callback = () => {
                    let child = node;
                    let renderer = Tools.getMeshRender(child);
                    if (renderer) {
                        let matArr = [];
                        for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                            let matOld = renderer.sharedMaterials[j];
                            if (matOld.name != "youchi_1" && matOld.name != "zuochi_1" && matOld.name != "youchi_2" && matOld.name != "zuochi_2") {
                                matArr.push(matOld);
                                continue;
                            }
                            let mat = matOld.clone();
                            matArr.push(mat);
                            if (type == 1) {
                                if (matOld.name != "youchi_1" && matOld.name != "youchi_2") {
                                    continue;
                                }
                            }
                            else if (type == 2) {
                                if (matOld.name != "zuochi_1" && matOld.name != "zuochi_2") {
                                    continue;
                                }
                            }
                            if (matOld.name == "youchi_1" || matOld.name == "zuochi_1") {
                                mat.renderQueue = 2900;
                                if (colorData.paint == "") {
                                    mat.albedoTexture = null;
                                    mat.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                }
                                else {
                                    let texture = mgrLoader.get2dRes(colorData.paint);
                                    let text2d = texture.bitmap;
                                    if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                        text2d.wrapModeU = Laya.WarpMode.Repeat;
                                        text2d.wrapModeV = Laya.WarpMode.Repeat;
                                        text2d.filterMode = Laya.FilterMode.Bilinear;
                                        text2d.generateMipmap();
                                    }
                                    mat.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                    mat.albedoTexture = text2d;
                                }
                            }
                            else if (matOld.name == "youchi_2" || matOld.name == "zuochi_2") {
                                if (gridId && gridData) {
                                    let texture = mgrLoader.get2dRes(gridData.paint);
                                    let text2d = texture.bitmap;
                                    if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                        text2d.wrapModeU = Laya.WarpMode.Repeat;
                                        text2d.wrapModeV = Laya.WarpMode.Repeat;
                                        text2d.filterMode = Laya.FilterMode.Bilinear;
                                        text2d.generateMipmap();
                                    }
                                    mat.albedoTexture = text2d;
                                    mat.tilingOffset = new Laya.Vector4(gridData.tillingOffset[0], gridData.tillingOffset[1], 1, 1);
                                }
                                else if (shineId && shineData) {
                                    let texture = mgrLoader.get2dRes(shineData.paint);
                                    let text2d = texture.bitmap;
                                    if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                        text2d.wrapModeU = Laya.WarpMode.Repeat;
                                        text2d.wrapModeV = Laya.WarpMode.Repeat;
                                        text2d.filterMode = Laya.FilterMode.Bilinear;
                                        text2d.generateMipmap();
                                    }
                                    mat.albedoTexture = text2d;
                                    mat.tilingOffset = new Laya.Vector4(shineData.tillingOffset[0], shineData.tillingOffset[1], 1, 1);
                                }
                                else {
                                    mat.renderQueue = 2800;
                                }
                            }
                        }
                        renderer.sharedMaterials = matArr;
                    }
                };
                let loadPaintArr = [];
                if (colorData && colorData.paint) {
                    loadPaintArr.push(colorData.paint);
                }
                if (gridData && gridData.paint) {
                    loadPaintArr.push(gridData.paint);
                }
                if (shineData && shineData.paint) {
                    loadPaintArr.push(shineData.paint);
                }
                if (loadPaintArr.length <= 0) {
                    callback();
                }
                else {
                    mgrLoader.batchLoadResources([], [], loadPaintArr, () => {
                        callback();
                    });
                }
            }
            changePenguanColor(penguanEffModel, colorId) {
                let colorData = mgrCfg.get_from_design_part_color_db(colorId);
                let color = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                let numChildren = penguanEffModel.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let child = penguanEffModel.getChildAt(i);
                    child.particleSystem.startColorConstant = color;
                    child.particleSystem.startColorConstantMin = color;
                    child.particleSystem.startColorConstantMax = color;
                    let numChildren2 = child.numChildren;
                    for (let i = 0; i < numChildren2; i++) {
                        let child2 = child.getChildAt(i);
                        child2.particleSystem.startColorConstant = color;
                        child2.particleSystem.startColorConstantMin = color;
                        child2.particleSystem.startColorConstantMax = color;
                    }
                }
            }
            showPreview() {
                this.spritePreivewMask.visible = true;
                this.spritePreviewContainer["_originPos"] = this.spritePreviewContainer["_originPos"] || new Laya.Vector2(this.spritePreviewContainer.x, this.spritePreviewContainer.y);
                cc.tween(this.spritePreviewContainer, true).parallel(cc.tween().toScale(0.3, 1), cc.tween().toPos(0.3, this.spritePreviewContainer["_originPos"].x, this.spritePreviewContainer["_originPos"].y)).start();
            }
            hidePreivew() {
                this.spritePreivewMask.visible = false;
                cc.tween(this.spritePreviewContainer, true).parallel(cc.tween().toScale(0.3, 0.5), cc.tween().toPos(0.3, this.buttonPreview.__node.x, this.buttonPreview.__node.y)).start();
            }
            extractPartModelIdsFromStageMode() {
                let model = this.mapStage;
                let partIds = [];
                let numChildren = 0;
                let partShoeNodes = model.getChildByName("partShoeNodes");
                if (!!partShoeNodes) {
                    numChildren = partShoeNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let clothPaNode = partShoeNodes.getChildAt(i);
                        let partId = parseInt(clothPaNode.name);
                        partIds.push(partId);
                    }
                }
                let partClothNodes = model.getChildByName("partClothNodes");
                if (!!partClothNodes) {
                    numChildren = partClothNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let clothPaNode = partClothNodes.getChildAt(i);
                        let partId = parseInt(clothPaNode.name);
                        partIds.push(partId);
                    }
                }
                let partHairNodes = model.getChildByName("partHairNodes");
                if (!!partHairNodes) {
                    numChildren = partHairNodes.numChildren;
                    for (let i = 0; i < numChildren; i++) {
                        let clothPaNode = partHairNodes.getChildAt(i);
                        let partId = parseInt(clothPaNode.name);
                        partIds.push(partId);
                    }
                }
                partIds = partIds.filter((item, index) => {
                    return partIds.indexOf(item) == index;
                });
                let arr = [];
                for (let k in partIds) {
                    let partData = mgrCfg.get_from_part_db(partIds[k]);
                    if (!partData.modelId || arr.indexOf(partData.modelId) >= 0 || mgrLoader.Pool.containModel(partData.modelId)) {
                        continue;
                    }
                    arr.push(partData.modelId);
                }
                return arr;
            }
            inInit() {
                this.MOVE_FPS = this.stageData.moveFps;
                let roleId = mgrRole.showingRoleId;
                let initPartIds = [13000, 16000];
                let roleData = mgrCfg.get_from_role_db(roleId);
                for (let k in roleData.centerPartIds) {
                    let partData = mgrCfg.get_from_part_db(roleData.centerPartIds[k]);
                    if (partData.type == PartType.hair || partData.type == PartType.face) {
                        initPartIds.push(partData.id);
                    }
                }
                let usePartIds = null;
                let onResPreloadedFunc = () => {
                    this.initLoadedStageMapModel();
                    if (!this.avatar) {
                        this.avatar = new RoleAvatar({ roleId, bDisableLoadShadow: true, bDesignPartForceUseTextureColor: true });
                    }
                    this.avatar.fillByPartIds(usePartIds);
                    this.mapAvatarNode.addChild(this.avatar);
                    this.avatar.registerLoadEndCallback(() => {
                        mgrTip.hideLoadingTip("parkour_avatar_loading");
                        Timer.callLater(2, () => {
                            this.hidePreivew();
                        });
                        this.avatar.transform.localPosition = new Laya.Vector3(0, 0.1, 0);
                        this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.waitStart);
                    });
                };
                let onSkinConfirmFunc = (skinPartIds) => {
                    let modelIds = this.extractPartModelIdsFromStageMode();
                    let partIds = skinPartIds || initPartIds;
                    partIds.forEach(v => {
                        let partData = mgrCfg.get_from_part_db(v);
                        if (partData.type == PartType.cloth) {
                            this.curDressClothPartId = v;
                        }
                        if (partData.type == PartType.hair) {
                            this.curDressHairPartId = v;
                        }
                        if (partData.type == PartType.shoe) {
                            this.curDressShoePartId = v;
                        }
                        if (!partData.modelId || modelIds.indexOf(partData.modelId) >= 0 || mgrLoader.Pool.containModel(partData.modelId)) {
                            return;
                        }
                        modelIds.push(partData.modelId);
                    });
                    usePartIds = partIds;
                    mgrTip.showLoadingTip("parkour_avatar_loading", null, 0, true, "正在装饰跑道");
                    mgrLoader.batchLoadResources(modelIds, null, null, () => {
                        onResPreloadedFunc();
                    });
                };
                if (this.stageData.id > 3 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmusePenRoleTrialDialog_trial)) {
                    let skinIds = this.stageData.trialSkinIds;
                    let skinId = Tools.randomGotOneArrayData(skinIds);
                    let skinData = mgrCfg.get_from_amaze_parkour_skin_db(skinId);
                    mgrDirector.openDialog("vAmusePenRoleTrialDialog", {
                        adEventId: AD_EVENT_ID.VIDEO.video_vAmusePenRoleTrialDialog_trial,
                        skinId: skinId,
                        previewImg: skinData.previewImg,
                        fOnAdResult: (bAded) => {
                            if (!!bAded) {
                                onSkinConfirmFunc(skinData.partIds);
                            }
                            else {
                                onSkinConfirmFunc(null);
                            }
                        }
                    });
                }
                else {
                    onSkinConfirmFunc(null);
                }
            }
            exeInit() { }
            outInit() { }
            inWaitStart() {
                Tools.registerTouchHander(this.boxBackPanel, this.onTouchSpriteBg.bind(this));
            }
            exeWaitStart() { }
            outWaitStart() { }
            inTurnReady() {
                this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.avatarComing);
            }
            exeTurnReady() { }
            outTurnReady() { }
            inAvatarComing() {
                mgrVideoRecorder.startRecord();
                this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.avatarMoving);
            }
            exeAvatarComing() { }
            outAvatarComing() { }
            inAvatarMoving() {
                if (mgrSdk.getCopNumberValueByKey("super_parkour_dialog_alert_mode") == 1) {
                    this.checkTriggerSuper(true);
                }
                let avatarPosCameraDict = this.avatarPosCameraDict[1];
                let param = avatarPosCameraDict.cameraData;
                this.avatar.playAnimation("paoku_move-paoku_run", 0, () => {
                }, null, true);
                let bInitedCamera = false;
                this.cameraWithAvatarZDiffDis = param.pos.z - this.mapAvatarNode.transform.position.z;
                this.avatar.registerLoadEndCallback(() => {
                    let doLerpPosFunc = (percent) => {
                        this.avatar.transform.localRotationEulerY = 180 * percent;
                        if (percent >= 0.6 && !bInitedCamera) {
                            bInitedCamera = true;
                            this.cameraFollow.position = param.pos.clone();
                            this.cameraFollow.endRotation = param.rot.clone();
                            this.cameraFollow.fov = param.fov;
                            this.cameraFollow.lerpValue = 0.03 * this.MOVE_FPS;
                        }
                        if (percent == 1) {
                            this.flagMoveReadyFunc();
                        }
                    };
                    let startTime = Tools.time();
                    let dur = 0.5;
                    Timer.callLoop(0.016, (timer) => {
                        if (!this.nodeResource || this.nodeResource.destroyed || this.stManager.getCurState() != AMUSE_PARKOUR_SHOE_STATE.avatarMoving) {
                            timer.stop();
                            return;
                        }
                        let passTime = Tools.time() - startTime;
                        if (passTime >= dur) {
                            doLerpPosFunc(1);
                            timer.stop();
                            return;
                        }
                        doLerpPosFunc(passTime / dur);
                    }, this);
                });
            }
            exeAvatarMoving(deltaTime) {
                if (this.bPaused || !this.bAvatarMovingReadyed) {
                    return;
                }
                this.doAvatarMovingLerp(deltaTime);
                if (this.bInvincible) {
                    this.checkMlb();
                    this.checkMagnet();
                }
                else {
                    this.checkDoPaintColor();
                    this.checkSprayHair();
                    this.checkTriggerSuper();
                    this.checkFrozen();
                    this.checkMagnet();
                    this.checkMlb();
                }
                this.checkChangeShoePart();
                this.checkChangeClothPart();
                this.checkChangeHairPart();
                this.checkRecoverCenter();
            }
            outAvatarMoving() {
                this.avatar.timeScale = 1;
                this.avatar.transform.localRotationEulerX = 0;
            }
            inNextTurnReady() { }
            exeNextTurnReady() { }
            outNextTurnReady() { }
            inRestartCurrTurn() { }
            exeRestartCurrTurn() { }
            outRestartCurrTurn() { }
            inAddFlyShoe() { }
            exeAddFlyShoe() { }
            outAddFlyShoe() { }
            calculateRightPartCount() {
                let count = 0;
                let rightCount = 0;
                if (this.stageData.targetClothPartId) {
                    count++;
                    if (this.stageData.targetClothPartId == this.curDressClothPartId) {
                        rightCount++;
                    }
                }
                if (this.stageData.targetClothColorId) {
                    count++;
                    if (this.stageData.targetClothColorId == this.clothColorId) {
                        rightCount++;
                    }
                }
                if (this.stageData.targetHairPartId) {
                    count++;
                    if (this.stageData.targetHairPartId == this.curDressHairPartId) {
                        rightCount++;
                    }
                }
                if (this.stageData.targetHairColorId) {
                    count++;
                    if (this.stageData.targetHairColorId == this.hairColorId) {
                        rightCount++;
                    }
                }
                if (this.stageData.targetShoePartId) {
                    count++;
                    if (this.stageData.targetShoePartId == this.curDressShoePartId) {
                        rightCount++;
                    }
                }
                this.targetPercentage = Math.floor((rightCount / count) * 100);
                this.bSuccess = rightCount >= count / 2 ? true : false;
                if (this.bInvincible) {
                    this.bSuccess = true;
                    this.targetPercentage = 100;
                }
            }
            inSuccess() {
                mgrLoader.loadFont("parkour_score", this.labelScorePercentage);
                let param = this.avatarPosCameraDict[2].cameraData;
                this.cameraFollow.position = param.pos.clone();
                this.cameraFollow.position.z = this.endNodes.transform.position.z;
                this.cameraFollow.endRotation = param.rot.clone();
                this.cameraFollow.fov = param.fov;
                this.cameraFollow.lerpValue = 0.1;
                this.cameraFollow.onLateUpdate();
                this.avatar.timeScale = 1;
                if (this.bSuccess) {
                    this.avatar.playFaceAnimation(["face_paoku_shengli-face_paoku_zhuanshen",
                        "face_paoku_shengli-face_paoku_zhanshi",
                    ], 0, null, () => {
                    }, false, true);
                    this.avatar.playAnimation(["paoku_shengli-paoku_zhuanshen",
                        "paoku_shengli-paoku_zhanshi",
                    ], 0, null, () => {
                        this.avatar.playAnimation(["paoku_shengli-paoku_zuoxia", "paoku_shengli-paoku_shengli"], 0, null, null, true, true);
                        this.labelScorePercentage.visible = false;
                        this.cameraFollow.position.x = 0;
                        this.cameraFollow.lerpValue = 0.2;
                        cc.tween(this.spritePreviewContainer, true)
                            .parallel(cc.tween().toScale(0.2, 0.5), cc.tween().toPos(0.2, this.buttonPreview.__node.x, this.buttonPreview.__node.y))
                            .delay(3)
                            .call(() => {
                            this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.reward);
                        })
                            .start();
                    }, false, true);
                }
                else {
                    this.avatar.playFaceAnimation(["face_paoku_shengli-face_paoku_zhuanshen",
                        "face_paoku_shengli-face_paoku_zhanshi",
                    ], 0, null, () => {
                    }, false, true);
                    this.avatar.playAnimation(["paoku_shengli-paoku_zhuanshen",
                        "paoku_shengli-paoku_zhanshi",
                    ], 0, null, () => {
                        this.avatar.playAnimation("paoku_kuqi-paoku_kuqi", 0.1, null, null, true, true);
                        this.labelScorePercentage.visible = false;
                        this.cameraFollow.position.x = 0;
                        this.cameraFollow.lerpValue = 0.2;
                        cc.tween(this.spritePreviewContainer, true)
                            .parallel(cc.tween().toScale(0.3, 0.5), cc.tween().toPos(0.3, this.buttonPreview.__node.x, this.buttonPreview.__node.y))
                            .delay(2)
                            .call(() => {
                            this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.reward);
                        })
                            .start();
                    }, false, true);
                }
                Timer.callLater(1 / 30 * 8, () => {
                    cc.tween(this.mapAvatarNode.transform)
                        .to(1 / 30 * 24, { localRotationEulerY: -180 })
                        .call(() => {
                        cc.tween(this.spritePreviewContainer)
                            .to(0.3, { scaleX: 0.8, scaleY: 0.8, y: 212 })
                            .call(() => {
                            this.labelScorePercentage.visible = true;
                            let targetPercentage = this.targetPercentage;
                            if (this.bInvincible) {
                                targetPercentage = 100;
                            }
                            let curPercentage = 0;
                            let totalTime = 1;
                            let speed = targetPercentage / totalTime;
                            Timer.callLoop(0.016, (timer) => {
                                let delataPercentage = speed * 0.016;
                                curPercentage += delataPercentage;
                                if (curPercentage >= targetPercentage) {
                                    curPercentage = targetPercentage;
                                    this.add3DEffectAtFront('116_ui_once_bao_02', this.labelScorePercentage);
                                    timer.stop();
                                }
                                this.labelScorePercentage.text = `${Math.floor(curPercentage)}%`;
                            }, this);
                        })
                            .start();
                    })
                        .start();
                }, this);
            }
            exeSuccess() { }
            outSuccess() { }
            inRecoverCenter() {
                Tools.unRegisterTouchHander(this.boxBackPanel);
                mgrEffect.playQuitbackAction([this.buttonBack.__node], -200, 0);
                let param = this.avatarPosCameraDict[3].cameraData;
                let cameraFollow = this.cameraBack.getComponent(CameraFollow);
                cameraFollow.position = param.pos;
                cameraFollow.position.x = this.mapAvatarNode.transform.position.x + param.pos.x;
                cameraFollow.position.z = this.mapAvatarNode.transform.position.z + this.cameraWithAvatarOffsetPosInRecover.z;
                cameraFollow.fov = param.fov;
                cameraFollow.lerpValue = 1;
                cameraFollow.endRotation = param.rot;
                cameraFollow.onLateUpdate();
                this.calculateRightPartCount();
                let aniIds = null;
                if (this.bSuccess) {
                    aniIds = [
                        "face_paoku_shengli-face_paoku_zhuanshen",
                        "face_paoku_shengli-face_paoku_zhanshi",
                        "paoku_shengli-paoku_zhuanshen",
                        "paoku_shengli-paoku_zhanshi",
                        "face_paoku_shengli-face_paoku_zuoxia",
                        "face_paoku_shengli-face_paoku_shengli",
                        "paoku_shengli-paoku_zuoxia",
                        "paoku_shengli-paoku_shengli",
                    ];
                }
                else {
                    aniIds = [
                        "face_paoku_shengli-face_paoku_zhuanshen",
                        "face_paoku_shengli-face_paoku_zhanshi",
                        "paoku_shengli-paoku_zhuanshen",
                        "paoku_shengli-paoku_zhanshi",
                        "face_paoku_kuqi-face_paoku_kuqi",
                        "paoku_kuqi-paoku_kuqi"
                    ];
                }
                mgrTip.showLoadingTip("parkour_avatar_loading");
                mgrLoader.batchLoadResources([], aniIds, [], () => {
                    mgrTip.hideLoadingTip("parkour_avatar_loading");
                    let distance = Math.abs(this.successPosZ - this.recoverCenterPos.transform.position.z);
                    let time = distance / 0.6;
                    cc.tween(this.mapAvatarNode.transform)
                        .to(time, { localPositionX: 0, localPositionY: 0.15, localPositionZ: this.mapAvatarNode.transform.localPositionZ - distance })
                        .call(() => {
                        this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.success);
                    })
                        .start();
                });
                this.avatar.playAnimation(["paoku_walk-paoku_walk"], 0.1, null, null, true, true);
            }
            exeRecoverCenter(deltaTime) {
                let cameraFollow = this.cameraBack.getComponent(CameraFollow);
                cameraFollow.position.z = this.mapAvatarNode.transform.position.z + this.cameraWithAvatarOffsetPosInRecover.z;
            }
            outRecoverCenter() { }
            inReward() {
                this.spriteTitleSuccess.visible = !!this.bSuccess;
                this.spriteTitleFaild.visible = !this.spriteTitleSuccess.visible;
                this.spriteTitle.visible = true;
                this.spriteTitle.scale(3, 3, true);
                cc.tween(this.spriteTitle).toScale(0.1, 1)
                    .call(() => {
                    if (!!this.bSuccess) {
                        mgrSound.play(312);
                    }
                    else {
                        mgrSound.play(313);
                    }
                })
                    .delay(0.5)
                    .call(() => {
                    Tools.takeAPhoto(512, 512, this.cameraBack, (tex2d) => {
                        this.shareTex2d = tex2d;
                        let rewardColorPoint = 0;
                        if (this.bSuccess) {
                            rewardColorPoint = this.stageData.bestRewardColorPoint;
                        }
                        else {
                            rewardColorPoint = this.stageData.goodRewardColorPoint;
                        }
                        if (this.bSuccess) {
                            let gameWorldDailyData = mgrCfg.get_from_parkour_daily_quest_config(mgrWorldDaily.getWorldDay()) || mgrCfg.get_from_parkour_daily_quest_config(1);
                            mgrPlayer.addItemAmount(gameWorldDailyData.rewardItemId, gameWorldDailyData.rewardItemAmount, "服装跑酷结算奖励");
                        }
                        this.oldColorPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_PARKOUR_COLOR);
                        this.currGotColorPoint = rewardColorPoint;
                        mgrPlayer.addItemAmount(Const.ITEM_ID_PARKOUR_COLOR, rewardColorPoint, "服装跑酷结算奖励");
                        this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.palette);
                    }, Laya.RenderTextureFormat.R8G8B8A8);
                })
                    .start();
            }
            exeReward() { }
            outReward() { }
            inPalette() {
                let gotCoinFunc = () => {
                    let rewardRmb = !!this.bSuccess ? this.stageData.bestRewardRmbAmount : this.stageData.goodRewardRmbAmount;
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, rewardRmb, "服装跑酷结算奖励");
                    mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, rewardRmb, null, {
                        fOnClose: () => {
                            let partId = mgrWorldDaily.getUnownedVipPart(DailyGameType.parkour);
                            if (!!partId && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment) && (Tools.random(0, 100) <= mgrSdk.getCopNumberValueByKey("surprise_parkour_ratio"))) {
                                mgrDirector.openDialog("vSurpriseRewardDialog", {
                                    bVip: false,
                                    partId,
                                    fOnClose: () => {
                                        this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.finish);
                                    }
                                });
                            }
                            else {
                                this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.finish);
                            }
                        }
                    });
                };
                if (!this.bSuccess) {
                    gotCoinFunc();
                }
                else {
                    let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.parkour);
                    if (!rewardPartId) {
                        gotCoinFunc();
                        return;
                    }
                    mgrDirector.openDialog("vAmuseCakeResultDialog", {
                        colorItemId: Const.ITEM_ID_PARKOUR_COLOR,
                        oldColorPoint: this.oldColorPoint,
                        currGotColorPoint: this.currGotColorPoint,
                        dailyGameType: DailyGameType.parkour,
                        bSuccess: this.bSuccess,
                        rewardPartId: rewardPartId,
                        fOnClose: () => {
                            gotCoinFunc();
                        }
                    });
                }
            }
            exePalette() { }
            outPalette() { }
            inFinish() {
                this.stageData.statisPointId && mgrSdk.statisOnStageEnd(`${this.stageData.statisPointId}`, this.bSuccess ? 1 : 0, `${this.stageData.id}`);
                mgrVideoRecorder.stopRecord();
                mgrTip.tryShowPhotoShare("vAmuseParkourScene", this.shareTex2d, null, () => {
                    this.stManager.stopUpdate();
                    mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene", {
                        bSuccess: this.bSuccess,
                        dailyGameType: DailyGameType.parkour,
                        bFromGameResult: true
                    });
                });
            }
            exeFinish() { }
            outFinish() { }
            checkDoPaintColor() {
                let bLockHorizontalMove = false;
                let bInColorPoor = false;
                this.colorPoorNodesArr.forEach((v, i) => {
                    let nodeSize1 = v.getChildByName("size1");
                    let nodeSize2 = v.getChildByName("size2");
                    let gridNode = v.getChildByName("gridNode");
                    let shineNode = v.getChildByName("shineNode");
                    let colorId = parseInt(v.name);
                    let deltaXValue = 0.15;
                    let leftX = nodeSize2.transform.position.x;
                    let topZ = nodeSize2.transform.position.z;
                    let rightX = nodeSize1.transform.position.x;
                    let bottomZ = nodeSize1.transform.position.z;
                    let curPos = this.mapAvatarNode.transform.position;
                    if (curPos.x > leftX + deltaXValue && curPos.x < rightX - deltaXValue && curPos.z < bottomZ && curPos.z > topZ) {
                        bLockHorizontalMove = true;
                    }
                    if (curPos.x > leftX + deltaXValue && curPos.x < rightX - deltaXValue && curPos.z < (topZ + bottomZ) / 2 && curPos.z > topZ) {
                        this.clothColorId = colorId;
                        if (!this.coloredLog[i] && this.clothColorId) {
                            let posAvatar = this.mapAvatarNode.transform.position;
                            let effExplodeModel = mgrLoader.Pool.getModel("eff_ui_chaoxie_spglow");
                            this.add3DEffectAtBack(effExplodeModel, 1);
                            effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, 0, posAvatar.z - 1);
                            effExplodeModel.transform.setWorldLossyScale(new Laya.Vector3(0.5, 0.5, 0.5));
                            if (gridNode && gridNode.numChildren > 0 && parseInt(gridNode.getChildAt(0).name) > 0) {
                                this.clothGridId = parseInt(gridNode.getChildAt(0).name);
                            }
                            if (shineNode && shineNode.numChildren > 0 && parseInt(shineNode.getChildAt(0).name) > 0) {
                                this.clothShineId = parseInt(shineNode.getChildAt(0).name);
                            }
                            if (this.curDressClothPartId) {
                                let newPartId = mgrDesign.addTempDesignPart(this.curDressClothPartId, this.clothColorId || 4086, this.clothGridId || 4299, this.clothShineId || 4199);
                                this.avatar.fillByPartIds([newPartId]);
                                mgrSound.play(167);
                                this.coloredLog[i] = true;
                            }
                        }
                    }
                    if (curPos.x > leftX + deltaXValue && curPos.x < rightX - deltaXValue && curPos.z < bottomZ && curPos.z > topZ) {
                        let disFromCenterColorPoor = Math.abs((curPos.z - (topZ + bottomZ) / 2));
                        let maxDis = Math.abs(topZ - bottomZ) / 2;
                        this.curSinkHeight = this.SINK_HIGHT * (1 - (disFromCenterColorPoor / maxDis));
                        this.mapAvatarNode.transform.localPositionY = -this.curSinkHeight;
                        bInColorPoor = true;
                    }
                });
                if (!bInColorPoor) {
                    this.mapAvatarNode.transform.localPositionY = 0;
                }
                this.bLockHorizontalMove = bLockHorizontalMove;
            }
            checkChangeShoePart() {
                this.partShoeNodesArr.forEach((v, i) => {
                    let nodeSize1 = v.getChildByName("size1");
                    let nodeSize2 = v.getChildByName("size2");
                    let partId = parseInt(v.name);
                    let leftX = nodeSize2.transform.position.x;
                    let topZ = nodeSize2.transform.position.z;
                    let rightX = nodeSize1.transform.position.x;
                    let bottomZ = nodeSize1.transform.position.z;
                    let curPos = this.mapAvatarNode.transform.position;
                    if (curPos.x > leftX && curPos.x < rightX && curPos.z < bottomZ && curPos.z > topZ) {
                        if (partId && !this.shoedLog[i]) {
                            v.active = false;
                            if (this.bInvincible) {
                                let posAvatar = this.mapAvatarNode.transform.position;
                                let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                                this.add3DEffectAtBack(effExplodeModel, 1);
                                effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, posAvatar.y, posAvatar.z);
                                return;
                            }
                            let posAvatar = this.mapAvatarNode.transform.position;
                            let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                            this.add3DEffectAtBack(effExplodeModel, 1);
                            effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, posAvatar.y, posAvatar.z);
                            this.curDressShoePartId = partId;
                            this.avatar.fillByPartIds([this.curDressShoePartId]);
                            mgrSound.play(167);
                            this.shoedLog[i] = true;
                        }
                    }
                });
            }
            checkChangeClothPart() {
                this.partClothNodesArr.forEach((v, i) => {
                    let nodeSize1 = v.getChildByName("size1");
                    let nodeSize2 = v.getChildByName("size2");
                    let gridNode = v.getChildByName("gridNode");
                    let shineNode = v.getChildByName("shineNode");
                    let colorNode = v.getChildByName("colorNode");
                    let partId = parseInt(v.name);
                    let leftX = nodeSize2.transform.position.x;
                    let topZ = nodeSize2.transform.position.z;
                    let rightX = nodeSize1.transform.position.x;
                    let bottomZ = nodeSize1.transform.position.z;
                    let curPos = this.mapAvatarNode.transform.position;
                    if (curPos.x > leftX && curPos.x < rightX && curPos.z < bottomZ && curPos.z > topZ) {
                        if (partId && !this.clothedLog[i]) {
                            v.active = false;
                            if (this.bInvincible) {
                                let posAvatar = this.mapAvatarNode.transform.position;
                                let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                                this.add3DEffectAtBack(effExplodeModel, 1);
                                effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, posAvatar.y, posAvatar.z);
                                return;
                            }
                            let posAvatar = this.mapAvatarNode.transform.position;
                            let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                            this.add3DEffectAtBack(effExplodeModel, 1);
                            effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, posAvatar.y, posAvatar.z);
                            this.curDressClothPartId = partId;
                            if (gridNode && gridNode.numChildren > 0 && parseInt(gridNode.getChildAt(0).name) > 0) {
                                this.clothGridId = parseInt(gridNode.getChildAt(0).name);
                            }
                            if (shineNode && shineNode.numChildren > 0 && parseInt(shineNode.getChildAt(0).name) > 0) {
                                this.clothShineId = parseInt(shineNode.getChildAt(0).name);
                            }
                            if (colorNode && colorNode.numChildren > 0 && parseInt(colorNode.getChildAt(0).name) > 0) {
                                this.clothColorId = parseInt(colorNode.getChildAt(0).name);
                            }
                            let newPartId = mgrDesign.addTempDesignPart(this.curDressClothPartId, this.clothColorId || 4086, this.clothGridId || 4299, this.clothShineId || 4199);
                            this.avatar.fillByPartIds([newPartId]);
                            mgrSound.play(167);
                            this.clothedLog[i] = true;
                        }
                    }
                });
            }
            checkChangeHairPart() {
                this.partHairNodesArr.forEach((v, i) => {
                    let nodeSize1 = v.getChildByName("size1");
                    let nodeSize2 = v.getChildByName("size2");
                    let gridNode = v.getChildByName("gridNode");
                    let shineNode = v.getChildByName("shineNode");
                    let colorNode = v.getChildByName("colorNode");
                    let partId = parseInt(v.name);
                    let leftX = nodeSize2.transform.position.x;
                    let topZ = nodeSize2.transform.position.z;
                    let rightX = nodeSize1.transform.position.x;
                    let bottomZ = nodeSize1.transform.position.z;
                    let curPos = this.mapAvatarNode.transform.position;
                    if (curPos.x > leftX && curPos.x < rightX && curPos.z < bottomZ && curPos.z > topZ) {
                        if (partId && !this.hairedLog[i]) {
                            v.active = false;
                            if (this.bInvincible) {
                                let posAvatar = this.mapAvatarNode.transform.position;
                                let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                                this.add3DEffectAtBack(effExplodeModel, 1);
                                effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, posAvatar.y, posAvatar.z);
                                return;
                            }
                            let posAvatar = this.mapAvatarNode.transform.position;
                            let effExplodeModel = mgrLoader.Pool.getModel("e_explode");
                            this.add3DEffectAtBack(effExplodeModel, 1);
                            effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, posAvatar.y, posAvatar.z);
                            this.curDressHairPartId = partId;
                            if (gridNode && gridNode.numChildren > 0 && parseInt(gridNode.getChildAt(0).name) > 0) {
                                this.hairGridId = parseInt(gridNode.getChildAt(0).name);
                            }
                            if (shineNode && shineNode.numChildren > 0 && parseInt(shineNode.getChildAt(0).name) > 0) {
                                this.hairShineId = parseInt(shineNode.getChildAt(0).name);
                            }
                            if (colorNode && colorNode.numChildren > 0 && parseInt(colorNode.getChildAt(0).name) > 0) {
                                this.hairColorId = parseInt(colorNode.getChildAt(0).name);
                            }
                            let newPartId = mgrDesign.addTempDesignPart(this.curDressHairPartId, this.hairColorId || 4086, this.hairGridId || 4299, this.hairShineId || 4199);
                            this.avatar.fillByPartIds([newPartId]);
                            mgrSound.play(167);
                            this.hairedLog[i] = true;
                        }
                    }
                });
            }
            checkSprayHair() {
                this.hairSprayNodesArr.forEach(v => {
                    let nodeSize1 = v.getChildByName("size1");
                    let nodeSize2 = v.getChildByName("size2");
                    let gridNode = v.getChildByName("gridNode");
                    let shineNode = v.getChildByName("shineNode");
                    let colorId = parseInt(v.name);
                    let leftX = nodeSize2.transform.position.x;
                    let topZ = nodeSize2.transform.position.z;
                    let rightX = nodeSize1.transform.position.x;
                    let bottomZ = nodeSize1.transform.position.z;
                    let curPos = this.mapAvatarNode.transform.position;
                    if (curPos.x > leftX && curPos.x < rightX && curPos.z < bottomZ && curPos.z > topZ) {
                        this.hairColorId = colorId;
                        if (gridNode && gridNode.numChildren > 0 && parseInt(gridNode.getChildAt(0).name) > 0) {
                            this.hairGridId = parseInt(gridNode.getChildAt(0).name);
                        }
                        if (shineNode && shineNode.numChildren > 0 && parseInt(shineNode.getChildAt(0).name) > 0) {
                            this.hairShineId = parseInt(shineNode.getChildAt(0).name);
                        }
                        if (this.curDressHairPartId) {
                            let newPartId = mgrDesign.addTempDesignPart(this.curDressHairPartId, this.hairColorId || 4086, this.hairGridId || 4299, this.hairShineId || 4199);
                            this.avatar.fillByPartIds([newPartId]);
                            mgrSound.play(167);
                        }
                    }
                });
            }
            checkTriggerSuper(bSkipCheck) {
                if (!this.superRunNode || !this.bTriggeredSuper || !mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseParkourScene_super)) {
                    return;
                }
                let nodeSize1 = this.superRunNode.getChildByName("size1");
                let nodeSize2 = this.superRunNode.getChildByName("size2");
                let leftX = nodeSize2.transform.position.x;
                let topZ = nodeSize2.transform.position.z;
                let rightX = nodeSize1.transform.position.x;
                let bottomZ = nodeSize1.transform.position.z;
                let curPos = this.mapAvatarNode.transform.position;
                if (bSkipCheck || (curPos.x > leftX && curPos.x < rightX && curPos.z < bottomZ && curPos.z > topZ)) {
                    if (!bSkipCheck) {
                        this.bTriggeredSuper = false;
                    }
                    this.bPaused = true;
                    mgrDirector.openDialog("vAmusePenSuperDialog1", {
                        adEventId: AD_EVENT_ID.VIDEO.video_vAmuseParkourScene_super,
                        fOnAdResult: (bAded) => {
                            this.bPaused = false;
                            if (!bAded) {
                                return;
                            }
                            this.beginPenSuper();
                        }
                    });
                }
            }
            beginPenSuper() {
                let rightPartId = mgrDesign.addTempDesignPart(this.stageData.targetClothPartId, this.stageData.targetClothColorId, this.stageData.targetClothGridId, this.stageData.targetClothShineId);
                this.avatar.fillByPartIds([rightPartId]);
                this.avatar.registerLoadEndCallback(() => {
                    let rightPartId = mgrDesign.addTempDesignPart(this.stageData.targetHairPartId, this.stageData.targetHairColorId, this.stageData.targetHairGridId, this.stageData.targetHairShineId);
                    this.avatar.fillByPartIds([rightPartId, this.stageData.targetShoePartId]);
                });
                let model = mgrLoader.Pool.getModel("e_daoju_wudi");
                this.add3DEffectAtAavtarBip01(model, 0);
                this.eDaojuWudiModel = model;
                this.bInvincible = true;
                this.MOVE_FPS = 6;
                this.avatar.timeScale = this.INVINCIBLE_FPS_RATIO / 2;
                this.bTouchBg = false;
                this.bLockHorizontalMove = false;
                this.avatar.playAnimation("paoku_move-paoku_fly", 0, null, null, true, true);
            }
            add3DEffectAtAavtarBip01(modelId, duration = 3) {
                let addFunc = (mode) => {
                    mode.transform.localPositionY = 1;
                    mode.transform.localRotationEulerX = -90;
                    this.avatar.addChild(mode);
                    duration > 0 && Timer.callLater(duration, () => {
                        mgrLoader.Pool.recoverModel(mode);
                    }, this);
                };
                if (modelId instanceof Laya.Sprite3D) {
                    addFunc(modelId);
                    return;
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    if (!this.scene3DBack)
                        return;
                    if (!this.avatar || this.avatar.destroyed) {
                        return;
                    }
                    let mode = mgrLoader.Pool.getModel(modelId);
                    addFunc(mode);
                }, this, 1);
            }
            checkRecoverCenter() {
                let curPos = this.mapAvatarNode.transform.position;
                if (curPos.z <= this.recoverCenterPos.transform.position.z) {
                    this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.recoverCenter);
                }
            }
            doAvatarMovingLerp(deltaTime) {
                try {
                    if (this.lastTouchBgPos && this.touchBgBeginPos) {
                        let tmpx = (this.lastTouchBgPos.x - this.touchBgBeginPos.x) / (mgrDirector.width * 0.6) * this.ROAD_WH + (this.touchBgBeginAvatarPosX);
                        this.lastTouchResultMapAvatarPositionX = ul.clamp(tmpx, -this.ROAD_WH / 2, this.ROAD_WH / 2);
                    }
                    this.mapAvatarNode.transform.localPositionX = this.lastTouchResultMapAvatarPositionX;
                    let deltaDis = 0;
                    deltaDis = deltaTime * this.MOVE_FPS;
                    this.mapAvatarNode.transform.localPositionZ -= (deltaDis);
                    this.cameraFollow.lerpValue = 0.05;
                    this.cameraFollow.position.z = this.mapAvatarNode.transform.localPositionZ + this.cameraWithAvatarZDiffDis;
                    this.mapSky.transform.localPositionZ -= (deltaDis);
                }
                catch (error) {
                    console.log("-------avtarMoving lerp Error", error);
                }
            }
            flagMoveReadyFunc() {
                this.avatar.resume();
                let faceAniIdArr = [
                    ROLE_FACE_MOV.daxiao,
                    ROLE_FACE_MOV.kaixin
                ];
                this.avatar.playRoleFaceAnimation(faceAniIdArr[Tools.random(0, faceAniIdArr.length - 1)]);
                this.bAvatarMovingReadyed = true;
                this.avatar.timeScale = 1.1;
                this.avatar.transform.localRotationEulerX = 15;
            }
            onTouchSpriteBg(e) {
                if (this.bLockHorizontalMove) {
                    return;
                }
                if (this.stManager.getCurState() == AMUSE_PARKOUR_SHOE_STATE.waitStart) {
                    if (!this.bTouchOnce) {
                        this.boxGuideStart.visible = false;
                        this.bTouchOnce = true;
                        this.stManager.setNextState(AMUSE_PARKOUR_SHOE_STATE.turnReady);
                    }
                    return;
                }
                if (this.stManager.getCurState() != AMUSE_PARKOUR_SHOE_STATE.avatarMoving) {
                    return;
                }
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.touchBgBeginPos = new Laya.Vector2(e.pos.x, e.pos.y);
                    this.touchBgBeginAvatarPosX = this.mapAvatarNode.transform.localPositionX - this.baseRoadPosition.x;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                    this.lastTouchBgPos = null;
                    this.touchBgBeginPos = null;
                }
                if (!this.touchBgBeginPos) {
                    this.touchBgBeginPos = null;
                    this.lastTouchBgPos = null;
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    this.lastTouchBgPos = e.pos;
                }
            }
            cleanStageMapNode() {
                if (this.partClothNodesArr.length > 0) {
                    this.partClothNodesArr.forEach(v => {
                        v.active = true;
                    });
                }
                if (this.partHairNodesArr.length > 0) {
                    this.partHairNodesArr.forEach(v => {
                        v.active = true;
                    });
                }
                if (this.partShoeNodesArr.length > 0) {
                    this.partShoeNodesArr.forEach(v => {
                        v.active = true;
                    });
                }
                if (this.pengguanModelsArr.length > 0) {
                    this.pengguanModelsArr.forEach(v => {
                        let pengguanModel = v;
                        pengguanModel && mgrLoader.Pool.recoverModel(pengguanModel);
                    });
                }
                if (this.partModels.length > 0) {
                    this.partModels.forEach(v => {
                        let partModel = v;
                        partModel && mgrLoader.Pool.recoverModel(partModel);
                    });
                }
                if (this.eDaojuWudiModel) {
                    mgrLoader.Pool.recoverModel(this.eDaojuWudiModel);
                    this.eDaojuWudiModel = null;
                }
                if (this.avatar) {
                    this.avatar.destroy();
                    this.avatar = null;
                }
                if (this.mapAvatarNode) {
                    let numChildren = this.mapAvatarNode.numChildren;
                    for (let i = (numChildren - 1); i >= 0; i--) {
                        let tmp = this.mapAvatarNode.getChildAt(i);
                        mgrLoader.Pool.recoverModel(tmp);
                    }
                    this.mapAvatarNode.destroy();
                    this.mapAvatarNode = null;
                }
                this.bAvatarMovingReadyed = false;
                this.lastTouchResultMapAvatarPositionX = 0;
                if (this.mapStage) {
                    mgrLoader.Pool.recoverModel(this.mapStage);
                    this.mapStage = null;
                }
                if (this.avatar) {
                    this.avatar.destroy();
                }
                this.avatar = null;
                this.touchBgBeginAvatarPosX = 0;
                this.lastTouchBgPos = null;
            }
            checkFrozen() {
                if (!this.frozenNode || !this.bTriggeredForzen || this.bPaused || this.bInvincible) {
                    return;
                }
                let nodeSize1 = this.frozenNode.getChildByName("size1");
                let nodeSize2 = this.frozenNode.getChildByName("size2");
                let leftX = nodeSize2.transform.position.x;
                let topZ = nodeSize2.transform.position.z;
                let rightX = nodeSize1.transform.position.x;
                let bottomZ = nodeSize1.transform.position.z;
                let curPos = this.mapAvatarNode.transform.position;
                if (curPos.x > leftX && curPos.x < rightX && curPos.z < bottomZ && curPos.z > topZ) {
                    this.bPaused = true;
                    this.bTriggeredForzen = false;
                    this.avatar.playAnimation("paoku_idle-paoku_idle", 0, () => {
                    }, null, true);
                    let posAvatar = this.mapAvatarNode.transform.position;
                    let effExplodeModel = mgrLoader.Pool.getModel("117_e_loop_snow");
                    this.add3DEffectAtBack(effExplodeModel, 1);
                    effExplodeModel.transform.position = new Laya.Vector3(posAvatar.x, posAvatar.y, posAvatar.z);
                    Timer.callLater(3, () => {
                        this.bPaused = false;
                        effExplodeModel = null;
                        this.frozenNode.active = false;
                        this.avatar.playAnimation("paoku_move-paoku_run", 0, () => {
                        }, null, true);
                    }, this);
                }
            }
            checkMlb() {
                if (this.mlbNodeArr.length > 0) {
                    this.mlbNodeArr.forEach((v, i) => {
                        let nodeSize1 = v.getChildByName("size1");
                        let nodeSize2 = v.getChildByName("size2");
                        let leftX = nodeSize2.transform.position.x;
                        let topZ = nodeSize2.transform.position.z;
                        let rightX = nodeSize1.transform.position.x;
                        let bottomZ = nodeSize1.transform.position.z;
                        let curPos = this.mapAvatarNode.transform.position;
                        if (this.bMagneted) {
                            if (v.active && curPos.z < bottomZ && curPos.z > topZ) {
                                mgrSound.play(111);
                                cc.tween(v.transform)
                                    .to(0.15, { localPositionX: curPos.x, localPositionY: 1.2, localPositionZ: curPos.z - 0.5 })
                                    .call(() => {
                                    v.active = false;
                                })
                                    .start();
                                mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, 1, "女王跑酷魔力币");
                                let posAvatar = this.mapAvatarNode.transform.position;
                                let effExplodeModel = mgrLoader.Pool.getModel("117_e_loop_cointrail");
                                v.addChild(effExplodeModel);
                            }
                        }
                        else {
                            if (v.active && curPos.x > leftX && curPos.x < rightX && curPos.z < bottomZ && curPos.z > topZ) {
                                mgrSound.play(111);
                                v.active = false;
                                mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, 1, "女王跑酷魔力币");
                            }
                        }
                    });
                }
            }
            checkMagnet() {
                if (!this.magnetNode || !this.bTriggeredMagneted || this.bPaused) {
                    return;
                }
                let nodeSize1 = this.magnetNode.getChildByName("size1");
                let nodeSize2 = this.magnetNode.getChildByName("size2");
                let leftX = nodeSize2.transform.position.x;
                let topZ = nodeSize2.transform.position.z;
                let rightX = nodeSize1.transform.position.x;
                let bottomZ = nodeSize1.transform.position.z;
                let curPos = this.mapAvatarNode.transform.position;
                if (curPos.x > leftX && curPos.x < rightX && curPos.z < bottomZ && curPos.z > topZ) {
                    this.bMagneted = true;
                    this.bTriggeredMagneted = false;
                    this.magnetNode.active = false;
                    Timer.callLater(3, () => {
                        this.bMagneted = false;
                    }, this);
                }
            }
            onClosed() {
                this.cleanStageMapNode();
                super.onClosed();
                mgrTip.hideLoadingTip("parkour_avatar_loading");
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene");
            }
            onTouchButtonPreview() {
                this.showPreview();
            }
        }

        const CAMERA_PRARAM_INIT$1 = {
            fov: 30,
            position: new Laya.Vector3(0, 0.93, 3.25),
            rotation: new Laya.Vector3(-5),
            lerpValue: 0.1,
        };
        const CAMERA_PRARAM_ITEM_EFFECT_DICT = {
            [1]: {
                fov: 30,
                position: new Laya.Vector3(0, 0.98, 5.0),
                rotation: new Laya.Vector3(-5),
                lerpValue: 0.1,
            },
            [2]: {
                fov: 30,
                position: new Laya.Vector3(0, 0.98, 5.0),
                rotation: new Laya.Vector3(-5),
                lerpValue: 0.1,
            },
            [3]: {
                fov: 30,
                position: new Laya.Vector3(0, 0.98, 5.0),
                rotation: new Laya.Vector3(-5),
                lerpValue: 0.1,
            },
            [4]: {
                fov: 30,
                position: new Laya.Vector3(0, 0.98, 5.0),
                rotation: new Laya.Vector3(-5),
                lerpValue: 0.1,
            },
        };
        const CAMERA_PRARAM_FOR_PHOTO = {
            fov: 75,
            position: new Laya.Vector3(0, 1.08, 0.93),
            rotation: new Laya.Vector3(-14),
            lerpValue: 1,
        };
        const CAMERA_PRARAM_FOR_SHOW = {
            fov: 30,
            position: new Laya.Vector3(0, 1.19, 4.68),
            rotation: new Laya.Vector3(-5),
            lerpValue: 0.1,
        };
        const ROLE_POS_PARAM = {
            position: new Laya.Vector3(0, 0, 0.1),
            rotation: new Laya.Vector3,
        };
        var AMUSE_DESIGN_ROOM_STATE;
        (function (AMUSE_DESIGN_ROOM_STATE) {
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["init"] = 1] = "init";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["selectPart"] = 2] = "selectPart";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["paintColor"] = 3] = "paintColor";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["grid"] = 4] = "grid";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["shine"] = 5] = "shine";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["complete"] = 6] = "complete";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["getShow"] = 7] = "getShow";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["reward"] = 8] = "reward";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["palette"] = 9] = "palette";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["finish"] = 10] = "finish";
        })(AMUSE_DESIGN_ROOM_STATE || (AMUSE_DESIGN_ROOM_STATE = {}));
        class vCustomMadeClothesScene extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vCustomMadeClothesScene";
                this.exportNodeNames = [];
                this.tryingPartIds = [];
                this.avatar = null;
                this.avatarPartContainer = null;
                this.reuseList = null;
                this.customOrderedTypeDict = {};
                this.initedType2CameraDict = {};
                this.type2RecommandPartIdDict = {};
                this.TAB_PART = 1;
                this.TAB_COLOR = 2;
                this.TAB_GRID = 3;
                this.TAB_SHINE = 4;
                this.selectTab2IdDict = {};
                this.completedTabDict = {};
                this.currGridTillingOffsetScale = 1;
                this.currShineTillingOffsetScale = 1;
                this.dbName2DatasDict = {};
                this.context.stageId = this.context.stageId;
                this.context.roleId = this.context.roleId || mgrRole.showingRoleId;
                this.stageData = mgrCfg.get_from_custom_made_clothes_stage_db(this.context.stageId);
                this.stageData.statisPointId && mgrSdk.statisOnStageStart(`${this.stageData.statisPointId}`, `${this.stageData.id}`);
            }
            onOpened() {
                super.onOpened();
                Tools.registerTouchHander(this.boxOperation, this.onTouchSpriteBg.bind(this));
                this.buildScene(() => {
                    this.buildUi();
                    this.fillData();
                    this.widget();
                    this.playOutUi();
                    this.playInUi();
                    this.stManager = new FSMObject;
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.selectPart, this.inSelectPart.bind(this), this.exeSelectPart.bind(this), this.outSelectPart.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.paintColor, this.inPaintColor.bind(this), this.exePaintColor.bind(this), this.outPaintColor.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.grid, this.inGrid.bind(this), this.exeGrid.bind(this), this.outGrid.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.shine, this.inShine.bind(this), this.exeShine.bind(this), this.outShine.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.complete, this.inComplete.bind(this), this.exeComplete.bind(this), this.outComplete.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.getShow, this.inGetShow.bind(this), this.exeGetShow.bind(this), this.outGetShow.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.reward, this.inReward.bind(this), this.exeReward.bind(this), this.outReward.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.palette, this.inPalette.bind(this), this.exePalette.bind(this), this.outPalette.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE.finish, this.inFinish.bind(this), this.exeFinish.bind(this), this.outFinish.bind(this));
                    this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.init);
                    this.stManager.startUpdate(this);
                    mgrVideoRecorder.startRecord();
                    this.registerListeners({
                        MSG_SHOP_BUY_SUCCESSED: this.onMsgShopBuySuccessed.bind(this),
                        MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                    });
                    this.registerGuideNode();
                });
            }
            onClosed() {
                if (this.gunlunEffModel) {
                    mgrLoader.Pool.recoverModel(this.gunlunEffModel);
                    this.gunlunEffModel = null;
                }
                if (this.penguanEffModelLeft) {
                    mgrLoader.Pool.recoverModel(this.penguanEffModelLeft);
                    this.penguanEffModelLeft = null;
                }
                if (this.penguanEffModelRight) {
                    mgrLoader.Pool.recoverModel(this.penguanEffModelRight);
                    this.penguanEffModelRight = null;
                }
                if (this.lastHuangZhuangEffModel) {
                    Tools.unLink2Node(this.lastHuangZhuangEffModel);
                    this.lastHuangZhuangEffModel = null;
                }
                mgrTip.hideLoadingTip("vCustomMadeClothesScene_loadingAvatar");
                mgrTip.hideLoadingTip("vCustomMadeClothesScene_loadingPart");
                if (!!this.avatarPartContainer) {
                    let numChildren = this.avatarPartContainer.numChildren;
                    for (let i = numChildren - 1; i >= 0; i--) {
                        let child = this.avatarPartContainer.getChildAt(i);
                        if (!child) {
                            continue;
                        }
                        mgrLoader.Pool.recoverModel(child);
                    }
                    this.avatarPartContainer.destroy();
                    this.avatarPartContainer = null;
                }
                super.onClosed();
            }
            getPreLoadModelIds() {
                let arr = [
                    "chizi",
                    "yijia",
                    "penping_design",
                    "gunlun",
                    "117_ui_loop_spraysmoke_01",
                    "116_ui_loop_star_01",
                    "117_ui_once_ribbon_02",
                    "design_room_bg",
                    "117_e_once_diychange_01"
                ];
                if (this.stageData.defaultPartId) {
                    let partData = mgrCfg.get_from_part_db(this.stageData.defaultPartId);
                    arr.push(partData.modelId);
                }
                return arr;
            }
            getPreLoadAnimationIds() {
                return ["diy_jiesuan-diy_jiesuan"];
            }
            getPreLoadImagePaths() {
                let arr = [];
                if (this.stageData.defaultColorId) {
                    let partData = mgrCfg.get_from_design_part_color_db(this.stageData.defaultColorId);
                    if (!!partData.paint && partData.paint != "") {
                        arr.push(partData.paint);
                    }
                }
                if (this.stageData.defaultGridId) {
                    let partData = mgrCfg.get_from_design_grid_db(this.stageData.defaultGridId);
                    if (!!partData.paint && partData.paint != "") {
                        arr.push(partData.paint);
                    }
                }
                if (this.stageData.defaultShineId) {
                    let partData = mgrCfg.get_from_design_shine_db(this.stageData.defaultShineId);
                    if (!!partData.paint && partData.paint != "") {
                        arr.push(partData.paint);
                    }
                }
                return arr;
            }
            isShowShadow() {
                return false;
            }
            registerGuideNode() {
            }
            widget() {
                mgrLayout.widgetBottomMC(this.boxPartContainer);
                mgrLayout.widgetRightTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetRightBottomMC(this.buttonSummit.__node);
                mgrLayout.widgetLeftTopMC(this.spriteTarget);
                mgrLayout.widgetRightTopMC(this.spriteStageTarget);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            playOutUi() {
            }
            playInUi() {
                mgrEffect.playComebackAction([this.buttonBack.__node], -150, 0, 1);
                mgrEffect.playComebackAction([this.boxPartContainer], 0, 700, 0.5, 0.5, () => {
                }, cc.Ease.circOut);
                this.buttonSummit.__node.scale(0, 0, true);
            }
            buildScene(callback) {
                let bgModel = mgrLoader.Pool.getModel("design_room_bg");
                this.add3DEffectAtBack(bgModel, 0);
                let render = Tools.getMeshRender(bgModel.getChildAt(0));
                if (render) {
                    Tools.loadMaterialTexture("res/ui/room_design_zz/bg.jpg", render.sharedMaterials[0], "albedoTexture");
                }
                bgModel.active = false;
                this.bgModel = bgModel;
                this.hangerModel = mgrLoader.Pool.getModel("yijia");
                mgrMaterial.setCustomMaterial(this.hangerModel, "yijia");
                this.add3DEffectAtBack(this.hangerModel, 0);
                let nodeRoot = this.hangerModel.getChildByName("Guadian_Part");
                nodeRoot.removeChildren();
                this.avatarPartContainer = new Laya.Sprite3D;
                nodeRoot.addChild(this.avatarPartContainer);
                this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                this.hangerModel.transform.rotationEuler = ROLE_POS_PARAM.rotation;
                this.hangerModel.transform.position = ROLE_POS_PARAM.position;
                let cf = this.cameraBack.getComponent(CameraFollow);
                cf.lookMode = E_CAMERA_MODE.fixMode;
                cf.fov = CAMERA_PRARAM_INIT$1.fov;
                cf.position = CAMERA_PRARAM_INIT$1.position;
                cf.endRotation = CAMERA_PRARAM_INIT$1.rotation;
                cf.lerpValue = 1;
                cf.onLateUpdate();
                cf.lerpValue = CAMERA_PRARAM_INIT$1.lerpValue;
                this.penguanLeft = mgrLoader.Pool.getModel("penping_design");
                this.add3DEffectAtBack(this.penguanLeft, 0);
                mgrMaterial.setCustomMaterial(this.penguanLeft, "penping_design");
                this.penguanLeft.transform.localRotationEulerY = -75;
                this.penguanLeft.transform.position = new Laya.Vector3(ROLE_POS_PARAM.position.x - 0.55, ROLE_POS_PARAM.position.y + 1.2, ROLE_POS_PARAM.position.z + 0.2);
                this.penguanLeft['_originLocalPos'] = this.penguanLeft.transform.localPosition.clone();
                this.penguanLeft.transform.localPositionX = this.penguanLeft['_originLocalPos'].x - 2;
                this.penguanLeft.transform.setWorldLossyScale(new Laya.Vector3(2, 2, 2));
                this.penguanLeft.active = false;
                this.penguanRight = mgrLoader.Pool.getModel("penping_design");
                this.add3DEffectAtBack(this.penguanRight, 0);
                mgrMaterial.setCustomMaterial(this.penguanRight, "penping_design");
                this.penguanRight.transform.localRotationEulerY = 75;
                this.penguanRight.transform.position = new Laya.Vector3(ROLE_POS_PARAM.position.x + 0.55, ROLE_POS_PARAM.position.y + 1.2, ROLE_POS_PARAM.position.z + 0.2);
                this.penguanRight['_originLocalPos'] = this.penguanRight.transform.localPosition.clone();
                this.penguanRight.transform.localPositionX = this.penguanRight['_originLocalPos'].x + 2;
                this.penguanRight.transform.setWorldLossyScale(new Laya.Vector3(2, 2, 2));
                this.penguanRight.active = false;
                let penguanEffNode = Tools.findNode("guadian_eff", this.penguanLeft);
                let penguanEffModel = mgrLoader.Pool.getModel("117_ui_loop_spraysmoke_01");
                penguanEffModel.transform.setWorldLossyScale(new Laya.Vector3(1.2, 1.2, 1.2));
                penguanEffNode.addChild(penguanEffModel);
                penguanEffModel.active = false;
                penguanEffModel.transform.localRotationEulerY = -90;
                this.penguanEffModelLeft = penguanEffModel;
                penguanEffNode = Tools.findNode("guadian_eff", this.penguanRight);
                penguanEffModel = mgrLoader.Pool.getModel("117_ui_loop_spraysmoke_01");
                penguanEffModel.transform.setWorldLossyScale(new Laya.Vector3(1.2, 1.2, 1.2));
                penguanEffNode.addChild(penguanEffModel);
                penguanEffModel.active = false;
                penguanEffModel.transform.localRotationEulerY = -90;
                this.penguanEffModelRight = penguanEffModel;
                this.colorVat = mgrLoader.Pool.getModel("chizi");
                this.add3DEffectAtBack(this.colorVat, 0);
                mgrMaterial.setCustomMaterial(this.colorVat, "chizi");
                this.colorVat.transform.position = new Laya.Vector3(ROLE_POS_PARAM.position.x, ROLE_POS_PARAM.position.y + 0.3, ROLE_POS_PARAM.position.z);
                this.colorVat['_originLocalPos'] = this.colorVat.transform.localPosition.clone();
                this.colorVat.active = false;
                this.gunlunModel = mgrLoader.Pool.getModel("gunlun");
                this.add3DEffectAtBack(this.gunlunModel, 0);
                mgrMaterial.setCustomMaterial(this.gunlunModel, "gunlun");
                this.gunlunModel.transform.setWorldLossyScale(new Laya.Vector3(2, 2, 2));
                this.gunlunModel.transform.position = new Laya.Vector3(ROLE_POS_PARAM.position.x, ROLE_POS_PARAM.position.y, ROLE_POS_PARAM.position.z + 0.4);
                this.gunlunModel['_originLocalPos'] = this.gunlunModel.transform.localPosition.clone();
                this.gunlunModel.active = false;
                penguanEffModel = mgrLoader.Pool.getModel("116_ui_loop_star_01");
                this.add3DEffectAtFront(penguanEffModel, { x: mgrDirector.width / 2, y: mgrDirector.height * 0.35 });
                penguanEffModel.active = false;
                this.gunlunEffModel = penguanEffModel;
                callback && callback();
            }
            buildUi() {
                mgrLoader.loadFont("room_score", this.labelStagePower);
                let topBar = new vTopBar({ bDisableGold: true, bDisableEnergy: true });
                this.spriteTopBarHolder.addChild(topBar);
                this.spriteTitle.visible = false;
                this.spriteBg.zOrder = -4;
                this.buttonSummit.__node.visible = true;
                this.spriteTillingoffset.visible = false;
                this.buttonDevColor.__node.visible = !!mgrDebug.bShowDevButton;
                if (this.imageSliderTillingDev.visible) {
                    let minMaxArr = [0, 100];
                    let slideValue = this.getTillingoffsetScale1SliderValue();
                    this.__registerAsSlider(this.imageSliderTillingDev, slideValue, minMaxArr, (value) => {
                        let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * (1 - value);
                        let scale = Const.DESIGN_ROOM_TILLING_MIN_SCALE + useValue / 100 * (Const.DESIGN_ROOM_TILLING_MAX_SCALE - Const.DESIGN_ROOM_TILLING_MIN_SCALE);
                        this._doChangeTextureTillingOffset(scale);
                        let label = this.imageSliderTillingDev.getChildByName("label");
                        if (!!label) {
                            label.text = `纹理缩放: ${(useValue).toFixed(4)}`;
                        }
                    }, () => {
                    });
                }
                this.reuseList = new ReuseList(6, 0, 20);
                this.reuseList.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseList);
                this.reuseList.setItemClass(vRoomDesignPart);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(4);
                this.reuseList.setSpaceY(2);
                this.spriteStageScoreUpFlag.visible = false;
                this.spriteStageScoreDownFlag.visible = false;
                this.refreshTargetScore();
            }
            fillData() {
                this.initTarget();
            }
            initTarget() {
                let str = this.stageData.name.replace(",", "\n");
                this.labelTarget.text = str;
            }
            inInit() {
                let datas = this.getWhitePartDatas(true);
                for (let k in datas) {
                    let data = datas[k];
                    if (mgrPlayer.getItemAmount(data.id) > 0) {
                        this.selectTab2IdDict[this.TAB_PART] = data.id;
                        this.doClickItem(data.id, this.TAB_PART, false, true);
                        break;
                    }
                }
                this.bDesignEffecting = false;
                this.onClickTab(this.TAB_COLOR);
            }
            exeInit() { }
            outInit() { }
            inSelectPart() {
                let datas = this.getWhitePartDatas();
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
                if (!this.selectTab2IdDict[this.TAB_PART]) {
                    if (!!this.stageData.defaultPartId) {
                        this.doClickItem(this.stageData.defaultPartId, this.TAB_PART, false, true);
                    }
                    else {
                        for (let k in datas) {
                            let data = datas[k];
                            if (mgrPlayer.getItemAmount(data.id) > 0) {
                                this.doClickItem(data.id, this.TAB_PART, false, true);
                                break;
                            }
                        }
                    }
                }
            }
            exeSelectPart() { }
            outSelectPart() { }
            inPaintColor() {
                let datas = this.getPartDataByDbName("design_part_color_db", this.TAB_COLOR);
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            exePaintColor() { }
            outPaintColor() { }
            inShine() {
                this.refreshTextureTillingOffsetTab(3);
                let datas = this.getPartDataByDbName("design_shine_db", this.TAB_SHINE);
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            exeShine() { }
            outShine() { }
            inGrid() {
                this.refreshTextureTillingOffsetTab(3);
                let datas = this.getPartDataByDbName("design_grid_db", this.TAB_GRID);
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            exeGrid() { }
            outGrid() { }
            inComplete() {
                this.penguanLeft.active = false;
                this.penguanRight.active = false;
                this.colorVat.active = false;
                this.gunlunModel.active = false;
                this.buttonBack.__node.visible = false;
                this.buttonSummit.__node.visible = false;
                this.boxPartContainer.visible = false;
                this.spriteTillingoffset.visible = false;
                this.imageSliderTillingDev.visible = false;
                this.spriteTarget.visible = false;
                this.spriteStageTarget.visible = false;
                this.add3DEffectAtFront("117_ui_once_ribbon_02", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 1);
                mgrSound.play(127);
                Timer.callLater(1, () => {
                    this.cameraFollow.fov = CAMERA_PRARAM_FOR_PHOTO.fov;
                    this.cameraFollow.position = CAMERA_PRARAM_FOR_PHOTO.position;
                    this.cameraFollow.endRotation = CAMERA_PRARAM_FOR_PHOTO.rotation;
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                    let oldPos = this.avatarPartContainer.transform.position.clone();
                    this.avatarPartContainer.removeSelf();
                    this.hangerModel.active = false;
                    this.add3DEffectAtBack(this.avatarPartContainer);
                    this.avatarPartContainer.transform.position = oldPos;
                    Tools.takeAPhoto(Const.CUSTOM_PART_ICON_SIZE_WH, Const.CUSTOM_PART_ICON_SIZE_WH, this.cameraBack, (tex2d) => {
                        if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                            return;
                        }
                        this.cameraFollow.fov = CAMERA_PRARAM_FOR_SHOW.fov;
                        this.cameraFollow.position = CAMERA_PRARAM_FOR_SHOW.position;
                        this.cameraFollow.endRotation = CAMERA_PRARAM_FOR_SHOW.rotation;
                        this.cameraFollow.lerpValue = 1;
                        this.cameraFollow.onLateUpdate();
                        this.tet2dCompletePart = tex2d;
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.getShow);
                    }, Laya.RenderTextureFormat.R8G8B8A8);
                }, this);
            }
            exeComplete() { }
            outComplete() { }
            inGetShow() {
                this.avatar = new RoleAvatar({ roleId: this.context.roleId });
                this.add3DEffectAtBack(this.avatar, 0);
                this.avatar.fillByPartIds(mgrPart.getLastClothes(this.context.roleId));
                this.avatar.registerLoadEndCallback(() => {
                    this.add3DEffectAtBack("117_e_once_diychange_01");
                    mgrSound.play(641);
                    this.avatar.playAnimation(["diy_jiesuan-diy_jiesuan"], 0, () => {
                        Timer.callLater(0.1, () => {
                            this.cameraFollow.fov = CAMERA_PRARAM_FOR_SHOW.fov;
                            this.cameraFollow.position = CAMERA_PRARAM_FOR_SHOW.position;
                            this.cameraFollow.endRotation = CAMERA_PRARAM_FOR_SHOW.rotation;
                            this.cameraFollow.lerpValue = 0.2;
                            this.cameraFollow.onLateUpdate();
                            this.avatar.transform.rotationEuler = ROLE_POS_PARAM.rotation;
                            this.avatar.transform.position = ROLE_POS_PARAM.position;
                            let model = this.avatarPartContainer.getChildAt(0);
                            mgrLoader.Pool.recoverModel(model);
                            mgrLoader.Pool.recoverModel(this.hangerModel);
                        }, this);
                        Timer.callLater(0.7, () => {
                            this.avatar.fillByPartIds([this.newDesignPartId]);
                        }, this);
                    }, () => {
                        this.cameraFollow.position = new Laya.Vector3(0, 1.26, 2.6);
                        this.cameraFollow.lerpValue = 1;
                        this.cameraFollow.onLateUpdate();
                        this.bgModel.active = true;
                        Tools.takeAPhoto(512, 512, this.cameraBack, (tex2d) => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.bgModel.active = false;
                            this.shareTex2d = tex2d;
                            this.cameraFollow.position = CAMERA_PRARAM_FOR_SHOW.position;
                            this.cameraFollow.onLateUpdate();
                            Timer.callLater(0.3, () => {
                                this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.reward);
                            }, this);
                        }, Laya.RenderTextureFormat.R8G8B8A8);
                    });
                });
            }
            exeGetShow() { }
            outGetShow() { }
            inReward() {
                let partIds = [
                    this.selectTab2IdDict[this.TAB_PART],
                    this.selectTab2IdDict[this.TAB_COLOR],
                    this.selectTab2IdDict[this.TAB_GRID],
                    this.selectTab2IdDict[this.TAB_SHINE]
                ];
                let score = mgrDesign.calcCustomMadeStageScore(this.context.stageId, partIds);
                let passScore = this.stageData.passScore;
                this.bSuccess = score > passScore ? true : false;
                this.spriteTitleSuccess.visible = !!this.bSuccess;
                this.spriteTitleFaild.visible = !this.spriteTitleSuccess.visible;
                this.spriteTitle.visible = true;
                this.spriteTitle.scale(3, 3, true);
                cc.tween(this.spriteTitle).toScale(0.1, 1)
                    .call(() => {
                    if (!!this.bSuccess) {
                        mgrSound.play(312);
                    }
                    else {
                        mgrSound.play(313);
                    }
                })
                    .delay(0.5)
                    .call(() => {
                    let rewardColorPoint = 0;
                    rewardColorPoint = !!this.bSuccess ? this.stageData.bestRewardColorPoint : this.stageData.goodRewardColorPoint;
                    if (this.bSuccess) {
                        let gameWorldDailyData = mgrCfg.get_from_custom_made_cloth_daily_quest_config(mgrWorldDaily.getWorldDay()) || mgrCfg.get_from_custom_made_cloth_daily_quest_config(1);
                        mgrPlayer.addItemAmount(gameWorldDailyData.rewardItemId, gameWorldDailyData.rewardItemAmount, "服装设计结算奖励");
                    }
                    this.oldColorPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_MAKE_CLOTH_COLOR);
                    this.currGotColorPoint = rewardColorPoint;
                    mgrPlayer.addItemAmount(Const.ITEM_ID_MAKE_CLOTH_COLOR, rewardColorPoint, "服装设计结算奖励");
                    this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.palette);
                })
                    .start();
            }
            exeReward() { }
            outReward() { }
            inPalette() {
                let gotCoinFunc = () => {
                    let rewardRmb = !!this.bSuccess ? this.stageData.bestRewardRmbAmount : this.stageData.goodRewardRmbAmount;
                    let moonCakeAmount = !!this.bSuccess ? this.stageData.successMoonCakeAmount : this.stageData.failMoonCakeAmount;
                    mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, rewardRmb, "服装设计结算奖励");
                    mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, rewardRmb, null, {
                        fOnClose: () => {
                            let partId = mgrWorldDaily.getUnownedVipPart(DailyGameType.custom_made);
                            if (!!partId && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vSurpriseRewardDialog_fragment) && (Tools.random(0, 100) <= mgrSdk.getCopNumberValueByKey("surprise_custom_made_ratio") || !!this.context.bVip)) {
                                mgrDirector.openDialog("vSurpriseRewardDialog", {
                                    bVip: !!this.context.bVip,
                                    partId,
                                    fOnClose: () => {
                                        if (mgrMidAutumn.isEnable() && !!moonCakeAmount) {
                                            mgrPlayer.addItemAmount(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, "蛋糕结算月饼奖励");
                                            mgrTip.addGotItemTip(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, null, {
                                                fOnClose: () => {
                                                    this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.finish);
                                                }
                                            });
                                        }
                                        else {
                                            this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.finish);
                                        }
                                    }
                                });
                            }
                            else {
                                if (mgrMidAutumn.isEnable() && !!moonCakeAmount) {
                                    mgrPlayer.addItemAmount(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, "蛋糕结算月饼奖励");
                                    mgrTip.addGotItemTip(Const.ITEM_ID_MOON_CAKE, moonCakeAmount, null, {
                                        fOnClose: () => {
                                            this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.finish);
                                        }
                                    });
                                }
                                else {
                                    this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.finish);
                                }
                            }
                        }
                    });
                };
                if (!this.bSuccess) {
                    gotCoinFunc();
                }
                else {
                    let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.custom_made);
                    if (!rewardPartId) {
                        gotCoinFunc();
                        return;
                    }
                    mgrDirector.openDialog("vAmuseCakeResultDialog", {
                        colorItemId: Const.ITEM_ID_MAKE_CLOTH_COLOR,
                        oldColorPoint: this.oldColorPoint,
                        currGotColorPoint: this.currGotColorPoint,
                        dailyGameType: DailyGameType.custom_made,
                        bSuccess: this.bSuccess,
                        rewardPartId: rewardPartId,
                        fOnClose: () => {
                            gotCoinFunc();
                        }
                    });
                }
            }
            exePalette() { }
            outPalette() { }
            inFinish() {
                this.stageData.statisPointId && mgrSdk.statisOnStageEnd(`${this.stageData.statisPointId}`, this.bSuccess ? 1 : 0, `${this.stageData.id}`);
                mgrVideoRecorder.stopRecord();
                mgrTip.tryShowPhotoShare("vCustomMadeClothesScene", this.shareTex2d, null, () => {
                    this.stManager.stopUpdate();
                    mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene", {
                        bSuccess: this.bSuccess,
                        dailyGameType: DailyGameType.custom_made,
                        bFromGameResult: true
                    });
                });
            }
            exeFinish() { }
            outFinish() { }
            isRecommend(id) {
                return false;
            }
            isTry(id) {
                return this.tryingPartIds.indexOf(id) >= 0;
            }
            isSelectItem(id) {
                for (let k in this.selectTab2IdDict) {
                    let selectedId = this.selectTab2IdDict[k];
                    if (selectedId == id) {
                        return true;
                    }
                }
                return false;
            }
            onClickItem(id, tab, bTryBuy = false, bDisableChangeCamera) {
                this.tryPopClickItemTrial(id, tab);
                this.doClickItem(id, tab, bTryBuy, bDisableChangeCamera);
            }
            tryPopClickItemTrial(partId, tab) {
                if (mgrGuide.isGuiding()) {
                    return;
                }
                if (mgrPlayer.getItemAmount(partId) <= 0 || mgrSdk.getCopNumberValueByKey("b_click_part_item_pop_trial") != 1) {
                    return;
                }
                let gap = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_gap") || 0;
                if (Tools.time() < (mgrPart.roomPopClickItemPartLastTime + gap)) {
                    return;
                }
                let popCount = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_count_per_stage") || 0;
                if (this.roomPopClickItemPartCount > popCount) {
                    return;
                }
                if (!mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial, true)) {
                    return;
                }
                this.roomPopClickItemPartCount++;
                mgrPart.roomPopClickItemPartLastTime = Tools.time();
                let lockedPartIdArr = [];
                switch (tab) {
                    case this.TAB_PART: {
                        let template = mgrCfg.get_from_design_part_config(1);
                        let partIds = template.partIds;
                        for (let i = 0; i < partIds.length; i++) {
                            let partId = partIds[i];
                            let shopData = mgrCfg.get_from_shop_template_db(partId);
                            if (mgrPlayer.getItemAmount(partId) <= 0 && !shopData) {
                                lockedPartIdArr.push(partId);
                            }
                        }
                        break;
                    }
                    default: {
                        let tab2DbName = {
                            [this.TAB_COLOR]: "design_part_color_db",
                            [this.TAB_GRID]: "design_grid_db",
                            [this.TAB_SHINE]: "design_shine_db",
                        };
                        let dbName = tab2DbName[tab];
                        if (!dbName) {
                            return;
                        }
                        let dbData = mgrCfg.getDb(dbName);
                        for (let k in dbData) {
                            let data = dbData[k];
                            let shopData = mgrCfg.get_from_shop_template_db(data.id);
                            if (mgrPlayer.getItemAmount(data.id) <= 0 && !shopData) {
                                lockedPartIdArr.push(data.id);
                            }
                        }
                        break;
                    }
                }
                if (lockedPartIdArr.length == 0) {
                    return;
                }
                let partIdAd = Tools.randomGotOneArrayData(lockedPartIdArr);
                mgrDirector.openDialog("vAdFreeTrialPartDialog", {
                    adEventId: AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial,
                    partId: partIdAd,
                    adTriggerParams: {
                        partId: partIdAd,
                        tab: tab
                    }
                });
            }
            doClickItem(id, tab, bTryBuy = false, bDisableChangeCamera) {
                if (!!this.bDesignEffecting) {
                    return;
                }
                if (bTryBuy && mgrPlayer.getItemAmount(id) <= 0 && !this.isTry(id)) {
                    let shopData = mgrCfg.get_from_shop_template_db(id);
                    if (!shopData) {
                        if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial)) {
                            if (mgrSdk.getCopNumberValueByKey(`b_room_try_ad_tip`) == 0) {
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial, { partId: id, tab: tab }, true);
                            }
                            else {
                                mgrTip.alertPrompt2("提示", "是否看视频免费试用？", "取消", "确定", null, () => {
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial, { partId: id, tab: tab }, true);
                                }, true, false);
                            }
                        }
                        else {
                            mgrTip.showMsgTip("广告准备中,请稍后再试");
                        }
                    }
                    else {
                        if (!shopData || !shopData.price || !shopData.priceUnit) {
                            mgrTip.showMsgTip("还未获得此部件");
                            return;
                        }
                        let doBuyFunc = () => {
                            if (mgrShop.requestBuy(id, "设计部件")) {
                                Timer.callLoop(0.016, (timer) => {
                                    if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                        return;
                                    timer.stop();
                                    this.doClickItem(id, tab, false);
                                    this.reuseList.refresh();
                                }, this);
                            }
                            else {
                            }
                        };
                        if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                            let partData = mgrCfg.get_from_item_template_db(id);
                            let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                            mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                doBuyFunc();
                            });
                        }
                        else {
                            doBuyFunc();
                        }
                    }
                    return;
                }
                let statisItemData = mgrCfg.get_from_part_db(id) || mgrCfg.get_from_design_part_color_db(id) || mgrCfg.get_from_design_grid_db(id) || mgrCfg.get_from_design_shine_db(id);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!statisItemData.statisPointId && mgrSdk.statisCommonEvent(statisItemData.statisPointId);
                }
                this.selectTab2IdDict[tab] = id;
                if (tab != this.TAB_PART) {
                    let cf = this.cameraBack.getComponent(CameraFollow);
                    cf.fov = CAMERA_PRARAM_ITEM_EFFECT_DICT[tab].fov;
                    cf.position = CAMERA_PRARAM_ITEM_EFFECT_DICT[tab].position;
                    cf.endRotation = CAMERA_PRARAM_ITEM_EFFECT_DICT[tab].rotation;
                    cf.lerpValue = CAMERA_PRARAM_ITEM_EFFECT_DICT[tab].lerpValue;
                }
                switch (tab) {
                    case this.TAB_PART: {
                        this.bDesignEffecting = true;
                        let partData = mgrCfg.get_from_part_db(id);
                        mgrLoader.loadModeWithModeId(partData.modelId, () => {
                            mgrLoader.markPartResLoaded(id);
                            let numChildren = this.avatarPartContainer.numChildren;
                            for (let i = numChildren - 1; i >= 0; i--) {
                                let child = this.avatarPartContainer.getChildAt(i);
                                if (!child) {
                                    continue;
                                }
                                mgrLoader.Pool.recoverModel(child);
                            }
                            let model = mgrLoader.Pool.getModel(partData.modelId);
                            mgrMaterial.setCustomMaterial(model, partData.modelId, 0, true);
                            for (let i = 0; i < model.numChildren; i++) {
                                let child = model.getChildAt(i);
                                let renderer = Tools.getMeshRender(child);
                                if (renderer) {
                                    for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                        let material = renderer.sharedMaterials[j];
                                        if (material.PlayerCustomChangeFlag < 0.5) {
                                            continue;
                                        }
                                        Tools.loadMaterialTexture(Const.SKIN_CONTROL_GRID_SHINE_PATH, material, "controlDetailTexture");
                                        material.albedoColor = new Laya.Vector4(0.88, 0.88, 0.88, 1.0);
                                        material.albedoTexture = null;
                                        material.AlbedoTillingX = 1.0;
                                        material.AlbedoTillingY = 1.0;
                                        material.gridTexture = null;
                                        material.shineTexture = null;
                                        material.gridTextureScale = 1.0;
                                        material.shineTextureScale = 1.0;
                                    }
                                }
                            }
                            this.avatarPartContainer.addChild(model);
                            this.completedTabDict[tab] = true;
                            this.doDesignByItemId(this.selectTab2IdDict[this.TAB_COLOR] || this.stageData.defaultColorId);
                            this.doDesignByItemId(this.selectTab2IdDict[this.TAB_GRID] || this.stageData.defaultGridId);
                            this.doDesignByItemId(this.selectTab2IdDict[this.TAB_SHINE] || this.stageData.defaultShineId);
                            cc.tween(this.hangerModel.transform)
                                .by(0.5, { localRotationEulerY: 360 })
                                .call(() => {
                                this.bDesignEffecting = false;
                                this.refreshTabUsedStatus();
                                this.refreshTargetScore();
                            })
                                .start();
                        }, this, 1);
                        break;
                    }
                    case this.TAB_COLOR: {
                        this.bDesignEffecting = true;
                        let colorData = mgrCfg.get_from_design_part_color_db(id);
                        let callback = () => {
                            let node = this.colorVat.getChildByName("chizi");
                            let render = Tools.getMeshRender(node);
                            for (let k in render.sharedMaterials) {
                                let material = render.sharedMaterials[k];
                                if (material.name == "shui") {
                                    if (colorData.paint == "") {
                                        material.albedoTexture = null;
                                        material.AlbedoTillingX = 1;
                                        material.AlbedoTillingY = 1;
                                        material.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                    }
                                    else {
                                        let texture = mgrLoader.get2dRes(colorData.paint);
                                        let text2d = texture.bitmap;
                                        if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                            text2d.wrapModeU = Laya.WarpMode.Repeat;
                                            text2d.wrapModeV = Laya.WarpMode.Repeat;
                                            text2d.filterMode = Laya.FilterMode.Bilinear;
                                            text2d.generateMipmap();
                                        }
                                        material.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                        material.albedoTexture = text2d;
                                        material.AlbedoTillingX = colorData.tillingOffset[0];
                                        material.AlbedoTillingY = colorData.tillingOffset[1];
                                    }
                                    break;
                                }
                            }
                            mgrSound.play(161);
                            cc.tween(this.hangerModel.transform)
                                .to(0.3, { localPositionY: -1.1 })
                                .by(0.5, { localRotationEulerY: 360 })
                                .by(0.5, { localRotationEulerY: 360 })
                                .call(() => {
                                let model = this.avatarPartContainer.getChildAt(0);
                                for (let i = 0; i < model.numChildren; i++) {
                                    let child = model.getChildAt(i);
                                    let renderer = Tools.getMeshRender(child);
                                    if (renderer) {
                                        for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                            let material = renderer.sharedMaterials[j];
                                            if (material.PlayerCustomChangeFlag < 0.5) {
                                                continue;
                                            }
                                            if (colorData.paint == "") {
                                                material.albedoTexture = null;
                                                material.AlbedoTillingX = 1;
                                                material.AlbedoTillingY = 1;
                                                material.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                            }
                                            else {
                                                let texture = mgrLoader.get2dRes(colorData.paint);
                                                let text2d = texture.bitmap;
                                                if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                                    text2d.wrapModeU = Laya.WarpMode.Repeat;
                                                    text2d.wrapModeV = Laya.WarpMode.Repeat;
                                                    text2d.filterMode = Laya.FilterMode.Bilinear;
                                                    text2d.generateMipmap();
                                                }
                                                material.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                                material.albedoTexture = text2d;
                                                material.AlbedoTillingX = colorData.tillingOffset[0];
                                                material.AlbedoTillingY = colorData.tillingOffset[1];
                                            }
                                        }
                                    }
                                }
                                this.completedTabDict[tab] = true;
                            })
                                .to(0.5, { localPositionY: 0 })
                                .call(() => {
                                this.add3DEffectAtFront("117_ui_once_water_01", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 1);
                                this.bDesignEffecting = false;
                                this.refreshTabUsedStatus();
                                this.refreshTargetScore();
                                let cf = this.cameraBack.getComponent(CameraFollow);
                                cf.fov = CAMERA_PRARAM_INIT$1.fov;
                                cf.position = CAMERA_PRARAM_INIT$1.position;
                                cf.endRotation = CAMERA_PRARAM_INIT$1.rotation;
                                cf.lerpValue = CAMERA_PRARAM_INIT$1.lerpValue;
                            })
                                .start();
                        };
                        if (colorData.paint == "") {
                            callback();
                        }
                        else {
                            mgrLoader.batchLoadResources([], [], [colorData.paint], () => {
                                callback();
                            });
                        }
                        break;
                    }
                    case this.TAB_SHINE: {
                        this.bDesignEffecting = true;
                        this.imageSliderTillingDev.scale(0, 0, true);
                        let shineData = mgrCfg.get_from_design_shine_db(id);
                        mgrLoader.Load2dRes(shineData.paint, Laya.Loader.IMAGE, this, (res) => {
                            this.changePenguanColor(this.penguanEffModelLeft);
                            this.changePenguanColor(this.penguanEffModelRight);
                            let standbyLeftX = this.penguanLeft.transform.localPositionX = this.penguanLeft['_originLocalPos'].x - 2;
                            cc.tween(this.penguanLeft.transform)
                                .to(0.1, { localPositionX: this.penguanLeft['_originLocalPos'].x })
                                .call(() => {
                                this.penguanEffModelLeft.active = true;
                                mgrSound.play(162);
                            })
                                .delay(1.6)
                                .call(() => {
                                this.penguanEffModelLeft.active = false;
                            })
                                .to(0.1, { localPositionX: standbyLeftX })
                                .start();
                            let standbyRightX = this.penguanRight.transform.localPositionX = this.penguanRight['_originLocalPos'].x + 2;
                            cc.tween(this.penguanRight.transform)
                                .to(0.1, { localPositionX: this.penguanRight['_originLocalPos'].x })
                                .call(() => {
                                this.penguanEffModelRight.active = true;
                                cc.tween(this.hangerModel.transform)
                                    .by(0.8, { localRotationEulerY: 180 })
                                    .call(() => {
                                    let model = this.avatarPartContainer.getChildAt(0);
                                    for (let i = 0; i < model.numChildren; i++) {
                                        let child = model.getChildAt(i);
                                        let renderer = Tools.getMeshRender(child);
                                        if (renderer) {
                                            for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                                let material = renderer.sharedMaterials[j];
                                                if (material.PlayerCustomChangeFlag < 0.5) {
                                                    continue;
                                                }
                                                material.shineTextureScale = shineData.tillingOffset[0] || 1;
                                                Tools.loadMaterialTexture(shineData.paint, material, "shineTexture");
                                            }
                                        }
                                    }
                                    this.completedTabDict[tab] = true;
                                })
                                    .by(0.8, { localRotationEulerY: 180 })
                                    .call(() => {
                                })
                                    .start();
                            })
                                .delay(1.6)
                                .call(() => {
                                this.penguanEffModelRight.active = false;
                            })
                                .to(0.1, { localPositionX: standbyRightX })
                                .call(() => {
                                this.currShineTillingOffsetScale = 1;
                                this.centerRegisteredSliderBar(this.imageSliderTillingDev);
                                this.adaptTextureTillingOffsetTabTexture(shineData.icon);
                                this.imageSliderTillingDev.scale(1, 1, true);
                                this.bDesignEffecting = false;
                                this.refreshTabUsedStatus();
                                this.refreshTargetScore();
                                let cf = this.cameraBack.getComponent(CameraFollow);
                                cf.fov = CAMERA_PRARAM_INIT$1.fov;
                                cf.position = CAMERA_PRARAM_INIT$1.position;
                                cf.endRotation = CAMERA_PRARAM_INIT$1.rotation;
                                cf.lerpValue = CAMERA_PRARAM_INIT$1.lerpValue;
                            })
                                .start();
                        });
                        break;
                    }
                    case this.TAB_GRID: {
                        this.bDesignEffecting = true;
                        let gridData = mgrCfg.get_from_design_grid_db(id);
                        this.imageSliderTillingDev.scale(0, 0, true);
                        mgrLoader.Load2dRes(gridData.paint, Laya.Loader.IMAGE, this, (res) => {
                            let node = this.gunlunModel.getChildByName("gunlun");
                            let render = Tools.getMeshRender(node);
                            if (!!render) {
                                for (let k in render.sharedMaterials) {
                                    let material = render.sharedMaterials[k];
                                    if (material.name == "gunlun_huawen") {
                                        let texture = mgrLoader.get2dRes(gridData.paint);
                                        let text2d = texture.bitmap;
                                        if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                            text2d.wrapModeU = Laya.WarpMode.Repeat;
                                            text2d.wrapModeV = Laya.WarpMode.Repeat;
                                            text2d.filterMode = Laya.FilterMode.Bilinear;
                                            text2d.generateMipmap();
                                        }
                                        material.albedoColor = new Laya.Vector4(233 / 255, 116 / 255, 212 / 255, 1);
                                        material.paintLayer1Texture = text2d;
                                        material.paintLayer1TilingOffset = new Laya.Vector4(gridData.tillingOffset[0], gridData.tillingOffset[1], 0, 0);
                                        break;
                                    }
                                }
                            }
                            cc.tween(this.gunlunModel.transform, true)
                                .to(0.1, { localPositionY: this.gunlunModel['_originLocalPos'].y + 0.8 })
                                .call(() => {
                                this.gunlunEffModel.active = true;
                                mgrSound.play(163);
                            })
                                .by(0.25, { localPositionY: 0.3, localPositionX: -0.1 })
                                .by(0.5, { localPositionY: -0.6, localPositionX: 0.2 })
                                .by(0.25, { localPositionY: 0.3, localPositionX: -0.1 })
                                .call(() => {
                                let model = this.avatarPartContainer.getChildAt(0);
                                for (let i = 0; i < model.numChildren; i++) {
                                    let child = model.getChildAt(i);
                                    let renderer = Tools.getMeshRender(child);
                                    if (renderer) {
                                        for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                            let material = renderer.sharedMaterials[j];
                                            if (material.PlayerCustomChangeFlag < 0.5) {
                                                continue;
                                            }
                                            material.gridTextureScale = gridData.tillingOffset[0] || 1;
                                            Tools.loadMaterialTexture(gridData.paint, material, "gridTexture");
                                        }
                                    }
                                }
                                this.completedTabDict[tab] = true;
                            })
                                .by(0.25, { localPositionY: 0.3, localPositionX: -0.1 })
                                .by(0.5, { localPositionY: -0.6, localPositionX: 0.2 })
                                .call(() => {
                                this.gunlunEffModel.active = false;
                            })
                                .to(0.1, { localPositionY: this.gunlunModel['_originLocalPos'].y, localPositionX: this.gunlunModel['_originLocalPos'].x })
                                .call(() => {
                                this.currGridTillingOffsetScale = 1;
                                this.centerRegisteredSliderBar(this.imageSliderTillingDev);
                                this.adaptTextureTillingOffsetTabTexture(gridData.icon);
                                this.imageSliderTillingDev.scale(1, 1, true);
                                this.bDesignEffecting = false;
                                this.refreshTabUsedStatus();
                                this.refreshTargetScore();
                                let cf = this.cameraBack.getComponent(CameraFollow);
                                cf.fov = CAMERA_PRARAM_INIT$1.fov;
                                cf.position = CAMERA_PRARAM_INIT$1.position;
                                cf.endRotation = CAMERA_PRARAM_INIT$1.rotation;
                                cf.lerpValue = CAMERA_PRARAM_INIT$1.lerpValue;
                            })
                                .start();
                        });
                        break;
                    }
                    default:
                        break;
                }
            }
            doDesignByItemId(id) {
                if (!id) {
                    return;
                }
                let tab = null;
                let colorData = mgrCfg.get_from_design_part_color_db(id);
                let shineData = mgrCfg.get_from_design_shine_db(id);
                let gridData = mgrCfg.get_from_design_grid_db(id);
                if (!!colorData) {
                    tab = this.TAB_COLOR;
                }
                else if (!!shineData) {
                    tab = this.TAB_SHINE;
                }
                else if (!!gridData) {
                    tab = this.TAB_GRID;
                }
                else {
                    return;
                }
                switch (tab) {
                    case this.TAB_COLOR: {
                        let callback = () => {
                            let model = this.avatarPartContainer.getChildAt(0);
                            for (let i = 0; i < model.numChildren; i++) {
                                let child = model.getChildAt(i);
                                let renderer = Tools.getMeshRender(child);
                                if (renderer) {
                                    for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                        let material = renderer.sharedMaterials[j];
                                        if (material.PlayerCustomChangeFlag < 0.5) {
                                            continue;
                                        }
                                        if (colorData.paint == "") {
                                            material.albedoTexture = null;
                                            material.AlbedoTillingX = 1;
                                            material.AlbedoTillingY = 1;
                                            material.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                        }
                                        else {
                                            let texture = mgrLoader.get2dRes(colorData.paint);
                                            let text2d = texture.bitmap;
                                            if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                                text2d.wrapModeU = Laya.WarpMode.Repeat;
                                                text2d.wrapModeV = Laya.WarpMode.Repeat;
                                                text2d.filterMode = Laya.FilterMode.Bilinear;
                                                text2d.generateMipmap();
                                            }
                                            material.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                            material.albedoTexture = text2d;
                                            material.AlbedoTillingX = colorData.tillingOffset[0];
                                            material.AlbedoTillingY = colorData.tillingOffset[1];
                                        }
                                    }
                                }
                            }
                        };
                        if (colorData.paint == "") {
                            callback();
                        }
                        else {
                            mgrLoader.batchLoadResources([], [], [colorData.paint], () => {
                                callback();
                            });
                        }
                        break;
                    }
                    case this.TAB_GRID: {
                        mgrLoader.Load2dRes(gridData.paint, Laya.Loader.IMAGE, this, (res) => {
                            let model = this.avatarPartContainer.getChildAt(0);
                            for (let i = 0; i < model.numChildren; i++) {
                                let child = model.getChildAt(i);
                                let renderer = Tools.getMeshRender(child);
                                if (renderer) {
                                    for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                        let material = renderer.sharedMaterials[j];
                                        if (material.PlayerCustomChangeFlag < 0.5) {
                                            continue;
                                        }
                                        material.gridTextureScale = (gridData.tillingOffset[0] || 1) * (this.currGridTillingOffsetScale || 1);
                                        Tools.loadMaterialTexture(gridData.paint, material, "gridTexture");
                                    }
                                }
                            }
                        });
                        break;
                    }
                    case this.TAB_SHINE: {
                        mgrLoader.Load2dRes(shineData.paint, Laya.Loader.IMAGE, this, (res) => {
                            let model = this.avatarPartContainer.getChildAt(0);
                            for (let i = 0; i < model.numChildren; i++) {
                                let child = model.getChildAt(i);
                                let renderer = Tools.getMeshRender(child);
                                if (renderer) {
                                    for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                        let material = renderer.sharedMaterials[j];
                                        if (material.PlayerCustomChangeFlag < 0.5) {
                                            continue;
                                        }
                                        material.shineTextureScale = (shineData.tillingOffset[0] || 1) * (this.currShineTillingOffsetScale || 1);
                                        Tools.loadMaterialTexture(shineData.paint, material, "shineTexture");
                                    }
                                }
                            }
                        });
                        break;
                    }
                    default:
                        break;
                }
            }
            changePenguanColor(penguanEffModel) {
                let color = new Laya.Vector4(Tools.random(255) / 255, Tools.random(255) / 255, Tools.random(255) / 255, 1.0);
                let numChildren = penguanEffModel.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let child = penguanEffModel.getChildAt(i);
                    child.particleSystem.startColorConstant = color;
                    child.particleSystem.startColorConstantMin = color;
                    child.particleSystem.startColorConstantMax = color;
                    let numChildren2 = child.numChildren;
                    for (let i = 0; i < numChildren2; i++) {
                        let child2 = child.getChildAt(i);
                        child2.particleSystem.startColorConstant = color;
                        child2.particleSystem.startColorConstantMin = color;
                        child2.particleSystem.startColorConstantMax = color;
                    }
                }
            }
            refreshTextureTillingOffsetTab(tab) {
                for (let i = 1; i <= 3; i++) {
                    let button = this["buttonTilling0" + i];
                    if (!button) {
                        continue;
                    }
                    let node = button.__node;
                    let select = node.getChildByName("select");
                    select.visible = tab == i ? true : false;
                }
            }
            adaptTextureTillingOffsetTabTexture(iconPath) {
                Tools.loadImg(this.spriteTillingBarIconDev, iconPath);
            }
            _doChangeTextureTillingOffset(scale) {
                let model = this.avatarPartContainer.getChildAt(0);
                if (!model) {
                    return;
                }
                let state = this.stManager.getCurState();
                switch (state) {
                    case AMUSE_DESIGN_ROOM_STATE.shine:
                        this.currShineTillingOffsetScale = scale;
                        let shineId = this.selectTab2IdDict[this.TAB_SHINE];
                        let shineData = mgrCfg.get_from_design_shine_db(shineId);
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    material.shineTextureScale = (shineData.tillingOffset[0] || 1) * scale;
                                }
                            }
                        }
                        break;
                    case AMUSE_DESIGN_ROOM_STATE.grid:
                        this.currGridTillingOffsetScale = scale;
                        let gridId = this.selectTab2IdDict[this.TAB_GRID];
                        let gridData = mgrCfg.get_from_design_grid_db(gridId);
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    material.gridTextureScale = (gridData.tillingOffset[0] || 1) * scale;
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            onClickTab(tab) {
                if (!!this.bDesignEffecting) {
                    return;
                }
                if (tab != this.TAB_PART && !this.selectTab2IdDict[this.TAB_PART]) {
                    mgrTip.showMsgTip("先选择一条裙子吧");
                    cc.tween(this.buttonTab01.__node)
                        .toScale(0.05, 1.1).toScale(0.05, 1)
                        .toScale(0.05, 1.1).toScale(0.05, 1)
                        .start();
                    return;
                }
                this.penguanLeft.active = false;
                this.penguanRight.active = false;
                this.colorVat.active = false;
                this.gunlunModel.active = false;
                switch (tab) {
                    case this.TAB_PART: {
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.selectPart);
                        break;
                    }
                    case this.TAB_COLOR: {
                        this.colorVat.active = true;
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.paintColor);
                        break;
                    }
                    case this.TAB_SHINE: {
                        this.penguanLeft.active = true;
                        this.penguanRight.active = true;
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.shine);
                        break;
                    }
                    case this.TAB_GRID: {
                        this.gunlunModel.active = true;
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.grid);
                        break;
                    }
                    default:
                        break;
                }
                this.onSelectTab(tab);
                this.boxPartList.alpha = 0;
                cc.tween(this.boxPartList, true).toAlpha(0.5, 1).start();
            }
            onSelectTab(tab) {
                this.imageSliderTillingDev.visible = (tab == this.TAB_GRID || tab == this.TAB_SHINE) ? true : false;
                if (this.imageSliderTillingDev.visible) {
                    let scale = !!this.selectTab2IdDict[tab] ? 1 : 0;
                    this.imageSliderTillingDev.scale(scale, scale, true);
                }
                for (let i = 1; i <= 4; i++) {
                    let node = this["buttonTab0" + i].__node;
                    let spriteSelect = node.getChildAt(0);
                    spriteSelect.visible = tab == i ? true : false;
                }
            }
            refreshTabUsedStatus() {
                let bShowButtonSubmit = false;
                for (let i = 1; i <= 4; i++) {
                    let node = this["buttonTab0" + i].__node;
                    let spriteUsed = node.getChildAt(1);
                    spriteUsed.visible = !!this.selectTab2IdDict[i];
                    if (!bShowButtonSubmit && i > 1 && spriteUsed.visible) {
                        bShowButtonSubmit = true;
                    }
                }
                if (bShowButtonSubmit && this.buttonSummit.__node.scaleX < 0.1) {
                    cc.tween(this.buttonSummit.__node).toScale(0.3, 1).start();
                }
                if (!!this.reuseList) {
                    this.reuseList.refresh();
                }
            }
            refreshTargetScore(duration) {
                let partIds = [
                    this.selectTab2IdDict[this.TAB_PART],
                    this.selectTab2IdDict[this.TAB_COLOR],
                    this.selectTab2IdDict[this.TAB_GRID],
                    this.selectTab2IdDict[this.TAB_SHINE]
                ];
                let score = mgrDesign.calcCustomMadeStageScore(this.context.stageId, partIds);
                let maxScore = Math.ceil(this.stageData.passScore / (2 / 3));
                this.spriteStageRate01.visible = score < this.stageData.passScore ? true : false;
                this.spriteStageRate02.visible = (score >= this.stageData.passScore && score < maxScore) ? true : false;
                this.spriteStageRate03.visible = score >= maxScore ? true : false;
                this.spriteStageScoreGood.visible = !!this.spriteStageRate03.visible;
                this.spriteStageScoreBad.visible = !this.spriteStageScoreGood.visible;
                this.labelStagePower.text = `${score}`;
                if (!!this.lastRecordTargetScore) {
                    this.spriteStageScoreUpFlag.visible = !!score && this.lastRecordTargetScore < score ? true : false;
                    this.spriteStageScoreDownFlag.visible = !!score && this.lastRecordTargetScore > score ? true : false;
                    if (!!this.spriteStageScoreUpFlag.visible) {
                        this.add3DEffectAtFront("117_ui_once_up_01", this.spriteStageScoreUpFlag, 2);
                    }
                    else if (!!this.spriteStageScoreDownFlag.visible) {
                        this.add3DEffectAtFront("117_ui_once_down_01", this.spriteStageScoreDownFlag, 2);
                    }
                }
                this.lastRecordTargetScore = score;
                if (this.spriteStageRate03.visible) {
                    mgrEffect.shineNode(this.spriteStageScoreGood);
                }
                else {
                    mgrEffect.stopShineNode(this.spriteStageScoreGood);
                }
            }
            getWhitePartDatas(bDisableStatisticsAd) {
                let dbName = "design_part_config";
                let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial);
                if (bCanAd && !bDisableStatisticsAd) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
                if (!!this.dbName2DatasDict[dbName]) {
                    return this.dbName2DatasDict[dbName];
                }
                let gotedPartIdArr = [];
                let lockedPartIdArr = [];
                let coinPartIdArr = [];
                let specialPartArr = [];
                let template = mgrCfg.get_from_design_part_config(1);
                let partIds = template.partIds;
                for (let i = 0; i < partIds.length; i++) {
                    let partId = partIds[i];
                    let v = mgrCfg.get_from_part_db(partId);
                    let data = {
                        tab: this.TAB_PART,
                        guideOrder: 0,
                        __customOrderValue: 0,
                        id: v.id,
                        order: 0,
                        fOnClickItem: this.onClickItem.bind(this),
                        fIsSelected: this.isSelectItem.bind(this),
                        fIsTry: this.isTry.bind(this),
                        fIsRecommend: this.isRecommend.bind(this),
                        fStaticsShow: () => {
                        },
                        bAd: bCanAd
                    };
                    if (this.isRecommend(v.id)) {
                        specialPartArr.push(data);
                    }
                    else {
                        if (mgrPlayer.getItemAmount(v.id) <= 0) {
                            let shopData = mgrCfg.get_from_shop_template_db(v.id);
                            if (!!shopData) {
                                coinPartIdArr.push(data);
                            }
                            else {
                                lockedPartIdArr.push(data);
                            }
                        }
                        else {
                            gotedPartIdArr.push(data);
                        }
                    }
                }
                let datas = [];
                let dataDict = {
                    [0]: gotedPartIdArr,
                    [1]: lockedPartIdArr,
                    [2]: coinPartIdArr
                };
                let count = Math.max(Math.max(gotedPartIdArr.length, lockedPartIdArr.length), coinPartIdArr.length);
                for (let i = 0; i < count; i++) {
                    let indexDataArr = Tools.randomGotArrayDatas([0, 1, 2], 3);
                    for (let tmp in indexDataArr) {
                        let tmpDatas = dataDict[indexDataArr[tmp]];
                        if (tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                        if (indexDataArr[tmp] == 1 && Tools.random(100) > 50 && tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                    }
                }
                specialPartArr = Tools.randomGotArrayDatas(specialPartArr, specialPartArr.length);
                for (let i = 0; i < specialPartArr.length; i++) {
                    let index = Tools.random(2, 9);
                    datas.splice(index, 0, specialPartArr[i]);
                }
                for (let i = 0; i < datas.length; i++) {
                    datas[i].__customOrderValue = i;
                }
                datas = Tools.sortArrayByField(datas, ["-order", "-guideOrder", "__customOrderValue"]);
                this.dbName2DatasDict[dbName] = datas;
                return datas;
            }
            getPartDataByDbName(dbName, tab) {
                let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial);
                if (bCanAd) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
                if (!!this.dbName2DatasDict[dbName]) {
                    return this.dbName2DatasDict[dbName];
                }
                let gotedPartIdArr = [];
                let lockedPartIdArr = [];
                let coinPartIdArr = [];
                let specialPartArr = [];
                let db = mgrCfg.getDb(dbName);
                for (let k in db) {
                    let v = db[k];
                    if (!!v.bDisableShowInRoom || (mgrPlayer.getItemAmount(v.id) <= 0 && !!v.bDisableShowWhenUnown)) {
                        continue;
                    }
                    let data = {
                        tab: tab,
                        guideOrder: 0,
                        __customOrderValue: 0,
                        id: v.id,
                        order: v.order,
                        fOnClickItem: this.onClickItem.bind(this),
                        fIsSelected: this.isSelectItem.bind(this),
                        fIsTry: this.isTry.bind(this),
                        fIsRecommend: this.isRecommend.bind(this),
                        fStaticsShow: () => {
                        },
                        bAd: bCanAd
                    };
                    if (this.isRecommend(v.id)) {
                        specialPartArr.push(data);
                    }
                    else {
                        if (mgrPlayer.getItemAmount(v.id) <= 0) {
                            let shopData = mgrCfg.get_from_shop_template_db(v.id);
                            if (!!shopData) {
                                coinPartIdArr.push(data);
                            }
                            else {
                                lockedPartIdArr.push(data);
                            }
                        }
                        else {
                            gotedPartIdArr.push(data);
                        }
                    }
                }
                let datas = [];
                let dataDict = {
                    [0]: gotedPartIdArr,
                    [1]: lockedPartIdArr,
                    [2]: coinPartIdArr
                };
                let count = Math.max(Math.max(gotedPartIdArr.length, lockedPartIdArr.length), coinPartIdArr.length);
                for (let i = 0; i < count; i++) {
                    let indexDataArr = Tools.randomGotArrayDatas([0, 1, 2], 3);
                    for (let tmp in indexDataArr) {
                        let tmpDatas = dataDict[indexDataArr[tmp]];
                        if (tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                        if (indexDataArr[tmp] == 1 && Tools.random(100) > 50 && tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                    }
                }
                specialPartArr = Tools.randomGotArrayDatas(specialPartArr, specialPartArr.length);
                for (let i = 0; i < specialPartArr.length; i++) {
                    let index = Tools.random(2, 9);
                    datas.splice(index, 0, specialPartArr[i]);
                }
                let sortedPartId2OrderDict = mgrPart.getGameRoomListSortedId2OrderDictByType(DailyGameType.custom_made, dbName);
                if (!!sortedPartId2OrderDict && Tools.getObjSize(sortedPartId2OrderDict) > 0) {
                    for (let i = 0; i < datas.length; i++) {
                        let sortedOrder = parseInt(sortedPartId2OrderDict[datas[i].id]);
                        datas[i].__customOrderValue = !!isNaN(sortedOrder) ? i : sortedOrder;
                    }
                }
                else {
                    let sortedPartId2OrderDict = {};
                    for (let i = 0; i < datas.length; i++) {
                        datas[i].__customOrderValue = i;
                        sortedPartId2OrderDict[datas[i].id] = i;
                    }
                    mgrPart.setGameRoomListSortedId2OrderDictByType(DailyGameType.custom_made, dbName, sortedPartId2OrderDict);
                }
                datas = Tools.sortArrayByField(datas, ["-order", "-guideOrder", "__customOrderValue"]);
                this.dbName2DatasDict[dbName] = datas;
                return datas;
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vCustomMadeClothesScene_trial) {
                    this.tryingPartIds.push(e.userData.partId);
                    this.reuseList.refresh();
                    this.doClickItem(e.userData.partId, e.userData.tab);
                }
            }
            onMsgShopBuySuccessed() {
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.hangerModel && this.hangerModel.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            onTouchButtonBack() {
                mgrTip.alertPrompt2("提示", "确定要离开吗？", "取消", "确定", () => { }, () => {
                    mgrDirector.warpSceneWidthEffect(this.context.backSceneName || "vWorldDailyQuestMainScene");
                });
            }
            onTouchButtonSummit() {
                if (!!this.bDesignEffecting) {
                    return;
                }
                let originPartId = this.selectTab2IdDict[this.TAB_PART];
                let colorId = this.selectTab2IdDict[this.TAB_COLOR];
                let gridId = this.selectTab2IdDict[this.TAB_GRID];
                let shineId = this.selectTab2IdDict[this.TAB_SHINE];
                if (!originPartId) {
                    mgrTip.showMsgTip("先选择一条裙子吧");
                    return;
                }
                if (!colorId && !gridId && !shineId) {
                    mgrTip.showMsgTip("还没有设计好的呢");
                    return;
                }
                if (mgrDebug.bShowDevButton) {
                    this.penguanLeft.active = false;
                    this.penguanRight.active = false;
                    this.colorVat.active = false;
                    this.gunlunModel.active = false;
                    this.buttonBack.__node.visible = false;
                    this.buttonSummit.__node.visible = false;
                    this.boxPartContainer.visible = false;
                    this.spriteTillingoffset.visible = false;
                    this.imageSliderTillingDev.visible = false;
                    let position = this.avatarPartContainer.transform.position.clone();
                    this.avatarPartContainer.removeSelf();
                    this.hangerModel.active = false;
                    this.add3DEffectAtBack(this.avatarPartContainer, 0);
                    this.avatarPartContainer.transform.position = position;
                    this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                    this.cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                    this.cameraFollow.position = new Laya.Vector3(0, 1.35, 3.3);
                    this.cameraFollow.endRotation = new Laya.Vector3(-11);
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                    Tools.cameraForSaveImg(this.cameraBack, "preview_design");
                    return;
                }
                let doExcFunc = () => {
                    this.completedTabDict[this.TAB_GRID] = true;
                    this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE.complete);
                    let newPartId = mgrDesign.addTempDesignPart(originPartId, colorId, gridId, shineId, this.currGridTillingOffsetScale, this.currShineTillingOffsetScale);
                    this.newDesignPartId = newPartId;
                };
                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                    mgrTip.alertPrompt2("提示", `确定提交装扮吗?`, "再想想", "确定", null, () => {
                        doExcFunc();
                    });
                }
                else {
                    doExcFunc();
                }
            }
            onTouchButtonTilling01() {
            }
            onTouchButtonTilling02() {
            }
            onTouchButtonTilling03() {
            }
            onTouchButtonTab01() {
                this.onClickTab(1);
            }
            onTouchButtonTab02() {
                this.onClickTab(2);
            }
            onTouchButtonTab03() {
                this.onClickTab(3);
            }
            onTouchButtonTab04() {
                this.onClickTab(4);
            }
            onTouchButtonDevColor() {
                mgrDirector.openDialog(`vEditorColorDialog`, {
                    colorChange: (color) => {
                        console.warn("---color=", color);
                        let model = this.avatarPartContainer.getChildAt(0);
                        if (!model) {
                            return;
                        }
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    material.albedoTexture = null;
                                    material.AlbedoTillingX = 1;
                                    material.AlbedoTillingY = 1;
                                    material.albedoColor = new Laya.Vector4(color.r / 255, color.g / 255, color.b / 255, 1);
                                }
                            }
                        }
                    }
                });
            }
            getTillingoffsetScale1SliderValue() {
                let slideValue = (1 - Const.DESIGN_ROOM_TILLING_MIN_SCALE) / (Const.DESIGN_ROOM_TILLING_MAX_SCALE - Const.DESIGN_ROOM_TILLING_MIN_SCALE);
                return slideValue;
            }
            centerRegisteredSliderBar(node) {
                let slideValue = this.getTillingoffsetScale1SliderValue();
                this.repositionRegisteredSliderBar(node, slideValue);
                cc.tween(this.spriteTillingBarIconDev.parent).toScale(0.1, 1.3).toScale(0.1, 1).toScale(0.1, 1.3).toScale(0.1, 1).start();
            }
            repositionRegisteredSliderBar(node, initValue) {
                let bgProgressOffsetWidth = 20;
                let bgProgress = node.getChildByName("bgProgress");
                let minBarX = bgProgress.x + bgProgressOffsetWidth / 2;
                let maxBarX = bgProgress.x + bgProgress.width - bgProgressOffsetWidth / 2;
                let bar = node.getChildByName("bar");
                bar.x = ul.clamp(bgProgress.x + bgProgressOffsetWidth / 2 + (bgProgress.width - bgProgressOffsetWidth) * initValue, minBarX, maxBarX);
                cc.tween(bar, true).toPos(0.05, bar.x, bar.y).start();
            }
            __registerAsSlider(node, initValue, minMaxArr, slideCallback, clickCallback, inputCallback) {
                let input = node.getChildByName("input");
                let label = this.imageSliderTillingDev.getChildByName("label");
                if (!!label) {
                    label.visible = !!mgrDebug.bShowDevButton;
                }
                let bgProgressOffsetWidth = 20;
                let bgProgress = node.getChildByName("bgProgress");
                let minBarX = bgProgress.x + bgProgressOffsetWidth / 2;
                let maxBarX = bgProgress.x + bgProgress.width - bgProgressOffsetWidth / 2;
                let progressValidWidth = bgProgress.width - bgProgressOffsetWidth;
                let bar = node.getChildByName("bar");
                bar.x = ul.clamp(bgProgress.x + bgProgressOffsetWidth / 2 + (bgProgress.width - bgProgressOffsetWidth) * initValue, minBarX, maxBarX);
                let bDown = false;
                node.on(Laya.Event.MOUSE_OVER, node, (e) => {
                    console.log("-------e.MOUSE_OVER=");
                    if (clickCallback) {
                        clickCallback();
                    }
                });
                Tools.registerTouchHander(node, (e) => {
                    console.log("-------e.isClick=", e.isClick);
                    if (e.isBegin) {
                        if (!!input && Tools.isWorldLocaInNode(input, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            return;
                        }
                        bDown = true;
                    }
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        bar.x = ul.clamp(point.x, minBarX, maxBarX);
                        let pValue = (bar.x - minBarX) / progressValidWidth;
                        slideCallback(pValue);
                        if (input) {
                            let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * pValue;
                            input.text = `${useValue}`;
                        }
                    }
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                });
                if (input) {
                    let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * initValue;
                    input.text = `${useValue}`;
                    input.on(Laya.Event.INPUT, this, () => {
                        let inputValue = parseFloat(input.text) || 0;
                        let useValue = ul.clamp(inputValue, minMaxArr[0], minMaxArr[1]);
                        if (inputValue < minMaxArr[0] || inputValue > minMaxArr[1]) {
                            mgrTip.showMsgTip("数据超限");
                        }
                        inputCallback && inputCallback(useValue);
                        let slideValue = (useValue - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                        bar.x = node.width * slideValue;
                        slideCallback(slideValue);
                    });
                }
                slideCallback(initValue);
            }
        }

        const CAMERA_PRARAM_END$1 = {
            fov: 30,
            position: new Laya.Vector3(0, 0.88, 5.5),
            rotation: new Laya.Vector3(-5),
            lerpValue: 0.1,
        };
        const ROLE_POS_PARAM$1 = {
            position: new Laya.Vector3(0, 0, 0.1),
            rotation: new Laya.Vector3,
        };
        class vDesignCollectScene extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vDesignCollectScene";
                this.exportNodeNames = [];
                this.tryingPartIds = [];
                this.avatar = null;
                this.reuseList = null;
                this.customOrderedTypeDict = {};
                this.initedType2CameraDict = {};
                this.type2RecommandPartIdDict = {};
                this.TAB_PART = 1;
                this.TAB_COLOR = 2;
                this.TAB_SHINE = 3;
                this.TAB_GRID = 4;
                this.selectTab2IdDict = {};
                this.completedTabDict = {};
                this.currGridTillingOffsetScale = 1;
                this.currShineTillingOffsetScale = 1;
                this.context.stageId = this.context.stageId;
            }
            onOpened() {
                super.onOpened();
                Tools.registerTouchHander(this.boxOperation, this.onTouchSpriteBg.bind(this));
                this.buildUi();
                this.initUi();
                this.fillData();
                this.widget();
                this.playOutUi();
                this.playInUi();
                mgrVideoRecorder.startRecord();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                });
                this.registerGuideNode();
            }
            onClosed() {
                if (this.lastHuangZhuangEffModel) {
                    Tools.unLink2Node(this.lastHuangZhuangEffModel);
                    this.lastHuangZhuangEffModel = null;
                }
                mgrTip.hideLoadingTip("vDesignCollectScene_loadingAvatar");
                mgrTip.hideLoadingTip("vDesignCollectScene_loadingPart");
                mgrDesign.deleteTempDesignPart();
                super.onClosed();
            }
            getPreLoadModelIds() {
                return [
                    "e_huanzhuang"
                ];
            }
            getPreLoadAnimationIds() {
                return [];
            }
            isShowShadow() {
                return false;
            }
            registerGuideNode() {
            }
            widget() {
                mgrLayout.widgetBottomMC(this.boxPartContainer);
                mgrLayout.widgetRightTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetBottomMC(this.spriteAdButtonContainer);
                mgrLayout.widgetBottomMC(this.buttonSavePart.__node);
            }
            playOutUi() {
            }
            playInUi() {
                this.buttonBack.__node.scale(0, 0, true);
                this.buttonSavePart.__node.scale(0, 0, true);
                this.spriteAdButtonContainer.scale(0, 0, true);
                mgrEffect.playComebackAction([this.boxPartContainer], 0, 700, 0.5, 0.7, () => {
                    cc.tween(this.buttonBack.__node).delay(0.3).toScale(0.3, 1, cc.Ease.backOut).start();
                    cc.tween(this.buttonSavePart.__node).toScale(0.3, 1, cc.Ease.backOut).start();
                    cc.tween(this.spriteAdButtonContainer).toScale(0.3, 1, cc.Ease.backOut).start();
                });
            }
            buildUi() {
                this.spriteBg.zOrder = -4;
                this.reuseList = new ReuseList(6, 0, 20);
                this.reuseList.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseList);
                this.reuseList.setItemClass(vDesignCollectCell);
                this.reuseList.setVerticalMoveEnable(false);
                this.reuseList.setTouchEnable(false);
                this.reuseList.setSpaceX(4);
                this.reuseList.setSpaceY(2);
                this.avatar = new RoleAvatar({ roleId: mgrRole.showingRoleId });
                this.add3DEffectAtBack(this.avatar, 0);
                this.avatar.transform.rotationEuler = ROLE_POS_PARAM$1.rotation;
                this.avatar.transform.position = ROLE_POS_PARAM$1.position;
                if (this.context.bFromTypeScene) {
                    this.avatar.fillByPartIds(mgrPart.getLastClothes(mgrRole.showingRoleId));
                }
                else {
                    this.avatar.fillByPartIds(this.context.partIds || []);
                }
                this.avatar.registerAllLoadEndCallback(() => {
                    Timer.callLater(0.5, () => {
                        this.avatar.playAnimation("dangao-dg_jl");
                    }, this);
                });
                this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                let cf = this.cameraBack.getComponent(CameraFollow);
                cf.lookMode = E_CAMERA_MODE.fixMode;
                cf.fov = CAMERA_PRARAM_END$1.fov;
                cf.position = CAMERA_PRARAM_END$1.position;
                cf.endRotation = CAMERA_PRARAM_END$1.rotation;
                cf.lerpValue = 1;
                cf.onLateUpdate();
                cf.lerpValue = CAMERA_PRARAM_END$1.lerpValue;
            }
            initUi() {
                let newDesignPartId = mgrDesign.getEmptyUnlockedPartCellPartId();
                this.spriteAdButtonContainer.visible = !newDesignPartId;
                this.buttonSavePart.__node.visible = !!newDesignPartId;
                if (this.context.bFromTypeScene) {
                    this.spriteAdButtonContainer.visible = false;
                    this.buttonSavePart.__node.visible = false;
                }
            }
            fillData() {
                let arr = [];
                let dict = mgrDesign.getDesignPartDataDict();
                for (let k in dict) {
                    let partId = parseInt(k);
                    arr.push({
                        partId: partId,
                        bShowSelectFlag: this.context.bFromTypeScene,
                        fIsSelect: this.isSelectItem.bind(this),
                        fOnClick: this.onClickItem.bind(this),
                    });
                }
                arr = Tools.sortArrayByField(arr, "partId");
                this.reuseList.setDatas(arr);
            }
            onClickItem(id) {
                if (!this.context.bFromTypeScene) {
                    return;
                }
                this.avatar.fillByPartIds([id]);
                this.selectedId = id;
            }
            isSelectItem(id) {
                return this.selectedId && this.selectedId == id ? true : false;
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            doSaveDesignPart(newDesignPartId) {
                let worldPos = null;
                let cells = this.reuseList.getAllCells();
                for (let k in cells) {
                    let cell = cells[k];
                    let data = cell["data"];
                    if (data && data.partId && data.partId == newDesignPartId) {
                        worldPos = cell.localToGlobal(new Laya.Point(0, 0));
                        break;
                    }
                }
                worldPos = worldPos || this.boxPartList.localToGlobal(new Laya.Point(this.boxPartList.width / 2, this.boxPartList.height / 2));
                let targetPos = this.globalToLocal(worldPos);
                let tmpPartData = mgrDesign.getTempDesignPartData();
                mgrDesign.deleteTempDesignPart();
                mgrDesign.updateDesignPart(newDesignPartId, tmpPartData.originPartId, tmpPartData.designColorId, tmpPartData.designGridId, tmpPartData.designShineId, tmpPartData.designGridScale, tmpPartData.designShineScale);
                this.avatar.fillByPartIds([newDesignPartId]);
                mgrPart.setLastClothes(this.avatar.getPartIds());
                let textureKey = mgrDesign.getDesignPartIconKey(newDesignPartId);
                let texture2d = this.context.tex2d;
                let pixels = texture2d.getPixels();
                pixels = Tools.transparentBlackArea(pixels, Const.CUSTOM_PART_ICON_SIZE_WH, Const.CUSTOM_PART_ICON_SIZE_WH);
                texture2d.setPixels(pixels);
                mgrRole.savePhoto(textureKey, texture2d);
                this.buttonBack.__node.visible = false;
                let texture = new Laya.Texture(this.context.tex2d);
                let spriteEff = new Laya.Sprite;
                spriteEff.texture = texture;
                spriteEff.pos(mgrDirector.width / 2, mgrDirector.height / 2, true);
                this.addChild(spriteEff);
                cc.tween(spriteEff)
                    .then(cc.jumpTo(1, targetPos.x, targetPos.y + 6, 100, 1))
                    .call(() => {
                    mgrSound.play(412);
                })
                    .delay(1)
                    .call(() => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    mgrTip.alertPrompt1("提示", "衣柜又增加新衣服啦", "确定", () => {
                        this.onTouchButtonBack();
                    });
                })
                    .start();
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(this.context.backSceneName || "vHubScene");
            }
            onTouchButtonGetNormal() {
                this.onTouchButtonBack();
            }
            onTouchButtonGetAd() {
                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vDesignCollectScene_unlock, null, true);
            }
            onTouchButtonSavePart() {
                let newDesignPartId = mgrDesign.getEmptyUnlockedPartCellPartId();
                if (!newDesignPartId) {
                    newDesignPartId = mgrDesign.getMinLockPartCellPartId();
                    if (!newDesignPartId) {
                        newDesignPartId = mgrDesign.randomGetUnlockedPartCellPartId();
                    }
                }
                this.doSaveDesignPart(newDesignPartId);
                this.spriteAdButtonContainer.visible = false;
                this.buttonSavePart.__node.visible = false;
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vDesignCollectScene_unlock) {
                    let newDesignPartId = mgrDesign.getMinLockPartCellPartId();
                    mgrDesign.unlockPartCellByPartId(newDesignPartId);
                    this.reuseList.refresh();
                    Timer.callLater(0.1, () => {
                        this.onTouchButtonSavePart();
                    }, this);
                }
            }
        }

        const CAMERA_PRARAM_INIT$2 = {
            fov: 30,
            position: new Laya.Vector3(0, 0.93, 3.25),
            rotation: new Laya.Vector3(-5),
            lerpValue: 0.1,
        };
        const CAMERA_PRARAM_ITEM_EFFECT_DICT$1 = {
            [1]: {
                fov: 30,
                position: new Laya.Vector3(0, 0.98, 5.0),
                rotation: new Laya.Vector3(-5),
                lerpValue: 0.1,
            },
            [2]: {
                fov: 30,
                position: new Laya.Vector3(0, 0.98, 5.0),
                rotation: new Laya.Vector3(-5),
                lerpValue: 0.1,
            },
            [3]: {
                fov: 30,
                position: new Laya.Vector3(0, 0.98, 5.0),
                rotation: new Laya.Vector3(-5),
                lerpValue: 0.1,
            },
            [4]: {
                fov: 30,
                position: new Laya.Vector3(0, 0.98, 5.0),
                rotation: new Laya.Vector3(-5),
                lerpValue: 0.1,
            },
        };
        const CAMERA_PRARAM_FOR_PHOTO$1 = {
            fov: 75,
            position: new Laya.Vector3(0, 1.08, 0.93),
            rotation: new Laya.Vector3(-14),
            lerpValue: 1,
        };
        const CAMERA_PRARAM_FOR_SHOW$1 = {
            fov: 30,
            position: new Laya.Vector3(0, 1.19, 4.68),
            rotation: new Laya.Vector3(-5),
            lerpValue: 0.1,
        };
        const ROLE_POS_PARAM$2 = {
            position: new Laya.Vector3(0, 0, 0.1),
            rotation: new Laya.Vector3,
        };
        var AMUSE_DESIGN_ROOM_STATE$1;
        (function (AMUSE_DESIGN_ROOM_STATE) {
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["init"] = 1] = "init";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["selectPart"] = 2] = "selectPart";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["paintColor"] = 3] = "paintColor";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["grid"] = 4] = "grid";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["shine"] = 5] = "shine";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["complete"] = 6] = "complete";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["getShow"] = 7] = "getShow";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["reward"] = 8] = "reward";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["palette"] = 9] = "palette";
            AMUSE_DESIGN_ROOM_STATE[AMUSE_DESIGN_ROOM_STATE["finish"] = 10] = "finish";
        })(AMUSE_DESIGN_ROOM_STATE$1 || (AMUSE_DESIGN_ROOM_STATE$1 = {}));
        class vDesignRoomScene extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vDesignRoomScene";
                this.exportNodeNames = [];
                this.tryingPartIds = [];
                this.avatar = null;
                this.avatarPartContainer = null;
                this.reuseList = null;
                this.customOrderedTypeDict = {};
                this.initedType2CameraDict = {};
                this.type2RecommandPartIdDict = {};
                this.TAB_PART = 1;
                this.TAB_COLOR = 2;
                this.TAB_GRID = 3;
                this.TAB_SHINE = 4;
                this.selectTab2IdDict = {};
                this.completedTabDict = {};
                this.currGridTillingOffsetScale = 1;
                this.currShineTillingOffsetScale = 1;
                this.dbName2DatasDict = {};
                this.roomPopClickItemPartCount = 0;
                this.context.stageId = this.context.stageId;
                this.context.roleId = this.context.roleId || mgrRole.showingRoleId;
            }
            onOpened() {
                super.onOpened();
                Tools.registerTouchHander(this.boxOperation, this.onTouchSpriteBg.bind(this));
                this.buildScene(() => {
                    this.buildUi();
                    this.fillData();
                    this.widget();
                    this.playOutUi();
                    this.playInUi();
                    this.stManager = new FSMObject;
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.selectPart, this.inSelectPart.bind(this), this.exeSelectPart.bind(this), this.outSelectPart.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.paintColor, this.inPaintColor.bind(this), this.exePaintColor.bind(this), this.outPaintColor.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.grid, this.inGrid.bind(this), this.exeGrid.bind(this), this.outGrid.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.shine, this.inShine.bind(this), this.exeShine.bind(this), this.outShine.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.complete, this.inComplete.bind(this), this.exeComplete.bind(this), this.outComplete.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.getShow, this.inGetShow.bind(this), this.exeGetShow.bind(this), this.outGetShow.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.reward, this.inReward.bind(this), this.exeReward.bind(this), this.outReward.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.palette, this.inPalette.bind(this), this.exePalette.bind(this), this.outPalette.bind(this));
                    this.stManager.registerState(AMUSE_DESIGN_ROOM_STATE$1.finish, this.inFinish.bind(this), this.exeFinish.bind(this), this.outFinish.bind(this));
                    this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.init);
                    this.stManager.startUpdate(this);
                    mgrVideoRecorder.startRecord();
                    this.registerListeners({
                        MSG_SHOP_BUY_SUCCESSED: this.onMsgShopBuySuccessed.bind(this),
                        MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this),
                    });
                    this.registerGuideNode();
                    mgrTip.tryShowFullScreenMoreGameFixed("b_fsmgfs_cloth_design");
                });
                this.buttonMoreGameBox.__node.visible = mgrAd.showMoreGameBox(3);
            }
            onClosed() {
                if (this.gunlunEffModel) {
                    mgrLoader.Pool.recoverModel(this.gunlunEffModel);
                    this.gunlunEffModel = null;
                }
                if (this.penguanEffModelLeft) {
                    mgrLoader.Pool.recoverModel(this.penguanEffModelLeft);
                    this.penguanEffModelLeft = null;
                }
                if (this.penguanEffModelRight) {
                    mgrLoader.Pool.recoverModel(this.penguanEffModelRight);
                    this.penguanEffModelRight = null;
                }
                if (this.lastHuangZhuangEffModel) {
                    Tools.unLink2Node(this.lastHuangZhuangEffModel);
                    this.lastHuangZhuangEffModel = null;
                }
                mgrTip.hideLoadingTip("vDesignRoomScene_loadingAvatar");
                mgrTip.hideLoadingTip("vDesignRoomScene_loadingPart");
                if (!!this.avatarPartContainer) {
                    let numChildren = this.avatarPartContainer.numChildren;
                    for (let i = numChildren - 1; i >= 0; i--) {
                        let child = this.avatarPartContainer.getChildAt(i);
                        if (!child) {
                            continue;
                        }
                        mgrLoader.Pool.recoverModel(child);
                    }
                    this.avatarPartContainer.destroy();
                    this.avatarPartContainer = null;
                }
                super.onClosed();
            }
            getPreLoadModelIds() {
                return [
                    "chizi",
                    "yijia",
                    "penping_design",
                    "gunlun",
                    "117_ui_loop_spraysmoke_01",
                    "116_ui_loop_star_01",
                    "117_ui_once_ribbon_02",
                    "design_room_bg",
                    "117_e_once_diychange_01"
                ];
            }
            getPreLoadAnimationIds() {
                return ["diy_jiesuan-diy_jiesuan"];
            }
            isShowShadow() {
                return false;
            }
            registerGuideNode() {
                mgrGuide.registerGuideNode("vDesignRoomScene.buttonSummit", this.buttonSummit.__node);
            }
            widget() {
                mgrLayout.widgetBottomMC(this.boxPartContainer);
                mgrLayout.widgetRightTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftBottomMC(this.buttonBack.__node);
                mgrLayout.widgetRightBottomMC(this.buttonSummit.__node);
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            playOutUi() {
            }
            playInUi() {
                mgrEffect.playComebackAction([this.spriteTopBarHolder], -400, 0, 0.5, 0.6, null, cc.Ease.backOut);
                mgrEffect.playComebackAction([this.buttonBack.__node], -400, 0, 0.5, 0.6, null, cc.Ease.backOut);
                mgrEffect.playComebackAction([this.boxPartContainer], 0, 700, 0.5, 0.5, () => {
                }, cc.Ease.circOut);
                this.buttonSummit.__node.scale(0, 0, true);
            }
            buildScene(callback) {
                let bgModel = mgrLoader.Pool.getModel("design_room_bg");
                this.add3DEffectAtBack(bgModel, 0);
                let render = Tools.getMeshRender(bgModel.getChildAt(0));
                if (render) {
                    Tools.loadMaterialTexture("res/ui/room_design_zz/bg.jpg", render.sharedMaterials[0], "albedoTexture");
                }
                bgModel.active = false;
                this.bgModel = bgModel;
                this.hangerModel = mgrLoader.Pool.getModel("yijia");
                mgrMaterial.setCustomMaterial(this.hangerModel, "yijia");
                this.add3DEffectAtBack(this.hangerModel, 0);
                let nodeRoot = this.hangerModel.getChildByName("Guadian_Part");
                nodeRoot.removeChildren();
                this.avatarPartContainer = new Laya.Sprite3D;
                nodeRoot.addChild(this.avatarPartContainer);
                this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                this.hangerModel.transform.rotationEuler = ROLE_POS_PARAM$2.rotation;
                this.hangerModel.transform.position = ROLE_POS_PARAM$2.position;
                let cf = this.cameraBack.getComponent(CameraFollow);
                cf.lookMode = E_CAMERA_MODE.fixMode;
                cf.fov = CAMERA_PRARAM_INIT$2.fov;
                cf.position = CAMERA_PRARAM_INIT$2.position;
                cf.endRotation = CAMERA_PRARAM_INIT$2.rotation;
                cf.lerpValue = 1;
                cf.onLateUpdate();
                cf.lerpValue = CAMERA_PRARAM_INIT$2.lerpValue;
                this.penguanLeft = mgrLoader.Pool.getModel("penping_design");
                this.add3DEffectAtBack(this.penguanLeft, 0);
                mgrMaterial.setCustomMaterial(this.penguanLeft, "penping_design");
                this.penguanLeft.transform.localRotationEulerY = -75;
                this.penguanLeft.transform.position = new Laya.Vector3(ROLE_POS_PARAM$2.position.x - 0.55, ROLE_POS_PARAM$2.position.y + 1.2, ROLE_POS_PARAM$2.position.z + 0.2);
                this.penguanLeft['_originLocalPos'] = this.penguanLeft.transform.localPosition.clone();
                this.penguanLeft.transform.localPositionX = this.penguanLeft['_originLocalPos'].x - 2;
                this.penguanLeft.transform.setWorldLossyScale(new Laya.Vector3(2, 2, 2));
                this.penguanLeft.active = false;
                this.penguanRight = mgrLoader.Pool.getModel("penping_design");
                this.add3DEffectAtBack(this.penguanRight, 0);
                mgrMaterial.setCustomMaterial(this.penguanRight, "penping_design");
                this.penguanRight.transform.localRotationEulerY = 75;
                this.penguanRight.transform.position = new Laya.Vector3(ROLE_POS_PARAM$2.position.x + 0.55, ROLE_POS_PARAM$2.position.y + 1.2, ROLE_POS_PARAM$2.position.z + 0.2);
                this.penguanRight['_originLocalPos'] = this.penguanRight.transform.localPosition.clone();
                this.penguanRight.transform.localPositionX = this.penguanRight['_originLocalPos'].x + 2;
                this.penguanRight.transform.setWorldLossyScale(new Laya.Vector3(2, 2, 2));
                this.penguanRight.active = false;
                let penguanEffNode = Tools.findNode("guadian_eff", this.penguanLeft);
                let penguanEffModel = mgrLoader.Pool.getModel("117_ui_loop_spraysmoke_01");
                penguanEffModel.transform.setWorldLossyScale(new Laya.Vector3(1.2, 1.2, 1.2));
                penguanEffNode.addChild(penguanEffModel);
                penguanEffModel.active = false;
                penguanEffModel.transform.localRotationEulerY = -90;
                this.penguanEffModelLeft = penguanEffModel;
                penguanEffNode = Tools.findNode("guadian_eff", this.penguanRight);
                penguanEffModel = mgrLoader.Pool.getModel("117_ui_loop_spraysmoke_01");
                penguanEffModel.transform.setWorldLossyScale(new Laya.Vector3(1.2, 1.2, 1.2));
                penguanEffNode.addChild(penguanEffModel);
                penguanEffModel.active = false;
                penguanEffModel.transform.localRotationEulerY = -90;
                this.penguanEffModelRight = penguanEffModel;
                this.colorVat = mgrLoader.Pool.getModel("chizi");
                this.add3DEffectAtBack(this.colorVat, 0);
                mgrMaterial.setCustomMaterial(this.colorVat, "chizi");
                this.colorVat.transform.position = new Laya.Vector3(ROLE_POS_PARAM$2.position.x, ROLE_POS_PARAM$2.position.y + 0.3, ROLE_POS_PARAM$2.position.z);
                this.colorVat['_originLocalPos'] = this.colorVat.transform.localPosition.clone();
                this.colorVat.active = false;
                this.gunlunModel = mgrLoader.Pool.getModel("gunlun");
                this.add3DEffectAtBack(this.gunlunModel, 0);
                mgrMaterial.setCustomMaterial(this.gunlunModel, "gunlun");
                this.gunlunModel.transform.setWorldLossyScale(new Laya.Vector3(2, 2, 2));
                this.gunlunModel.transform.position = new Laya.Vector3(ROLE_POS_PARAM$2.position.x, ROLE_POS_PARAM$2.position.y, ROLE_POS_PARAM$2.position.z + 0.4);
                this.gunlunModel['_originLocalPos'] = this.gunlunModel.transform.localPosition.clone();
                this.gunlunModel.active = false;
                penguanEffModel = mgrLoader.Pool.getModel("116_ui_loop_star_01");
                this.add3DEffectAtFront(penguanEffModel, { x: mgrDirector.width / 2, y: mgrDirector.height * 0.35 });
                penguanEffModel.active = false;
                this.gunlunEffModel = penguanEffModel;
                callback && callback();
            }
            buildUi() {
                let topBar = new vTopBar({ bDisableGold: true, bDisableEnergy: true });
                this.spriteTopBarHolder.addChild(topBar);
                this.spriteBg.zOrder = -4;
                this.buttonSummit.__node.visible = true;
                this.spriteTillingoffset.visible = false;
                this.buttonDevColor.__node.visible = !!mgrDebug.bShowDevButton;
                if (this.imageSliderTillingDev.visible) {
                    let minMaxArr = [0, 100];
                    let slideValue = this.getTillingoffsetScale1SliderValue();
                    this.__registerAsSlider(this.imageSliderTillingDev, slideValue, minMaxArr, (value) => {
                        let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * (1 - value);
                        let scale = Const.DESIGN_ROOM_TILLING_MIN_SCALE + useValue / 100 * (Const.DESIGN_ROOM_TILLING_MAX_SCALE - Const.DESIGN_ROOM_TILLING_MIN_SCALE);
                        this._doChangeTextureTillingOffset(scale);
                        let label = this.imageSliderTillingDev.getChildByName("label");
                        if (!!label) {
                            label.text = `纹理缩放: ${(useValue).toFixed(4)}`;
                        }
                    }, () => {
                    });
                }
                this.reuseList = new ReuseList(6, 0, 20);
                this.reuseList.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseList);
                this.reuseList.setItemClass(vRoomDesignPart);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseList.setSpaceX(4);
                this.reuseList.setSpaceY(2);
            }
            fillData() {
            }
            inInit() {
                this.onClickTab(this.TAB_PART);
            }
            exeInit() { }
            outInit() { }
            inSelectPart() {
                let datas = this.getWhitePartDatas();
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
                if (!this.selectTab2IdDict[this.TAB_PART]) {
                    for (let k in datas) {
                        let data = datas[k];
                        if (mgrPlayer.getItemAmount(data.id) > 0) {
                            this.doClickItem(data.id, this.TAB_PART, false, true);
                            break;
                        }
                    }
                }
            }
            exeSelectPart() { }
            outSelectPart() { }
            inPaintColor() {
                let datas = this.getPartDataByDbName("design_part_color_db", this.TAB_COLOR);
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            exePaintColor() { }
            outPaintColor() { }
            inShine() {
                this.refreshTextureTillingOffsetTab(3);
                let datas = this.getPartDataByDbName("design_shine_db", this.TAB_SHINE);
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            exeShine() { }
            outShine() { }
            inGrid() {
                this.refreshTextureTillingOffsetTab(3);
                let datas = this.getPartDataByDbName("design_grid_db", this.TAB_GRID);
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            exeGrid() { }
            outGrid() { }
            inComplete() {
                this.penguanLeft.active = false;
                this.penguanRight.active = false;
                this.colorVat.active = false;
                this.gunlunModel.active = false;
                this.buttonBack.__node.visible = false;
                this.buttonSummit.__node.visible = false;
                this.boxPartContainer.visible = false;
                this.spriteTillingoffset.visible = false;
                this.imageSliderTillingDev.visible = false;
                this.add3DEffectAtFront("117_ui_once_ribbon_02", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 1);
                mgrSound.play(127);
                Timer.callLater(1, () => {
                    this.cameraFollow.fov = CAMERA_PRARAM_FOR_PHOTO$1.fov;
                    this.cameraFollow.position = CAMERA_PRARAM_FOR_PHOTO$1.position;
                    this.cameraFollow.endRotation = CAMERA_PRARAM_FOR_PHOTO$1.rotation;
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                    let oldPos = this.avatarPartContainer.transform.position.clone();
                    this.avatarPartContainer.removeSelf();
                    this.hangerModel.active = false;
                    this.add3DEffectAtBack(this.avatarPartContainer);
                    this.avatarPartContainer.transform.position = oldPos;
                    Tools.takeAPhoto(Const.CUSTOM_PART_ICON_SIZE_WH, Const.CUSTOM_PART_ICON_SIZE_WH, this.cameraBack, (tex2d) => {
                        if (!this.nodeResource || this.nodeResource.destroyed || this.destroyed) {
                            return;
                        }
                        this.cameraFollow.fov = CAMERA_PRARAM_INIT$2.fov;
                        this.cameraFollow.position = CAMERA_PRARAM_INIT$2.position;
                        this.cameraFollow.endRotation = CAMERA_PRARAM_INIT$2.rotation;
                        this.cameraFollow.lerpValue = 1;
                        this.cameraFollow.onLateUpdate();
                        this.tet2dCompletePart = tex2d;
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.getShow);
                    }, Laya.RenderTextureFormat.R8G8B8A8);
                }, this);
            }
            exeComplete() { }
            outComplete() { }
            inGetShow() {
                this.avatar = new RoleAvatar({ roleId: this.context.roleId });
                this.add3DEffectAtBack(this.avatar, 0);
                this.avatar.fillByPartIds(mgrPart.getLastClothes(this.context.roleId));
                this.avatar.registerLoadEndCallback(() => {
                    this.add3DEffectAtBack("117_e_once_diychange_01");
                    mgrSound.play(641);
                    this.avatar.playAnimation(["diy_jiesuan-diy_jiesuan"], 0, () => {
                        Timer.callLater(0.1, () => {
                            this.cameraFollow.fov = CAMERA_PRARAM_FOR_SHOW$1.fov;
                            this.cameraFollow.position = CAMERA_PRARAM_FOR_SHOW$1.position;
                            this.cameraFollow.endRotation = CAMERA_PRARAM_FOR_SHOW$1.rotation;
                            this.cameraFollow.lerpValue = 0.2;
                            this.cameraFollow.onLateUpdate();
                            this.avatar.transform.rotationEuler = ROLE_POS_PARAM$2.rotation;
                            this.avatar.transform.position = ROLE_POS_PARAM$2.position;
                            let model = this.avatarPartContainer.getChildAt(0);
                            mgrLoader.Pool.recoverModel(model);
                            mgrLoader.Pool.recoverModel(this.hangerModel);
                        }, this);
                        Timer.callLater(0.7, () => {
                            this.avatar.fillByPartIds([this.newDesignPartId]);
                        }, this);
                    }, () => {
                        this.cameraFollow.position = new Laya.Vector3(0, 1.26, 2.6);
                        this.cameraFollow.lerpValue = 1;
                        this.cameraFollow.onLateUpdate();
                        this.bgModel.active = true;
                        Tools.takeAPhoto(512, 512, this.cameraBack, (tex2d) => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.bgModel.active = false;
                            this.shareTex2d = tex2d;
                            this.cameraFollow.position = CAMERA_PRARAM_FOR_SHOW$1.position;
                            this.cameraFollow.onLateUpdate();
                            Timer.callLater(0.3, () => {
                                this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.reward);
                            }, this);
                        }, Laya.RenderTextureFormat.R8G8B8A8);
                    });
                });
            }
            exeGetShow() { }
            outGetShow() { }
            inReward() {
                let rewardColorPoint = 0;
                let rewardRmb = Tools.random(5, 10);
                mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, rewardRmb, "自由服装设计结算奖励");
                mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, rewardRmb, null, {
                    fOnClose: () => {
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.finish);
                    }
                });
            }
            exeReward() { }
            outReward() { }
            inPalette() {
            }
            exePalette() { }
            outPalette() { }
            inFinish() {
                mgrVideoRecorder.stopRecord();
                mgrTip.tryShowPhotoShare("vCustomMadeClothesScene", this.shareTex2d, null, () => {
                    this.stManager.stopUpdate();
                    mgrDirector.warpSceneWidthEffect("vDesignCollectScene", { partIds: this.avatar.getPartIds(), tex2d: this.tet2dCompletePart });
                });
            }
            exeFinish() { }
            outFinish() { }
            isRecommend(id) {
                return false;
            }
            isTry(id) {
                return this.tryingPartIds.indexOf(id) >= 0;
            }
            isSelectItem(id) {
                for (let k in this.selectTab2IdDict) {
                    let selectedId = this.selectTab2IdDict[k];
                    if (selectedId == id) {
                        return true;
                    }
                }
                return false;
            }
            onClickItem(id, tab, bTryBuy = false, bDisableChangeCamera) {
                this.tryPopClickItemTrial(id, tab);
                this.doClickItem(id, tab, bTryBuy, bDisableChangeCamera);
            }
            tryPopClickItemTrial(partId, tab) {
                if (mgrGuide.isGuiding()) {
                    return;
                }
                if (mgrPlayer.getItemAmount(partId) <= 0 || mgrSdk.getCopNumberValueByKey("b_click_part_item_pop_trial") != 1) {
                    return;
                }
                let gap = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_gap") || 0;
                if (Tools.time() < (mgrPart.roomPopClickItemPartLastTime + gap)) {
                    return;
                }
                let popCount = mgrSdk.getCopNumberValueByKey("click_part_item_pop_trial_count_per_stage") || 0;
                if (this.roomPopClickItemPartCount > popCount) {
                    return;
                }
                if (!mgrAd.preCheckAdNoCd(AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial, true)) {
                    return;
                }
                this.roomPopClickItemPartCount++;
                mgrPart.roomPopClickItemPartLastTime = Tools.time();
                let lockedPartIdArr = [];
                switch (tab) {
                    case this.TAB_PART: {
                        let template = mgrCfg.get_from_design_part_config(1);
                        let partIds = template.partIds;
                        for (let i = 0; i < partIds.length; i++) {
                            let partId = partIds[i];
                            let shopData = mgrCfg.get_from_shop_template_db(partId);
                            if (mgrPlayer.getItemAmount(partId) <= 0 && !shopData) {
                                lockedPartIdArr.push(partId);
                            }
                        }
                        break;
                    }
                    default: {
                        let tab2DbName = {
                            [this.TAB_COLOR]: "design_part_color_db",
                            [this.TAB_GRID]: "design_grid_db",
                            [this.TAB_SHINE]: "design_shine_db",
                        };
                        let dbName = tab2DbName[tab];
                        if (!dbName) {
                            return;
                        }
                        let dbData = mgrCfg.getDb(dbName);
                        for (let k in dbData) {
                            let data = dbData[k];
                            let shopData = mgrCfg.get_from_shop_template_db(data.id);
                            if (mgrPlayer.getItemAmount(data.id) <= 0 && !shopData) {
                                lockedPartIdArr.push(data.id);
                            }
                        }
                        break;
                    }
                }
                if (lockedPartIdArr.length == 0) {
                    return;
                }
                let partIdAd = Tools.randomGotOneArrayData(lockedPartIdArr);
                mgrDirector.openDialog("vAdFreeTrialPartDialog", {
                    adEventId: AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial,
                    partId: partIdAd,
                    adTriggerParams: {
                        partId: partIdAd,
                        tab: tab
                    }
                });
            }
            doClickItem(id, tab, bTryBuy = false, bDisableChangeCamera) {
                if (!!this.bDesignEffecting) {
                    return;
                }
                if (bTryBuy && mgrPlayer.getItemAmount(id) <= 0 && !this.isTry(id)) {
                    let shopData = mgrCfg.get_from_shop_template_db(id);
                    if (!shopData) {
                        if (mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial)) {
                            if (mgrSdk.getCopNumberValueByKey(`b_room_try_ad_tip`) == 0) {
                                mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial, { partId: id, tab: tab }, true);
                            }
                            else {
                                mgrTip.alertPrompt2("提示", "是否看视频免费试用？", "取消", "确定", null, () => {
                                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial, { partId: id, tab: tab }, true);
                                }, true, false);
                            }
                        }
                        else {
                            mgrTip.showMsgTip("广告准备中,请稍后再试");
                        }
                    }
                    else {
                        if (!shopData || !shopData.price || !shopData.priceUnit) {
                            mgrTip.showMsgTip("还未获得此部件");
                            return;
                        }
                        let doBuyFunc = () => {
                            if (mgrShop.requestBuy(id, "设计部件")) {
                                Timer.callLoop(0.016, (timer) => {
                                    if (DialogBase.ShowingDialog.length > 0 || mgrTip.isShowingLoadingTip())
                                        return;
                                    timer.stop();
                                    this.doClickItem(id, tab, false);
                                    this.reuseList.refresh();
                                }, this);
                            }
                            else {
                            }
                        };
                        if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                            let partData = mgrCfg.get_from_item_template_db(id);
                            let itemData = mgrCfg.get_from_item_template_db(shopData.priceUnit);
                            mgrTip.alertPrompt2("提示", `是否花费【${shopData.price}${itemData.name}】购买\n\n【${partData.name}】?`, "不了", "好的", null, () => {
                                doBuyFunc();
                            });
                        }
                        else {
                            doBuyFunc();
                        }
                    }
                    return;
                }
                let statisItemData = mgrCfg.get_from_part_db(id) || mgrCfg.get_from_design_part_color_db(id) || mgrCfg.get_from_design_grid_db(id) || mgrCfg.get_from_design_shine_db(id);
                if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                    !!statisItemData.statisPointId && mgrSdk.statisCommonEvent(statisItemData.statisPointId);
                }
                this.selectTab2IdDict[tab] = id;
                if (tab != this.TAB_PART) {
                    let cf = this.cameraBack.getComponent(CameraFollow);
                    cf.fov = CAMERA_PRARAM_ITEM_EFFECT_DICT$1[tab].fov;
                    cf.position = CAMERA_PRARAM_ITEM_EFFECT_DICT$1[tab].position;
                    cf.endRotation = CAMERA_PRARAM_ITEM_EFFECT_DICT$1[tab].rotation;
                    cf.lerpValue = CAMERA_PRARAM_ITEM_EFFECT_DICT$1[tab].lerpValue;
                }
                switch (tab) {
                    case this.TAB_PART: {
                        this.bDesignEffecting = true;
                        let partData = mgrCfg.get_from_part_db(id);
                        mgrLoader.loadModeWithModeId(partData.modelId, () => {
                            mgrLoader.markPartResLoaded(id);
                            let numChildren = this.avatarPartContainer.numChildren;
                            for (let i = numChildren - 1; i >= 0; i--) {
                                let child = this.avatarPartContainer.getChildAt(i);
                                if (!child) {
                                    continue;
                                }
                                mgrLoader.Pool.recoverModel(child);
                            }
                            let model = mgrLoader.Pool.getModel(partData.modelId);
                            mgrMaterial.setCustomMaterial(model, partData.modelId, 0, true);
                            for (let i = 0; i < model.numChildren; i++) {
                                let child = model.getChildAt(i);
                                let renderer = Tools.getMeshRender(child);
                                if (renderer) {
                                    for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                        let material = renderer.sharedMaterials[j];
                                        if (material.PlayerCustomChangeFlag < 0.5) {
                                            continue;
                                        }
                                        Tools.loadMaterialTexture(Const.SKIN_CONTROL_GRID_SHINE_PATH, material, "controlDetailTexture");
                                        material.albedoColor = new Laya.Vector4(0.88, 0.88, 0.88, 1.0);
                                        material.albedoTexture = null;
                                        material.AlbedoTillingX = 1.0;
                                        material.AlbedoTillingY = 1.0;
                                        material.gridTexture = null;
                                        material.shineTexture = null;
                                        material.gridTextureScale = 1.0;
                                        material.shineTextureScale = 1.0;
                                    }
                                }
                            }
                            this.avatarPartContainer.addChild(model);
                            this.completedTabDict[tab] = true;
                            this.doDesignByItemId(this.selectTab2IdDict[this.TAB_COLOR]);
                            this.doDesignByItemId(this.selectTab2IdDict[this.TAB_GRID]);
                            this.doDesignByItemId(this.selectTab2IdDict[this.TAB_SHINE]);
                            cc.tween(this.hangerModel.transform)
                                .by(0.5, { localRotationEulerY: 360 })
                                .call(() => {
                                this.bDesignEffecting = false;
                                this.refreshTabUsedStatus();
                            })
                                .start();
                        }, this, 1);
                        break;
                    }
                    case this.TAB_COLOR: {
                        this.bDesignEffecting = true;
                        let colorData = mgrCfg.get_from_design_part_color_db(id);
                        let callback = () => {
                            let node = this.colorVat.getChildByName("chizi");
                            let render = Tools.getMeshRender(node);
                            for (let k in render.sharedMaterials) {
                                let material = render.sharedMaterials[k];
                                if (material.name == "shui") {
                                    if (colorData.paint == "") {
                                        material.albedoTexture = null;
                                        material.AlbedoTillingX = 1;
                                        material.AlbedoTillingY = 1;
                                        material.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                    }
                                    else {
                                        let texture = mgrLoader.get2dRes(colorData.paint);
                                        let text2d = texture.bitmap;
                                        if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                            text2d.wrapModeU = Laya.WarpMode.Repeat;
                                            text2d.wrapModeV = Laya.WarpMode.Repeat;
                                            text2d.filterMode = Laya.FilterMode.Bilinear;
                                            text2d.generateMipmap();
                                        }
                                        material.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                        material.albedoTexture = text2d;
                                        material.AlbedoTillingX = colorData.tillingOffset[0];
                                        material.AlbedoTillingY = colorData.tillingOffset[1];
                                    }
                                    break;
                                }
                            }
                            mgrSound.play(161);
                            cc.tween(this.hangerModel.transform)
                                .to(0.3, { localPositionY: -1.1 })
                                .by(0.5, { localRotationEulerY: 360 })
                                .by(0.5, { localRotationEulerY: 360 })
                                .call(() => {
                                let model = this.avatarPartContainer.getChildAt(0);
                                for (let i = 0; i < model.numChildren; i++) {
                                    let child = model.getChildAt(i);
                                    let renderer = Tools.getMeshRender(child);
                                    if (renderer) {
                                        for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                            let material = renderer.sharedMaterials[j];
                                            if (material.PlayerCustomChangeFlag < 0.5) {
                                                continue;
                                            }
                                            if (colorData.paint == "") {
                                                material.albedoTexture = null;
                                                material.AlbedoTillingX = 1;
                                                material.AlbedoTillingY = 1;
                                                material.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                            }
                                            else {
                                                let texture = mgrLoader.get2dRes(colorData.paint);
                                                let text2d = texture.bitmap;
                                                if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                                    text2d.wrapModeU = Laya.WarpMode.Repeat;
                                                    text2d.wrapModeV = Laya.WarpMode.Repeat;
                                                    text2d.filterMode = Laya.FilterMode.Bilinear;
                                                    text2d.generateMipmap();
                                                }
                                                material.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                                material.albedoTexture = text2d;
                                                material.AlbedoTillingX = colorData.tillingOffset[0];
                                                material.AlbedoTillingY = colorData.tillingOffset[1];
                                            }
                                        }
                                    }
                                }
                                this.completedTabDict[tab] = true;
                            })
                                .to(0.5, { localPositionY: 0 })
                                .call(() => {
                                this.add3DEffectAtFront("117_ui_once_water_01", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 }, 1);
                                this.bDesignEffecting = false;
                                this.refreshTabUsedStatus();
                                let cf = this.cameraBack.getComponent(CameraFollow);
                                cf.fov = CAMERA_PRARAM_INIT$2.fov;
                                cf.position = CAMERA_PRARAM_INIT$2.position;
                                cf.endRotation = CAMERA_PRARAM_INIT$2.rotation;
                                cf.lerpValue = CAMERA_PRARAM_INIT$2.lerpValue;
                            })
                                .start();
                        };
                        if (colorData.paint == "") {
                            callback();
                        }
                        else {
                            mgrLoader.batchLoadResources([], [], [colorData.paint], () => {
                                callback();
                            });
                        }
                        break;
                    }
                    case this.TAB_SHINE: {
                        this.bDesignEffecting = true;
                        this.imageSliderTillingDev.scale(0, 0, true);
                        let shineData = mgrCfg.get_from_design_shine_db(id);
                        mgrLoader.Load2dRes(shineData.paint, Laya.Loader.IMAGE, this, (res) => {
                            this.changePenguanColor(this.penguanEffModelLeft);
                            this.changePenguanColor(this.penguanEffModelRight);
                            let standbyLeftX = this.penguanLeft.transform.localPositionX = this.penguanLeft['_originLocalPos'].x - 2;
                            cc.tween(this.penguanLeft.transform)
                                .to(0.1, { localPositionX: this.penguanLeft['_originLocalPos'].x })
                                .call(() => {
                                this.penguanEffModelLeft.active = true;
                                mgrSound.play(162);
                            })
                                .delay(1.6)
                                .call(() => {
                                this.penguanEffModelLeft.active = false;
                            })
                                .to(0.1, { localPositionX: standbyLeftX })
                                .start();
                            let standbyRightX = this.penguanRight.transform.localPositionX = this.penguanRight['_originLocalPos'].x + 2;
                            cc.tween(this.penguanRight.transform)
                                .to(0.1, { localPositionX: this.penguanRight['_originLocalPos'].x })
                                .call(() => {
                                this.penguanEffModelRight.active = true;
                                cc.tween(this.hangerModel.transform)
                                    .by(0.8, { localRotationEulerY: 180 })
                                    .call(() => {
                                    let model = this.avatarPartContainer.getChildAt(0);
                                    for (let i = 0; i < model.numChildren; i++) {
                                        let child = model.getChildAt(i);
                                        let renderer = Tools.getMeshRender(child);
                                        if (renderer) {
                                            for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                                let material = renderer.sharedMaterials[j];
                                                if (material.PlayerCustomChangeFlag < 0.5) {
                                                    continue;
                                                }
                                                material.shineTextureScale = shineData.tillingOffset[0] || 1;
                                                Tools.loadMaterialTexture(shineData.paint, material, "shineTexture");
                                            }
                                        }
                                    }
                                    this.completedTabDict[tab] = true;
                                })
                                    .by(0.8, { localRotationEulerY: 180 })
                                    .call(() => {
                                })
                                    .start();
                            })
                                .delay(1.6)
                                .call(() => {
                                this.penguanEffModelRight.active = false;
                            })
                                .to(0.1, { localPositionX: standbyRightX })
                                .call(() => {
                                this.currShineTillingOffsetScale = 1;
                                this.centerRegisteredSliderBar(this.imageSliderTillingDev);
                                this.adaptTextureTillingOffsetTabTexture(shineData.icon);
                                this.imageSliderTillingDev.scale(1, 1, true);
                                this.bDesignEffecting = false;
                                this.refreshTabUsedStatus();
                                let cf = this.cameraBack.getComponent(CameraFollow);
                                cf.fov = CAMERA_PRARAM_INIT$2.fov;
                                cf.position = CAMERA_PRARAM_INIT$2.position;
                                cf.endRotation = CAMERA_PRARAM_INIT$2.rotation;
                                cf.lerpValue = CAMERA_PRARAM_INIT$2.lerpValue;
                            })
                                .start();
                        });
                        break;
                    }
                    case this.TAB_GRID: {
                        this.bDesignEffecting = true;
                        let gridData = mgrCfg.get_from_design_grid_db(id);
                        this.imageSliderTillingDev.scale(0, 0, true);
                        mgrLoader.Load2dRes(gridData.paint, Laya.Loader.IMAGE, this, (res) => {
                            let node = this.gunlunModel.getChildByName("gunlun");
                            let render = Tools.getMeshRender(node);
                            if (!!render) {
                                for (let k in render.sharedMaterials) {
                                    let material = render.sharedMaterials[k];
                                    if (material.name == "gunlun_huawen") {
                                        let texture = mgrLoader.get2dRes(gridData.paint);
                                        let text2d = texture.bitmap;
                                        if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                            text2d.wrapModeU = Laya.WarpMode.Repeat;
                                            text2d.wrapModeV = Laya.WarpMode.Repeat;
                                            text2d.filterMode = Laya.FilterMode.Bilinear;
                                            text2d.generateMipmap();
                                        }
                                        material.albedoColor = new Laya.Vector4(233 / 255, 116 / 255, 212 / 255, 1);
                                        material.paintLayer1Texture = text2d;
                                        material.paintLayer1TilingOffset = new Laya.Vector4(gridData.tillingOffset[0], gridData.tillingOffset[1], 0, 0);
                                        break;
                                    }
                                }
                            }
                            cc.tween(this.gunlunModel.transform, true)
                                .to(0.1, { localPositionY: this.gunlunModel['_originLocalPos'].y + 0.8 })
                                .call(() => {
                                this.gunlunEffModel.active = true;
                                mgrSound.play(163);
                            })
                                .by(0.25, { localPositionY: 0.3, localPositionX: -0.1 })
                                .by(0.5, { localPositionY: -0.6, localPositionX: 0.2 })
                                .by(0.25, { localPositionY: 0.3, localPositionX: -0.1 })
                                .call(() => {
                                let model = this.avatarPartContainer.getChildAt(0);
                                for (let i = 0; i < model.numChildren; i++) {
                                    let child = model.getChildAt(i);
                                    let renderer = Tools.getMeshRender(child);
                                    if (renderer) {
                                        for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                            let material = renderer.sharedMaterials[j];
                                            if (material.PlayerCustomChangeFlag < 0.5) {
                                                continue;
                                            }
                                            material.gridTextureScale = gridData.tillingOffset[0] || 1;
                                            Tools.loadMaterialTexture(gridData.paint, material, "gridTexture");
                                        }
                                    }
                                }
                                this.completedTabDict[tab] = true;
                            })
                                .by(0.25, { localPositionY: 0.3, localPositionX: -0.1 })
                                .by(0.5, { localPositionY: -0.6, localPositionX: 0.2 })
                                .call(() => {
                                this.gunlunEffModel.active = false;
                            })
                                .to(0.1, { localPositionY: this.gunlunModel['_originLocalPos'].y, localPositionX: this.gunlunModel['_originLocalPos'].x })
                                .call(() => {
                                this.currGridTillingOffsetScale = 1;
                                this.centerRegisteredSliderBar(this.imageSliderTillingDev);
                                this.adaptTextureTillingOffsetTabTexture(gridData.icon);
                                this.imageSliderTillingDev.scale(1, 1, true);
                                this.bDesignEffecting = false;
                                this.refreshTabUsedStatus();
                                let cf = this.cameraBack.getComponent(CameraFollow);
                                cf.fov = CAMERA_PRARAM_INIT$2.fov;
                                cf.position = CAMERA_PRARAM_INIT$2.position;
                                cf.endRotation = CAMERA_PRARAM_INIT$2.rotation;
                                cf.lerpValue = CAMERA_PRARAM_INIT$2.lerpValue;
                            })
                                .start();
                        });
                        break;
                    }
                    default:
                        break;
                }
            }
            doDesignByItemId(id) {
                if (!id) {
                    return;
                }
                let tab = null;
                let colorData = mgrCfg.get_from_design_part_color_db(id);
                let shineData = mgrCfg.get_from_design_shine_db(id);
                let gridData = mgrCfg.get_from_design_grid_db(id);
                if (!!colorData) {
                    tab = this.TAB_COLOR;
                }
                else if (!!shineData) {
                    tab = this.TAB_SHINE;
                }
                else if (!!gridData) {
                    tab = this.TAB_GRID;
                }
                else {
                    return;
                }
                switch (tab) {
                    case this.TAB_COLOR: {
                        let callback = () => {
                            let model = this.avatarPartContainer.getChildAt(0);
                            for (let i = 0; i < model.numChildren; i++) {
                                let child = model.getChildAt(i);
                                let renderer = Tools.getMeshRender(child);
                                if (renderer) {
                                    for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                        let material = renderer.sharedMaterials[j];
                                        if (material.PlayerCustomChangeFlag < 0.5) {
                                            continue;
                                        }
                                        if (colorData.paint == "") {
                                            material.albedoTexture = null;
                                            material.AlbedoTillingX = 1;
                                            material.AlbedoTillingY = 1;
                                            material.albedoColor = new Laya.Vector4(colorData.color[0] / 255, colorData.color[1] / 255, colorData.color[2] / 255, 1);
                                        }
                                        else {
                                            let texture = mgrLoader.get2dRes(colorData.paint);
                                            let text2d = texture.bitmap;
                                            if (text2d.wrapModeU != Laya.WarpMode.Repeat) {
                                                text2d.wrapModeU = Laya.WarpMode.Repeat;
                                                text2d.wrapModeV = Laya.WarpMode.Repeat;
                                                text2d.filterMode = Laya.FilterMode.Bilinear;
                                                text2d.generateMipmap();
                                            }
                                            material.albedoColor = new Laya.Vector4(1, 1, 1, 1);
                                            material.albedoTexture = text2d;
                                            material.AlbedoTillingX = colorData.tillingOffset[0];
                                            material.AlbedoTillingY = colorData.tillingOffset[1];
                                        }
                                    }
                                }
                            }
                        };
                        if (colorData.paint == "") {
                            callback();
                        }
                        else {
                            mgrLoader.batchLoadResources([], [], [colorData.paint], () => {
                                callback();
                            });
                        }
                        break;
                    }
                    case this.TAB_GRID: {
                        mgrLoader.Load2dRes(gridData.paint, Laya.Loader.IMAGE, this, (res) => {
                            let model = this.avatarPartContainer.getChildAt(0);
                            for (let i = 0; i < model.numChildren; i++) {
                                let child = model.getChildAt(i);
                                let renderer = Tools.getMeshRender(child);
                                if (renderer) {
                                    for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                        let material = renderer.sharedMaterials[j];
                                        if (material.PlayerCustomChangeFlag < 0.5) {
                                            continue;
                                        }
                                        material.gridTextureScale = (gridData.tillingOffset[0] || 1) * (this.currGridTillingOffsetScale || 1);
                                        Tools.loadMaterialTexture(gridData.paint, material, "gridTexture");
                                    }
                                }
                            }
                        });
                        break;
                    }
                    case this.TAB_SHINE: {
                        mgrLoader.Load2dRes(shineData.paint, Laya.Loader.IMAGE, this, (res) => {
                            let model = this.avatarPartContainer.getChildAt(0);
                            for (let i = 0; i < model.numChildren; i++) {
                                let child = model.getChildAt(i);
                                let renderer = Tools.getMeshRender(child);
                                if (renderer) {
                                    for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                        let material = renderer.sharedMaterials[j];
                                        if (material.PlayerCustomChangeFlag < 0.5) {
                                            continue;
                                        }
                                        material.shineTextureScale = (shineData.tillingOffset[0] || 1) * (this.currShineTillingOffsetScale || 1);
                                        Tools.loadMaterialTexture(shineData.paint, material, "shineTexture");
                                    }
                                }
                            }
                        });
                        break;
                    }
                    default:
                        break;
                }
            }
            changePenguanColor(penguanEffModel) {
                let color = new Laya.Vector4(Tools.random(255) / 255, Tools.random(255) / 255, Tools.random(255) / 255, 1.0);
                let numChildren = penguanEffModel.numChildren;
                for (let i = 0; i < numChildren; i++) {
                    let child = penguanEffModel.getChildAt(i);
                    child.particleSystem.startColorConstant = color;
                    child.particleSystem.startColorConstantMin = color;
                    child.particleSystem.startColorConstantMax = color;
                    let numChildren2 = child.numChildren;
                    for (let i = 0; i < numChildren2; i++) {
                        let child2 = child.getChildAt(i);
                        child2.particleSystem.startColorConstant = color;
                        child2.particleSystem.startColorConstantMin = color;
                        child2.particleSystem.startColorConstantMax = color;
                    }
                }
            }
            refreshTextureTillingOffsetTab(tab) {
                for (let i = 1; i <= 3; i++) {
                    let button = this["buttonTilling0" + i];
                    if (!button) {
                        continue;
                    }
                    let node = button.__node;
                    let select = node.getChildByName("select");
                    select.visible = tab == i ? true : false;
                }
            }
            adaptTextureTillingOffsetTabTexture(iconPath) {
                Tools.loadImg(this.spriteTillingBarIconDev, iconPath);
            }
            _doChangeTextureTillingOffset(scale) {
                let model = this.avatarPartContainer.getChildAt(0);
                if (!model) {
                    return;
                }
                let state = this.stManager.getCurState();
                switch (state) {
                    case AMUSE_DESIGN_ROOM_STATE$1.shine:
                        this.currShineTillingOffsetScale = scale;
                        let shineId = this.selectTab2IdDict[this.TAB_SHINE];
                        let shineData = mgrCfg.get_from_design_shine_db(shineId);
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    material.shineTextureScale = (shineData.tillingOffset[0] || 1) * scale;
                                }
                            }
                        }
                        break;
                    case AMUSE_DESIGN_ROOM_STATE$1.grid:
                        this.currGridTillingOffsetScale = scale;
                        let gridId = this.selectTab2IdDict[this.TAB_GRID];
                        let gridData = mgrCfg.get_from_design_grid_db(gridId);
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    material.gridTextureScale = (gridData.tillingOffset[0] || 1) * scale;
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            onClickTab(tab) {
                if (!!this.bDesignEffecting) {
                    return;
                }
                if (tab != this.TAB_PART && !this.selectTab2IdDict[this.TAB_PART]) {
                    mgrTip.showMsgTip("先选择一条裙子吧");
                    cc.tween(this.buttonTab01.__node)
                        .toScale(0.05, 1.1).toScale(0.05, 1)
                        .toScale(0.05, 1.1).toScale(0.05, 1)
                        .start();
                    return;
                }
                this.penguanLeft.active = false;
                this.penguanRight.active = false;
                this.colorVat.active = false;
                this.gunlunModel.active = false;
                switch (tab) {
                    case this.TAB_PART: {
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.selectPart);
                        break;
                    }
                    case this.TAB_COLOR: {
                        this.colorVat.active = true;
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.paintColor);
                        break;
                    }
                    case this.TAB_SHINE: {
                        this.penguanLeft.active = true;
                        this.penguanRight.active = true;
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.shine);
                        break;
                    }
                    case this.TAB_GRID: {
                        this.gunlunModel.active = true;
                        this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.grid);
                        break;
                    }
                    default:
                        break;
                }
                this.onSelectTab(tab);
                this.boxPartList.alpha = 0;
                cc.tween(this.boxPartList, true).toAlpha(0.5, 1).start();
            }
            onSelectTab(tab) {
                this.imageSliderTillingDev.visible = (tab == this.TAB_GRID || tab == this.TAB_SHINE) ? true : false;
                if (this.imageSliderTillingDev.visible) {
                    let scale = !!this.selectTab2IdDict[tab] ? 1 : 0;
                    this.imageSliderTillingDev.scale(scale, scale, true);
                }
                for (let i = 1; i <= 4; i++) {
                    let node = this["buttonTab0" + i].__node;
                    let spriteSelect = node.getChildAt(0);
                    spriteSelect.visible = tab == i ? true : false;
                }
            }
            refreshTabUsedStatus() {
                let bShowButtonSubmit = false;
                for (let i = 1; i <= 4; i++) {
                    let node = this["buttonTab0" + i].__node;
                    let spriteUsed = node.getChildAt(1);
                    spriteUsed.visible = !!this.selectTab2IdDict[i];
                    if (!bShowButtonSubmit && i > 1 && spriteUsed.visible) {
                        bShowButtonSubmit = true;
                    }
                }
                if (bShowButtonSubmit && this.buttonSummit.__node.scaleX < 0.1) {
                    cc.tween(this.buttonSummit.__node).toScale(0.3, 1).start();
                }
                if (!!this.reuseList) {
                    this.reuseList.refresh();
                }
            }
            getWhitePartDatas(bDisableStatisticsAd) {
                let dbName = "design_part_config";
                let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial);
                if (bCanAd && !bDisableStatisticsAd) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
                if (!!this.dbName2DatasDict[dbName]) {
                    return this.dbName2DatasDict[dbName];
                }
                let gotedPartIdArr = [];
                let lockedPartIdArr = [];
                let coinPartIdArr = [];
                let specialPartArr = [];
                let template = mgrCfg.get_from_design_part_config(1);
                let partIds = template.partIds;
                for (let i = 0; i < partIds.length; i++) {
                    let partId = partIds[i];
                    let v = mgrCfg.get_from_part_db(partId);
                    let data = {
                        tab: this.TAB_PART,
                        guideOrder: 0,
                        __customOrderValue: 0,
                        id: v.id,
                        order: 0,
                        fOnClickItem: this.onClickItem.bind(this),
                        fIsSelected: this.isSelectItem.bind(this),
                        fIsTry: this.isTry.bind(this),
                        fIsRecommend: this.isRecommend.bind(this),
                        fStaticsShow: () => {
                        },
                        bAd: bCanAd
                    };
                    if (this.isRecommend(v.id)) {
                        specialPartArr.push(data);
                    }
                    else {
                        if (mgrPlayer.getItemAmount(v.id) <= 0) {
                            let shopData = mgrCfg.get_from_shop_template_db(v.id);
                            if (!!shopData) {
                                coinPartIdArr.push(data);
                            }
                            else {
                                lockedPartIdArr.push(data);
                            }
                        }
                        else {
                            gotedPartIdArr.push(data);
                        }
                    }
                }
                let datas = [];
                let dataDict = {
                    [0]: gotedPartIdArr,
                    [1]: lockedPartIdArr,
                    [2]: coinPartIdArr
                };
                let count = Math.max(Math.max(gotedPartIdArr.length, lockedPartIdArr.length), coinPartIdArr.length);
                for (let i = 0; i < count; i++) {
                    let indexDataArr = Tools.randomGotArrayDatas([0, 1, 2], 3);
                    for (let tmp in indexDataArr) {
                        let tmpDatas = dataDict[indexDataArr[tmp]];
                        if (tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                        if (indexDataArr[tmp] == 1 && Tools.random(100) > 50 && tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                    }
                }
                specialPartArr = Tools.randomGotArrayDatas(specialPartArr, specialPartArr.length);
                for (let i = 0; i < specialPartArr.length; i++) {
                    let index = Tools.random(2, 9);
                    datas.splice(index, 0, specialPartArr[i]);
                }
                for (let i = 0; i < datas.length; i++) {
                    datas[i].__customOrderValue = i;
                }
                datas = Tools.sortArrayByField(datas, ["-order", "-guideOrder", "__customOrderValue"]);
                this.dbName2DatasDict[dbName] = datas;
                return datas;
            }
            getPartDataByDbName(dbName, tab) {
                let bCanAd = mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial);
                if (bCanAd) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial);
                    if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                        mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                    }
                }
                if (!!this.dbName2DatasDict[dbName]) {
                    return this.dbName2DatasDict[dbName];
                }
                let gotedPartIdArr = [];
                let lockedPartIdArr = [];
                let coinPartIdArr = [];
                let specialPartArr = [];
                let db = mgrCfg.getDb(dbName);
                for (let k in db) {
                    let v = db[k];
                    if (!!v.bDisableShowInRoom || (mgrPlayer.getItemAmount(v.id) <= 0 && !!v.bDisableShowWhenUnown)) {
                        continue;
                    }
                    let data = {
                        tab: tab,
                        guideOrder: 0,
                        __customOrderValue: 0,
                        id: v.id,
                        order: v.order,
                        fOnClickItem: this.onClickItem.bind(this),
                        fIsSelected: this.isSelectItem.bind(this),
                        fIsTry: this.isTry.bind(this),
                        fIsRecommend: this.isRecommend.bind(this),
                        fStaticsShow: () => {
                        },
                        bAd: bCanAd
                    };
                    if (this.isRecommend(v.id)) {
                        specialPartArr.push(data);
                    }
                    else {
                        if (mgrPlayer.getItemAmount(v.id) <= 0) {
                            let shopData = mgrCfg.get_from_shop_template_db(v.id);
                            if (!!shopData) {
                                coinPartIdArr.push(data);
                            }
                            else {
                                lockedPartIdArr.push(data);
                            }
                        }
                        else {
                            gotedPartIdArr.push(data);
                        }
                    }
                }
                let datas = [];
                let dataDict = {
                    [0]: gotedPartIdArr,
                    [1]: lockedPartIdArr,
                    [2]: coinPartIdArr
                };
                let count = Math.max(Math.max(gotedPartIdArr.length, lockedPartIdArr.length), coinPartIdArr.length);
                for (let i = 0; i < count; i++) {
                    let indexDataArr = Tools.randomGotArrayDatas([0, 1, 2], 3);
                    for (let tmp in indexDataArr) {
                        let tmpDatas = dataDict[indexDataArr[tmp]];
                        if (tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                        if (indexDataArr[tmp] == 1 && Tools.random(100) > 50 && tmpDatas.length > 0) {
                            let tmpData = Tools.randomRemoveArrayDatas(tmpDatas, 1)[0];
                            datas.push(tmpData);
                        }
                    }
                }
                specialPartArr = Tools.randomGotArrayDatas(specialPartArr, specialPartArr.length);
                for (let i = 0; i < specialPartArr.length; i++) {
                    let index = Tools.random(2, 9);
                    datas.splice(index, 0, specialPartArr[i]);
                }
                let sortedPartId2OrderDict = mgrPart.getGameRoomListSortedId2OrderDictByType(DailyGameType.custom_made, dbName);
                if (!!sortedPartId2OrderDict && Tools.getObjSize(sortedPartId2OrderDict) > 0) {
                    for (let i = 0; i < datas.length; i++) {
                        let sortedOrder = parseInt(sortedPartId2OrderDict[datas[i].id]);
                        datas[i].__customOrderValue = !!isNaN(sortedOrder) ? i : sortedOrder;
                    }
                }
                else {
                    let sortedPartId2OrderDict = {};
                    for (let i = 0; i < datas.length; i++) {
                        datas[i].__customOrderValue = i;
                        sortedPartId2OrderDict[datas[i].id] = i;
                    }
                    mgrPart.setGameRoomListSortedId2OrderDictByType(DailyGameType.custom_made, dbName, sortedPartId2OrderDict);
                }
                datas = Tools.sortArrayByField(datas, ["-order", "-guideOrder", "__customOrderValue"]);
                this.dbName2DatasDict[dbName] = datas;
                return datas;
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vDesignRoomScene_trial) {
                    this.tryingPartIds.push(e.userData.partId);
                    this.reuseList.refresh();
                    this.doClickItem(e.userData.partId, e.userData.tab);
                }
            }
            onMsgShopBuySuccessed() {
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.hangerModel && this.hangerModel.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(this.context.backSceneName || "vHubScene");
            }
            onTouchButtonSummit() {
                if (!!this.bDesignEffecting) {
                    return;
                }
                let originPartId = this.selectTab2IdDict[this.TAB_PART];
                let colorId = this.selectTab2IdDict[this.TAB_COLOR];
                let gridId = this.selectTab2IdDict[this.TAB_GRID];
                let shineId = this.selectTab2IdDict[this.TAB_SHINE];
                if (!originPartId) {
                    mgrTip.showMsgTip("先选择一条裙子吧");
                    return;
                }
                if (!colorId && !gridId && !shineId) {
                    mgrTip.showMsgTip("还没有设计好的呢");
                    return;
                }
                if (mgrDebug.bShowDevButton) {
                    this.penguanLeft.active = false;
                    this.penguanRight.active = false;
                    this.colorVat.active = false;
                    this.gunlunModel.active = false;
                    this.buttonBack.__node.visible = false;
                    this.buttonSummit.__node.visible = false;
                    this.boxPartContainer.visible = false;
                    this.spriteTillingoffset.visible = false;
                    this.imageSliderTillingDev.visible = false;
                    let position = this.avatarPartContainer.transform.position.clone();
                    this.avatarPartContainer.removeSelf();
                    this.hangerModel.active = false;
                    this.add3DEffectAtBack(this.avatarPartContainer, 0);
                    this.avatarPartContainer.transform.position = position;
                    this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                    this.cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                    this.cameraFollow.position = new Laya.Vector3(0, 1.35, 3.3);
                    this.cameraFollow.endRotation = new Laya.Vector3(-11);
                    this.cameraFollow.lerpValue = 1;
                    this.cameraFollow.onLateUpdate();
                    Tools.cameraForSaveImg(this.cameraBack, "preview_design");
                    return;
                }
                let doExcFunc = () => {
                    this.completedTabDict[this.TAB_GRID] = true;
                    this.stManager.setNextState(AMUSE_DESIGN_ROOM_STATE$1.complete);
                    let newPartId = mgrDesign.addTempDesignPart(originPartId, colorId, gridId, shineId, this.currGridTillingOffsetScale, this.currShineTillingOffsetScale);
                    this.newDesignPartId = newPartId;
                };
                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                    mgrTip.alertPrompt2("提示", `确定提交装扮吗?`, "再想想", "确定", null, () => {
                        doExcFunc();
                    });
                }
                else {
                    doExcFunc();
                }
            }
            onTouchButtonTilling01() {
            }
            onTouchButtonTilling02() {
            }
            onTouchButtonTilling03() {
            }
            onTouchButtonTab01() {
                this.onClickTab(1);
            }
            onTouchButtonTab02() {
                this.onClickTab(2);
            }
            onTouchButtonTab03() {
                this.onClickTab(3);
            }
            onTouchButtonTab04() {
                this.onClickTab(4);
            }
            onTouchButtonDevColor() {
                mgrDirector.openDialog(`vEditorColorDialog`, {
                    colorChange: (color) => {
                        console.warn("---color=", color);
                        let model = this.avatarPartContainer.getChildAt(0);
                        if (!model) {
                            return;
                        }
                        for (let i = 0; i < model.numChildren; i++) {
                            let child = model.getChildAt(i);
                            let renderer = Tools.getMeshRender(child);
                            if (renderer) {
                                for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                    let material = renderer.sharedMaterials[j];
                                    if (material.PlayerCustomChangeFlag < 0.5) {
                                        continue;
                                    }
                                    material.albedoTexture = null;
                                    material.AlbedoTillingX = 1;
                                    material.AlbedoTillingY = 1;
                                    material.albedoColor = new Laya.Vector4(color.r / 255, color.g / 255, color.b / 255, 1);
                                }
                            }
                        }
                    }
                });
            }
            onTouchButtonMoreGameBox() {
                mgrSdk.opentChannelMoreGameBox();
            }
            getTillingoffsetScale1SliderValue() {
                let slideValue = (1 - Const.DESIGN_ROOM_TILLING_MIN_SCALE) / (Const.DESIGN_ROOM_TILLING_MAX_SCALE - Const.DESIGN_ROOM_TILLING_MIN_SCALE);
                return slideValue;
            }
            centerRegisteredSliderBar(node) {
                let slideValue = this.getTillingoffsetScale1SliderValue();
                this.repositionRegisteredSliderBar(node, slideValue);
                cc.tween(this.spriteTillingBarIconDev.parent).toScale(0.1, 1.3).toScale(0.1, 1).toScale(0.1, 1.3).toScale(0.1, 1).start();
            }
            repositionRegisteredSliderBar(node, initValue) {
                let bgProgressOffsetWidth = 20;
                let bgProgress = node.getChildByName("bgProgress");
                let minBarX = bgProgress.x + bgProgressOffsetWidth / 2;
                let maxBarX = bgProgress.x + bgProgress.width - bgProgressOffsetWidth / 2;
                let bar = node.getChildByName("bar");
                bar.x = ul.clamp(bgProgress.x + bgProgressOffsetWidth / 2 + (bgProgress.width - bgProgressOffsetWidth) * initValue, minBarX, maxBarX);
            }
            __registerAsSlider(node, initValue, minMaxArr, slideCallback, clickCallback, inputCallback) {
                let input = node.getChildByName("input");
                let label = this.imageSliderTillingDev.getChildByName("label");
                if (!!label) {
                    label.visible = !!mgrDebug.bShowDevButton;
                }
                let bgProgressOffsetWidth = 20;
                let bgProgress = node.getChildByName("bgProgress");
                let minBarX = bgProgress.x + bgProgressOffsetWidth / 2;
                let maxBarX = bgProgress.x + bgProgress.width - bgProgressOffsetWidth / 2;
                let progressValidWidth = bgProgress.width - bgProgressOffsetWidth;
                let bar = node.getChildByName("bar");
                bar.x = ul.clamp(bgProgress.x + bgProgressOffsetWidth / 2 + (bgProgress.width - bgProgressOffsetWidth) * initValue, minBarX, maxBarX);
                let bDown = false;
                node.on(Laya.Event.MOUSE_OVER, node, (e) => {
                    console.log("-------e.MOUSE_OVER=");
                    if (clickCallback) {
                        clickCallback();
                    }
                });
                Tools.registerTouchHander(node, (e) => {
                    console.log("-------e.isClick=", e.isClick);
                    if (e.isBegin) {
                        if (!!input && Tools.isWorldLocaInNode(input, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            return;
                        }
                        bDown = true;
                    }
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        bar.x = ul.clamp(point.x, minBarX, maxBarX);
                        let pValue = (bar.x - minBarX) / progressValidWidth;
                        slideCallback(pValue);
                        if (input) {
                            let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * pValue;
                            input.text = `${useValue}`;
                        }
                    }
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                });
                if (input) {
                    let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * initValue;
                    input.text = `${useValue}`;
                    input.on(Laya.Event.INPUT, this, () => {
                        let inputValue = parseFloat(input.text) || 0;
                        let useValue = ul.clamp(inputValue, minMaxArr[0], minMaxArr[1]);
                        if (inputValue < minMaxArr[0] || inputValue > minMaxArr[1]) {
                            mgrTip.showMsgTip("数据超限");
                        }
                        inputCallback && inputCallback(useValue);
                        let slideValue = (useValue - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                        bar.x = node.width * slideValue;
                        slideCallback(slideValue);
                    });
                }
                slideCallback(initValue);
            }
        }

        class vEditorAnimationCheckScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorAnimationCheckScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                mgrDirector.adaptStageSize(2304, 1580);
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
                mgrDirector.adaptStageSize();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 50);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorSpineItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                let taskManager = new TaskManager;
                let taskSamples = [];
                this.avatar = new RoleAvatar({ roleId: mgrRole.showingRoleId });
                this.add3DEffectAtBack(this.avatar, 0);
                taskSamples.push((endCallback) => {
                    this.avatar.registerLoadEndCallback(() => {
                        this.avatar.transform.position = new Laya.Vector3(0.3, -0.8, 0);
                        let cf = this.cameraBack.getComponent(CameraFollow);
                        cf.fov = 20;
                        endCallback();
                    });
                });
                taskManager.push(taskSamples);
                taskManager.start(() => {
                    let datas = [];
                    mgrCfg.forDb_from_animation_db((k, v) => {
                        datas.push({
                            spineId: v.id,
                            onClickSpine: this.onClickSpine.bind(this),
                        });
                    });
                    this.reuseListSpine.setDatas(datas);
                });
                Tools.registerTouchHander(this.nodeResource, this.onTouchSpriteBg.bind(this));
            }
            onClickSpine(spineId) {
                if (!this.avatar) {
                    return;
                }
                this.avatar.playAnimation(spineId);
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    this.lastTouchBgPos = e.pos;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            onTouchButtonClose() {
                mgrDirector.warpSceneWidthEffect("vHubScene");
            }
        }
        class vEditorSpineItem extends ReuseListItem {
            constructor() {
                super();
                let width = 335;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.spineId);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `${data.spineId}`;
            }
        }

        class vEditorCakeStageScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorCakeStageScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorCakeStageItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_cake_stage_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
            }
            onClickSpine(id) {
                mgrDirector.warpSceneWidthEffect("vAmuseCakeMakeScene", { stageId: id });
            }
        }
        class vEditorCakeStageItem extends ReuseListItem {
            constructor() {
                super();
                let width = 500;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                let template = mgrCfg.get_from_cake_stage_db(data.id);
                this.label.text = `关卡：${data.id}`;
            }
        }

        class vEditorCardStageScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorCardStageScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorCardStageItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_amaze_card_stage_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
            }
            onClickSpine(id) {
                mgrDirector.open2DScene(`vAmuseCardTeamSetScene`, {
                    stageId: id,
                });
            }
        }
        class vEditorCardStageItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `关卡：${data.id}`;
            }
        }

        class vEditorClothCrossingStageScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorClothCrossingStageScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorClothCrossingStageItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_amaze_cloth_crossing_stage_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
            }
            onClickSpine(id) {
                mgrDirector.openDialog("vAmuseClothCrossingPreviewDialog", { stageId: id });
            }
        }
        class vEditorClothCrossingStageItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `关卡：${data.id}`;
            }
        }

        class vEditorClothStageScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorClothStageScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorClothStageItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_stage_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
            }
            onClickSpine(id) {
                let stageId = id;
                let roleData = this.getRoleExceptShowingRole(DailyGameType.cloth);
                mgrWorldDaily.setGameTempParms(DailyGameType.cloth, roleData.id);
                mgrDirector.openDialog("vFreedomRoomPreviewDialog", {
                    targetRoleId: roleData.id,
                    stageId: stageId,
                    backSceneName: `vWorldDailyQuestMainScene`,
                }, true);
            }
            getRoleExceptShowingRole(gameType, muteRoleId) {
                let roleId = mgrWorldDaily.getGameTempParms(gameType);
                if (!!roleId && roleId != muteRoleId && roleId != mgrRole.showingRoleId) {
                    return mgrCfg.get_from_role_db(roleId);
                }
                let arr = [];
                let roleDataShowing = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (!!muteRoleId && v.id == muteRoleId) {
                        return;
                    }
                    if (!v.rootRoleId || v.rootRoleId != roleDataShowing.rootRoleId) {
                        arr.push(v);
                    }
                });
                return Tools.randomGotOneArrayData(arr);
            }
        }
        class vEditorClothStageItem extends ReuseListItem {
            constructor() {
                super();
                let width = 500;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                let template = mgrCfg.get_from_stage_db(data.id);
                this.label.text = `关卡：${data.id}`;
            }
        }

        class vEditorDesignStageScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorDesignStageScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorDesignStageItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_custom_made_clothes_stage_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
            }
            onClickSpine(id) {
                let roleData = this.getRoleExceptShowingRole(DailyGameType.custom_made);
                mgrWorldDaily.setGameTempParms(DailyGameType.custom_made, roleData.id);
                mgrDirector.openDialog("vCustomMadeClothesPreviewDialog", { stageId: id, roleId: roleData.id, bVip: false });
            }
            getRoleExceptShowingRole(gameType, muteRoleId) {
                let roleId = mgrWorldDaily.getGameTempParms(gameType);
                if (!!roleId && roleId != muteRoleId && roleId != mgrRole.showingRoleId) {
                    return mgrCfg.get_from_role_db(roleId);
                }
                let arr = [];
                let roleDataShowing = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (!!muteRoleId && v.id == muteRoleId) {
                        return;
                    }
                    if (!v.rootRoleId || v.rootRoleId != roleDataShowing.rootRoleId) {
                        arr.push(v);
                    }
                });
                return Tools.randomGotOneArrayData(arr);
            }
        }
        class vEditorDesignStageItem extends ReuseListItem {
            constructor() {
                super();
                let width = 500;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                let template = mgrCfg.get_from_custom_made_clothes_stage_db(data.id);
                this.label.text = `关卡：${data.id}`;
            }
        }

        class vEditorDynamicBone extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorDynamicBone";
                this.exportNodeNames = [];
                this.listRootRouterDataArr = [];
                this.reuseListChildNodeArr = [];
                this.DEFAULT_DYNAMIC_CONFIG = {
                    gBoneConfig: {
                        parm1: 0.15,
                        tansRatio: 1,
                        radius: 0.03,
                        displacementFactor: 0.5,
                        maxDisplacement: 0.1,
                        gravity: 0,
                    },
                    gColliderConfig: {
                        c1s: 0.05,
                        c2s: 0.05,
                        c3s: 0.05,
                        c4s: 0.05,
                        c5s: 0.05,
                        c6s: 0.05,
                    },
                    routers: [],
                };
            }
            onOpened() {
                super.onOpened();
                mgrDirector.adaptStageSize(2304, 1580);
                this.inputSearchRouterText.on(Laya.Event.INPUT, this, this.onInputSearch.bind(this));
                Tools.registerTouchHander(this.spriteBgTop, this.onTouchSpriteBgTop.bind(this));
                this.buttonSure.__node.visible = false;
                this.buildUi();
                this.fillData();
                this.registerListeners({
                    MSG_DEBUG_KEY_DOWN: (k) => {
                        if (k == "ctrl_number_1") {
                            if (!Const.GlobalRouter) {
                                mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                                let seasion = NetworkWS.newSeasion(`127.0.0.1`, 8081);
                                seasion.on("open", this, () => {
                                    Timer.callLater(1, () => {
                                        mgrTip.showMsgTip("链接存档服务器成功!可以存档！");
                                    });
                                    Const.GlobalRouter = new GameRemoteRouter(seasion);
                                });
                                seasion.on("error", this, () => {
                                    mgrTip.showMsgTip("链接存档服务器失败!请打开本地服务器!");
                                });
                            }
                            else {
                                mgrTip.showMsgTip("保存成功");
                            }
                        }
                    }
                });
            }
            onClosed() {
                super.onClosed();
                mgrDirector.adaptStageSize();
            }
            buildUi() {
                this.spriteBg.zOrder = -4;
                this.spriteBgTop.zOrder = -2;
                this.reuseListPart = new ReuseList(1, 0, 25);
                this.reuseListPart.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseListPart);
                this.reuseListPart.setItemClass(vEditorDynamicBonePart);
                this.reuseListPart.setVerticalMoveEnable(true);
                this.reuseListRootRouter = new ReuseList(1, 0, 15);
                this.reuseListRootRouter.size(this.boxRootRouterList.width, this.boxRootRouterList.height);
                this.boxRootRouterList.addChild(this.reuseListRootRouter);
                this.reuseListRootRouter.setItemClass(vEditorDynamicBoneChild);
                this.reuseListRootRouter.setVerticalMoveEnable(true);
                this.reuseListChildNode = new ReuseList(1, 0, 15);
                this.reuseListChildNode.size(this.boxChildRouterList.width, this.boxChildRouterList.height);
                this.boxChildRouterList.addChild(this.reuseListChildNode);
                this.reuseListChildNode.setItemClass(vEditorDynamicBoneChild);
                this.reuseListChildNode.setVerticalMoveEnable(true);
                this.reuseListSearchRouterList = new ReuseList(1, 0, 15);
                this.reuseListSearchRouterList.size(this.boxSearchRouterList.width, this.boxSearchRouterList.height);
                this.boxSearchRouterList.addChild(this.reuseListSearchRouterList);
                this.reuseListSearchRouterList.setItemClass(vEditorDynamicBoneSearchRouterItem);
                this.reuseListSearchRouterList.setVerticalMoveEnable(true);
                this.avatar = new RoleAvatar();
                this.add3DEffectAtBack(this.avatar, 0);
                this.avatar.registerLoadEndCallback(() => {
                    this.avatar.transform.position = new Laya.Vector3(0, -1, 0);
                    this.avatar.playAnimation(ANIMATION_ID.idle);
                    let cf = this.cameraBack.getComponent(CameraFollow);
                    cf.fov = 20;
                    this.reuseListRootRouter.setDatas([]);
                    this.reuseListChildNode.setDatas([]);
                    this.reuseListSearchRouterList.setDatas([]);
                });
            }
            fillData() {
                this.selectType(PartType.hair);
            }
            selectType(type) {
                this.currentSelectType = type;
                let datas = [];
                mgrCfg.forDb_from_part_db((k, v) => {
                    v.type == type && datas.push({
                        partId: v.id,
                        fOnClickPart: this.onClickPart.bind(this),
                    });
                });
                this.reuseListPart.setDatas(datas);
            }
            onClickPart(partId) {
                this.currPartId = partId;
                this.curPartModelId = null;
                this.curPartModel = null;
                this.allSearchedRouters = [];
                this.reuseListSearchRouterList.setDatas([]);
                this.reuseListRootRouter.setDatas([]);
                this.reuseListChildNode.setDatas([]);
                this.spriteModelBonePanel.visible = true;
                this.spriteSelectedBonePanel.visible = false;
                this.currSelectedRootRouterData = null;
                this.currSelectedChildRouterData = null;
                this.allSearchedRouters = [];
                this.avatar.fillByPartIds([partId]);
                this.avatar.registerLoadEndCallback(() => {
                    let partData = mgrCfg.get("part_db", partId);
                    this.curPartModelId = partData.modelId;
                    this.curPartModel = this.avatar.getNodeByType(mgrCfg.get_from_part_db(partId).type);
                    this.curModelRouterConfig = mgrDynamicBone.getDynamicConfig(this.curPartModelId) || this.DEFAULT_DYNAMIC_CONFIG;
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                    this.refresModelData();
                    this.__registerRootRouterOperation();
                });
            }
            onClickSearchedRootRouter(router) {
                for (let k in this.allSearchedRouters) {
                    let data = this.allSearchedRouters[k];
                    if (data.router == router) {
                        data.bSelected = !data.bSelected;
                    }
                }
                this.reuseListSearchRouterList.setDatas(this.allSearchedRouters);
            }
            onClickRootRouter(dataChild) {
                this.currSelectedRootRouterData = null;
                let routers = this.curModelRouterConfig.routers || [];
                for (let index = 0; index < routers.length; index++) {
                    let rData = routers[index];
                    if (dataChild.router == rData.router) {
                        this.currSelectedRootRouterData = rData;
                    }
                }
                this.currSelectedChildRouterData = null;
                if (!!this.currSelectedRootRouterData) {
                    this.spriteSelectedBonePanel.visible = true;
                    this.__registerSelectedBoneOperation();
                }
                else {
                    this.spriteSelectedBonePanel.visible = false;
                }
                this.refreshCurrRootRouterChildBoneList();
            }
            refreshCurrRootRouterChildBoneList() {
                if (!this.currSelectedRootRouterData) {
                    return;
                }
                let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                if (!boneManager) {
                    return;
                }
                let root = boneManager.findChildByRouter(boneManager.owner, this.currSelectedRootRouterData.router);
                this.reuseListChildNodeArr = [];
                while (root.getChildAt(0)) {
                    this.reuseListChildNodeArr.push(root.getChildAt(0));
                    root = root.getChildAt(0);
                }
                let arr = [];
                for (let k in this.reuseListChildNodeArr) {
                    let node = this.reuseListChildNodeArr[k];
                    arr.push({
                        node: node,
                        onClickNode: this.onClickChildRouterNode.bind(this),
                        onClickAdd: this.onClickChildRouterAdd.bind(this),
                        onClickRemove: this.onClickChildRouterRemove.bind(this),
                        bShowBtnAddRemove: true,
                        isAddedRouter: (dataChild) => {
                            let child = dataChild.node;
                            let routerInfo = this.currSelectedRootRouterData;
                            for (let i = 0; i < routerInfo.children.length; i++) {
                                const element = routerInfo.children[i];
                                if (element.router.indexOf(child.name) >= 0) {
                                    return true;
                                }
                            }
                            return false;
                        }
                    });
                }
                this.reuseListChildNode.setDatas(arr);
            }
            onClickRootRouterRemove(dataChild) {
                console.log("-----onClickRootRouterRemove", dataChild.router);
            }
            onClickChildRouterNode(dataChild) {
                console.log("-----onClickChildRouterNode", dataChild.node.name);
                this.currSelectedChildRouterData = null;
                let child = dataChild.node;
                let routerInfo = this.currSelectedRootRouterData;
                for (let i = 0; i < routerInfo.children.length; i++) {
                    const element = routerInfo.children[i];
                    if (element.router.indexOf(child.name) >= 0) {
                        this.currSelectedChildRouterData = element;
                        break;
                    }
                }
                if (!!this.currSelectedChildRouterData) {
                    this.spriteSelectedBonePanel.visible = true;
                    this.__registerSelectedBoneOperation();
                }
                else {
                    this.spriteSelectedBonePanel.visible = false;
                    mgrTip.showMsgTip("请先添加此子骨骼");
                }
            }
            onClickChildRouterAdd(dataChild) {
                console.log("-----onClickChildRouterAdd", dataChild.node.name);
                let child = dataChild.node;
                let routerInfo = this.currSelectedRootRouterData;
                let childConfig = null;
                for (let i = 0; i < routerInfo.children.length; i++) {
                    const element = routerInfo.children[i];
                    if (element.router.indexOf(child.name) >= 0) {
                        childConfig = element;
                        break;
                    }
                }
                if (!childConfig) {
                    let childRouter = "";
                    let recurive = (root) => {
                        if (routerInfo.router.indexOf(root.name) == -1) {
                            childRouter = root.name + "/" + childRouter;
                            recurive(root.parent);
                        }
                    };
                    recurive(child);
                    childConfig = {
                        router: childRouter,
                        config: {},
                    };
                    routerInfo.children.push(childConfig);
                }
                mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                this.refresModelData();
                this.refreshCurrRootRouterChildBoneList();
                this.onClickChildRouterNode(dataChild);
            }
            onClickChildRouterRemove(dataChild) {
                console.log("-----onClickChildRouterRemove", dataChild.node.name);
                let child = dataChild.node;
                let routerInfo = this.currSelectedRootRouterData;
                let childConfig = null;
                let children = routerInfo.children || [];
                for (let i = 0; i < children.length; i++) {
                    const element = children[i];
                    if (element.router.indexOf(child.name) >= 0) {
                        childConfig = element;
                        children.splice(i, 1);
                        break;
                    }
                }
                mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                this.refresModelData();
                this.refreshCurrRootRouterChildBoneList();
                this.onClickChildRouterNode(dataChild);
            }
            refresModelData() {
                let editorData = mgrDynamicBone.getDynamicConfig(this.curPartModelId);
                this.curModelRouterConfig = editorData;
                if (!editorData) {
                }
                else {
                    this.useDynamicData(() => {
                        let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                        if (!boneManager) {
                            return;
                        }
                        boneManager.setCurentEditorRouter("/", this.curPartModelId);
                    });
                }
                this.refreshEditorPanel();
            }
            refreshEditorPanel() {
                this.onTouchButtonAddAllSelectedSearchedRouter();
            }
            useDynamicData(callback) {
                let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                if (!boneManager) {
                    return;
                }
                boneManager.addDynamicConfig(this.curModelRouterConfig, this.curPartModelId);
                callback && callback();
            }
            getBoneRouter() {
                let repx = new RegExp("");
                let recuriveSearch = (root) => {
                    if (repx.test(root.name)) {
                    }
                    else {
                        for (let i = 0; i < root.numChildren; i++) {
                            let child = root.getChildAt(i);
                            recuriveSearch(child);
                        }
                    }
                };
                recuriveSearch(new Laya.Sprite3D);
            }
            traceToFindRouter(rootName, cursorNode) {
                let router = "/";
                while (cursorNode.name !== rootName) {
                    router = "/" + cursorNode.name + router;
                    cursorNode = cursorNode.parent;
                }
                return router;
            }
            OnClickAnimation(animationId) {
                this.avatar.playAnimation(animationId);
            }
            __registerRootRouterOperation() {
                Tools.registerAsHSlider(this.imageSliderParm1, this.curModelRouterConfig.gBoneConfig.parm1, "一级:软 <------> 硬:", (value) => {
                    this.curModelRouterConfig.gBoneConfig.parm1 = value;
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.parm1 = value;
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 1);
                Tools.registerAsHSlider(this.imageSliderDisplacementFactor, this.curModelRouterConfig.gBoneConfig.displacementFactor, "二级:软 <------> 硬:", (value) => {
                    this.curModelRouterConfig.gBoneConfig.displacementFactor = value;
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.displacementFactor = value;
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 1);
                Tools.registerAsHSlider(this.imageSliderMaxDisplacement, this.curModelRouterConfig.gBoneConfig.maxDisplacement, "限制:小 <------> 大:", (value) => {
                    this.curModelRouterConfig.gBoneConfig.maxDisplacement = value;
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.maxDisplacement = value;
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 1);
                Tools.registerAsHSlider(this.imageSliderRadius, this.curModelRouterConfig.gBoneConfig.radius, "碰撞半径:", (value) => {
                    this.curModelRouterConfig.gBoneConfig.radius = value;
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.radius = value;
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 0.1);
                Tools.registerAsHSlider(this.imageSliderGravity, this.curModelRouterConfig.gBoneConfig.gravity, "重力:", (value) => {
                    this.curModelRouterConfig.gBoneConfig.gravity = value;
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.gravity = value;
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 0.05);
                Tools.registerAsHSlider(this.imageSliderBone1Size, this.curModelRouterConfig.gColliderConfig.c1s, "1级碰撞size:", (value) => {
                    this.curModelRouterConfig.gColliderConfig.c1s = parseFloat(value);
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.c1s = parseFloat(value);
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 0.2);
                Tools.registerAsHSlider(this.imageSliderBone2Size, this.curModelRouterConfig.gColliderConfig.c2s, "2级碰撞size:", (value) => {
                    this.curModelRouterConfig.gColliderConfig.c2s = parseFloat(value);
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.c2s = parseFloat(value);
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 0.2);
                Tools.registerAsHSlider(this.imageSliderBone3Size, this.curModelRouterConfig.gColliderConfig.c3s, "3级碰撞size:", (value) => {
                    this.curModelRouterConfig.gColliderConfig.c3s = parseFloat(value);
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.c3s = parseFloat(value);
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 0.2);
                Tools.registerAsHSlider(this.imageSliderBone4Size, this.curModelRouterConfig.gColliderConfig.c4s, "4级碰撞size:", (value) => {
                    this.curModelRouterConfig.gColliderConfig.c4s = parseFloat(value);
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.c4s = parseFloat(value);
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 0.2);
                Tools.registerAsHSlider(this.imageSliderBone5Size, this.curModelRouterConfig.gColliderConfig.c5s, "5级碰撞size:", (value) => {
                    this.curModelRouterConfig.gColliderConfig.c5s = parseFloat(value);
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.c5s = parseFloat(value);
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 0.2);
                Tools.registerAsHSlider(this.imageSliderBone6Size, this.curModelRouterConfig.gColliderConfig.c6s, "6级碰撞size:", (value) => {
                    this.curModelRouterConfig.gColliderConfig.c6s = parseFloat(value);
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.c6s = parseFloat(value);
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                }, 0.2);
            }
            __registerSelectedBoneOperation() {
                let doChangeFunc = (fieldName, value) => {
                    if (this.currSelectedChildRouterData) {
                        let children = this.currSelectedRootRouterData.children || [];
                        for (let k in children) {
                            let cdata = children[k];
                            if (cdata.router == this.currSelectedChildRouterData.router) {
                                cdata.config[fieldName] = value;
                            }
                        }
                    }
                    else if (this.currSelectedRootRouterData) {
                        this.currSelectedRootRouterData.config[fieldName] = value;
                    }
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                };
                Tools.registerAsHSlider(this.imageSliderParm1SelectedBone, this.curModelRouterConfig.gBoneConfig.parm1, "一级:软 <------> 硬:", (value) => {
                    doChangeFunc("parm1", value);
                }, 1);
                Tools.registerAsHSlider(this.imageSliderDisplacementFactorSelectedBone, this.curModelRouterConfig.gBoneConfig.displacementFactor, "二级:软 <------> 硬:", (value) => {
                    doChangeFunc("displacementFactor", value);
                }, 1);
                Tools.registerAsHSlider(this.imageSliderMaxDisplacementSelectedBone, this.curModelRouterConfig.gBoneConfig.maxDisplacement, "限制:小 <------> 大:", (value) => {
                    doChangeFunc("maxDisplacement", value);
                }, 1);
                Tools.registerAsHSlider(this.imageSliderRadiusSelectedBone, this.curModelRouterConfig.gBoneConfig.radius, "碰撞半径:", (value) => {
                    doChangeFunc("radius", value);
                }, 0.1);
                Tools.registerAsHSlider(this.imageSliderGravitySelectedBone, this.curModelRouterConfig.gBoneConfig.gravity, "重力:", (value) => {
                    doChangeFunc("gravity", value);
                }, 0.05);
            }
            generateRoute(child, parent) {
                if (child == parent)
                    return "/";
                let routes = [];
                while (true) {
                    routes.push(child.name);
                    child = child.parent;
                    if (child == parent)
                        break;
                }
                let router = "/";
                for (let i = routes.length - 1; i >= 0; i--) {
                    router += `${routes[i]}`;
                    if (i != 0) {
                        router += "/";
                    }
                }
                return router;
            }
            onTouchSpriteBgTop(e) {
                if (e.isBegin) {
                    this.bTouchBgTop = true;
                    this.lastTouchBgTopPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBgTop = false;
                }
                if (this.bTouchBgTop) {
                    let deltaX = e.pos.x - this.lastTouchBgTopPos.x;
                    this.lastTouchBgTopPos = e.pos;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            onInputSearch() {
                this.allSearchedRouters = [];
                let repxStr = this.inputSearchRouterText.text;
                if (repxStr.length == 0)
                    return;
                let firstFindedValidChild = null;
                for (let i = 0; i < this.curPartModel.numChildren; i++) {
                    let child = this.curPartModel.getChildAt(i);
                    let meshRenderer = Tools.getMeshRender(child);
                    if (!meshRenderer) {
                        firstFindedValidChild = child;
                        break;
                    }
                }
                let rootBone = firstFindedValidChild;
                let repx = new RegExp(repxStr);
                let recuriveSearch = (root) => {
                    if (repx.test(root.name)) {
                        let router = this.traceToFindRouter(rootBone.name, root);
                        let bContained = false;
                        for (let k in this.listRootRouterDataArr) {
                            let data = this.listRootRouterDataArr[k];
                            if (data.router == router) {
                                bContained = true;
                                break;
                            }
                        }
                        if (!bContained) {
                            this.allSearchedRouters.push({ modelId: this.curPartModelId, router: router, bSelected: false, fOnClick: this.onClickSearchedRootRouter.bind(this) });
                        }
                    }
                    else {
                        for (let i = 0; i < root.numChildren; i++) {
                            let child = root.getChildAt(i);
                            recuriveSearch(child);
                        }
                    }
                };
                recuriveSearch(rootBone);
                this.reuseListSearchRouterList.setDatas(this.allSearchedRouters);
            }
            addSearchedRouter(bOnlySelected) {
                let saveRouters = this.curModelRouterConfig.routers;
                for (let k in this.allSearchedRouters) {
                    let data = this.allSearchedRouters[k];
                    if (!bOnlySelected || !!data.bSelected) {
                        let bDoAdd = true;
                        for (let tmp in saveRouters) {
                            let oldoldRouter = saveRouters[tmp];
                            if (oldoldRouter.router == data.router) {
                                bDoAdd = false;
                                break;
                            }
                        }
                        if (bDoAdd) {
                            saveRouters.push({
                                "router": data.router,
                                "children": [],
                                "config": {},
                            });
                        }
                    }
                }
                this.listRootRouterDataArr = [];
                for (let k in saveRouters) {
                    let data = saveRouters[k];
                    this.listRootRouterDataArr.push({
                        router: data.router,
                        onClickNode: this.onClickRootRouter.bind(this),
                        onClickRemove: this.onClickRootRouterRemove.bind(this)
                    });
                }
                this.reuseListRootRouter.setDatas(this.listRootRouterDataArr);
                this.curModelRouterConfig.routers = saveRouters;
                mgrDynamicBone.setDynamicConfig(this.curPartModelId, this.curModelRouterConfig);
                this.useDynamicData(() => {
                    let boneManager = this.avatar.getBoneManager(this.currentSelectType);
                    if (!boneManager) {
                        return;
                    }
                    boneManager.setCurentEditorRouter("/", this.curPartModelId);
                });
                this.onInputSearch();
            }
            onTouchButtonHair() {
                this.selectType(PartType.hair);
            }
            onTouchButtonHeadWear() {
                this.selectType(PartType.headDec);
            }
            onTouchButtonCloth() {
                this.selectType(PartType.cloth);
            }
            onTouchButtonDress() {
            }
            onTouchButtonHandDeco() {
                this.selectType(PartType.handDec);
            }
            onTouchButtonSure() {
            }
            onTouchButtonRemove() {
            }
            onTouchButtonAnimation() {
                let datas = [];
                let fOnClick = (data) => {
                    this.avatar.playAnimation(data, 0.1, null, () => {
                        fOnClick(data);
                    });
                };
                mgrCfg.forDb_from_animation_db((k, v) => {
                    if (v.bDance) {
                        datas.push({
                            text: v.id,
                            data: v.id,
                            fOnClick: fOnClick,
                        });
                    }
                });
                mgrDirector.openDialog(`vEditorSelectDialog`, {
                    datas: datas,
                });
            }
            onTouchButtonIdle() {
                this.avatar.playAnimation(`idle-idle_01`);
            }
            onTouchButtonClose() {
                mgrDirector.warpSceneWidthEffect("vHubScene");
            }
            onTouchButtonAddAllSearchedRouter() {
                this.addSearchedRouter(false);
            }
            onTouchButtonRemoveModelDynamic() {
                if (!this.curPartModelId || !this.currPartId) {
                    return;
                }
                let partData = mgrCfg.get("part_db", this.currPartId);
                mgrTip.alertPrompt2("提示", `是否移除部件\n【${partData.name}】\n骨骼配置?`, "不了", "移除", null, () => {
                    mgrDynamicBone.setDynamicConfig(this.curPartModelId, null);
                    this.onClickPart(this.currPartId);
                });
            }
            onTouchButtonAddAllSelectedSearchedRouter() {
                this.addSearchedRouter(true);
            }
            onTouchButtonTimeScale0() {
                if (this.avatar) {
                    this.avatar.pause();
                }
            }
            onTouchButtonTimeScale1() {
                if (this.avatar) {
                    this.avatar.resume();
                }
            }
        }

        class vEditorHumanBone extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorHumanBone";
                this.exportNodeNames = [];
                this.curSelectIndex = 101;
                this.selectedBoneName = "";
            }
            onOpened() {
                super.onOpened();
                mgrDirector.adaptStageSize(2304, 1580);
                this.inputSearchRouterText.on(Laya.Event.INPUT, this, this.onInputSearch.bind(this));
                Tools.registerTouchHander(this.spriteBgTop, this.onTouchSpriteBgTop.bind(this));
                this.buildUi();
                this.registerListeners({
                    MSG_DEBUG_KEY_DOWN: (k) => {
                        if (k == "ctrl_number_1") {
                            if (!Const.GlobalRouter) {
                                mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                                let seasion = NetworkWS.newSeasion(`127.0.0.1`, 8081);
                                seasion.on("open", this, () => {
                                    Timer.callLater(1, () => {
                                        mgrTip.showMsgTip("链接存档服务器成功!可以存档！");
                                    });
                                    Const.GlobalRouter = new GameRemoteRouter(seasion);
                                });
                                seasion.on("error", this, () => {
                                    mgrTip.showMsgTip("链接存档服务器失败!请打开本地服务器!");
                                });
                            }
                            else {
                                mgrTip.showMsgTip("保存成功");
                            }
                        }
                    }
                });
            }
            onClosed() {
                super.onClosed();
                mgrDirector.adaptStageSize();
            }
            buildUi() {
                this.spriteBg.zOrder = -4;
                this.spriteBgTop.zOrder = -2;
                this.reuseListRoleList = new ReuseList(1, 0, 15);
                this.reuseListRoleList.size(this.boxRoleList.width, this.boxRoleList.height);
                this.boxRoleList.addChild(this.reuseListRoleList);
                this.reuseListRoleList.setItemClass(vEditorHumanRoleItem);
                this.reuseListRoleList.setVerticalMoveEnable(true);
                this.reuseListHumanIndexList = new ReuseList(1, 0, 15);
                this.reuseListHumanIndexList.size(this.boxHumanIndexList.width, this.boxHumanIndexList.height);
                this.boxHumanIndexList.addChild(this.reuseListHumanIndexList);
                this.reuseListHumanIndexList.setItemClass(vEditorHumanIndexItem);
                this.reuseListHumanIndexList.setVerticalMoveEnable(true);
                this.reuseListSearchRouterList = new ReuseList(1, 0, 15);
                this.reuseListSearchRouterList.size(this.boxSearchRouterList.width, this.boxSearchRouterList.height);
                this.boxSearchRouterList.addChild(this.reuseListSearchRouterList);
                this.reuseListSearchRouterList.setItemClass(vEditorHumanBoneItem);
                this.reuseListSearchRouterList.setVerticalMoveEnable(true);
                let dataRoles = [];
                mgrCfg.forDb_from_role_db((k, v) => {
                    dataRoles.push({ id: v.id, fOnClick: (id) => { this.currSelectRoleId = id; this.reuseListRoleList.refresh(); }, fIsSelect: (id) => { return this.currSelectRoleId == id; } });
                });
                this.reuseListRoleList.setDatas(dataRoles);
                this.avatar = new RoleAvatar();
                this.add3DEffectAtBack(this.avatar, 0);
                this.avatar.registerLoadEndCallback(() => {
                    this.avatar.transform.position = new Laya.Vector3(-0.3, -1, 0);
                    this.avatar.playAnimation(ANIMATION_ID.idle);
                    let cf = this.cameraBack.getComponent(CameraFollow);
                    cf.fov = 20;
                    this.scaleAvatar = new RoleAvatar();
                    this.add3DEffectAtBack(this.scaleAvatar, 0);
                    this.scaleAvatar.registerLoadEndCallback(() => {
                        this.scaleAvatar.transform.position = new Laya.Vector3(0.3, -1, 0);
                        this.scaleAvatar.playAnimation(ANIMATION_ID.idle);
                        let datas = [];
                        for (let i = 1; i <= 20; i++) {
                            datas.push({ index: i, fOnClick: this.onClickHumanIndexListItem.bind(this), fIsSelect: (index) => { return this.curSelectIndex == index; } });
                        }
                        this.reuseListHumanIndexList.setDatas(datas);
                        this.onClickHumanIndexListItem(this.curSelectIndex);
                    });
                });
            }
            onBoneScaneChanged() {
                let nodeNames = [
                    `${Const.BASE_BONE_NAME}`,
                    `${Const.BASE_BONE_NAME} Pelvis`,
                    `${Const.BASE_BONE_NAME} L Thigh`,
                    `${Const.BASE_BONE_NAME} L Calf`,
                    `${Const.BASE_BONE_NAME} L Foot`,
                    `${Const.BASE_BONE_NAME} L Toe0`,
                ];
                let weights = {};
                for (let i = 0; i < nodeNames.length; i++) {
                    const nodeName = nodeNames[i];
                    if (nodeName == "Bip001") {
                        weights[nodeName] = HumanBone.allHumanBoneConfig[Const.BODY_FBXNAME].rootPos.y;
                    }
                    else {
                        weights[nodeName] = HumanBone.allHumanBoneConfig[Const.BODY_FBXNAME].rootPos.y;
                        for (let __i = 1; __i < i; __i++) {
                            weights[nodeName] -= HumanBone.allHumanBoneConfig[Const.BODY_FBXNAME].boneMap[nodeNames[__i]].x;
                        }
                        weights[nodeName] -= HumanBone.allHumanBoneConfig[Const.BODY_FBXNAME].boneMap[nodeName].x;
                    }
                }
                Tools.forEachMap(weights, (k, v) => {
                    weights[k] = v / HumanBone.allHumanBoneConfig[Const.BODY_FBXNAME].rootPos.y;
                });
                let wholeRatio = 1;
                for (let i = 0; i < nodeNames.length; i++) {
                    const nodeName = nodeNames[i];
                    let info = HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][this.curSelectIndex].boneMap[nodeName];
                    if (info) {
                        wholeRatio += weights[nodeName] * (info.scale.x - 1);
                    }
                }
                HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][this.curSelectIndex].wholeRatio = wholeRatio;
                if (!Const.GlobalRouter) {
                    mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                    let seasion = NetworkWS.newSeasion(`127.0.0.1`, 8081);
                    seasion.on("open", this, () => {
                        Timer.callLater(1, () => {
                            mgrTip.showMsgTip("链接存档服务器成功!可以存档！");
                        });
                        Const.GlobalRouter = new GameRemoteRouter(seasion);
                    });
                    seasion.on("error", this, () => {
                        mgrTip.showMsgTip("链接存档服务器失败!请打开本地服务器!");
                    });
                }
                else {
                    Const.GlobalRouter.sendMsgToServer({
                        route: "keepInFile",
                        data: {
                            filePath: `res/cfg/humanScale.txt`,
                            data: HumanBone.allHumanBoneScaleInfo,
                        },
                    });
                }
            }
            registerAllOperation() {
                if (!this.currBoneOperateData) {
                    return;
                }
                let configValueArr = [
                    { nodeName: `imgScaleX`, fieldName: `scaleX`, labelTip: `x轴缩放`, labelDesc: `x轴缩放`, range: [0, 2] },
                    { nodeName: `imgScaleY`, fieldName: `scaleY`, labelTip: `y轴缩放`, labelDesc: `y轴缩放`, range: [0, 2] },
                    { nodeName: `imgScaleZ`, fieldName: `scaleZ`, labelTip: `z轴缩放`, labelDesc: `z轴缩放`, range: [0, 2] },
                    { nodeName: `imgPosX`, fieldName: `posX`, labelTip: `x轴位移`, labelDesc: `x轴位移`, range: [0, 2] },
                    { nodeName: `imgPosY`, fieldName: `posY`, labelTip: `y轴位移`, labelDesc: `y轴位移`, range: [0, 2] },
                    { nodeName: `imgPosZ`, fieldName: `posZ`, labelTip: `z轴位移`, labelDesc: `z轴位移`, range: [0, 2] },
                    { nodeName: `imgRotationX`, fieldName: `rotationX`, labelTip: `旋转x`, labelDesc: `旋转x`, range: [0, 2] },
                    { nodeName: `imgRotationY`, fieldName: `rotationY`, labelTip: `旋转y`, labelDesc: `旋转y`, range: [0, 2] },
                    { nodeName: `imgRotationZ`, fieldName: `rotationZ`, labelTip: `旋转z`, labelDesc: `旋转z`, range: [0, 2] },
                    { nodeName: `imgRotationW`, fieldName: `rotationW`, labelTip: `旋转w`, labelDesc: `旋转w`, range: [0, 2] },
                ];
                for (let k in configValueArr) {
                    let dataConfig = configValueArr[k];
                    let minMaxArr = dataConfig.range;
                    let slideValue = (this.currBoneOperateData[dataConfig.fieldName] - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                    this.__registerAsSlider(this[`${dataConfig.nodeName}`], slideValue, (value) => {
                        let fieldKey = dataConfig.fieldName;
                        let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * value;
                        this.currBoneOperateData[dataConfig.fieldName] = useValue;
                        let label = this[`${dataConfig.nodeName}`].getChildByName("label");
                        label.text = `[${dataConfig.labelTip}]: ${useValue.toFixed(4)}`;
                        this.onBoneScaneChanged();
                    }, () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                    });
                }
            }
            refreshSearchRouterList() {
                let arr = [];
                let bones = this.showingBones || this.allBones || [];
                for (let i = 0; i < bones.length; i++) {
                    let bone = bones[i];
                    arr.push({ index: i, name: bone.name, fOnClick: this.onClickBone.bind(this), fIsSelect: (name) => { return this.selectedBoneName == name; } });
                    if (bone.name == this.selectedBoneName) {
                        this.curSelectBone = bone;
                    }
                }
                this.reuseListSearchRouterList.setDatas(arr);
            }
            onClickBone(name) {
                this.selectedBoneName = name;
                this.refreshSearchRouterList();
                if (HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][this.curSelectIndex].boneMap[this.selectedBoneName] == null) {
                    HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][this.curSelectIndex].boneMap[this.curSelectBone.name] = {
                        scale: { x: 1, y: 1, z: 1 },
                        pos: { x: 0, y: 0, z: 0 },
                        rotation: { x: 0, y: 0, z: 0, w: 1 },
                    };
                }
                this.currBoneOperateData = new OperateData(HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][this.curSelectIndex].boneMap, this.curSelectBone, () => {
                    return false;
                });
                this.registerAllOperation();
            }
            onClickHumanIndexListItem(index) {
                if (!HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME]) {
                    HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME] = {};
                }
                if (!HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][index]) {
                    HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][index] = {
                        boneMap: {},
                        wholeRatio: 1,
                    };
                }
                this.curSelectIndex = index;
                this.reuseListHumanIndexList.refresh();
                let roleData = mgrCfg.get_from_role_db(this.currSelectRoleId);
                this.scaleAvatar.fillByPartIds(roleData.partIds);
                this.scaleAvatar.baseBodyAnimator[`humanScaleInfo`] = null;
                this.scaleAvatar.registerAllLoadEndCallback(() => {
                    this.scaleAvatar.humanBoneIndex = this.curSelectIndex;
                    let renderArr = Tools.findAllSkinnedMeshRenderers(this.avatar.baseBody, undefined, false);
                    let skinMeshRenderForMain = renderArr[0];
                    this.allBones = skinMeshRenderForMain.bones;
                    this.scaleAvatar.baseBodyAnimator[`humanScaleInfo`] = HumanBone.allHumanBoneScaleInfo[Const.BODY_FBXNAME][this.curSelectIndex];
                    this.refreshSearchRouterList();
                });
            }
            currSelectRoleId(currSelectRoleId) {
                throw new Error("Method not implemented.");
            }
            onClickRootRouterRemove(dataChild) {
                console.log("-----onClickRootRouterRemove", dataChild.router);
            }
            getBoneRouter() {
                let repx = new RegExp("");
                let recuriveSearch = (root) => {
                    if (repx.test(root.name)) {
                    }
                    else {
                        for (let i = 0; i < root.numChildren; i++) {
                            let child = root.getChildAt(i);
                            recuriveSearch(child);
                        }
                    }
                };
                recuriveSearch(new Laya.Sprite3D);
            }
            traceToFindRouter(rootName, cursorNode) {
                let router = "/";
                while (cursorNode.name !== rootName) {
                    router = "/" + cursorNode.name + router;
                    cursorNode = cursorNode.parent;
                }
                return router;
            }
            OnClickAnimation(animationId) {
                this.avatar.playAnimation(animationId);
            }
            generateRoute(child, parent) {
                if (child == parent)
                    return "/";
                let routes = [];
                while (true) {
                    routes.push(child.name);
                    child = child.parent;
                    if (child == parent)
                        break;
                }
                let router = "/";
                for (let i = routes.length - 1; i >= 0; i--) {
                    router += `${routes[i]}`;
                    if (i != 0) {
                        router += "/";
                    }
                }
                return router;
            }
            onTouchSpriteBgTop(e) {
                if (e.isBegin) {
                    this.bTouchBgTop = true;
                    this.lastTouchBgTopPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBgTop = false;
                }
                if (this.bTouchBgTop) {
                    let deltaX = e.pos.x - this.lastTouchBgTopPos.x;
                    this.lastTouchBgTopPos = e.pos;
                    this.scaleAvatar && this.scaleAvatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            onInputSearch() {
                this.showingBones = null;
                let repxStr = this.inputSearchRouterText.text;
                if (repxStr.length == 0)
                    return;
                let arr = [];
                let repx = new RegExp(repxStr);
                for (let i = 0; i < this.allBones.length; i++) {
                    let bone = this.allBones[i];
                    if (repx.test(bone.name)) {
                        arr.push(bone);
                    }
                }
                this.showingBones = arr;
            }
            __registerAsSlider(node, initValue, slideCallback, clickCallback) {
                let bar = node.getChildAt(0);
                bar.x = node.width * initValue;
                let bDown = false;
                node.on(Laya.Event.MOUSE_OVER, node, (e) => {
                    console.log("-------e.MOUSE_OVER=");
                    if (clickCallback) {
                        clickCallback();
                    }
                });
                Tools.registerTouchHander(node, (e) => {
                    console.log("-------e.isClick=", e.isClick);
                    if (e.isBegin) {
                        bDown = true;
                    }
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        point.y = node.height / 2;
                        point.x = ul.clamp(point.x, 0, node.width);
                        bar.x = point.x;
                        bar.y = point.y;
                        slideCallback(point.x / node.width);
                    }
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                });
                slideCallback(initValue);
            }
            onTouchButtonAnimation() {
                let datas = [];
                let fOnClick = (data) => {
                    this.scaleAvatar.playAnimation(data, 0.1, null, () => {
                        fOnClick(data);
                    });
                };
                mgrCfg.forDb_from_animation_db((k, v) => {
                    if (v.bDance) {
                        datas.push({
                            text: v.id,
                            data: v.id,
                            fOnClick: fOnClick,
                        });
                    }
                });
                mgrDirector.openDialog(`vEditorSelectDialog`, {
                    datas: datas,
                });
            }
            onTouchButtonIdle() {
                this.scaleAvatar.playAnimation(`idle-idle_01`);
            }
            onTouchButtonClose() {
                mgrDirector.warpSceneWidthEffect("vHubScene");
            }
            onTouchButtonRemoveModelDynamic() {
            }
            onTouchButtonTimeScale0() {
                if (this.scaleAvatar) {
                    this.scaleAvatar.pause();
                }
            }
            onTouchButtonTimeScale1() {
                if (this.scaleAvatar) {
                    this.scaleAvatar.resume();
                }
            }
            onTouchButtonFace() {
                this.labelChangeBoneTypeTip.text = `正在调整:脸部`;
            }
            onTouchButtonBody() {
                this.labelChangeBoneTypeTip.text = `正在调整:身体`;
            }
        }
        class OperateData {
            constructor(data, bone, isChildScale) {
                this.data = data;
                this.bone = bone;
                this.isChildScale = isChildScale;
                this.unifyData = {};
                let root = null;
                let curBone = this.bone;
                while (true) {
                    if (!curBone.parent || curBone.name == "Bip001") {
                        root = curBone;
                        break;
                    }
                    else {
                        curBone = curBone.parent;
                    }
                }
                let recurveAllBone = (bone, scaleX = 1, scaleY = 1, scaleZ = 1) => {
                    if (!this.data[bone.name]) {
                        this.data[bone.name] = {
                            scale: { x: 1, y: 1, z: 1 },
                            pos: { x: 0, y: 0, z: 0 },
                            rotation: { x: 0, y: 0, z: 0, w: 1 },
                        };
                    }
                    this.unifyData[bone.name] = {
                        x: this.data[bone.name].scale.x * scaleX,
                        y: this.data[bone.name].scale.y * scaleY,
                        z: this.data[bone.name].scale.z * scaleZ,
                    };
                    for (let i = 0; i < bone.numChildren; i++) {
                        let child = bone.getChildAt(i);
                        recurveAllBone(child, this.unifyData[bone.name].x, this.unifyData[bone.name].y, this.unifyData[bone.name].z);
                    }
                };
                recurveAllBone(root);
            }
            get scaleX() {
                return this.getData(`scale.x`);
            }
            set scaleX(value) {
                this.setData(`scale.x`, value);
            }
            get scaleY() {
                return this.getData(`scale.y`);
            }
            set scaleY(value) {
                this.setData(`scale.y`, value);
            }
            get scaleZ() {
                return this.getData(`scale.z`);
            }
            set scaleZ(value) {
                this.setData(`scale.z`, value);
            }
            get posX() {
                return this.getData(`pos.x`);
            }
            set posX(value) {
                this.setData(`pos.x`, value);
            }
            get posY() {
                return this.getData(`pos.y`);
            }
            set posY(value) {
                this.setData(`pos.y`, value);
            }
            get posZ() {
                return this.getData(`pos.z`);
            }
            set posZ(value) {
                this.setData(`pos.z`, value);
            }
            get rotationX() {
                return this.getData(`rotation.x`);
            }
            set rotationX(value) {
                this.setData(`rotation.x`, value);
            }
            get rotationY() {
                return this.getData(`rotation.y`);
            }
            set rotationY(value) {
                this.setData(`rotation.y`, value);
            }
            get rotationZ() {
                return this.getData(`rotation.z`);
            }
            set rotationZ(value) {
                this.setData(`rotation.z`, value);
            }
            get rotationW() {
                return this.getData(`rotation.w`);
            }
            set rotationW(value) {
                this.setData(`rotation.w`, value);
            }
            setData(parmName, value) {
                let strs = parmName.split(".");
                let realName = strs[1];
                if (strs[0] == "scale") {
                    let factor = value / this.unifyData[this.bone.name][realName];
                    this.unifyData[this.bone.name][realName] = value;
                    this.data[this.bone.name].scale[realName] = value / this.unifyData[this.bone.parent.name][realName];
                    if (!this.isChildScale()) {
                        let recurveAllBone = (bone, unifyScale) => {
                            for (let i = 0; i < bone.numChildren; i++) {
                                let child = bone.getChildAt(i);
                                this.data[child.name].scale[realName] = this.unifyData[child.name][realName] / unifyScale;
                                recurveAllBone(child, this.unifyData[child.name][realName]);
                            }
                        };
                        recurveAllBone(this.bone, this.unifyData[this.bone.name][realName]);
                    }
                    else {
                        let recurveAllBone = (bone, unifyScale, factor) => {
                            for (let i = 0; i < bone.numChildren; i++) {
                                let child = bone.getChildAt(i);
                                this.unifyData[child.name][realName] *= factor;
                                this.data[child.name].scale[realName] = this.unifyData[child.name][realName] / unifyScale;
                                recurveAllBone(child, this.unifyData[child.name][realName], factor);
                            }
                        };
                        recurveAllBone(this.bone, this.unifyData[this.bone.name][realName], factor);
                    }
                }
                else if (strs[0] == "pos") {
                    this.data[this.bone.name].pos[realName] = value;
                }
                else if (strs[0] == "rotation") {
                    this.data[this.bone.name].rotation[realName] = value;
                }
            }
            getData(parmName) {
                let strs = parmName.split(".");
                if (/scale/.test(parmName)) {
                    return this.unifyData[this.bone.name][strs[1]];
                }
                else if (/pos/.test(parmName)) {
                    return this.data[this.bone.name].pos[strs[1]];
                }
                else if (/rotation/.test(parmName)) {
                    return this.data[this.bone.name].rotation[strs[1]];
                }
            }
        }
        class vEditorHumanRoleItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                let bSelected = this.data.fIsSelect(this.data.id);
                this.label.color = !bSelected ? `#ffffff` : `#ff0000`;
                let roleData = mgrCfg.get_from_role_db(this.data.id);
                this.label.text = `${this.data.id}-${roleData.name}`;
            }
        }
        class vEditorHumanIndexItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.index);
            }
            fillByData(data) {
                this.data = data;
                let bSelected = this.data.fIsSelect(this.data.index);
                this.label.color = !bSelected ? `#ffffff` : `#ff0000`;
                let usedRoleIdStr = "";
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (v.humanBoneIndex == this.data.index) {
                        usedRoleIdStr += `${v.id},`;
                    }
                });
                this.label.text = `${this.data.index}-${usedRoleIdStr}`;
            }
        }
        class vEditorHumanBoneItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.name);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `${this.data.name}`;
            }
        }

        class vEditorParkourStageScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorParkourStageScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorParkourStageItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_amaze_parkour_stage_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
            }
            onClickSpine(id) {
                let stageData = mgrCfg.get_from_amaze_parkour_stage_db(id);
                let skinIds = stageData.trialSkinIds;
                let skinId = Tools.randomGotOneArrayData(skinIds);
                let skinData = mgrCfg.get_from_amaze_parkour_skin_db(skinId);
                mgrDirector.openDialog("vAmusePenRoleTrialDialog", {
                    adEventId: AD_EVENT_ID.VIDEO.video_vAmusePenRoleTrialDialog_trial,
                    skinId: skinId,
                    previewImg: skinData.previewImg,
                    fOnAdResult: (bAded) => {
                        if (bAded) {
                            mgrDirector.warpSceneWidthEffect("vAmuseParkourScene", { stageId: id, skinId });
                        }
                        else {
                            mgrDirector.warpSceneWidthEffect("vAmuseParkourScene", { stageId: id });
                        }
                    }
                });
            }
        }
        class vEditorParkourStageItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `关卡：${data.id}`;
            }
        }

        class vEditorPartCheck extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorPartCheck";
                this.exportNodeNames = [];
                this.reuseList = null;
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.fillData();
                Tools.registerTouchHander(this.boxBg, this.onTouchSpriteBg.bind(this));
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseList = new ReuseList(1, 0, 10);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vEditorDynamicBonePart);
                this.reuseList.setVerticalMoveEnable(true);
            }
            fillData() {
                let datas = [];
                mgrCfg.forDb_from_part_db((k, v) => {
                    v.type == PartType.hair && datas.push({
                        partId: v.id,
                        fOnClickPart: this.onClickPart.bind(this),
                    });
                });
                this.reuseList.setDatas(datas);
            }
            onClickPart(partId) {
                if (this.partMode) {
                    this.partMode.destroy();
                    this.partMode = null;
                }
                let partData = mgrCfg.get_from_part_db(partId);
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    this.lastTouchBgPos = e.pos;
                    this.partMode && this.partMode.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
            }
            useCartonMaterial(mode, partId) {
                let sharedMeshsp = mode.getChildAt(mode.numChildren - 1);
            }
        }

        class vEditorPartIconShotScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorPartIconShotScene";
                this.exportNodeNames = [];
                this.CAMERA_TYPE_2_CONFIG_DICT = {
                    [0]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.45, 4),
                        rot: new Laya.Vector3(-9)
                    },
                    ["1"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.45, 1.1),
                        rot: new Laya.Vector3(-9)
                    },
                    ["2"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.6, 0.85),
                        rot: new Laya.Vector3(-9)
                    },
                    ["3"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.15, 1.85),
                        rot: new Laya.Vector3(-9)
                    },
                    ["5"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 0.3, 0.7),
                        rot: new Laya.Vector3(-9)
                    },
                    ["6"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 0.3, 0.7),
                        rot: new Laya.Vector3(-9)
                    },
                    ["7"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.45, 4),
                        rot: new Laya.Vector3(-9)
                    },
                    ["8"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.45, 4),
                        rot: new Laya.Vector3(-9)
                    },
                    ["9"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.35, 0.65),
                        rot: new Laya.Vector3(-9)
                    },
                    ["10"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.55, 0.7),
                        rot: new Laya.Vector3(-9)
                    },
                    ["11"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.45, 2.45),
                        rot: new Laya.Vector3(-9)
                    },
                    ["12"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.45, 4),
                        rot: new Laya.Vector3(-9)
                    },
                    ["13"]: {
                        fov: 45,
                        pos: new Laya.Vector3(0, 1.55, 0.7),
                        rot: new Laya.Vector3(-9)
                    },
                };
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.avatarPartContainer = new Laya.Sprite3D;
                this.add3DEffectAtBack(this.avatarPartContainer, 0);
                this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                this.cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                this.cameraFollow.fov = this.CAMERA_TYPE_2_CONFIG_DICT[0].fov;
                this.cameraFollow.position = this.CAMERA_TYPE_2_CONFIG_DICT[0].pos.clone();
                this.cameraFollow.endRotation = this.CAMERA_TYPE_2_CONFIG_DICT[0].rot.clone();
                this.cameraFollow.lerpValue = 1;
                this.cameraFollow.onLateUpdate();
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorPartIconItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                this.buttonShot.fOnClick = () => {
                    if (!this.cameraBack || !this.partData) {
                        mgrTip.showMsgTip("nonono");
                        return;
                    }
                    let saveImageName = `part_icon${this.partData.id}`;
                    Tools.cameraForSaveImg(this.cameraBack, saveImageName);
                };
                this.buttonResetCamera.fOnClick = () => {
                    let type = !!this.partData ? this.partData.type : 0;
                    let cameraConfig = this.CAMERA_TYPE_2_CONFIG_DICT[type] || this.CAMERA_TYPE_2_CONFIG_DICT[type];
                    this.cameraFollow.fov = cameraConfig.fov;
                    this.cameraFollow.position = cameraConfig.pos.clone();
                    this.cameraFollow.endRotation = cameraConfig.rot.clone();
                    this.cameraFollow.onLateUpdate();
                };
                this.buttonUseWhite.fOnClick = () => {
                    let model = this.avatarPartContainer.getChildAt(0);
                    for (let i = 0; i < model.numChildren; i++) {
                        let child = model.getChildAt(i);
                        let renderer = Tools.getMeshRender(child);
                        if (renderer) {
                            for (let j = 0; j < renderer.sharedMaterials.length; j++) {
                                let material = renderer.sharedMaterials[j];
                                if (material.PlayerCustomChangeFlag < 0.5) {
                                    continue;
                                }
                                Tools.loadMaterialTexture(Const.SKIN_CONTROL_GRID_SHINE_PATH, material, "controlDetailTexture");
                                material.albedoColor = new Laya.Vector4(0.88, 0.88, 0.88, 1.0);
                                material.albedoTexture = null;
                                material.AlbedoTillingX = 1.0;
                                material.AlbedoTillingY = 1.0;
                                material.gridTexture = null;
                                material.shineTexture = null;
                                material.gridTextureScale = 1.0;
                                material.shineTextureScale = 1.0;
                            }
                        }
                    }
                };
                let datas = [];
                mgrCfg.forDb_from_part_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
                let rightDown = false;
                let lastX = 0;
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_DOWN, this, (e) => {
                    rightDown = true;
                    lastX = e.stageX;
                });
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_UP, this, (e) => {
                    rightDown = false;
                });
                Laya.stage.on(Laya.Event.MOUSE_MOVE, this, (e) => {
                    if (!rightDown)
                        return;
                    let delta = e.stageX - lastX;
                    lastX = e.stageX;
                    this.avatarPartContainer && this.avatarPartContainer.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                });
            }
            onClickSpine(id) {
                this.partData = mgrCfg.get_from_part_db(id);
                let cameraConfig = this.CAMERA_TYPE_2_CONFIG_DICT[this.partData.type] || this.CAMERA_TYPE_2_CONFIG_DICT[0];
                this.cameraFollow.fov = cameraConfig.fov;
                this.cameraFollow.position = cameraConfig.pos.clone();
                this.cameraFollow.endRotation = cameraConfig.rot.clone();
                this.cameraFollow.onLateUpdate();
                mgrLoader.loadModeWithModeId(this.partData.modelId, () => {
                    let numChildren = this.avatarPartContainer.numChildren;
                    for (let i = (numChildren - 1); i >= 0; i--) {
                        this.avatarPartContainer.removeChildAt(i);
                    }
                    let oldModel = this.avatarPartContainer.getChildAt(0);
                    if (!!oldModel) {
                        mgrLoader.Pool.recoverModel(oldModel);
                    }
                    let model = mgrLoader.Pool.getModel(this.partData.modelId);
                    let animator = model.getComponent(Laya.Animator);
                    if (!animator) {
                        animator = model.addComponent(Laya.Animator);
                    }
                    animator.speed = 0.00001;
                    mgrMaterial.setCustomMaterial(model, this.partData.modelId, this.partData.modelMaterialNo);
                    this.avatarPartContainer.addChild(model);
                    let particles = Tools.findAllShurikenParticleSystem(model);
                    if (!!particles && particles.length > 0) {
                        for (let k in particles) {
                            let p = particles[k];
                            p.stop();
                        }
                    }
                }, this, 1);
            }
        }
        class vEditorPartIconItem extends ReuseListItem {
            constructor() {
                super();
                let width = 500;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                let template = mgrCfg.get_from_part_db(data.id);
                this.label.text = `ID：${data.id}-名:${template.name}`;
            }
        }

        class vEditorPartSuitShotScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorPartSuitShotScene";
                this.exportNodeNames = [];
                this.loadedAniId2FlagDict = {};
                this.type = 1;
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.widget();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.avatarPartContainer = new Laya.Sprite3D;
                this.add3DEffectAtBack(this.avatarPartContainer, 0);
                this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                this.cameraFollow.lookMode = E_CAMERA_MODE.fixMode;
                this.cameraFollow.fov = 30;
                this.cameraFollow.position = new Laya.Vector3(0, 1.45, 4);
                this.cameraFollow.endRotation = new Laya.Vector3(-9);
                this.cameraFollow.lerpValue = 1;
                this.cameraFollow.onLateUpdate();
                this.reuseListAni = new ReuseList(1, 0, 50);
                this.reuseListAni.size(this.boxAniList.width, this.boxAniList.height);
                this.boxAniList.addChild(this.reuseListAni);
                this.reuseListAni.setItemClass(vEditorSpineItem$1);
                this.reuseListAni.setVerticalMoveEnable(true);
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorSuitIconItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                this.buttonShot.fOnClick = () => {
                    if (this.type == 1) {
                        if (!this.cameraBack || !this.partData) {
                            mgrTip.showMsgTip("nonono");
                            return;
                        }
                        let saveImageName = `suit_icon${this.partData.id}`;
                        Tools.cameraForSaveImg(this.cameraBack, saveImageName);
                    }
                    else if (this.type == 2) {
                        if (!this.cameraBack) {
                            mgrTip.showMsgTip("nonono");
                            return;
                        }
                        let saveImageName = `target_icon${this.stageId}`;
                        if (this.stageId < 10) {
                            saveImageName = `target_icon0${this.stageId}`;
                        }
                        Tools.cameraForSaveImg(this.cameraBack, saveImageName);
                    }
                    else {
                        if (!this.cameraBack) {
                            mgrTip.showMsgTip("nonono");
                            return;
                        }
                        let saveImageName = `skin${this.skinId}`;
                        if (this.skinId < 10) {
                            saveImageName = `skin0${this.skinId}`;
                        }
                        Tools.cameraForSaveImg(this.cameraBack, saveImageName);
                    }
                };
                this.buttonSuitChange.fOnClick = () => {
                    this.type = 1;
                    let datas = [];
                    mgrCfg.forDb_from_suit_db((k, v) => {
                        datas.push({
                            id: v.id,
                            onClickSpine: this.onClickSpine.bind(this),
                            type: 1,
                        });
                    });
                    this.reuseListSpine.setDatas(datas);
                };
                this.buttonStageChange.fOnClick = () => {
                    this.type = 2;
                    let datas = [];
                    mgrCfg.forDb_from_amaze_parkour_stage_db((k, v) => {
                        datas.push({
                            id: v.id,
                            onClickSpine: this.onClickStage.bind(this),
                            type: 2,
                        });
                    });
                    this.reuseListSpine.setDatas(datas);
                };
                this.buttonSkinChange.fOnClick = () => {
                    this.type = 3;
                    let datas = [];
                    mgrCfg.forDb_from_amaze_parkour_skin_db((k, v) => {
                        datas.push({
                            id: v.id,
                            onClickSpine: this.onClickSkin.bind(this),
                            type: 3,
                        });
                    });
                    this.reuseListSpine.setDatas(datas);
                };
                let datasAni = [];
                mgrCfg.forDb_from_animation_db((k, v) => {
                    datasAni.push({
                        spineId: v.id,
                        onClickSpine: this.onClickAni.bind(this),
                    });
                });
                this.reuseListAni.setDatas(datasAni);
                let minMaxArr = [0, 1];
                let slideValue = 0;
                this.__registerAsSlider(this.imageAnimationProgress, slideValue, minMaxArr, (value) => {
                    let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * value;
                    let label = this.imageAnimationProgress.getChildByName("label");
                    label.text = `百分比: ${useValue.toFixed(4)}`;
                    if (this.loadedAniId2FlagDict[this.animationId]) {
                        this.avatar.baseBodyAnimator.speed = 0.0001;
                        let template = mgrCfg.get_from_animation_db(this.animationId);
                        this.avatar.baseBodyAnimator.play(template.id, 0, useValue);
                    }
                }, () => {
                });
                let rightDown = false;
                let lastX = 0;
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_DOWN, this, (e) => {
                    rightDown = true;
                    lastX = e.stageX;
                });
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_UP, this, (e) => {
                    rightDown = false;
                });
                Laya.stage.on(Laya.Event.MOUSE_MOVE, this, (e) => {
                    if (!rightDown)
                        return;
                    let delta = e.stageX - lastX;
                    lastX = e.stageX;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                });
            }
            onClickAni(spineId) {
                if (!this.avatar) {
                    return;
                }
                this.avatar.baseBodyAnimator.speed = 1;
                this.animationId = spineId;
                this.avatar.playAnimation(spineId, 0, () => {
                    this.loadedAniId2FlagDict[spineId] = true;
                });
            }
            onClickSpine(id) {
                this.avatar = null;
                this.partData = mgrCfg.get_from_suit_db(id);
                let oldModel = this.avatarPartContainer.getChildAt(0);
                if (!!oldModel) {
                    oldModel.destroy();
                }
                this.avatar = new RoleAvatar({ roleId: 101 });
                this.avatar.fillByPartIds(this.partData.onlyDressPartIds);
                this.avatar.baseBodyAnimator.speed = 0.1;
                this.avatar.transform.position = new Laya.Vector3;
                this.avatarPartContainer.addChild(this.avatar);
            }
            onClickStage(id) {
                this.stageId = id;
                this.avatar = null;
                let oldModel = this.avatarPartContainer.getChildAt(0);
                if (!!oldModel) {
                    oldModel.destroy();
                }
                this.avatar = new RoleAvatar({ roleId: mgrRole.showingRoleId });
                this.avatar.baseBodyAnimator.speed = 0.1;
                this.avatar.transform.position = new Laya.Vector3;
                this.avatarPartContainer.addChild(this.avatar);
                let stageData = mgrCfg.get_from_amaze_parkour_stage_db(id);
                let targetClothColorId = stageData.targetClothColorId;
                let targetClothGridId = stageData.targetClothGridId;
                let targetClothPartId = stageData.targetClothPartId;
                let targetClothShineId = stageData.targetClothShineId;
                let targetHairColorId = stageData.targetHairColorId;
                let targetHairGridId = stageData.targetHairGridId;
                let targetHairPartId = stageData.targetHairPartId;
                let targetHairShineId = stageData.targetHairShineId;
                let targetShoePartId = stageData.targetShoePartId;
                this.avatar.registerLoadEndCallback(() => {
                    let newPartId = mgrDesign.addTempDesignPart(targetClothPartId, targetClothColorId, targetClothGridId, targetClothShineId);
                    this.avatar.fillByPartIds([newPartId]);
                    this.avatar.registerLoadEndCallback(() => {
                        let newPartId = mgrDesign.addTempDesignPart(targetHairPartId, targetHairColorId, targetHairGridId, targetHairShineId);
                        this.avatar.fillByPartIds([newPartId, targetShoePartId]);
                    });
                });
            }
            onClickSkin(id) {
                this.skinId = id;
                let oldModel = this.avatarPartContainer.getChildAt(0);
                if (!!oldModel) {
                    oldModel.destroy();
                }
                this.avatar = new RoleAvatar({ roleId: mgrRole.showingRoleId });
                this.avatar.baseBodyAnimator.speed = 0.1;
                this.avatar.transform.position = new Laya.Vector3;
                this.avatarPartContainer.addChild(this.avatar);
                this.avatar.registerLoadEndCallback(() => {
                    this.avatar.fillByPartIds(mgrCfg.get_from_amaze_parkour_skin_db(id).partIds);
                });
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.boxSpineList);
                mgrLayout.widgetRightTopMC(this.boxAniList);
                mgrLayout.widgetBottomMC(this.imageAnimationProgress);
            }
            __registerAsSlider(node, initValue, minMaxArr, slideCallback, clickCallback, inputCallback) {
                let input = node.getChildByName("input");
                let bar = node.getChildAt(0);
                bar.x = node.width * initValue;
                let bDown = false;
                node.on(Laya.Event.MOUSE_OVER, node, (e) => {
                    console.log("-------e.MOUSE_OVER=");
                    if (clickCallback) {
                        clickCallback();
                    }
                });
                Tools.registerTouchHander(node, (e) => {
                    console.log("-------e.isClick=", e.isClick);
                    if (e.isBegin) {
                        if (Tools.isWorldLocaInNode(input, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            return;
                        }
                        bDown = true;
                    }
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        point.y = node.height / 2;
                        point.x = ul.clamp(point.x, 0, node.width);
                        bar.x = point.x;
                        bar.y = point.y;
                        let pValue = point.x / node.width;
                        slideCallback(pValue);
                        if (input) {
                            let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * pValue;
                            input.text = `${useValue}`;
                        }
                    }
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                });
                if (input) {
                    let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * initValue;
                    input.text = `${useValue}`;
                    input.on(Laya.Event.INPUT, this, () => {
                        let inputValue = parseFloat(input.text) || 0;
                        let useValue = ul.clamp(inputValue, minMaxArr[0], minMaxArr[1]);
                        if (inputValue < minMaxArr[0] || inputValue > minMaxArr[1]) {
                            mgrTip.showMsgTip("数据超限");
                        }
                        inputCallback && inputCallback(useValue);
                        let slideValue = (useValue - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                        bar.x = node.width * slideValue;
                        slideCallback(slideValue);
                    });
                }
                slideCallback(initValue);
            }
        }
        class vEditorSuitIconItem extends ReuseListItem {
            constructor() {
                super();
                let width = 500;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                let name;
                if (this.data.type == 1) {
                    let template = mgrCfg.get_from_suit_db(data.id);
                    if (template)
                        name = template.name;
                }
                else if (this.data.type == 2) {
                    name = mgrCfg.get_from_amaze_parkour_stage_db(data.id).name;
                }
                else {
                    name = mgrCfg.get_from_amaze_parkour_skin_db(data.id).id;
                }
                this.label.text = `ID：${data.id}-名:${name}`;
                this.data = data;
            }
        }
        class vEditorSpineItem$1 extends ReuseListItem {
            constructor() {
                super();
                let width = 335;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.spineId);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `${data.spineId}`;
            }
        }

        class vEditorPBRHairShaderScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorPBRHairShaderScene";
            }
            onOpened() {
                super.onOpened();
            }
            onClosed() {
                super.onClosed();
            }
            onTouchButtonAlbedoColor() {
            }
            onTouchButtonShaowColor() {
            }
            onTouchButtonSpecularColor() {
            }
            onTouchButtonOutlineColor() {
            }
            onTouchButtonSecondShaowColor() {
            }
            onTouchButtonEdgeHightLightColor() {
            }
            onTouchButtonSPR1SpecalurColor() {
            }
            onTouchButtonSPR2SpecalurColor() {
            }
            onTouchButtonSPSpecularInDark() {
            }
            onTouchButtonSPAbedoColor() {
            }
            onTouchButtonSkinSPEmissionColorBack() {
            }
            onTouchButtonSkinAlbedoColor() {
            }
            onTouchButtonSkinSPRed3SColor() {
            }
            onTouchButtonMaskAlbedoColor() {
            }
            onTouchButtonMaskSPSideLightColor() {
            }
            onTouchButtonMaskSPPBRResultMaxColor() {
            }
            onTouchButtonSetMat2Unlit() {
            }
            onTouchButtonSetMat2PBRHair() {
            }
            onTouchButtonSetMat2PBRSkin() {
            }
            onTouchButtonSetMat2PBRMask() {
            }
            onTouchButtonReceiveShadow() {
            }
            onTouchButtonCastShadow() {
            }
            onTouchButtonClose() {
            }
            onTouchButtonHideSkin() {
            }
            onTouchButtonShowSkin() {
            }
            onTouchButtonOpque() {
            }
            onTouchButtonOpqueDouble() {
            }
            onTouchButtonCutOffSingle() {
            }
            onTouchButtonCutOffDouble() {
            }
            onTouchButtonCutOffTransparent() {
            }
            onTouchButtonCutOffTransparentDouble() {
            }
            onTouchButtonRenderQuene() {
            }
        }

        class vEditorPenStageScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorPenStageScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorPenStageItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_amaze_pen_stage_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
            }
            onClickSpine(id) {
                mgrDirector.warpSceneWidthEffect("vAmuseFashionPenScene", { stageId: id });
            }
        }
        class vEditorPenStageItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `关卡：${data.id}`;
            }
        }

        class vEditorShaderCartonScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorShaderCartonScene";
                this.exportNodeNames = [];
                this.reuseList = null;
                this.reuseListCurrent = null;
                this.reuseListMaterial = null;
                this.avatar = null;
                this.curModel = null;
                this.operateMaterialIndex = "0";
            }
            canOperateCamera() {
                return false;
            }
            onOpened() {
                super.onOpened();
                this.spriteMaterialPropertyUI.scale(0, 0);
                mgrDirector.adaptStageSize(2304, 1580);
                Laya.stage.on(Laya.Event.MOUSE_WHEEL, this, (e) => {
                    this.avatar.transform.localPositionZ += e.delta / 20;
                });
                let rightDown = false;
                let lastX = 0;
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_DOWN, this, (e) => {
                    rightDown = true;
                    lastX = e.stageX;
                });
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_UP, this, (e) => {
                    rightDown = false;
                });
                Laya.stage.on(Laya.Event.MOUSE_MOVE, this, (e) => {
                    if (!rightDown)
                        return;
                    let delta = e.stageX - lastX;
                    lastX = e.stageX;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                    this.roleAvatar && this.roleAvatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                });
                this.registerListeners({
                    MSG_DEBUG_KEY_DOWN: (k) => {
                        if (k == "left") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, 3, 0), false, false);
                        }
                        else if (k == "right") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, -3, 0), false, false);
                        }
                        else if (k == "up") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(3, 0, 0), false, false);
                        }
                        else if (k == "down") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(-3, 0, 0), false, false);
                        }
                        let cf = this.directitonLight.getComponent(CameraFollow);
                        if (k == "a") {
                            cf.endRotation.y += 3;
                            console.log(`灯光旋转`);
                            console.log(cf.endRotation);
                        }
                        if (k == "d") {
                            cf.endRotation.y -= 3;
                            console.log(cf.endRotation);
                        }
                        if (k == "w") {
                            cf.endRotation.x += 3;
                            console.log(cf.endRotation);
                        }
                        if (k == "s") {
                            cf.endRotation.x -= 3;
                            console.log(cf.endRotation);
                        }
                        if (k == `escape`) {
                            this.curModel = null;
                            this.avatar.removeChildren();
                        }
                        if (k == "number_7") {
                            this.cameraBack.fieldOfView += 1;
                            console.log(`fov: ${this.cameraBack.fieldOfView}`);
                        }
                        if (k == "number_8") {
                            this.cameraBack.fieldOfView -= 1;
                            console.log(`fov: ${this.cameraBack.fieldOfView}`);
                        }
                        if (k == "ctrl_c") {
                            if (!this.modelId)
                                return;
                            if (!this.skinName)
                                return;
                            this.context.clipboard = ul.clone(mgrMaterial.getMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, CustomMaterialType.unlitCartoon));
                            mgrTip.showMsgTip("复制成功!");
                        }
                        if (k == "ctrl_v") {
                            if (!this.modelId)
                                return;
                            if (!this.skinName)
                                return;
                            if (!this.context.clipboard)
                                return;
                            mgrTip.showMsgTip("粘贴成功!");
                            mgrMaterial.setMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, ul.clone(this.context.clipboard));
                            this.onClickSkinName(this.skinName);
                        }
                        if (k == "ctrl_number_1") {
                            if (!Const.GlobalRouter) {
                                mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                                let seasion = NetworkWS.newSeasion(`127.0.0.1`, 8081);
                                seasion.on("open", this, () => {
                                    Timer.callLater(1, () => {
                                        mgrTip.showMsgTip("链接存档服务器成功!可以存档！");
                                    });
                                    Const.GlobalRouter = new GameRemoteRouter(seasion);
                                });
                                seasion.on("error", this, () => {
                                    mgrTip.showMsgTip("链接存档服务器失败!请打开本地服务器!");
                                });
                            }
                            else {
                                Const.GlobalRouter.sendMsgToServer({
                                    route: "keepInFile",
                                    data: {
                                        filePath: `res/cfg/materialInfo.json`,
                                        data: mgrMaterial.materialInfos,
                                    },
                                });
                            }
                        }
                    }
                });
                Tools.registerTouchHander(this.spriteBg, this.onTouchSpriteBg.bind(this));
                this.spriteBg.zOrder = -4;
                this.buildUi();
                this.fillData();
                this.buttonSearch.fOnClick = () => {
                    this.fillData();
                };
                this.buttonShowAllModel.fOnClick = () => {
                    this.bOnlyPart = false;
                    this.fillData();
                    this.labelShowAllModel.color = !this.bOnlyPart ? "#00ff00" : "#ffffff";
                    this.labelShowPartModel.color = !!this.bOnlyPart ? "#00ff00" : "#ffffff";
                };
                this.buttonShowPartModel.fOnClick = () => {
                    this.bOnlyPart = true;
                    this.fillData();
                    this.labelShowAllModel.color = !this.bOnlyPart ? "#00ff00" : "#ffffff";
                    this.labelShowPartModel.color = !!this.bOnlyPart ? "#00ff00" : "#ffffff";
                };
                this.buttonRefreshAvatar.fOnClick = () => {
                    if (!this.roleAvatar) {
                        return;
                    }
                    this.roleAvatar.fillByPartIds(this.roleAvatar.getPartIds());
                    this.roleAvatar.registerLoadEndCallback(() => {
                        this.roleAvatar.playAnimation([ANIMATION_ID.idle]);
                    });
                    this.roleAvatar.refreshMaterial();
                };
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
            }
            onClosed() {
                super.onClosed();
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.lastBeginPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.avatar
                        && this.avatar.transform
                            .translate(new Laya.Vector3(deltaX / mgrDirector.width, -deltaY / mgrDirector.height, 0), true);
                }
            }
            buildUi() {
                this.reuseList = new ReuseList(1, 0, 20);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vEditorCartonMaterialPart);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseListCurrent = new ReuseList(1, 0, 10);
                this.reuseListCurrent.size(this.boxCurrentList.width, this.boxCurrentList.height);
                this.boxCurrentList.addChild(this.reuseListCurrent);
                this.reuseListCurrent.setItemClass(vEditorCartonMaterialPart);
                this.reuseListCurrent.setVerticalMoveEnable(true);
                this.reuseListMaterial = new ReuseList(1, 0, 10);
                this.reuseListMaterial.size(this.boxMaterialList.width, this.boxMaterialList.height);
                this.boxMaterialList.addChild(this.reuseListMaterial);
                this.reuseListMaterial.setItemClass(vCartonMaterial);
                this.reuseListMaterial.setVerticalMoveEnable(true);
                this.avatar = new Laya.Sprite3D;
                this.avatar.transform.position = new Laya.Vector3(0, 0, 0);
                this.add3DEffectAtBack(this.avatar, 0);
                let cf = this.directitonLight.getComponent(CameraFollow);
                cf.endRotation = new Laya.Vector3(-5, 27, -17.27);
                this.roleAvatar = new RoleAvatar();
                this.roleAvatar.transform.position = new Laya.Vector3(0.5, 0, 0);
                this.add3DEffectAtBack(this.roleAvatar, 0);
            }
            fillData() {
                let regexp = null;
                if (this.inputText.text.length != 0) {
                    regexp = new RegExp(this.inputText.text);
                }
                if (!this.allPartModelDict) {
                    let partModelDict = {};
                    mgrCfg.forDb_from_part_db((k, v) => {
                        partModelDict[v.modelId] = v.id;
                    });
                    this.allPartModelDict = partModelDict;
                }
                let datas = [];
                mgrCfg.forDb_from_model_db((k, v) => {
                    if (v.id.startsWith("eff_") || v.id.startsWith("e_")) {
                        return;
                    }
                    if (this.bOnlyPart && !this.allPartModelDict[v.id]) {
                        return;
                    }
                    if (!regexp) {
                        datas.push({
                            modelId: v.id,
                            fOnClickModel: this.onSelectModel.bind(this),
                            skinName: null,
                            fOnClickSkinName: null,
                        });
                    }
                    else {
                        if (regexp.test(v.id)) {
                            datas.push({
                                modelId: v.id,
                                fOnClickModel: this.onSelectModel.bind(this),
                                skinName: null,
                                fOnClickSkinName: null,
                            });
                        }
                    }
                });
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            onSelectModel(modelId) {
                this.modelId = null;
                this.skinName = null;
                this.operatingMaterialData = null;
                this.operatingMaterial = null;
                for (let i = 0; i < this.avatar.numChildren; i++) {
                    let child = this.avatar.getChildAt(i);
                    if (child[`__modelId`] == modelId) {
                        this.curModel = child;
                        this.modelId = modelId;
                        this.fillCurrentList(this.curModel, modelId);
                        return;
                    }
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    this.curModel = mgrLoader.Pool.getModel(modelId);
                    mgrMaterial.setCustomMaterial(this.curModel, modelId);
                    this.avatar.addChild(this.curModel);
                    this.modelId = modelId;
                    this.fillCurrentList(this.curModel, modelId);
                    if (this.curModel.name == "body_skin") {
                        let avatarColliderName2TypeDict = {
                            ["Click_head"]: 1,
                            ["Click_l_hand"]: 2,
                            ["Click_r_hand"]: 3,
                            ["Click_cloth"]: 4,
                            ["Click_dress"]: 5,
                            ["Click_foot"]: 6,
                        };
                        for (let colliderName in avatarColliderName2TypeDict) {
                            let sprite3d = Tools.findNode(colliderName, this.curModel);
                            let meshRenderer = Tools.getMeshRender(sprite3d);
                            if (meshRenderer) {
                                meshRenderer.enable = false;
                            }
                        }
                    }
                    if (this.allPartModelDict[modelId] && this.roleAvatar) {
                        this.roleAvatar.fillByPartIds([this.allPartModelDict[modelId]]);
                    }
                }, this, 1);
            }
            fillCurrentList(model, modelId) {
                let datas = [];
                for (let i = 0; i < model.numChildren; i++) {
                    let child = model.getChildAt(i);
                    let skin = child[`skinnedMeshRenderer`] || child[`meshRenderer`];
                    if (skin) {
                        datas.push({
                            modelId: modelId,
                            fOnClickModel: null,
                            skinName: child.name,
                            fOnClickSkinName: this.onClickSkinName.bind(this),
                        });
                    }
                }
                this.reuseListCurrent.setDatas(datas);
            }
            onClickSkinName(skinName) {
                this.skinName = skinName;
                this.operationMode = this.curModel.getChildByName(skinName);
                let render = this.operationMode[`skinnedMeshRenderer`] || this.operationMode[`meshRenderer`];
                this.operationRenderer = render;
                let datas = [];
                if (render) {
                    let materials = this.__setCustomMaterial(render);
                    for (let i = 0; i < materials.length; i++) {
                        const element = materials[i];
                        datas.push({
                            modelId: this.modelId,
                            skinName: this.skinName,
                            index: i.toString(),
                            name: element.name,
                            fOnClick: this.onClickMaterial.bind(this),
                        });
                    }
                }
                this.reuseListMaterial.setDatas(datas);
                this.reuseListMaterial.scrollTo(0);
            }
            __setCustomMaterial(render) {
                return mgrMaterial.__setCustomMaterial(render, this.modelId, 0, this.skinName);
            }
            onClickMaterial(index) {
                if (!this.operationRenderer)
                    return;
                this.operateMaterialIndex = index;
                let currMaterialType = CustomMaterialType.unlitCartoon;
                let type = mgrMaterial.getMaterialType(this.modelId, 0, this.skinName, index);
                if (type != currMaterialType) {
                    mgrTip.alertPrompt2("删除并更换", "材质类型和当前不匹配\n是否删除并更换为当前类型材质", "不更换", "更换", () => {
                        this.spriteMaterialPropertyUI.scale(0, 0);
                    }, () => {
                        let defaultData = mgrMaterial.getDefaultMaterialDataByMaterialType(currMaterialType, this.modelId, this.skinName);
                        mgrMaterial.setMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, defaultData);
                        this.onClickSkinName(this.skinName);
                        this.spriteMaterialPropertyUI.scale(1, 1);
                        this.registerAllOperation(this.operationRenderer.sharedMaterials[index]);
                    });
                    return;
                }
                this.spriteMaterialPropertyUI.scale(1, 1);
                this.registerAllOperation(this.operationRenderer.sharedMaterials[index]);
            }
            refreshRenderQueueShow(mat) {
                this.inputRenderQueue.text = `${mat.renderQueue}`;
                this.labelOpaque.color = mat.renderMode == CartoonMaterial.RENDERMODE_OPAQUE ? "#00ff00" : "#ffffff";
                this.labelOpaqueCullNone.color = mat.renderMode == CartoonMaterial.RENDERMODE_OPAQUE_CULL_NONE ? "#00ff00" : "#ffffff";
                this.labelCutOffSingle.color = mat.renderMode == CartoonMaterial.RENDERMODE_CUTOUT ? "#00ff00" : "#ffffff";
                this.labelCutOffDouble.color = mat.renderMode == CartoonMaterial.RENDERMODE_CUTOUT_CULL_NONE ? "#00ff00" : "#ffffff";
                this.labelTransparent.color = mat.renderMode == CartoonMaterial.RENDERMODE_TRANSPARENT ? "#00ff00" : "#ffffff";
                this.labelTransparentDouble.color = mat.renderMode == CartoonMaterial.RENDERMODE_TRANSPARENT_CULL_NONE ? "#00ff00" : "#ffffff";
            }
            registerAllOperation(mat) {
                this.refreshRenderQueueShow(mat);
                this.buttonRenderQueue.fOnClick = () => {
                    mat.renderQueue = parseInt(this.inputRenderQueue.text) || mat.renderQueue;
                    this.operatingMaterialData.renderMode = mat.renderQueue;
                    this.refreshRenderQueueShow(mat);
                };
                this.operatingMaterialData = mgrMaterial.getMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, CustomMaterialType.unlitCartoon, true);
                this.operatingMaterial = mat;
                let configColorArr = [
                    { nodeName: "buttonAlbedoColor", labelTip: "albedoColor", materialFieldName: "albedoColor", labelDesc: "" },
                    { nodeName: "buttonShaowColor", labelTip: "shadowColor", materialFieldName: "shadowColor", labelDesc: "" },
                    { nodeName: "buttonSpecularColor", labelTip: "specularColor", materialFieldName: "specularColor", labelDesc: "" },
                    { nodeName: "buttonOutlineColor", labelTip: "outlineColor", materialFieldName: "outlineColor", labelDesc: "" },
                    { nodeName: "buttonSecondShaowColor", labelTip: "secondShadowColor", materialFieldName: "secondShadowColor", labelDesc: "" },
                    { nodeName: "buttonEdgeHightLightColor", labelTip: "EdgeHightColor", materialFieldName: "EdgeHightColor", labelDesc: "" },
                ];
                for (let k in configColorArr) {
                    let dataConfig = configColorArr[k];
                    let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                    if (!this.operatingMaterial[`${dataConfig.materialFieldName}`]) {
                        label.text = `未定义`;
                    }
                    else {
                        label.text = `${dataConfig.labelTip}: r:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].x * 255).toFixed(0)},g:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].y * 255).toFixed(0)},b:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].z * 255).toFixed(0)}`;
                        let hexColor = Tools.__colorToHex(new Laya.Color(this.operatingMaterial[`${dataConfig.materialFieldName}`].x * 255, this.operatingMaterial[`${dataConfig.materialFieldName}`].y * 255, this.operatingMaterial[`${dataConfig.materialFieldName}`].z * 255));
                        let sprite = this[`${dataConfig.nodeName}`].owner.getChildByName("sprite");
                        sprite.graphics.drawPie(0, 0, 10, 0, 360, hexColor);
                    }
                    this[`${dataConfig.nodeName}`].fOnClick = () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                        mgrDirector.openDialog(`vEditorColorDialog`, {
                            colorChange: (color) => {
                                this.operatingMaterial[`${dataConfig.materialFieldName}`] = new Laya.Vector4(color.r / 255, color.g / 255, color.b / 255, 1.0);
                                let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                                label.text = `${dataConfig.labelTip}: r:${color.r},g:${color.g},b:${color.b}`;
                                let hexColor = Tools.__colorToHex(color);
                                let sprite = this[`${dataConfig.nodeName}`].owner.getChildByName("sprite");
                                sprite.graphics.drawPie(0, 0, 10, 0, 360, hexColor);
                                this.operatingMaterialData[`${dataConfig.materialFieldName}`] = [color.r / 255, color.g / 255, color.b / 255, 1.0];
                            }
                        });
                    };
                }
                let configValueArr = [
                    { nodeName: "imageSliderAlbedoIdentity", labelTip: "albedoIdentity", materialFieldName: "albedoIdentity", labelDesc: "" },
                    { nodeName: "imageSliderShadowRange", labelTip: "shadowRange", materialFieldName: "shadowRange", labelDesc: "" },
                    { nodeName: "imageSliderShadowIdentity", labelTip: "shadowIntensity", materialFieldName: "shadowIntensity", labelDesc: "" },
                    { nodeName: "imageSliderShaowBoundaryIdentity", labelTip: "shadowBoundary", materialFieldName: "shadowBoundary", labelDesc: "" },
                    { nodeName: "imageSliderSpecularRange", labelTip: "specularRange", materialFieldName: "specularRange", labelDesc: "" },
                    { nodeName: "imageSliderSpecularIdentity", labelTip: "specularIntensity", materialFieldName: "specularIntensity", labelDesc: "" },
                    { nodeName: "imageSliderOutlineWidth", labelTip: "outlineWidth", materialFieldName: "outlineWidth", labelDesc: "" },
                    { nodeName: "imageSliderOutlineIdentity", labelTip: "outlineLightness", materialFieldName: "outlineLightness", labelDesc: "" },
                    { nodeName: "imageSliderSecondShadowRange", labelTip: "secondShadowRange", materialFieldName: "secondShadowRange", labelDesc: "" },
                    { nodeName: "imageSliderSecondShadowIdentity", labelTip: "secondShadowIntensity", materialFieldName: "secondShadowIntensity", labelDesc: "" },
                    { nodeName: "imageSliderSecondShaowBoundaryIdentity", labelTip: "secondShadowBoundary", materialFieldName: "secondShadowBoundary", labelDesc: "" },
                    { nodeName: "imageSliderEdgeHightLightRange", labelTip: "EdgeHightRange", materialFieldName: "EdgeHightRange", labelDesc: "" },
                    { nodeName: "imageSliderEdgeHightLightIdentity", labelTip: "EdgeHightIntensity", materialFieldName: "EdgeHightIntensity", labelDesc: "" },
                    { nodeName: "imageSliderEdgeHightLightBoundaryIdentity", labelTip: "EdgeHightBoundary", materialFieldName: "EdgeHightBoundary", labelDesc: "" },
                    { nodeName: "imageSliderAlphaTestValue", labelTip: "AlphaTestValue", materialFieldName: "alphaTestValue", labelDesc: "" },
                    { nodeName: "imageIsOnlyChangeBonePos", labelTip: "适配骨骼位置", materialFieldName: "onlyChangeBonePosFlag", labelDesc: "" },
                ];
                for (let k in configValueArr) {
                    let dataConfig = configValueArr[k];
                    let minMaxArr = this.operatingMaterial.getShaderValueRangeWithKey(CartoonMaterial[dataConfig.materialFieldName.toUpperCase()]);
                    let slideValue = (this.operatingMaterial[`${dataConfig.materialFieldName}`] - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                    this.__registerAsSlider(this[`${dataConfig.nodeName}`], slideValue, (value) => {
                        let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * value;
                        this.operatingMaterial[`${dataConfig.materialFieldName}`] = useValue;
                        let label = this[`${dataConfig.nodeName}`].getChildByName("label");
                        label.text = `[${dataConfig.labelTip}]: ${useValue.toFixed(4)}`;
                        this.operatingMaterialData[`${dataConfig.materialFieldName}`] = useValue;
                    }, () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                    });
                }
                this.buttonOpque.fOnClick = () => {
                    this.operatingMaterial.renderMode = CartoonMaterial.RENDERMODE_OPAQUE;
                    this.operatingMaterialData.renderMode = CartoonMaterial.RENDERMODE_OPAQUE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonOpqueCullNone.fOnClick = () => {
                    this.operatingMaterial.renderMode = CartoonMaterial.RENDERMODE_OPAQUE_CULL_NONE;
                    this.operatingMaterialData.renderMode = CartoonMaterial.RENDERMODE_OPAQUE_CULL_NONE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffSingle.fOnClick = () => {
                    this.operatingMaterial.renderMode = CartoonMaterial.RENDERMODE_CUTOUT;
                    this.operatingMaterialData.renderMode = CartoonMaterial.RENDERMODE_CUTOUT;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffDouble.fOnClick = () => {
                    this.operatingMaterial.renderMode = CartoonMaterial.RENDERMODE_CUTOUT_CULL_NONE;
                    this.operatingMaterialData.renderMode = CartoonMaterial.RENDERMODE_CUTOUT_CULL_NONE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffTransparent.fOnClick = () => {
                    this.operatingMaterial.renderMode = CartoonMaterial.RENDERMODE_TRANSPARENT;
                    this.operatingMaterialData.renderMode = CartoonMaterial.RENDERMODE_TRANSPARENT;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffTransparentDouble.fOnClick = () => {
                    this.operatingMaterial.renderMode = CartoonMaterial.RENDERMODE_TRANSPARENT_CULL_NONE;
                    this.operatingMaterialData.renderMode = CartoonMaterial.RENDERMODE_TRANSPARENT_CULL_NONE;
                    ;
                    this.refreshRenderQueueShow(mat);
                };
            }
            __registerAsSlider(node, initValue, slideCallback, clickCallback) {
                let bar = node.getChildAt(0);
                bar.x = node.width * initValue;
                let bDown = false;
                node.on(Laya.Event.MOUSE_OVER, node, (e) => {
                    console.log("-------e.MOUSE_OVER=");
                    if (clickCallback) {
                        clickCallback();
                    }
                });
                Tools.registerTouchHander(node, (e) => {
                    console.log("-------e.isClick=", e.isClick);
                    if (e.isBegin) {
                        bDown = true;
                    }
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        point.y = node.height / 2;
                        point.x = ul.clamp(point.x, 0, node.width);
                        bar.x = point.x;
                        bar.y = point.y;
                        slideCallback(point.x / node.width);
                    }
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                });
                slideCallback(initValue);
            }
        }
        class vCartonMaterial extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.index);
            }
            fillByData(data) {
                this.data = data;
                let typeMaterial = mgrMaterial.getMaterialType(this.data.modelId, 0, this.data.skinName, this.data.index);
                let typeDesc = Const.MATERIAL_TYPE_2_DESC_DICT[typeMaterial];
                this.label.text = `${[typeDesc]}${this.data.name}`;
            }
        }

        class vEditorShaderClothScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorShaderClothScene";
                this.exportNodeNames = [];
                this.reuseList = null;
                this.reuseListCurrent = null;
                this.reuseListMaterial = null;
                this.avatar = null;
                this.curModel = null;
                this.operateMaterialIndex = "0";
            }
            canOperateCamera() {
                return false;
            }
            onOpened() {
                super.onOpened();
                this.spriteMaterialPropertyUI.scale(0, 0);
                mgrDirector.adaptStageSize(2304, 1580);
                Laya.stage.on(Laya.Event.MOUSE_WHEEL, this, (e) => {
                    this.avatar.transform.localPositionZ += e.delta / 20;
                });
                let rightDown = false;
                let lastX = 0;
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_DOWN, this, (e) => {
                    rightDown = true;
                    lastX = e.stageX;
                });
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_UP, this, (e) => {
                    rightDown = false;
                });
                Laya.stage.on(Laya.Event.MOUSE_MOVE, this, (e) => {
                    if (!rightDown)
                        return;
                    let delta = e.stageX - lastX;
                    lastX = e.stageX;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                    this.roleAvatar && this.roleAvatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                });
                this.registerListeners({
                    MSG_DEBUG_KEY_DOWN: (k) => {
                        if (k == "left") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, 3, 0), false, false);
                        }
                        else if (k == "right") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, -3, 0), false, false);
                        }
                        else if (k == "up") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(3, 0, 0), false, false);
                        }
                        else if (k == "down") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(-3, 0, 0), false, false);
                        }
                        let cf = this.directitonLight.getComponent(CameraFollow);
                        if (k == "a") {
                            cf.endRotation.y += 3;
                            console.log(`灯光旋转`);
                            console.log(cf.endRotation);
                        }
                        if (k == "d") {
                            cf.endRotation.y -= 3;
                            console.log(cf.endRotation);
                        }
                        if (k == "w") {
                            cf.endRotation.x += 3;
                            console.log(cf.endRotation);
                        }
                        if (k == "s") {
                            cf.endRotation.x -= 3;
                            console.log(cf.endRotation);
                        }
                        if (k == `escape`) {
                            this.curModel = null;
                            this.avatar.removeChildren();
                        }
                        if (k == "number_7") {
                            this.cameraBack.fieldOfView += 1;
                            console.log(`fov: ${this.cameraBack.fieldOfView}`);
                        }
                        if (k == "number_8") {
                            this.cameraBack.fieldOfView -= 1;
                            console.log(`fov: ${this.cameraBack.fieldOfView}`);
                        }
                        if (k == "ctrl_c") {
                            if (!this.modelId)
                                return;
                            if (!this.skinName)
                                return;
                            this.context.clipboard = ul.clone(mgrMaterial.getMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, CustomMaterialType.pbrCloth));
                            mgrTip.showMsgTip("复制成功!");
                        }
                        if (k == "ctrl_v") {
                            if (!this.modelId)
                                return;
                            if (!this.skinName)
                                return;
                            if (!this.context.clipboard)
                                return;
                            mgrTip.showMsgTip("粘贴成功!");
                            mgrMaterial.setMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, ul.clone(this.context.clipboard));
                            this.onClickSkinName(this.skinName);
                            this.onClickMaterial(this.operateMaterialIndex);
                        }
                        if (k == "ctrl_number_1") {
                            if (!Const.GlobalRouter) {
                                mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                                let seasion = NetworkWS.newSeasion(`127.0.0.1`, 8081);
                                seasion.on("open", this, () => {
                                    Timer.callLater(1, () => {
                                        mgrTip.showMsgTip("链接存档服务器成功!可以存档！");
                                    });
                                    Const.GlobalRouter = new GameRemoteRouter(seasion);
                                });
                                seasion.on("error", this, () => {
                                    mgrTip.showMsgTip("链接存档服务器失败!请打开本地服务器!");
                                });
                            }
                            else {
                                Const.GlobalRouter.sendMsgToServer({
                                    route: "keepInFile",
                                    data: {
                                        filePath: `res/cfg/materialInfo.json`,
                                        data: mgrMaterial.materialInfos,
                                    },
                                });
                                mgrTip.showMsgTip("保存成功!");
                            }
                        }
                    }
                });
                Tools.registerTouchHander(this.spriteBg, this.onTouchSpriteBg.bind(this));
                this.spriteBg.zOrder = -4;
                this.buildUi();
                this.fillData();
                this.buttonSearch.fOnClick = () => {
                    this.fillData();
                };
                this.buttonShowAllModel.fOnClick = () => {
                    this.bOnlyPart = false;
                    this.fillData();
                    this.labelShowAllModel.color = !this.bOnlyPart ? "#00ff00" : "#ffffff";
                    this.labelShowPartModel.color = !!this.bOnlyPart ? "#00ff00" : "#ffffff";
                };
                this.buttonShowPartModel.fOnClick = () => {
                    this.bOnlyPart = true;
                    this.fillData();
                    this.labelShowAllModel.color = !this.bOnlyPart ? "#00ff00" : "#ffffff";
                    this.labelShowPartModel.color = !!this.bOnlyPart ? "#00ff00" : "#ffffff";
                };
                this.buttonRefreshAvatar.fOnClick = () => {
                    if (!this.roleAvatar) {
                        return;
                    }
                    this.roleAvatar.fillByPartIds(this.roleAvatar.getPartIds());
                    this.roleAvatar.registerLoadEndCallback(() => {
                        this.roleAvatar.playAnimation([ANIMATION_ID.idle]);
                    });
                    this.roleAvatar.refreshMaterial();
                };
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
            }
            onClosed() {
                super.onClosed();
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.lastBeginPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.avatar
                        && this.avatar.transform
                            .translate(new Laya.Vector3(deltaX / mgrDirector.width, -deltaY / mgrDirector.height, 0), true);
                }
            }
            buildUi() {
                this.reuseList = new ReuseList(1, 0, 20);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vEditorCartonMaterialPart);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseListCurrent = new ReuseList(1, 0, 10);
                this.reuseListCurrent.size(this.boxCurrentList.width, this.boxCurrentList.height);
                this.boxCurrentList.addChild(this.reuseListCurrent);
                this.reuseListCurrent.setItemClass(vEditorCartonMaterialPart);
                this.reuseListCurrent.setVerticalMoveEnable(true);
                this.reuseListMaterial = new ReuseList(1, 0, 10);
                this.reuseListMaterial.size(this.boxMaterialList.width, this.boxMaterialList.height);
                this.boxMaterialList.addChild(this.reuseListMaterial);
                this.reuseListMaterial.setItemClass(vCartonMaterial$1);
                this.reuseListMaterial.setVerticalMoveEnable(true);
                this.avatar = new Laya.Sprite3D;
                this.avatar.transform.position = new Laya.Vector3(0, 0, 0);
                this.add3DEffectAtBack(this.avatar, 0);
                let cf = this.directitonLight.getComponent(CameraFollow);
                cf.endRotation = new Laya.Vector3(-5, 27, -17.27);
                this.roleAvatar = new RoleAvatar();
                this.roleAvatar.transform.position = new Laya.Vector3(0.5, 0, 0);
                this.add3DEffectAtBack(this.roleAvatar, 0);
            }
            fillData() {
                let regexp = null;
                if (this.inputText.text.length != 0) {
                    regexp = new RegExp(this.inputText.text);
                }
                if (!this.allPartModelDict) {
                    let partModelDict = {};
                    mgrCfg.forDb_from_part_db((k, v) => {
                        partModelDict[v.modelId] = v.id;
                    });
                    this.allPartModelDict = partModelDict;
                }
                let datas = [];
                mgrCfg.forDb_from_model_db((k, v) => {
                    if (v.id.startsWith("eff_") || v.id.startsWith("e_")) {
                        return;
                    }
                    if (this.bOnlyPart && !this.allPartModelDict[v.id]) {
                        return;
                    }
                    if (!regexp) {
                        datas.push({
                            modelId: v.id,
                            fOnClickModel: this.onSelectModel.bind(this),
                            skinName: null,
                            fOnClickSkinName: null,
                        });
                    }
                    else {
                        if (regexp.test(v.id)) {
                            datas.push({
                                modelId: v.id,
                                fOnClickModel: this.onSelectModel.bind(this),
                                skinName: null,
                                fOnClickSkinName: null,
                            });
                        }
                    }
                });
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            onSelectModel(modelId) {
                this.modelId = null;
                this.skinName = null;
                this.operatingMaterialData = null;
                this.operatingMaterial = null;
                for (let i = 0; i < this.avatar.numChildren; i++) {
                    let child = this.avatar.getChildAt(i);
                    if (child[`__modelId`] == modelId) {
                        this.curModel = child;
                        this.modelId = modelId;
                        this.fillCurrentList(this.curModel, modelId);
                        return;
                    }
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    this.curModel = mgrLoader.Pool.getModel(modelId);
                    mgrMaterial.setCustomMaterial(this.curModel, modelId);
                    this.avatar.addChild(this.curModel);
                    this.modelId = modelId;
                    this.fillCurrentList(this.curModel, modelId);
                    if (this.curModel.name == "body_skin") {
                        let avatarColliderName2TypeDict = {
                            ["Click_head"]: 1,
                            ["Click_l_hand"]: 2,
                            ["Click_r_hand"]: 3,
                            ["Click_cloth"]: 4,
                            ["Click_dress"]: 5,
                            ["Click_foot"]: 6,
                        };
                        for (let colliderName in avatarColliderName2TypeDict) {
                            let sprite3d = Tools.findNode(colliderName, this.curModel);
                            let meshRenderer = Tools.getMeshRender(sprite3d);
                            if (meshRenderer) {
                                meshRenderer.enable = false;
                            }
                        }
                    }
                    if (this.allPartModelDict[modelId] && this.roleAvatar) {
                        this.roleAvatar.fillByPartIds([this.allPartModelDict[modelId]]);
                    }
                }, this, 1);
            }
            fillCurrentList(model, modelId) {
                let datas = [];
                for (let i = 0; i < model.numChildren; i++) {
                    let child = model.getChildAt(i);
                    let skin = child[`skinnedMeshRenderer`] || child[`meshRenderer`];
                    if (skin) {
                        datas.push({
                            modelId: modelId,
                            fOnClickModel: null,
                            skinName: child.name,
                            fOnClickSkinName: this.onClickSkinName.bind(this),
                        });
                    }
                }
                this.reuseListCurrent.setDatas(datas);
            }
            onClickSkinName(skinName) {
                this.skinName = skinName;
                this.operationMode = this.curModel.getChildByName(skinName);
                let render = this.operationMode[`skinnedMeshRenderer`] || this.operationMode[`meshRenderer`];
                this.operationRenderer = render;
                let datas = [];
                if (render) {
                    let materials = this.__setCustomMaterial(render);
                    for (let i = 0; i < materials.length; i++) {
                        const element = materials[i];
                        datas.push({
                            modelId: this.modelId,
                            skinName: this.skinName,
                            index: i.toString(),
                            name: element.name,
                            fOnClick: this.onClickMaterial.bind(this),
                        });
                    }
                }
                this.reuseListMaterial.setDatas(datas);
                this.reuseListMaterial.scrollTo(0);
            }
            __setCustomMaterial(render) {
                return mgrMaterial.__setCustomMaterial(render, this.modelId, 0, this.skinName);
            }
            onClickMaterial(index) {
                if (!this.operationRenderer)
                    return;
                this.operateMaterialIndex = index;
                let currMaterialType = CustomMaterialType.pbrCloth;
                let type = mgrMaterial.getMaterialType(this.modelId, 0, this.skinName, index);
                if (type != currMaterialType) {
                    mgrTip.alertPrompt2("删除并更换", "材质类型和当前不匹配\n是否删除并更换为当前类型材质", "不更换", "更换", () => {
                        this.spriteMaterialPropertyUI.scale(0, 0);
                    }, () => {
                        let defaultData = mgrMaterial.getDefaultMaterialDataByMaterialType(currMaterialType, this.modelId, this.skinName);
                        mgrMaterial.setMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, defaultData);
                        this.onClickSkinName(this.skinName);
                        this.spriteMaterialPropertyUI.scale(1, 1);
                        this.registerAllOperation(this.operationRenderer.sharedMaterials[index]);
                    });
                    return;
                }
                this.spriteMaterialPropertyUI.scale(1, 1);
                this.registerAllOperation(this.operationRenderer.sharedMaterials[index]);
            }
            refreshRenderQueueShow(mat) {
                this.inputRenderQueue.text = `${mat.renderQueue}`;
                this.labelOpaque.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_OPAQUE ? "#00ff00" : "#ffffff";
                this.labelOpaqueCullNone.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE ? "#00ff00" : "#ffffff";
                this.labelCutOffSingle.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_CUTOUT ? "#00ff00" : "#ffffff";
                this.labelCutOffDouble.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE ? "#00ff00" : "#ffffff";
                this.labelTransparent.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_TRANSPARENT ? "#00ff00" : "#ffffff";
                this.labelTransparentDouble.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE ? "#00ff00" : "#ffffff";
            }
            registerAllOperation(mat) {
                this.refreshRenderQueueShow(mat);
                this.buttonRenderQueue.fOnClick = () => {
                    mat.renderQueue = parseInt(this.inputRenderQueue.text) || mat.renderQueue;
                    this.operatingMaterialData.renderMode = mat.renderQueue;
                    this.refreshRenderQueueShow(mat);
                };
                this.operatingMaterialData = mgrMaterial.getMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, CustomMaterialType.pbrCloth, true);
                this.operatingMaterial = mat;
                let configTextureArr = [
                    { nodeName: "buttonTexturegridTexture", labelTip: "gridTexture", materialFieldName: "gridTexture", labelDesc: "网络图片", mType: 2 },
                    { nodeName: "buttonTextureshineTexture", labelTip: "shineTexture", materialFieldName: "shineTexture", labelDesc: "亮片图片", mType: 1 },
                    { nodeName: "buttonTexturecontrolDetailTexture", labelTip: "controlDetailTexture", materialFieldName: "controlDetailTexture", labelDesc: "区域显示控制图片", mType: 3 },
                ];
                for (let k in configTextureArr) {
                    let dataConfig = configTextureArr[k];
                    let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                    let path = this.operatingMaterialData[`${dataConfig.materialFieldName}Path`];
                    if (!path) {
                        label.text = `${dataConfig.labelTip}:未定义`;
                    }
                    else {
                        label.text = `${dataConfig.labelTip}:${path.substr(path.indexOf("\\"), 20)}`;
                    }
                    this[`${dataConfig.nodeName}`].fOnClick = () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                        mgrDirector.openDialog(`vEditorMaterialImgSelectDialog`, {
                            mType: dataConfig.mType,
                            fOnClick: (id) => {
                                let template = mgrCfg.get_from_material_img_db(id);
                                if (!template) {
                                    return;
                                }
                                Tools.loadMaterialTexture(template.materialImg, this.operatingMaterial, dataConfig.materialFieldName);
                                let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                                label.text = `${dataConfig.labelTip}:${template.id}`;
                                this.operatingMaterialData[`${dataConfig.materialFieldName}Path`] = template.materialImg;
                            },
                            fOnClean: () => {
                                this.operatingMaterial[dataConfig.materialFieldName] = null;
                                this.operatingMaterialData[`${dataConfig.materialFieldName}Path`] = null;
                            }
                        });
                    };
                }
                let configColorArr = [
                    { nodeName: "buttonMaskAlbedoColor", labelTip: "albedoColor", materialFieldName: "albedoColor", labelDesc: "材质色" },
                    { nodeName: "buttonSkinCustomDirectLightColor", labelTip: "CustomDirectLightColor", materialFieldName: "CustomDirectLightColor", labelDesc: "自定义主光色" },
                ];
                for (let k in configColorArr) {
                    let dataConfig = configColorArr[k];
                    let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                    if (!this.operatingMaterial[`${dataConfig.materialFieldName}`]) {
                        label.text = `未定义`;
                    }
                    else {
                        label.text = `${dataConfig.labelTip}: r:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].x * 255).toFixed(0)},g:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].y * 255).toFixed(0)},b:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].z * 255).toFixed(0)}`;
                    }
                    this[`${dataConfig.nodeName}`].fOnClick = () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                        mgrDirector.openDialog(`vEditorColorDialog`, {
                            colorChange: (color) => {
                                this.operatingMaterial[`${dataConfig.materialFieldName}`] = new Laya.Vector4(color.r / 255, color.g / 255, color.b / 255, 1.0);
                                let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                                label.text = `${dataConfig.labelTip}: r:${color.r},g:${color.g},b:${color.b}`;
                                let hexColor = Tools.__colorToHex(color);
                                let sprite = this[`${dataConfig.nodeName}`].owner.getChildByName("sprite");
                                sprite.graphics.drawPie(0, 0, 10, 0, 360, hexColor);
                                this.operatingMaterialData[`${dataConfig.materialFieldName}`] = [color.r / 255, color.g / 255, color.b / 255, 1.0];
                            }
                        });
                    };
                }
                let configValueArr = [
                    { nodeName: "imgMaskSPOcclusionStrength", labelTip: "Occlusion_Strength", materialFieldName: "SPOcclusionStrength", labelDesc: "遮挡强度" },
                    { nodeName: "imgMaskSPMetallic", labelTip: "Metallic", materialFieldName: "SPMetallic", labelDesc: "金属度" },
                    { nodeName: "imgMaskSPSmoothness", labelTip: "Smoothness", materialFieldName: "SPSmoothness", labelDesc: "光滑度" },
                    { nodeName: "imgMaskSPShadowAtten", labelTip: "ShadowAtten", materialFieldName: "SPShadowAtten", labelDesc: "阴影强度" },
                    { nodeName: "imgMaskSPSideLightScale", labelTip: "Side_Light_Scale", materialFieldName: "SPSideLightScale", labelDesc: "边缘光影响值" },
                    { nodeName: "imgMasknormalTextureScale", labelTip: "normalTextureScale", materialFieldName: "normalTextureScale", labelDesc: "法线强度" },
                    { nodeName: "imgMaskgridTextureScale", labelTip: "gridTextureScale", materialFieldName: "gridTextureScale", labelDesc: "网络重复度" },
                    { nodeName: "imgMaskshineTextureScale", labelTip: "shineTextureScale", materialFieldName: "shineTextureScale", labelDesc: "亮片重复度" },
                    { nodeName: "imgSkinLightResultIntensity", labelTip: "LightResultIntensity", materialFieldName: "LightResultIntensity", labelDesc: "灯光效果强度" },
                    { nodeName: "imgSkinspecularIntensity", labelTip: "specularIntensity", materialFieldName: "specularIntensity", labelDesc: "高光强度" },
                ];
                for (let k in configValueArr) {
                    let dataConfig = configValueArr[k];
                    let minMaxArr = this.operatingMaterial.getShaderValueRangeWithKey(ClothMaterial[dataConfig.materialFieldName.toUpperCase()]);
                    let slideValue = (this.operatingMaterial[`${dataConfig.materialFieldName}`] - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                    this.__registerAsSlider(this[`${dataConfig.nodeName}`], slideValue, (value) => {
                        let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * value;
                        this.operatingMaterial[`${dataConfig.materialFieldName}`] = useValue;
                        let label = this[`${dataConfig.nodeName}`].getChildByName("label");
                        label.text = `[${dataConfig.labelTip}]: ${useValue.toFixed(4)}`;
                        this.operatingMaterialData[`${dataConfig.materialFieldName}`] = useValue;
                    }, () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                    });
                }
                this.buttonOpque.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonOpqueCullNone.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffSingle.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffDouble.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffTransparent.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffTransparentDouble.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE;
                    ;
                    this.refreshRenderQueueShow(mat);
                };
            }
            __registerAsSlider(node, initValue, slideCallback, clickCallback) {
                let bar = node.getChildAt(0);
                bar.x = node.width * initValue;
                let bDown = false;
                node.on(Laya.Event.MOUSE_OVER, node, (e) => {
                    console.log("-------e.MOUSE_OVER=");
                    if (clickCallback) {
                        clickCallback();
                    }
                });
                Tools.registerTouchHander(node, (e) => {
                    console.log("-------e.isClick=", e.isClick);
                    if (e.isBegin) {
                        bDown = true;
                    }
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        point.y = node.height / 2;
                        point.x = ul.clamp(point.x, 0, node.width);
                        bar.x = point.x;
                        bar.y = point.y;
                        slideCallback(point.x / node.width);
                    }
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                });
                slideCallback(initValue);
            }
        }
        class vCartonMaterial$1 extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.index);
            }
            fillByData(data) {
                this.data = data;
                let typeMaterial = mgrMaterial.getMaterialType(this.data.modelId, 0, this.data.skinName, this.data.index);
                let typeDesc = Const.MATERIAL_TYPE_2_DESC_DICT[typeMaterial];
                this.label.text = `${[typeDesc]}${this.data.name}`;
            }
        }

        class vEditorShaderHairScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorShaderHairScene";
                this.exportNodeNames = [];
                this.reuseList = null;
                this.reuseListCurrent = null;
                this.reuseListMaterial = null;
                this.avatar = null;
                this.curModel = null;
                this.operateMaterialIndex = "0";
            }
            canOperateCamera() {
                return false;
            }
            onOpened() {
                super.onOpened();
                this.spriteMaterialPropertyUI.scale(0, 0);
                mgrDirector.adaptStageSize(2304, 1580);
                Laya.stage.on(Laya.Event.MOUSE_WHEEL, this, (e) => {
                    this.avatar.transform.localPositionZ += e.delta / 20;
                });
                let rightDown = false;
                let lastX = 0;
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_DOWN, this, (e) => {
                    rightDown = true;
                    lastX = e.stageX;
                });
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_UP, this, (e) => {
                    rightDown = false;
                });
                Laya.stage.on(Laya.Event.MOUSE_MOVE, this, (e) => {
                    if (!rightDown)
                        return;
                    let delta = e.stageX - lastX;
                    lastX = e.stageX;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                    this.roleAvatar && this.roleAvatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                });
                this.registerListeners({
                    MSG_DEBUG_KEY_DOWN: (k) => {
                        if (k == "left") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, 3, 0), false, false);
                        }
                        else if (k == "right") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, -3, 0), false, false);
                        }
                        else if (k == "up") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(3, 0, 0), false, false);
                        }
                        else if (k == "down") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(-3, 0, 0), false, false);
                        }
                        let cf = this.directitonLight.getComponent(CameraFollow);
                        if (k == "a") {
                            cf.endRotation.y += 3;
                            console.log(`灯光旋转`);
                            console.log(cf.endRotation);
                        }
                        if (k == "d") {
                            cf.endRotation.y -= 3;
                            console.log(cf.endRotation);
                        }
                        if (k == "w") {
                            cf.endRotation.x += 3;
                            console.log(cf.endRotation);
                        }
                        if (k == "s") {
                            cf.endRotation.x -= 3;
                            console.log(cf.endRotation);
                        }
                        if (k == `escape`) {
                            this.curModel = null;
                            this.avatar.removeChildren();
                        }
                        if (k == "number_7") {
                            this.cameraBack.fieldOfView += 1;
                            console.log(`fov: ${this.cameraBack.fieldOfView}`);
                        }
                        if (k == "number_8") {
                            this.cameraBack.fieldOfView -= 1;
                            console.log(`fov: ${this.cameraBack.fieldOfView}`);
                        }
                        if (k == "ctrl_c") {
                            if (!this.modelId)
                                return;
                            if (!this.skinName)
                                return;
                            this.context.clipboard = ul.clone(mgrMaterial.getMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, CustomMaterialType.pbrHair));
                            mgrTip.showMsgTip("复制成功!");
                        }
                        if (k == "ctrl_v") {
                            if (!this.modelId)
                                return;
                            if (!this.skinName)
                                return;
                            if (!this.context.clipboard)
                                return;
                            mgrTip.showMsgTip("粘贴成功!");
                            mgrMaterial.setMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, ul.clone(this.context.clipboard));
                            this.onClickSkinName(this.skinName);
                        }
                        if (k == "ctrl_number_1") {
                            if (!Const.GlobalRouter) {
                                mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                                let seasion = NetworkWS.newSeasion(`127.0.0.1`, 8081);
                                seasion.on("open", this, () => {
                                    Timer.callLater(1, () => {
                                        mgrTip.showMsgTip("链接存档服务器成功!可以存档！");
                                    });
                                    Const.GlobalRouter = new GameRemoteRouter(seasion);
                                });
                                seasion.on("error", this, () => {
                                    mgrTip.showMsgTip("链接存档服务器失败!请打开本地服务器!");
                                });
                            }
                            else {
                                Const.GlobalRouter.sendMsgToServer({
                                    route: "keepInFile",
                                    data: {
                                        filePath: `res/cfg/materialInfo.json`,
                                        data: mgrMaterial.materialInfos,
                                    },
                                });
                            }
                        }
                    }
                });
                Tools.registerTouchHander(this.spriteBg, this.onTouchSpriteBg.bind(this));
                this.spriteBg.zOrder = -4;
                this.buildUi();
                this.fillData();
                this.buttonSearch.fOnClick = () => {
                    this.fillData();
                };
                this.buttonShowAllModel.fOnClick = () => {
                    this.bOnlyPart = false;
                    this.fillData();
                    this.labelShowAllModel.color = !this.bOnlyPart ? "#00ff00" : "#ffffff";
                    this.labelShowPartModel.color = !!this.bOnlyPart ? "#00ff00" : "#ffffff";
                };
                this.buttonShowPartModel.fOnClick = () => {
                    this.bOnlyPart = true;
                    this.fillData();
                    this.labelShowAllModel.color = !this.bOnlyPart ? "#00ff00" : "#ffffff";
                    this.labelShowPartModel.color = !!this.bOnlyPart ? "#00ff00" : "#ffffff";
                };
                this.buttonRefreshAvatar.fOnClick = () => {
                    if (!this.roleAvatar) {
                        return;
                    }
                    this.roleAvatar.fillByPartIds(this.roleAvatar.getPartIds());
                    this.roleAvatar.registerLoadEndCallback(() => {
                        this.roleAvatar.playAnimation([ANIMATION_ID.idle]);
                    });
                    this.roleAvatar.refreshMaterial();
                };
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
            }
            onClosed() {
                super.onClosed();
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.lastBeginPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.avatar
                        && this.avatar.transform
                            .translate(new Laya.Vector3(deltaX / mgrDirector.width, -deltaY / mgrDirector.height, 0), true);
                }
            }
            buildUi() {
                this.reuseList = new ReuseList(1, 0, 20);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vEditorCartonMaterialPart);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseListCurrent = new ReuseList(1, 0, 10);
                this.reuseListCurrent.size(this.boxCurrentList.width, this.boxCurrentList.height);
                this.boxCurrentList.addChild(this.reuseListCurrent);
                this.reuseListCurrent.setItemClass(vEditorCartonMaterialPart);
                this.reuseListCurrent.setVerticalMoveEnable(true);
                this.reuseListMaterial = new ReuseList(1, 0, 10);
                this.reuseListMaterial.size(this.boxMaterialList.width, this.boxMaterialList.height);
                this.boxMaterialList.addChild(this.reuseListMaterial);
                this.reuseListMaterial.setItemClass(vHairMaterial);
                this.reuseListMaterial.setVerticalMoveEnable(true);
                this.avatar = new Laya.Sprite3D;
                this.avatar.transform.position = new Laya.Vector3(0, 0, 0);
                this.add3DEffectAtBack(this.avatar, 0);
                let cf = this.directitonLight.getComponent(CameraFollow);
                cf.endRotation = new Laya.Vector3(-5, 27, -17.27);
                this.roleAvatar = new RoleAvatar();
                this.roleAvatar.transform.position = new Laya.Vector3(0.5, 0, 0);
                this.add3DEffectAtBack(this.roleAvatar, 0);
            }
            fillData() {
                let regexp = null;
                if (this.inputText.text.length != 0) {
                    regexp = new RegExp(this.inputText.text);
                }
                if (!this.allPartModelDict) {
                    let partModelDict = {};
                    mgrCfg.forDb_from_part_db((k, v) => {
                        partModelDict[v.modelId] = v.id;
                    });
                    this.allPartModelDict = partModelDict;
                }
                let datas = [];
                mgrCfg.forDb_from_model_db((k, v) => {
                    if (v.id.startsWith("eff_") || v.id.startsWith("e_")) {
                        return;
                    }
                    if (this.bOnlyPart && !this.allPartModelDict[v.id]) {
                        return;
                    }
                    if (!regexp) {
                        datas.push({
                            modelId: v.id,
                            fOnClickModel: this.onSelectModel.bind(this),
                            skinName: null,
                            fOnClickSkinName: null,
                        });
                    }
                    else {
                        if (regexp.test(v.id)) {
                            datas.push({
                                modelId: v.id,
                                fOnClickModel: this.onSelectModel.bind(this),
                                skinName: null,
                                fOnClickSkinName: null,
                            });
                        }
                    }
                });
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
            }
            onSelectModel(modelId) {
                this.modelId = null;
                this.skinName = null;
                this.operatingMaterialData = null;
                this.operatingMaterial = null;
                for (let i = 0; i < this.avatar.numChildren; i++) {
                    let child = this.avatar.getChildAt(i);
                    if (child[`__modelId`] == modelId) {
                        this.curModel = child;
                        this.modelId = modelId;
                        this.fillCurrentList(this.curModel, modelId);
                        return;
                    }
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    this.curModel = mgrLoader.Pool.getModel(modelId);
                    mgrMaterial.setCustomMaterial(this.curModel, modelId);
                    this.avatar.addChild(this.curModel);
                    this.modelId = modelId;
                    this.fillCurrentList(this.curModel, modelId);
                    if (this.curModel.name == "body_skin") {
                        let avatarColliderName2TypeDict = {
                            ["Click_head"]: 1,
                            ["Click_l_hand"]: 2,
                            ["Click_r_hand"]: 3,
                            ["Click_cloth"]: 4,
                            ["Click_dress"]: 5,
                            ["Click_foot"]: 6,
                        };
                        for (let colliderName in avatarColliderName2TypeDict) {
                            let sprite3d = Tools.findNode(colliderName, this.curModel);
                            let meshRenderer = Tools.getMeshRender(sprite3d);
                            if (meshRenderer) {
                                meshRenderer.enable = false;
                            }
                        }
                    }
                    if (this.allPartModelDict[modelId] && this.roleAvatar) {
                        this.roleAvatar.fillByPartIds([this.allPartModelDict[modelId]]);
                    }
                }, this, 1);
            }
            fillCurrentList(model, modelId) {
                let datas = [];
                for (let i = 0; i < model.numChildren; i++) {
                    let child = model.getChildAt(i);
                    let skin = child[`skinnedMeshRenderer`] || child[`meshRenderer`];
                    if (skin) {
                        datas.push({
                            modelId: modelId,
                            fOnClickModel: null,
                            skinName: child.name,
                            fOnClickSkinName: this.onClickSkinName.bind(this),
                        });
                    }
                }
                this.reuseListCurrent.setDatas(datas);
            }
            onClickSkinName(skinName) {
                this.skinName = skinName;
                this.operationMode = this.curModel.getChildByName(skinName);
                let render = this.operationMode[`skinnedMeshRenderer`] || this.operationMode[`meshRenderer`];
                this.operationRenderer = render;
                let datas = [];
                if (render) {
                    let materials = this.__setCustomMaterial(render);
                    for (let i = 0; i < materials.length; i++) {
                        const element = materials[i];
                        datas.push({
                            modelId: this.modelId,
                            skinName: this.skinName,
                            index: i.toString(),
                            name: element.name,
                            fOnClick: this.onClickMaterial.bind(this),
                        });
                    }
                }
                this.reuseListMaterial.setDatas(datas);
                this.reuseListMaterial.scrollTo(0);
            }
            __setCustomMaterial(render) {
                return mgrMaterial.__setCustomMaterial(render, this.modelId, 0, this.skinName);
            }
            onClickMaterial(index) {
                if (!this.operationRenderer)
                    return;
                this.operateMaterialIndex = index;
                let currMaterialType = CustomMaterialType.pbrHair;
                let type = mgrMaterial.getMaterialType(this.modelId, 0, this.skinName, index);
                if (type != currMaterialType) {
                    mgrTip.alertPrompt2("删除并更换", "材质类型和当前不匹配\n是否删除并更换为当前类型材质", "不更换", "更换", () => {
                        this.spriteMaterialPropertyUI.scale(0, 0);
                    }, () => {
                        let defaultData = mgrMaterial.getDefaultMaterialDataByMaterialType(currMaterialType, this.modelId, this.skinName);
                        mgrMaterial.setMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, defaultData);
                        this.onClickSkinName(this.skinName);
                        this.spriteMaterialPropertyUI.scale(1, 1);
                        this.registerAllOperation(this.operationRenderer.sharedMaterials[index]);
                    });
                    return;
                }
                this.spriteMaterialPropertyUI.scale(1, 1);
                this.registerAllOperation(this.operationRenderer.sharedMaterials[index]);
            }
            refreshRenderQueueShow(mat) {
                this.inputRenderQueue.text = `${mat.renderQueue}`;
                this.labelOpaque.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_OPAQUE ? "#00ff00" : "#ffffff";
                this.labelOpaqueCullNone.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE ? "#00ff00" : "#ffffff";
                this.labelCutOffSingle.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_CUTOUT ? "#00ff00" : "#ffffff";
                this.labelCutOffDouble.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE ? "#00ff00" : "#ffffff";
                this.labelTransparent.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_TRANSPARENT ? "#00ff00" : "#ffffff";
                this.labelTransparentDouble.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE ? "#00ff00" : "#ffffff";
            }
            registerAllOperation(mat) {
                this.refreshRenderQueueShow(mat);
                this.buttonRenderQueue.fOnClick = () => {
                    mat.renderQueue = parseInt(this.inputRenderQueue.text) || mat.renderQueue;
                    this.operatingMaterialData.renderMode = mat.renderQueue;
                    this.refreshRenderQueueShow(mat);
                };
                this.operatingMaterialData = mgrMaterial.getMaterial(this.modelId, 0, this.skinName, this.operateMaterialIndex, CustomMaterialType.pbrHair, true);
                this.operatingMaterial = mat;
                let configColorArr = [
                    { nodeName: "buttonSPR1SpecalurColor", labelTip: "混合高光颜色1", materialFieldName: "SPR1SpecalurColor", labelDesc: "SPR1SpecalurColor 第一种混合高光颜色" },
                    { nodeName: "buttonSPR2SpecalurColor", labelTip: "混合高光颜色2", materialFieldName: "SPR2SpecalurColor", labelDesc: "SPR2SpecalurColor 第二种混合高光颜色" },
                    { nodeName: "buttonSPSpecularInDark", labelTip: "暗部高光色", materialFieldName: "SPSpecularInDark", labelDesc: "SPSpecularInDark 暗部高光色" },
                    { nodeName: "buttonSPAbedoColor", labelTip: "材质色", materialFieldName: "albedoColor", labelDesc: "SPAbedoColor 材质色" },
                ];
                for (let k in configColorArr) {
                    let dataConfig = configColorArr[k];
                    let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                    if (!this.operatingMaterial[`${dataConfig.materialFieldName}`]) {
                        label.text = `未定义`;
                    }
                    else {
                        label.text = `${dataConfig.labelTip}: r:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].x * 255).toFixed(0)},g:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].y * 255).toFixed(0)},b:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].z * 255).toFixed(0)}`;
                        let hexColor = Tools.__colorToHex(new Laya.Color(this.operatingMaterial[`${dataConfig.materialFieldName}`].x * 255, this.operatingMaterial[`${dataConfig.materialFieldName}`].y * 255, this.operatingMaterial[`${dataConfig.materialFieldName}`].z * 255));
                        let sprite = this[`${dataConfig.nodeName}`].owner.getChildByName("sprite");
                        sprite.graphics.drawPie(0, 0, 10, 0, 360, hexColor);
                    }
                    this[`${dataConfig.nodeName}`].fOnClick = () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                        mgrDirector.openDialog(`vEditorColorDialog`, {
                            colorChange: (color) => {
                                this.operatingMaterial[`${dataConfig.materialFieldName}`] = new Laya.Vector4(color.r / 255, color.g / 255, color.b / 255, 1.0);
                                let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                                label.text = `${dataConfig.labelTip}: r:${color.r},g:${color.g},b:${color.b}`;
                                let hexColor = Tools.__colorToHex(color);
                                let sprite = this[`${dataConfig.nodeName}`].owner.getChildByName("sprite");
                                sprite.graphics.drawPie(0, 0, 10, 0, 360, hexColor);
                                this.operatingMaterialData[`${dataConfig.materialFieldName}`] = [color.r / 255, color.g / 255, color.b / 255, 1.0];
                            }
                        });
                    };
                }
                let configValueArr = [
                    { nodeName: "imgSPUTiling", labelTip: "平铺度", materialFieldName: "SPUTiling", labelDesc: "UTiling 平铺度" },
                    { nodeName: "imgSPPBRInstensity", labelTip: "原本pbr色强度", materialFieldName: "SPPBRInstensity", labelDesc: "PBRInstensity 原本pbr色强度" },
                    { nodeName: "imgSPHairAlbedoAO", labelTip: "材质色强度", materialFieldName: "SPHairAlbedoAO", labelDesc: "HairAlbedoAO 材质色强度" },
                    { nodeName: "imgSPAnisotropyBiasG", labelTip: "贴图中G值强度", materialFieldName: "SPAnisotropyBiasG", labelDesc: "AnisotropyBiasGMask 贴图中G值强度" },
                    { nodeName: "imgSPAnisotropyBiasR", labelTip: "贴图中R值强度", materialFieldName: "SPAnisotropyBiasR", labelDesc: "AnisotropyBiasRMask 贴图中R值强度" },
                    { nodeName: "imgSPHairSpecularAO", labelTip: "贴图中B值强度", materialFieldName: "SPHairSpecularAO", labelDesc: "HairSpecularAOMask 贴图中B值强度" },
                    { nodeName: "imgSPAnisotropyRang1", labelTip: "高光颜色强度1", materialFieldName: "SPAnisotropyRang1", labelDesc: "AnisotropyRang1 第一种混合高光颜色强度" },
                    { nodeName: "imgSPAnisotropyRang2", labelTip: "高光颜色强度2", materialFieldName: "SPAnisotropyRang2", labelDesc: "AnisotropyRang2 第二种混合高光颜色强度" },
                    { nodeName: "imgSPHLFrePower", labelTip: "光线强度", materialFieldName: "SPHLFrePower", labelDesc: "HLFrePower 光线强度" },
                    { nodeName: "imgSPSpecularInDarkAlpha", labelTip: "暗部色强度", materialFieldName: "SPSpecularInDarkAlpha", labelDesc: "SpecularInDarkAlpha 暗部色强度" },
                    { nodeName: "imgSkinSPMetallic", labelTip: "金属度", materialFieldName: "SPMetallic", labelDesc: "Metallic 金属度" },
                    { nodeName: "imgSmoothness", labelTip: "光度度", materialFieldName: "smoothness", labelDesc: "smoothness 光度度" },
                    { nodeName: "imgnormalTextureScale", labelTip: "法线强度", materialFieldName: "normalTextureScale", labelDesc: "normalTextureScale 法线强度" },
                    { nodeName: "imageSliderAlphaTestValue", labelTip: "AlphaTestValue", materialFieldName: "alphaTestValue", labelDesc: "AlphaTestValue AlphaTestValue" },
                    { nodeName: "imgSkinLightResultIntensity", labelTip: "灯光效果强度", materialFieldName: "LightResultIntensity", labelDesc: "LightResultIntensity 灯光效果强度" },
                    { nodeName: "imageSliderSPPBRFinalLightRatio", labelTip: "最终灯光影响值", materialFieldName: "SPPBRFinalLightRatio", labelDesc: "SPPBRFinalLightRatio 最终灯光影响值" },
                    { nodeName: "imgSPPBRSecondLightYValue", labelTip: "灯光2旋转值", materialFieldName: "SPPBRSecondLightYValue", labelDesc: "SPPBRSecondLightYValue 第二灯光左右旋转值" },
                ];
                for (let k in configValueArr) {
                    let dataConfig = configValueArr[k];
                    let minMaxArr = this.operatingMaterial.getShaderValueRangeWithKey(HairMaterial[dataConfig.materialFieldName.toUpperCase()]);
                    let slideValue = (this.operatingMaterial[`${dataConfig.materialFieldName}`] - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                    this.__registerAsSlider(this[`${dataConfig.nodeName}`], slideValue, (value) => {
                        let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * value;
                        this.operatingMaterial[`${dataConfig.materialFieldName}`] = useValue;
                        let label = this[`${dataConfig.nodeName}`].getChildByName("label");
                        label.text = `[${dataConfig.labelTip}]: ${useValue.toFixed(4)}`;
                        this.operatingMaterialData[`${dataConfig.materialFieldName}`] = useValue;
                    }, () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                    });
                }
                this.buttonOpque.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonOpqueCullNone.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffSingle.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffDouble.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffTransparent.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffTransparentDouble.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE;
                    ;
                    this.refreshRenderQueueShow(mat);
                };
            }
            __registerAsSlider(node, initValue, slideCallback, clickCallback) {
                let bar = node.getChildAt(0);
                bar.x = node.width * initValue;
                let bDown = false;
                node.on(Laya.Event.MOUSE_OVER, node, (e) => {
                    console.log("-------e.MOUSE_OVER=");
                    if (clickCallback) {
                        clickCallback();
                    }
                });
                Tools.registerTouchHander(node, (e) => {
                    console.log("-------e.isClick=", e.isClick);
                    if (e.isBegin) {
                        bDown = true;
                    }
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        point.y = node.height / 2;
                        point.x = ul.clamp(point.x, 0, node.width);
                        bar.x = point.x;
                        bar.y = point.y;
                        slideCallback(point.x / node.width);
                    }
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                });
                slideCallback(initValue);
            }
        }
        class vHairMaterial extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.index);
            }
            fillByData(data) {
                this.data = data;
                let typeMaterial = mgrMaterial.getMaterialType(this.data.modelId, 0, this.data.skinName, this.data.index);
                let typeDesc = Const.MATERIAL_TYPE_2_DESC_DICT[typeMaterial];
                this.label.text = `${[typeDesc]}${this.data.name}`;
            }
        }

        class vEditorShaderSkinScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorShaderSkinScene";
                this.exportNodeNames = [];
                this.reuseList = null;
                this.reuseListCurrent = null;
                this.reuseListMaterial = null;
                this.avatar = null;
                this.curModel = null;
                this.currModelMaterialNo = 0;
                this.operateMaterialIndex = "0";
            }
            canOperateCamera() {
                return false;
            }
            onOpened() {
                super.onOpened();
                this.spriteMaterialPropertyUI.scale(0, 0);
                this.boxModelMaterialNoList.scale(0, 0, true);
                this.boxCurrentList.scale(0, 0, true);
                this.boxMaterialList.scale(0, 0, true);
                mgrDirector.adaptStageSize(2304, 1580);
                Laya.stage.on(Laya.Event.MOUSE_WHEEL, this, (e) => {
                    this.avatar.transform.localPositionZ += e.delta / 20;
                });
                let rightDown = false;
                let lastX = 0;
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_DOWN, this, (e) => {
                    rightDown = true;
                    lastX = e.stageX;
                });
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_UP, this, (e) => {
                    rightDown = false;
                });
                Laya.stage.on(Laya.Event.MOUSE_MOVE, this, (e) => {
                    if (!rightDown)
                        return;
                    let delta = e.stageX - lastX;
                    lastX = e.stageX;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                    this.roleAvatar && this.roleAvatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                });
                this.registerListeners({
                    MSG_DEBUG_KEY_DOWN: (k) => {
                        if (k == "left") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, 3, 0), false, false);
                        }
                        else if (k == "right") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, -3, 0), false, false);
                        }
                        else if (k == "up") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(3, 0, 0), false, false);
                        }
                        else if (k == "down") {
                            this.avatar && this.avatar.transform.rotate(new Laya.Vector3(-3, 0, 0), false, false);
                        }
                        let cf = this.directitonLight.getComponent(CameraFollow);
                        if (k == "a") {
                            cf.endRotation.y += 3;
                            console.log(`灯光旋转`);
                            console.log(cf.endRotation);
                        }
                        if (k == "d") {
                            cf.endRotation.y -= 3;
                            console.log(cf.endRotation);
                        }
                        if (k == "w") {
                            cf.endRotation.x += 3;
                            console.log(cf.endRotation);
                        }
                        if (k == "s") {
                            cf.endRotation.x -= 3;
                            console.log(cf.endRotation);
                        }
                        if (k == `escape`) {
                            this.curModel = null;
                            this.avatar.removeChildren();
                        }
                        if (k == "number_7") {
                            this.cameraBack.fieldOfView += 1;
                            console.log(`fov: ${this.cameraBack.fieldOfView}`);
                        }
                        if (k == "number_8") {
                            this.cameraBack.fieldOfView -= 1;
                            console.log(`fov: ${this.cameraBack.fieldOfView}`);
                        }
                        if (k == "ctrl_c") {
                            if (!this.modelId)
                                return;
                            if (!this.skinName)
                                return;
                            this.context.clipboard = ul.clone(mgrMaterial.getMaterial(this.modelId, this.currModelMaterialNo, this.skinName, this.operateMaterialIndex, CustomMaterialType.pbrSkin));
                            mgrTip.showMsgTip("复制成功!");
                        }
                        if (k == "ctrl_v") {
                            if (!this.modelId)
                                return;
                            if (!this.skinName)
                                return;
                            if (!this.context.clipboard)
                                return;
                            mgrTip.showMsgTip("粘贴成功!");
                            mgrMaterial.setMaterial(this.modelId, this.currModelMaterialNo, this.skinName, this.operateMaterialIndex, ul.clone(this.context.clipboard));
                            this.onClickSkinName(this.skinName);
                            this.onClickMaterial(this.operateMaterialIndex);
                        }
                        if (k == "ctrl_number_1") {
                            if (!Const.GlobalRouter) {
                                mgrTip.showMsgTip("未链接存档服务器,尝试重新连接!");
                                let seasion = NetworkWS.newSeasion(`127.0.0.1`, 8081);
                                seasion.on("open", this, () => {
                                    Timer.callLater(1, () => {
                                        mgrTip.showMsgTip("链接存档服务器成功!可以存档！");
                                    });
                                    Const.GlobalRouter = new GameRemoteRouter(seasion);
                                });
                                seasion.on("error", this, () => {
                                    mgrTip.showMsgTip("链接存档服务器失败!请打开本地服务器!");
                                });
                            }
                            else {
                                Const.GlobalRouter.sendMsgToServer({
                                    route: "keepInFile",
                                    data: {
                                        filePath: `res/cfg/materialInfo.json`,
                                        data: mgrMaterial.materialInfos,
                                    },
                                });
                                mgrTip.showMsgTip("保存成功!");
                            }
                        }
                    }
                });
                Tools.registerTouchHander(this.spriteBg, this.onTouchSpriteBg.bind(this));
                this.spriteBg.zOrder = -4;
                this.buildUi();
                this.fillData();
                this.buttonSearch.fOnClick = () => {
                    this.fillData();
                };
                this.buttonShowAllModel.fOnClick = () => {
                    this.bOnlyPart = false;
                    this.fillData();
                    this.labelShowAllModel.color = !this.bOnlyPart ? "#00ff00" : "#ffffff";
                    this.labelShowPartModel.color = !!this.bOnlyPart ? "#00ff00" : "#ffffff";
                };
                this.buttonShowPartModel.fOnClick = () => {
                    this.bOnlyPart = true;
                    this.fillData();
                    this.labelShowAllModel.color = !this.bOnlyPart ? "#00ff00" : "#ffffff";
                    this.labelShowPartModel.color = !!this.bOnlyPart ? "#00ff00" : "#ffffff";
                };
                this.buttonRefreshAvatar.fOnClick = () => {
                    if (!this.roleAvatar) {
                        return;
                    }
                    this.roleAvatar.fillByPartIds(this.roleAvatar.getPartIds());
                    this.roleAvatar.registerLoadEndCallback(() => {
                        this.roleAvatar.playAnimation([ANIMATION_ID.idle]);
                    });
                    this.roleAvatar.refreshMaterial();
                };
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
            }
            onClosed() {
                super.onClosed();
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.lastBeginPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.avatar
                        && this.avatar.transform
                            .translate(new Laya.Vector3(deltaX / mgrDirector.width, -deltaY / mgrDirector.height, 0), true);
                }
            }
            buildUi() {
                this.reuseList = new ReuseList(1, 0, 20);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vEditorCartonMaterialPart);
                this.reuseList.setVerticalMoveEnable(true);
                this.reuseListModelMaterialNo = new ReuseList(1, 0, 10);
                this.reuseListModelMaterialNo.size(this.boxModelMaterialNoList.width, this.boxModelMaterialNoList.height);
                this.boxModelMaterialNoList.addChild(this.reuseListModelMaterialNo);
                this.reuseListModelMaterialNo.setItemClass(vEditorModelMaterialNoItem);
                this.reuseListModelMaterialNo.setVerticalMoveEnable(true);
                this.reuseListCurrent = new ReuseList(1, 0, 10);
                this.reuseListCurrent.size(this.boxCurrentList.width, this.boxCurrentList.height);
                this.boxCurrentList.addChild(this.reuseListCurrent);
                this.reuseListCurrent.setItemClass(vEditorCartonMaterialPart);
                this.reuseListCurrent.setVerticalMoveEnable(true);
                this.reuseListMaterial = new ReuseList(1, 0, 10);
                this.reuseListMaterial.size(this.boxMaterialList.width, this.boxMaterialList.height);
                this.boxMaterialList.addChild(this.reuseListMaterial);
                this.reuseListMaterial.setItemClass(vCartonMaterial$2);
                this.reuseListMaterial.setVerticalMoveEnable(true);
                this.avatar = new Laya.Sprite3D;
                this.avatar.transform.position = new Laya.Vector3(0, 0, 0);
                this.add3DEffectAtBack(this.avatar, 0);
                let cf = this.directitonLight.getComponent(CameraFollow);
                cf.endRotation = new Laya.Vector3(-5, 27, -17.27);
                this.roleAvatar = new RoleAvatar();
                this.roleAvatar.transform.position = new Laya.Vector3(0.5, 0, 0);
                this.add3DEffectAtBack(this.roleAvatar, 0);
            }
            fillData() {
                let regexp = null;
                if (this.inputText.text.length != 0) {
                    regexp = new RegExp(this.inputText.text);
                }
                if (!this.allPartModelDict) {
                    let partModelDict = {};
                    mgrCfg.forDb_from_part_db((k, v) => {
                        if (mgrDesign.isDesignPart(v.id)) {
                            return;
                        }
                        partModelDict[v.modelId] = partModelDict[v.modelId] || {};
                        if (!partModelDict[v.modelId][v.modelMaterialNo || 0]) {
                            partModelDict[v.modelId][v.modelMaterialNo || 0] = v.id;
                        }
                    });
                    this.allPartModelDict = partModelDict;
                }
                let datas = [];
                mgrCfg.forDb_from_model_db((k, v) => {
                    if (v.id.startsWith("eff_") || v.id.startsWith("e_")) {
                        return;
                    }
                    if (this.bOnlyPart && !this.allPartModelDict[v.id][0]) {
                        return;
                    }
                    if (!regexp) {
                        datas.push({
                            modelId: v.id,
                            modelMaterialNo: this.currModelMaterialNo.toString(),
                            fOnClickModel: this.onSelectModel.bind(this),
                            skinName: null,
                            fOnClickSkinName: null,
                        });
                    }
                    else {
                        if (regexp.test(v.id)) {
                            datas.push({
                                modelId: v.id,
                                modelMaterialNo: this.currModelMaterialNo.toString(),
                                fOnClickModel: this.onSelectModel.bind(this),
                                skinName: null,
                                fOnClickSkinName: null,
                            });
                        }
                    }
                });
                this.reuseList.setDatas(datas);
                this.reuseList.scrollTo(0);
                this.fillModelMaterialNo();
            }
            fillModelMaterialNo() {
                let modelNoDataArr = [];
                for (let i = 0; i < 5; i++) {
                    let partId = 0;
                    if (this.allPartModelDict && this.allPartModelDict[this.modelId] && this.allPartModelDict[this.modelId][i]) {
                        partId = this.allPartModelDict[this.modelId][i];
                    }
                    modelNoDataArr.push({
                        id: i,
                        partId: partId,
                        fGetCurrModelId: () => { return this.modelId; },
                        fOnClick: this.onSelectModelMaterialNo.bind(this),
                    });
                }
                this.reuseListModelMaterialNo.setDatas(modelNoDataArr);
            }
            onSelectModelMaterialNo(no) {
                this.currModelMaterialNo = no;
                this.labelModelMaterialNoTip.text = `当前序号：${no}`;
                this.reuseListModelMaterialNo.refresh();
                mgrMaterial.setCustomMaterial(this.curModel, this.modelId, this.currModelMaterialNo);
                this.boxModelMaterialNoList.scale(1, 1, true);
                this.boxCurrentList.scale(1, 1, true);
                this.boxMaterialList.scale(0, 0, true);
                this.fillCurrentList(this.curModel, this.modelId);
                if (this.allPartModelDict[this.modelId][this.currModelMaterialNo] && this.roleAvatar) {
                    this.roleAvatar.fillByPartIds([this.allPartModelDict[this.modelId][this.currModelMaterialNo]]);
                }
            }
            onSelectModel(modelId) {
                this.modelId = null;
                this.skinName = null;
                this.operatingMaterialData = null;
                this.operatingMaterial = null;
                this.currModelMaterialNo = 0;
                this.boxModelMaterialNoList.scale(1, 1, true);
                this.boxCurrentList.scale(0, 0, true);
                this.boxMaterialList.scale(0, 0, true);
                for (let i = 0; i < this.avatar.numChildren; i++) {
                    let child = this.avatar.getChildAt(i);
                    if (child[`__modelId`] == modelId) {
                        this.curModel = child;
                        this.modelId = modelId;
                        this.fillModelMaterialNo();
                        return;
                    }
                }
                mgrLoader.loadModeWithModeId(modelId, () => {
                    this.curModel = mgrLoader.Pool.getModel(modelId);
                    this.avatar.addChild(this.curModel);
                    this.modelId = modelId;
                    this.fillModelMaterialNo();
                    if (this.curModel.name == "body_skin") {
                        let avatarColliderName2TypeDict = {
                            ["Click_head"]: 1,
                            ["Click_l_hand"]: 2,
                            ["Click_r_hand"]: 3,
                            ["Click_cloth"]: 4,
                            ["Click_dress"]: 5,
                            ["Click_foot"]: 6,
                        };
                        for (let colliderName in avatarColliderName2TypeDict) {
                            let sprite3d = Tools.findNode(colliderName, this.curModel);
                            if (!sprite3d) {
                                continue;
                            }
                            let meshRenderer = Tools.getMeshRender(sprite3d);
                            if (meshRenderer) {
                                meshRenderer.enable = false;
                            }
                        }
                    }
                }, this, 1);
            }
            fillCurrentList(model, modelId) {
                let datas = [];
                for (let i = 0; i < model.numChildren; i++) {
                    let child = model.getChildAt(i);
                    let skin = child[`skinnedMeshRenderer`] || child[`meshRenderer`];
                    if (skin) {
                        datas.push({
                            modelId: modelId,
                            modelMaterialNo: this.currModelMaterialNo.toString(),
                            fOnClickModel: null,
                            skinName: child.name,
                            fOnClickSkinName: this.onClickSkinName.bind(this),
                        });
                    }
                }
                this.reuseListCurrent.setDatas(datas);
            }
            onClickSkinName(skinName) {
                this.boxModelMaterialNoList.scale(1, 1, true);
                this.boxCurrentList.scale(1, 1, true);
                this.boxMaterialList.scale(1, 1, true);
                this.skinName = skinName;
                this.operationMode = this.curModel.getChildByName(skinName);
                let render = this.operationMode[`skinnedMeshRenderer`] || this.operationMode[`meshRenderer`];
                this.operationRenderer = render;
                let datas = [];
                if (render) {
                    let materials = this.__setCustomMaterial(render);
                    for (let i = 0; i < materials.length; i++) {
                        const element = materials[i];
                        datas.push({
                            modelId: this.modelId,
                            modelMaterialNo: this.currModelMaterialNo.toString(),
                            skinName: this.skinName,
                            index: i.toString(),
                            name: element.name,
                            fOnClick: this.onClickMaterial.bind(this),
                        });
                    }
                }
                this.reuseListMaterial.setDatas(datas);
                this.reuseListMaterial.scrollTo(0);
            }
            __setCustomMaterial(render) {
                return mgrMaterial.__setCustomMaterial(render, this.modelId, this.currModelMaterialNo, this.skinName);
            }
            onClickMaterial(index) {
                if (!this.operationRenderer)
                    return;
                this.operateMaterialIndex = index;
                let currMaterialType = CustomMaterialType.pbrSkin;
                let type = mgrMaterial.getMaterialType(this.modelId, this.currModelMaterialNo, this.skinName, index);
                if (type != currMaterialType) {
                    mgrTip.alertPrompt2("删除并更换", "材质类型和当前不匹配\n是否删除并更换为当前类型材质", "不更换", "更换", () => {
                        this.spriteMaterialPropertyUI.scale(0, 0);
                    }, () => {
                        let defaultData = mgrMaterial.getDefaultMaterialDataByMaterialType(currMaterialType, this.modelId, this.skinName);
                        mgrMaterial.setMaterial(this.modelId, this.currModelMaterialNo, this.skinName, this.operateMaterialIndex, defaultData);
                        this.onClickSkinName(this.skinName);
                        this.spriteMaterialPropertyUI.scale(1, 1);
                        this.registerAllOperation(this.operationRenderer.sharedMaterials[index]);
                    });
                    return;
                }
                this.spriteMaterialPropertyUI.scale(1, 1);
                this.registerAllOperation(this.operationRenderer.sharedMaterials[index]);
            }
            refreshRenderQueueShow(mat) {
                this.inputRenderQueue.text = `${mat.renderQueue}`;
                this.labelOpaque.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_OPAQUE ? "#00ff00" : "#ffffff";
                this.labelOpaqueCullNone.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE ? "#00ff00" : "#ffffff";
                this.labelCutOffSingle.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_CUTOUT ? "#00ff00" : "#ffffff";
                this.labelCutOffDouble.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE ? "#00ff00" : "#ffffff";
                this.labelTransparent.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_TRANSPARENT ? "#00ff00" : "#ffffff";
                this.labelTransparentDouble.color = mat.renderMode == CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE ? "#00ff00" : "#ffffff";
            }
            registerAllOperation(mat) {
                this.refreshRenderQueueShow(mat);
                this.buttonRenderQueue.fOnClick = () => {
                    mat.renderQueue = parseInt(this.inputRenderQueue.text) || mat.renderQueue;
                    this.operatingMaterialData.renderQueue = mat.renderQueue;
                    this.refreshRenderQueueShow(mat);
                };
                this.operatingMaterialData = mgrMaterial.getMaterial(this.modelId, this.currModelMaterialNo, this.skinName, this.operateMaterialIndex, CustomMaterialType.pbrSkin, true);
                this.operatingMaterial = mat;
                let configTextureArr = [
                    { nodeName: "buttonAlbedoTexture", labelTip: "基础图片", materialFieldName: "albedoTexture", labelDesc: "albedoTexture 基础图片", mType: 4 },
                    { nodeName: "buttonTexturenormalTexture", labelTip: "法线图片", materialFieldName: "normalTexture", labelDesc: "normalTexture 法线图片" },
                    { nodeName: "buttonTexturerampMapTexture", labelTip: "3s图片", materialFieldName: "rampMapTexture", labelDesc: "rampMapTexture 3s图片" },
                    { nodeName: "buttonTexturegridTexture", labelTip: "网络图片", materialFieldName: "gridTexture", labelDesc: "gridTexture 网络图片", mType: 2 },
                    { nodeName: "buttonTextureshineTexture", labelTip: "亮片图片", materialFieldName: "shineTexture", labelDesc: "shineTexture 亮片图片", mType: 1 },
                    { nodeName: "buttonTexturecontrolDetailTexture", labelTip: "区域显示控制图片", materialFieldName: "controlDetailTexture", labelDesc: "controlDetailTexture 区域显示控制图片", mType: 3 },
                ];
                for (let k in configTextureArr) {
                    let dataConfig = configTextureArr[k];
                    let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                    let path = this.operatingMaterialData[`${dataConfig.materialFieldName}Path`];
                    if (!path) {
                        label.text = `${dataConfig.labelTip}:未定义`;
                    }
                    else {
                        label.text = `${dataConfig.labelTip}:${path.substr(path.indexOf("/"), 20)}`;
                    }
                    this[`${dataConfig.nodeName}`].fOnClick = () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                        mgrDirector.openDialog(`vEditorMaterialImgSelectDialog`, {
                            mType: dataConfig.mType,
                            fOnClick: (id) => {
                                let template = mgrCfg.get_from_material_img_db(id);
                                if (!template) {
                                    return;
                                }
                                Tools.loadMaterialTexture(template.materialImg, this.operatingMaterial, dataConfig.materialFieldName);
                                let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                                label.text = `${dataConfig.labelTip}:${template.id}`;
                                this.operatingMaterialData[`${dataConfig.materialFieldName}Path`] = template.materialImg;
                            },
                            fOnClean: () => {
                                this.operatingMaterial[dataConfig.materialFieldName] = null;
                                this.operatingMaterialData[`${dataConfig.materialFieldName}Path`] = null;
                                let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                                label.text = `${dataConfig.labelTip}:未定义`;
                            }
                        });
                    };
                }
                let configColorArr = [
                    { nodeName: "buttonSkinSPEmissionColorBack", labelTip: "自发光底色", materialFieldName: "SPEmissionColorBack", labelDesc: "SPEmissionColorBack 自发光底色" },
                    { nodeName: "buttonSkinAlbedoColor", labelTip: "材质色", materialFieldName: "albedoColor", labelDesc: "albedoColor 材质色" },
                    { nodeName: "buttonSkinSPRed3SColor", labelTip: "透光性影响色调", materialFieldName: "SPRed3SColor", labelDesc: "SPRed3SColor 透光性影响色调" },
                    { nodeName: "buttonSkinCustomDirectLightColor", labelTip: "自定义主光色", materialFieldName: "CustomDirectLightColor", labelDesc: "CustomDirectLightColor 自定义主光色" },
                ];
                for (let k in configColorArr) {
                    let dataConfig = configColorArr[k];
                    let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                    if (!this.operatingMaterial[`${dataConfig.materialFieldName}`]) {
                        label.text = `未定义`;
                    }
                    else {
                        label.text = `${dataConfig.labelTip}: r:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].x * 255).toFixed(0)},g:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].y * 255).toFixed(0)},b:${(this.operatingMaterial[`${dataConfig.materialFieldName}`].z * 255).toFixed(0)}`;
                        let hexColor = Tools.__colorToHex(new Laya.Color(this.operatingMaterial[`${dataConfig.materialFieldName}`].x * 255, this.operatingMaterial[`${dataConfig.materialFieldName}`].y * 255, this.operatingMaterial[`${dataConfig.materialFieldName}`].z * 255));
                        let sprite = this[`${dataConfig.nodeName}`].owner.getChildByName("sprite");
                        sprite.graphics.drawPie(0, 0, 10, 0, 360, hexColor);
                    }
                    this[`${dataConfig.nodeName}`].fOnClick = () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                        mgrDirector.openDialog(`vEditorColorDialog`, {
                            colorChange: (color) => {
                                this.operatingMaterial[`${dataConfig.materialFieldName}`] = new Laya.Vector4(color.r / 255, color.g / 255, color.b / 255, 1.0);
                                let label = this[`${dataConfig.nodeName}`].owner.getChildByName("label");
                                label.text = `${dataConfig.labelTip}: r:${color.r},g:${color.g},b:${color.b}`;
                                let hexColor = Tools.__colorToHex(color);
                                let sprite = this[`${dataConfig.nodeName}`].owner.getChildByName("sprite");
                                sprite.graphics.drawPie(0, 0, 10, 0, 360, hexColor);
                                this.operatingMaterialData[`${dataConfig.materialFieldName}`] = [color.r / 255, color.g / 255, color.b / 255, 1.0];
                            }
                        });
                    };
                }
                let configValueArr = [
                    { nodeName: "imgSkinSPOcclusionStrength", labelTip: "遮挡强度", materialFieldName: "SPOcclusionStrength", labelDesc: "Occlusion_Strength 遮挡强度" },
                    { nodeName: "imgSkinSPMetallic", labelTip: "金属度", materialFieldName: "SPMetallic", labelDesc: "Metallic 金属度" },
                    { nodeName: "imgSkinSPSmoothness", labelTip: "光滑度", materialFieldName: "SPSmoothness", labelDesc: "Smoothness 光滑度" },
                    { nodeName: "imgSkinSPNoiseBump", labelTip: "噪点影响值1", materialFieldName: "SPNoiseBump", labelDesc: "NoiseBump 噪点影响值1，和2共同影响细节贴图颜色值" },
                    { nodeName: "imgSkinSPNoiseBumpTiling", labelTip: "细节贴图平铺度", materialFieldName: "SPNoiseBumpTiling", labelDesc: "Noise_Bump_Tiling 细节贴图平铺度" },
                    { nodeName: "imgSkinSPNoiseBumpBasicAO", labelTip: "噪点影响值2", materialFieldName: "SPNoiseBumpBasicAO", labelDesc: "Noise_Bump_BasicAO 噪点影响值2，和1共同影响细节贴图颜色值" },
                    { nodeName: "imgSkinSPShadowAtten", labelTip: "阴影强度", materialFieldName: "SPShadowAtten", labelDesc: "Shadow_Atten 阴影强度" },
                    { nodeName: "imgSkinSPEmissionColorBackIntensity", labelTip: "自发光底色强度", materialFieldName: "SPEmissionColorBackIntensity", labelDesc: "Emission_Color_Back_Intensity 自发光底色强度" },
                    { nodeName: "imgSkinSPBorderOffsetAO", labelTip: "偏移度", materialFieldName: "SPBorderOffsetAO", labelDesc: "Border_OffsetAO 偏移度" },
                    { nodeName: "imgSkinSPRedTranslucency", labelTip: "皮肤透光度影响值", materialFieldName: "SPRedTranslucency", labelDesc: "Red_Translucency 皮肤透光度影响值" },
                    { nodeName: "imgSkinSPRedTransShadow", labelTip: "皮肤暗部影响值", materialFieldName: "SPRedTransShadow", labelDesc: "Red_Trans_Shadow 皮肤暗部影响值" },
                    { nodeName: "imgSkinSPRedTransNormalDistortion", labelTip: "法线影响值", materialFieldName: "SPRedTransNormalDistortion", labelDesc: "Red_Trans_Normal_Distortion 法线影响值" },
                    { nodeName: "imgSkinSPRedTransScattering", labelTip: "透光散射1", materialFieldName: "SPRedTransScattering", labelDesc: "Red_Trans_Scattering 透光散射1，和2一起影响透光度" },
                    { nodeName: "imgSkinSPRedTransDirect", labelTip: "透光散射2", materialFieldName: "SPRedTransDirect", labelDesc: "Red_Trans_Direct 透光散射2，和1一起影响透光度" },
                    { nodeName: "imgSkinSPRedTransAmbient", labelTip: "反射度影响值", materialFieldName: "SPRedTransAmbient", labelDesc: "Red_Trans_Ambient 反射度影响值" },
                    { nodeName: "imgSkinSPRed3SOffset", labelTip: "法线偏移影响值", materialFieldName: "SPRed3SOffset", labelDesc: "Red_3SOffset 法线偏移影响值" },
                    { nodeName: "imgSkinnormalTextureScale", labelTip: "法线强度", materialFieldName: "normalTextureScale", labelDesc: "normalTextureScale 法线强度" },
                    { nodeName: "imgSkinLightResultIntensity", labelTip: "灯光效果强度", materialFieldName: "LightResultIntensity", labelDesc: "LightResultIntensity 灯光效果强度" },
                    { nodeName: "imgSkinspecularIntensity", labelTip: "高光强度", materialFieldName: "specularIntensity", labelDesc: "specularIntensity 高光强度" },
                    { nodeName: "imgMaskgridTextureScale", labelTip: "网络重复度", materialFieldName: "gridTextureScale", labelDesc: "gridTextureScale 网络重复度" },
                    { nodeName: "imgMaskshineTextureScale", labelTip: "亮片重复度", materialFieldName: "shineTextureScale", labelDesc: "shineTextureScale 亮片重复度" },
                    { nodeName: "imgMaskgridTextureIsMultiply", labelTip: "网络是否是叠加", materialFieldName: "gridTextureIsMultiply", labelDesc: "gridTextureIsMultiply 网络是否是叠加，默认不是，大于0.5代表是" },
                    { nodeName: "imgMaskshineTextureIsMultiply", labelTip: "亮片是否是叠加", materialFieldName: "shineTextureIsMultiply", labelDesc: "shineTextureIsMultiply 亮片是否是叠加，默认不是" },
                    { nodeName: "imageSliderAlphaTestValue", labelTip: "alphaTestValue", materialFieldName: "alphaTestValue", labelDesc: "AlphaTestValue alphaTestValue" },
                    { nodeName: "imgAlbedoTillingX", labelTip: "底图重复度X", materialFieldName: "AlbedoTillingX", labelDesc: "AlbedoTillingX 底图重复度" },
                    { nodeName: "imgAlbedoTillingY", labelTip: "底图重复度Y", materialFieldName: "AlbedoTillingY", labelDesc: "AlbedoTillingY 底图重复度" },
                    { nodeName: "imgSkinSPMetallic2", labelTip: "金属控制区域金属度", materialFieldName: "SPMetallic2", labelDesc: "Metallic2 金属度" },
                    { nodeName: "imgSkinSPSmoothness2", labelTip: "金属控制区域光滑度", materialFieldName: "SPSmoothness2", labelDesc: "Smoothness2 光滑度" },
                    { nodeName: "imgSkinSPEmissionColorBackIntensity2", labelTip: "金属控制区域自发光底色强度", materialFieldName: "SPEmissionColorBackIntensity2", labelDesc: "Emission_Color_Back_Intensity2 金属控制区域自发光底色强度" },
                    { nodeName: "imgSkinPlayerCustomChangeFlag", labelTip: "玩家是否可以更改", materialFieldName: "PlayerCustomChangeFlag", labelDesc: "玩家是否可以更改 默认不能，大于0.5代表能" },
                ];
                for (let k in configValueArr) {
                    let dataConfig = configValueArr[k];
                    let minMaxArr = this.operatingMaterial.getShaderValueRangeWithKey(SkinMaterial[dataConfig.materialFieldName.toUpperCase()]);
                    let slideValue = (this.operatingMaterial[`${dataConfig.materialFieldName}`] - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                    this.__registerAsSlider(this[`${dataConfig.nodeName}`], slideValue, minMaxArr, (value) => {
                        let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * value;
                        this.operatingMaterial[`${dataConfig.materialFieldName}`] = useValue;
                        let label = this[`${dataConfig.nodeName}`].getChildByName("label");
                        label.text = `[${dataConfig.labelTip}]: ${useValue.toFixed(4)}`;
                        this.operatingMaterialData[`${dataConfig.materialFieldName}`] = useValue;
                    }, () => {
                        this.labelSlideDesc.text = `${dataConfig.labelDesc || ""}`;
                    });
                }
                this.buttonOpque.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonOpqueCullNone.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_OPAQUE_CULL_NONE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffSingle.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffDouble.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_CUTOUT_CULL_NONE;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffTransparent.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT;
                    this.refreshRenderQueueShow(mat);
                };
                this.buttonCutOffTransparentDouble.fOnClick = () => {
                    this.operatingMaterial.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE;
                    this.operatingMaterialData.renderMode = CustomMaterialRenderMode.RENDERMODE_TRANSPARENT_CULL_NONE;
                    ;
                    this.refreshRenderQueueShow(mat);
                };
            }
            __registerAsSlider(node, initValue, minMaxArr, slideCallback, clickCallback, inputCallback) {
                let input = node.getChildByName("input");
                let bar = node.getChildAt(0);
                bar.x = node.width * initValue;
                let bDown = false;
                node.on(Laya.Event.MOUSE_OVER, node, (e) => {
                    console.log("-------e.MOUSE_OVER=");
                    if (clickCallback) {
                        clickCallback();
                    }
                });
                Tools.registerTouchHander(node, (e) => {
                    console.log("-------e.isClick=", e.isClick);
                    if (e.isBegin) {
                        if (Tools.isWorldLocaInNode(input, new Laya.Vector2(e.pos.x, e.pos.y))) {
                            return;
                        }
                        bDown = true;
                    }
                    if (bDown) {
                        let point = node.globalToLocal(new Laya.Point(e.pos.x, e.pos.y));
                        point.y = node.height / 2;
                        point.x = ul.clamp(point.x, 0, node.width);
                        bar.x = point.x;
                        bar.y = point.y;
                        let pValue = point.x / node.width;
                        slideCallback(pValue);
                        if (input) {
                            let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * pValue;
                            input.text = `${useValue}`;
                        }
                    }
                    if (e.isEnd || e.isCancel)
                        bDown = false;
                });
                if (input) {
                    let useValue = minMaxArr[0] + (minMaxArr[1] - minMaxArr[0]) * initValue;
                    input.text = `${useValue}`;
                    input.on(Laya.Event.INPUT, this, () => {
                        let inputValue = parseFloat(input.text) || 0;
                        let useValue = ul.clamp(inputValue, minMaxArr[0], minMaxArr[1]);
                        if (inputValue < minMaxArr[0] || inputValue > minMaxArr[1]) {
                            mgrTip.showMsgTip("数据超限");
                        }
                        inputCallback && inputCallback(useValue);
                        let slideValue = (useValue - minMaxArr[0]) / (minMaxArr[1] - minMaxArr[0]);
                        bar.x = node.width * slideValue;
                        slideCallback(slideValue);
                    });
                }
                slideCallback(initValue);
            }
        }
        class vCartonMaterial$2 extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.index);
            }
            fillByData(data) {
                this.data = data;
                let typeMaterial = mgrMaterial.getMaterialType(this.data.modelId, this.data.modelMaterialNo, this.data.skinName, this.data.index);
                let typeDesc = Const.MATERIAL_TYPE_2_DESC_DICT[typeMaterial];
                this.label.text = `${[typeDesc]}${this.data.name}`;
            }
        }
        class vEditorModelMaterialNoItem extends ReuseListItem {
            constructor() {
                super();
                let width = 340;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.fOnClick(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                let modelId = this.data.fGetCurrModelId();
                let materialDatas = mgrMaterial[`materialInfos`][modelId] || {};
                let count = Tools.getObjSize(materialDatas);
                let partData = mgrCfg.get_from_part_db(data.partId) || {};
                this.label.text = `${data.id}-${(data.id + 1) <= count ? "有" : "无"}-${data.partId}-${partData.name || ""}`;
            }
        }

        class vEditorSpineCheckScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorSpineCheckScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorSpineItem$2);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.reuseListAnimation = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxAnimationList.width, this.boxAnimationList.height);
                this.boxAnimationList.addChild(this.reuseListAnimation);
                this.reuseListAnimation.setItemClass(vEditorAnimationItem);
                this.reuseListAnimation.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_spine_db((k, v) => {
                    datas.push({
                        spineId: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
                let datas2 = [];
                for (let i = 1; i <= 30; i++) {
                    let animationId = "test";
                    if (!animationId)
                        break;
                    datas2.push({
                        animationId: animationId,
                        onClickAnimation: () => { }
                    });
                }
                this.reuseListAnimation.setDatas(datas2);
            }
            onClickSpine(spineId) {
                if (this.spine)
                    this.spine.destroy();
                this.spine = ULSkeleton.create(spineId, null, 60);
                this.addChild(this.spine);
                this.spine.pos(mgrDirector.width / 2, mgrDirector.height);
                let spineData = mgrCfg.get_from_spine_db(spineId);
                let datas = [];
                for (let i = 1; i <= 30; i++) {
                    let animationId = spineData[`l${i}`];
                    if (!animationId)
                        break;
                    datas.push({
                        movName: `l${i}`,
                        animationId: animationId,
                        onClickAnimation: this.onClickAnimation.bind(this),
                    });
                }
                this.reuseListAnimation.setDatas(datas);
            }
            onClickAnimation(animationId) {
                this.spine.playAnimation(animationId);
            }
        }
        class vEditorSpineItem$2 extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.spineId);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `${data.spineId}`;
            }
        }
        class vEditorAnimationItem extends ReuseListItem {
            constructor() {
                super();
                let width = 124;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickAnimation(this.data.animationId);
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `${data.movName}：${data.animationId}`;
            }
        }

        class vEditorStagePassCheck extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorStagePassCheck";
                this.exportNodeNames = [];
                this.targePersenValue = 1;
                this.curPartIds = [];
                this.curHashPartIds = {};
            }
            onOpened() {
                super.onOpened();
                this.buttonUseParam.fOnClick = this.onTouchButtonParam.bind(this),
                    this.buidUi();
                this.fillData();
            }
            onClosed() {
                super.onClosed();
            }
            buidUi() {
                this.reuseListStage = new ReuseList(1, 0, 20);
                this.reuseListStage.size(this.boxStageList.width, this.boxStageList.height);
                this.boxStageList.addChild(this.reuseListStage);
                this.reuseListStage.setItemClass(vStageCheckStage);
                this.reuseListStage.setVerticalMoveEnable(true);
                this.reuseListType = new ReuseList(1, 0, 20);
                this.reuseListType.size(this.boxTypeList.width, this.boxTypeList.height);
                this.boxTypeList.addChild(this.reuseListType);
                this.reuseListType.setItemClass(vStageCheckType);
                this.reuseListType.setVerticalMoveEnable(true);
                this.reuseListPart = new ReuseList(1, 0, 20);
                this.reuseListPart.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseListPart);
                this.reuseListPart.setItemClass(vStageCheckPart);
                this.reuseListPart.setVerticalMoveEnable(true);
                this.reuseListCurrentPart = new ReuseList(1, 0, 20);
                this.reuseListCurrentPart.size(this.boxCurrentPartList.width, this.boxCurrentPartList.height);
                this.boxCurrentPartList.addChild(this.reuseListCurrentPart);
                this.reuseListCurrentPart.setItemClass(vStageCheckCurrentPart);
                this.reuseListCurrentPart.setVerticalMoveEnable(true);
                this.reuseListSolution = new ReuseList(1, 0, 20);
                this.reuseListSolution.size(this.boxSolutionList.width, this.boxSolutionList.height);
                this.boxSolutionList.addChild(this.reuseListSolution);
                this.reuseListSolution.setItemClass(vStageSolution);
                this.reuseListSolution.setVerticalMoveEnable(true);
            }
            fillData() {
                let datas = [];
                mgrCfg.forDb_from_stage_db((k, v) => {
                    datas.push({
                        stageId: v.id,
                        fClickStage: this.selectStage.bind(this),
                    });
                });
                this.reuseListStage.setDatas(datas);
            }
            selectStage(stageId) {
                this.selectStageId = stageId;
                let stageData = mgrCfg.get_from_stage_db(stageId);
                this.labelStagePassScore.text = `通关分数: ${stageData.passScore}`;
                Tools.registerAsHSlider(this.imageSliderTargeScore, this.targePersenValue, "", (value) => {
                    this.labelTargetScore.text = `${Math.floor(value * 100)}% = ${Math.floor(stageData.passScore * value)}`;
                    this.targePersenValue = value;
                }, 2);
                let tempStr = "";
                for (let i = 0; i < stageData.tagWeights.length; i++) {
                    const element = stageData.tagWeights[i];
                    element > 0 && (tempStr += `${i + 1}=${element};`);
                }
                this.inputTagWeight.text = tempStr;
                tempStr = "";
                for (let i = 0; i < stageData.typeWeights.length; i++) {
                    const element = stageData.typeWeights[i];
                    element > 0 && (tempStr += `${i + 1}=${element};`);
                }
                this.inputTypeWeight.text = tempStr;
                let datas = [];
                mgrCfg.forDb_from_part_type_db((k, v) => {
                    datas.push({
                        typeId: v.id,
                        weight: stageData.typeWeights[v.id - 1],
                        fClickType: this.selectType.bind(this),
                    });
                });
                this.reuseListType.setDatas(datas);
                let typePartScores = [];
                mgrCfg.forDb_from_part_db((k, v) => {
                    if (!typePartScores[v.type])
                        typePartScores[v.type] = [];
                    typePartScores[v.type].push({
                        partId: v.id,
                        score: 0
                    });
                });
                for (const k in typePartScores) {
                    let data = typePartScores[k];
                    typePartScores[k] = Tools.sortArrayByField(data, "-score");
                }
                let solutionDatas = [];
                let index = 0;
                while (true) {
                    try {
                        let str = ``;
                        let score = 0;
                        let starStr = ``;
                        for (const k in typePartScores) {
                            let data = typePartScores[k];
                            if (data[index]) {
                                str += `${data[index].partId}+`;
                                score += data[index].score;
                                let partData = mgrCfg.get_from_part_db(data[index].partId);
                                starStr += `${partData.level}⭐+`;
                            }
                        }
                        str += `=${Math.floor(score)} ${Math.floor(score / stageData.passScore * 100)}%`;
                        starStr += `=${Math.floor(score)} ${Math.floor(score / stageData.passScore * 100)}%`;
                        if (score < stageData.passScore * this.targePersenValue) {
                            break;
                        }
                        solutionDatas.push({
                            text: str,
                            score: score,
                        });
                        solutionDatas.push({
                            text: starStr,
                            score: score + 0.01,
                        });
                        index++;
                    }
                    catch (error) {
                        break;
                    }
                }
                solutionDatas = Tools.sortArrayByField(solutionDatas, "score");
                this.reuseListSolution.setDatas(solutionDatas);
                this.reuseListSolution.setScroll(0);
            }
            selectType(typeId) {
                let curScore = 0;
                let stageData = mgrCfg.get_from_stage_db(this.selectStageId);
                let needScore = this.targePersenValue * stageData.passScore - curScore;
                let datas = [];
                mgrCfg.forDb_from_part_db((k, v) => {
                    let cScore = 0;
                    if (v.type == typeId) {
                        datas.push({
                            partId: v.id,
                            score: cScore,
                            fClickPart: this.selectPartId.bind(this),
                        });
                    }
                });
                datas = Tools.sortArrayByField(datas, "-score");
                this.reuseListPart.setDatas(datas);
                this.reuseListPart.setScroll(0);
            }
            selectPartId(partId) {
                let partData = mgrCfg.get_from_part_db(partId);
                let old = this.curHashPartIds[partData.type];
                if (!old) {
                    this.curPartIds.push(partId);
                    this.curHashPartIds[partData.type] = partId;
                }
                else {
                    let index = this.curPartIds.indexOf(old);
                    this.curPartIds.splice(index, 1);
                    this.curPartIds.push(partId);
                    this.curHashPartIds[partData.type] = partId;
                }
                let curScore = 0;
                this.labelCurScore.text = `当前分数:${curScore}`;
                let datas = [];
                for (let i = 0; i < this.curPartIds.length; i++) {
                    const element = this.curPartIds[i];
                    datas.push({
                        partId: element,
                        score: 0,
                        fClickCurrentPart: this.selectCurrentPart.bind(this),
                    });
                }
                this.reuseListCurrentPart.setDatas(datas);
            }
            selectCurrentPart(partId) {
                let partData = mgrCfg.get_from_part_db(partId);
                let old = this.curHashPartIds[partData.type];
                let index = this.curPartIds.indexOf(old);
                this.curPartIds.splice(index, 1);
                this.curHashPartIds[partData.type] = null;
                let curScore = 0;
                this.labelCurScore.text = `当前分数: ${curScore}`;
            }
            onTouchButtonParam() {
                let text = this.inputTagWeight.text;
                let weights = text.split(";");
                let tagWeights = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                for (let i = 0; i < weights.length; i++) {
                    const element = weights[i];
                    if (element && element.length > 0) {
                        let [i, w] = element.split("=");
                        tagWeights[parseInt(i) - 1] = parseFloat(w);
                    }
                }
                text = this.inputTypeWeight.text;
                weights = text.split(";");
                let typeWeights = [0, 0, 0, 0, 0, 0, 0, 0];
                for (let i = 0; i < weights.length; i++) {
                    const element = weights[i];
                    if (element && element.length > 0) {
                        let [i, w] = element.split("=");
                        typeWeights[parseInt(i) - 1] = parseFloat(w);
                    }
                }
                let stageData = mgrCfg.get_from_stage_db(this.selectStageId);
                stageData.tagWeights = tagWeights;
                stageData.typeWeights = typeWeights;
                this.selectStage(this.selectStageId);
            }
        }
        class vStageCheckStage extends ReuseListItem {
            constructor() {
                super();
                this.width = 100;
                this.height = 30;
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.anchorX = 0.5;
                this.addChild(this.label);
                this.label.x = this.width / 2;
                this.label.y = this.height / 2;
                Tools.registerTouchHander(this, (e) => {
                    if (!e.isClick)
                        return;
                    this.data.fClickStage(this.data.stageId);
                });
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `第${this.data.stageId}关`;
            }
        }
        class vStageCheckPart extends ReuseListItem {
            constructor() {
                super();
                this.width = 100;
                this.height = 30;
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.anchorX = 0.5;
                this.addChild(this.label);
                this.label.x = this.width / 2;
                this.label.y = this.height / 2;
                Tools.registerTouchHander(this, (e) => {
                    if (!e.isClick)
                        return;
                    this.data.fClickPart(this.data.partId);
                });
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `${this.data.partId}:${Math.floor(this.data.score)}`;
            }
        }
        class vStageCheckType extends ReuseListItem {
            constructor() {
                super();
                this.width = 100;
                this.height = 30;
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.anchorX = 0.5;
                this.addChild(this.label);
                this.label.x = this.width / 2;
                this.label.y = this.height / 2;
                Tools.registerTouchHander(this, (e) => {
                    if (!e.isClick)
                        return;
                    this.data.fClickType(this.data.typeId);
                });
            }
            fillByData(data) {
                this.data = data;
                let partTypeData = mgrCfg.get_from_part_type_db(this.data.typeId);
                this.label.text = partTypeData.name + " " + `${this.data.weight}`;
            }
        }
        class vStageCheckCurrentPart extends ReuseListItem {
            constructor() {
                super();
                this.width = 100;
                this.height = 30;
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.anchorX = 0.5;
                this.addChild(this.label);
                this.label.x = this.width / 2;
                this.label.y = this.height / 2;
                Tools.registerTouchHander(this, (e) => {
                    if (!e.isClick)
                        return;
                    this.data.fClickCurrentPart(this.data.partId);
                });
            }
            fillByData(data) {
                this.data = data;
                this.label.text = `${this.data.partId}:${Math.floor(this.data.score)}`;
            }
        }
        class vStageSolution extends ReuseListItem {
            constructor() {
                super();
                this.width = 510;
                this.height = 30;
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 20;
                this.label.anchorX = 1;
                this.addChild(this.label);
                this.label.x = this.width;
                this.label.y = this.height / 2;
            }
            fillByData(data) {
                this.data = data;
                this.label.text = this.data.text;
            }
        }

        class TimelineClip {
            constructor(track, data) {
                this.track = track;
                this.data = data;
                this.state = 0;
                this.clipElapsedTime = 0;
                this.startCount = 0;
            }
            dispose() {
                this.track = null;
                this.data = null;
                this.state = 2;
            }
            get start() {
                return this.data.start;
            }
            get end() {
                return this.data.end;
            }
            get duration() {
                return this.end - this.start;
            }
            get isUpdating() {
                return this.state == 1;
            }
            update(elapsedTime, bJump, bCrossAnim) {
                switch (this.state) {
                    case 0:
                        this.tryStart(elapsedTime, bCrossAnim);
                        break;
                    case 1:
                        this.tryUpdate(elapsedTime, bJump, bCrossAnim);
                        break;
                }
            }
            stop() {
                if (this.state == 1) {
                    this.state = 0;
                    this.onEnd();
                }
            }
            loopStart(elapsedTime) {
                if (this.state == 1) {
                    if (elapsedTime >= this.start) {
                        this.clipElapsedTime = elapsedTime - this.start;
                        this.onLoopStart();
                    }
                    else {
                        this.stop();
                    }
                }
            }
            onReset() {
                this.startCount = 0;
            }
            onStart(bCrossAnim) { }
            ;
            onUpdate() { }
            ;
            onEnd() { }
            ;
            onLoopStart() { }
            onJumpTo(bCrossAnim) { }
            tryStart(elapsedTime, bCrossAnim) {
                if (elapsedTime >= this.end)
                    return;
                if (elapsedTime >= this.start) {
                    this.clipElapsedTime = elapsedTime - this.start;
                    this.state = 1;
                    this.startCount++;
                    this.onStart(bCrossAnim);
                }
            }
            tryUpdate(elapsedTime, bJump, bCrossAnim) {
                this.clipElapsedTime = elapsedTime - this.start;
                if (elapsedTime >= this.end) {
                    this.stop();
                }
                else {
                    if (bJump) {
                        if (elapsedTime >= this.start) {
                            this.onJumpTo(bCrossAnim);
                        }
                        else {
                            this.stop();
                        }
                    }
                    this.onUpdate();
                }
            }
        }

        let DEBUG_TIME_LINE = false;
        class TimelineTools {
            static debugLog(msg1, msg2) {
                if (DEBUG_TIME_LINE) {
                    if (msg2) {
                        console.log("timeline:" + msg1, msg2, this.roundFloat(Laya.timer.currTimer / 1000), Laya.timer.currFrame);
                    }
                    else {
                        console.log("timeline:" + msg1, this.roundFloat(Laya.timer.currTimer / 1000), Laya.timer.currFrame);
                    }
                }
            }
            static getFileNameWithoutExt(file) {
                return file.replace(/(.*\/)*([^.]+).*/ig, "$2");
            }
            static findChild(root, childName) {
                if (!childName)
                    return null;
                if (!root)
                    return null;
                if (root.name == childName)
                    return root;
                for (let i = root.numChildren - 1; i >= 0; i--) {
                    let child = this.findChild(root.getChildAt(i), childName);
                    if (child) {
                        return child;
                    }
                }
            }
            static findChildPath(root, childPath) {
                if (childPath == null)
                    return null;
                if (!root)
                    return null;
                if (childPath == "")
                    return root;
                let paths = childPath.split("/");
                for (let i = 0; i < paths.length; i++) {
                    root = root.getChildByName(paths[i]);
                    if (!root)
                        return null;
                }
                return root;
            }
            static roundFloat(value) {
                value *= 1000;
                return Math.round(value) / 1000;
            }
            static clamp01(value) {
                if (value > 1)
                    return 1;
                else if (value < 0)
                    return 0;
                else
                    return value;
            }
            static clamp(value, min, max) {
                if (value < min)
                    return min;
                else if (value > max)
                    return max;
                else
                    return value;
            }
            static getComponentsInChildren(root, type, out) {
                out = out || [];
                for (let i = root.numChildren - 1; i >= 0; i--) {
                    let child = root.getChildAt(i);
                    if (child) {
                        let comp = child.getComponent(type);
                        if (comp) {
                            out.push(comp);
                        }
                        this.getComponentsInChildren(child, type, out);
                    }
                }
                return out;
            }
            static playParticleNode(node) {
                if (node.particleSystem) {
                    node.particleSystem.play();
                }
                for (let i = 0; i < node.numChildren; i++) {
                    this.playParticleNode(node.getChildAt(i));
                }
            }
            static stopParticleNode(node) {
                if (node.particleSystem) {
                    node.particleSystem.stop();
                }
                for (let i = 0; i < node.numChildren; i++) {
                    this.stopParticleNode(node.getChildAt(i));
                }
            }
        }
        TimelineTools.UP = new Laya.Vector3(0, 1, 0);

        class AnimationClip extends TimelineClip {
            get animator() {
                return this.track.bindObject;
            }
            onStart(bCrossAnim) {
                let animator = this.animator;
                if (!animator) {
                    console.error("AnimationClip：缺少Animator.");
                    return;
                }
                if (!this.data.assetPath) {
                    console.error("AnimationClip：缺少AnimationClip.");
                    return;
                }
                this.animName = TimelineTools.getFileNameWithoutExt(this.data.assetPath);
                let animState = animator.getControllerLayer(0).getAnimatorState(this.animName);
                if (!animState) {
                    let clip = Laya.loader.getRes(this.data.assetPath);
                    if (!clip) {
                        this.animName = null;
                        console.error("AnimationClip：未加载AnimationClip.");
                        return;
                    }
                    let state = new Laya.AnimatorState();
                    state.clip = clip;
                    state.clipStart = 0;
                    state.clipEnd = 1;
                    state.name = this.animName;
                    animator.getControllerLayer(0).addState(state);
                }
                animator.speed = this.data.timeScale;
                if (bCrossAnim) {
                    let t = TimelineTools.clamp(0.3 / this.duration, 0, 0.1);
                    animator.crossFade(this.animName, t, 0, this.normalizedTime);
                }
                else {
                    let track = this.track;
                    let crossTime = track.getCrossTime(this);
                    if (crossTime == 0) {
                        animator.play(this.animName, 0, this.normalizedTime);
                    }
                    else {
                        animator.crossFade(this.animName, crossTime / this.duration, 0, this.normalizedTime);
                    }
                }
                TimelineTools.debugLog("AnimationClip.start ", this.animName);
            }
            onEnd() {
                TimelineTools.debugLog("AnimationClip.end ", this.animName);
            }
            onLoopStart() {
                this.animator.crossFade(this.animName, 0.1, 0, this.normalizedTime);
            }
            onJumpTo(bCrossAnim) {
                if (bCrossAnim) {
                    let t = TimelineTools.clamp(0.3 / this.duration, 0, 0.1);
                    this.animator.crossFade(this.animName, t, 0, this.normalizedTime);
                }
                else {
                    this.animator.play(this.animName, 0, this.normalizedTime);
                }
            }
            get normalizedTime() {
                if (this.track.data.inClipMode) {
                    var time = this.clipElapsedTime / this.duration;
                }
                else {
                    var time = this.track.director.elapsedTime / this.end;
                }
                return TimelineTools.clamp01(time);
            }
        }

        class TrackBase {
            constructor(director, data) {
                this.clips = [];
                this.director = director;
                this.data = data;
            }
            get name() {
                return this.data.name;
            }
            dispose() {
                if (this.clips) {
                    for (let i = 0; i < this.clips.length; i++) {
                        this.clips[i].dispose();
                    }
                    this.clips = null;
                }
                this.bindObject = null;
            }
            getClipInfo() {
                return null;
            }
            createClip() {
                let clipInfo = this.getClipInfo();
                if (clipInfo) {
                    let clipClass = clipInfo.clipClass;
                    let clipList = clipInfo.clipList;
                    if (clipClass && clipList) {
                        for (let i = 0; i < clipList.length; i++) {
                            let clip = new clipClass(this, clipList[i]);
                            this.clips.push(clip);
                        }
                    }
                }
            }
            genericBinding(obj) {
                this.bindObject = obj;
            }
            reset() {
                for (let i = 0; i < this.clips.length; i++) {
                    this.clips[i].onReset();
                }
            }
            stop() {
                for (let i = 0; i < this.clips.length; i++) {
                    this.clips[i].stop();
                }
            }
            update(elapsedTime, bJump, bCrossAnim) {
                for (let i = 0; i < this.clips.length; i++) {
                    this.clips[i].update(elapsedTime, bJump, bCrossAnim);
                }
            }
            loopStart(elapsedTime) {
                for (let i = 0; i < this.clips.length; i++) {
                    this.clips[i].loopStart(elapsedTime);
                }
            }
        }

        class AnimationTrack extends TrackBase {
            dispose() {
                if (this.bindObject) {
                    let controller = this.bindObject.getControllerLayer(0);
                    if (controller) {
                        controller.playOnWake = this.defaultPlayOnWake;
                    }
                }
                super.dispose();
            }
            reset() {
                var bBindSuc = false;
                if (this.data.owner) {
                    let child = this.director.findChildPath(this.data.owner);
                    if (child) {
                        let animator = child.getComponent(Laya.Animator);
                        if (!animator) {
                            animator = child.addComponent(Laya.Animator);
                        }
                        animator.speed = 0;
                        this.genericBinding(animator);
                        bBindSuc = true;
                    }
                }
                if (!bBindSuc) {
                    console.error("AnimationTrack: 缺少Animator! owner:", this.data.owner);
                }
                super.reset();
            }
            getClipInfo() {
                return { clipClass: AnimationClip, clipList: this.data.clipList };
            }
            genericBinding(obj) {
                if (obj) {
                    super.genericBinding(obj);
                    let controller = obj.getControllerLayer(0);
                    if (!controller) {
                        controller = new Laya.AnimatorControllerLayer("default");
                        obj.addControllerLayer(controller);
                    }
                    this.defaultPlayOnWake = controller.playOnWake;
                    controller.playOnWake = false;
                }
            }
            getCrossTime(curClip) {
                for (let i = 0; i < this.clips.length; i++) {
                    let clip = this.clips[i];
                    if (clip.start < curClip.start && clip.end > curClip.start) {
                        return clip.end - curClip.start;
                    }
                }
                return 0;
            }
        }

        class ActivationClip extends TimelineClip {
            get node() {
                return this.track.bindObject;
            }
            onReset() {
                super.onReset();
                TimelineTools.stopParticleNode(this.node);
                this.node.active = false;
            }
            onStart() {
                this.node.active = true;
                TimelineTools.playParticleNode(this.node);
                TimelineTools.debugLog("ActivationClip.start ", this.node.name);
                let arr = this.track.director["trackList"];
                for (let index = 0; index < arr.length; index++) {
                    var anim = arr[index];
                    if (anim instanceof AnimationTrack) {
                        for (let i = 0; i < anim.clips.length; i++) {
                            const clip = anim.clips[i];
                            if (clip.state == 1) {
                                clip.animator.play(clip.animName, 0, clip.normalizedTime);
                            }
                        }
                    }
                }
            }
            onEnd() {
                TimelineTools.stopParticleNode(this.node);
                this.node.active = false;
                TimelineTools.debugLog("ActivationClip.end ", this.node.name);
            }
        }

        class ActivationTrack extends TrackBase {
            reset() {
                var bBindSuc = false;
                if (this.data.owner) {
                    let child = this.director.findChildPath(this.data.owner);
                    if (child) {
                        this.genericBinding(child);
                        bBindSuc = true;
                    }
                }
                if (!bBindSuc) {
                    console.error("ActivationTrack: 缺少Node! owner:", this.data.owner);
                }
                super.reset();
            }
            getClipInfo() {
                return { clipClass: ActivationClip, clipList: this.data.clipList };
            }
        }

        class CinemachineClip extends TimelineClip {
            onReset() {
                super.onReset();
                var data = this.data;
                let cvCameraNode = this.track.director.findChildPath(data.camera);
                if (!cvCameraNode) {
                    console.error("找不到VirtualCamera.", data.camera);
                    return;
                }
                if (this.camera && !this.camera.destroyed) {
                    this.camera.active = false;
                    return;
                }
                let newCamera = new Laya.Camera(0, 0.01, 1000);
                cvCameraNode.addChild(newCamera);
                newCamera.transform.localRotationEuler = new Laya.Vector3(0, 180, 0);
                newCamera.fieldOfView = data.fov;
                newCamera.name = "auto_create_" + data.displayName;
                newCamera.useOcclusionCulling = false;
                newCamera.enableHDR = false;
                newCamera.active = false;
                this.camera = newCamera;
                if (data.lookAt) {
                    this.lookAt = this.track.director.findChildPath(data.lookAt);
                }
            }
            onStart() {
                if (this.camera) {
                    this.camera.active = true;
                    TimelineTools.debugLog("CinemachineClip.start:", this.camera.name);
                }
                else {
                    console.log("CinemachineClip.start: 没有镜头.", this.data.camera);
                }
            }
            onUpdate() {
                if (this.lookAt && this.camera) {
                    this.camera.transform.lookAt(this.lookAt.transform.position, TimelineTools.UP, false);
                }
            }
            onEnd() {
                if (this.camera) {
                    this.camera.active = false;
                    TimelineTools.debugLog("CinemachineClip.end:", this.camera.name);
                }
                else {
                    console.log("CinemachineClip.end: 没有镜头.", this.data.camera);
                }
            }
        }

        class CinemachineTrack extends TrackBase {
            reset() {
                var bBindSuc = false;
                if (this.data.owner) {
                    let child = this.director.findChildPath(this.data.owner);
                    if (child) {
                        this.genericBinding(child);
                        bBindSuc = true;
                    }
                }
                if (!bBindSuc) {
                    console.error("CinemachineTrack: 缺少Camera! owner:", this.data.owner);
                }
                super.reset();
            }
            getClipInfo() {
                return { clipClass: CinemachineClip, clipList: this.data.clipList };
            }
            genericBinding(obj) {
                super.genericBinding(obj);
                obj.active = false;
            }
        }

        var ControlType;
        (function (ControlType) {
            ControlType[ControlType["ChildNode"] = 0] = "ChildNode";
            ControlType[ControlType["Resource"] = 1] = "Resource";
        })(ControlType || (ControlType = {}));
        class ControlClip extends TimelineClip {
            onReset() {
                super.onReset();
                var data = this.data;
                this.controlType = data.assetPath ? ControlType.Resource : ControlType.ChildNode;
                if (this.controlType == ControlType.ChildNode) {
                    this._node = this.track.director.findChildPath(data.parent);
                    if (this._node) {
                        TimelineTools.stopParticleNode(this._node);
                        this._node.active = false;
                    }
                    else {
                        console.error("找不到需要控制的子节点:", data.parent);
                    }
                }
            }
            onStart() {
                let data = this.data;
                if (this.controlType == ControlType.Resource) {
                    if (this._node) {
                        return;
                    }
                    let res = Laya.loader.getRes(data.assetPath);
                    if (!res) {
                        console.error("ControlClip.onStart: 节点未加载:", data.assetPath);
                        return;
                    }
                    this._node = Laya.Sprite3D.instantiate(res);
                    if (data.parent) {
                        let parentNode = this.track.director.findChildPath(data.parent);
                        if (!parentNode) {
                            this._node.destroy();
                            TimelineTools.debugLog("ControlClip.onStart: 找不到parent:", data.parent);
                            return;
                        }
                        parentNode.addChild(this._node);
                    }
                    else {
                        this.track.director.addChildToRoot(this._node);
                    }
                }
                else {
                    if (this._node) {
                        this._node.active = true;
                    }
                    else {
                        return;
                    }
                }
                TimelineTools.playParticleNode(this._node);
                TimelineTools.debugLog("ControlClip.start ", this._node.name);
            }
            onEnd() {
                if (this.controlType == ControlType.Resource) {
                    if (this._node) {
                        TimelineTools.debugLog("ControlClip.end ", this._node.name);
                        this._node.destroy();
                        this._node = null;
                    }
                }
                else {
                    if (this._node) {
                        TimelineTools.debugLog("ControlClip.end ", this._node.name);
                        TimelineTools.stopParticleNode(this._node);
                        this._node.active = false;
                    }
                }
            }
            onLoopStart() {
            }
            onJumpTo(bCrossAnim) {
            }
        }

        class ControlTrack extends TrackBase {
            getClipInfo() {
                return { clipClass: ControlClip, clipList: this.data.clipList };
            }
        }

        class PlayableDirector extends Laya.Sprite3D {
            constructor() {
                super(...arguments);
                this.elapsedTime = 0;
                this.endTime = 0;
                this.stopUpdateOnlyWhenFinish = false;
                this.loopStartFrame = -1;
                this.loopEndFrame = -1;
                this.trackList = [];
            }
            destroy(destoryChild) {
                if (this.trackList) {
                    for (let i = 0; i < this.trackList.length; i++) {
                        this.trackList[i].dispose();
                    }
                    this.trackList = null;
                }
                this.timelineAsset = null;
                if (this.timelineModel) {
                    this.timelineModel.destroy();
                    this.timelineModel = null;
                }
                super.destroy(destoryChild);
            }
            load(timelineAssetUrl, callback) {
                if (!timelineAssetUrl) {
                    console.error("load: timelineAssetUrl不能为空!");
                    return;
                }
                Laya.loader.load(timelineAssetUrl, Laya.Handler.create(this, this.onTimelineDataLoaded, [timelineAssetUrl, callback]), null, Laya.Loader.JSON);
            }
            onTimelineDataLoaded(timelineAssetUrl, callback) {
                if (this.destroyed)
                    return;
                let timelineAsset = Laya.loader.getRes(timelineAssetUrl);
                Laya.Sprite3D.load(timelineAsset.modelUrl, Laya.Handler.create(this, this.onModelLoaded, [timelineAsset, callback]));
            }
            onModelLoaded(timelineAsset, callback) {
                if (this.destroyed)
                    return;
                let timelineModel = Laya.Sprite3D.instantiate(Laya.loader.getRes(timelineAsset.modelUrl));
                this.init(timelineAsset, timelineModel);
                let resList = this.getDepRes();
                Laya.loader.create(resList, Laya.Handler.create(this, () => {
                    if (this.destroyed)
                        return;
                    this.event("LOADED");
                    callback && callback();
                }));
            }
            init(timelineAsset, timelineModel) {
                if (this.destroyed)
                    return;
                if (this.timelineAsset) {
                    console.error("PlayableDirector.createTracks: 重复加载");
                }
                this.timelineAsset = timelineAsset;
                this.timelineModel = timelineModel;
                if (!timelineAsset || !timelineModel) {
                    console.error("PlayableDirector.createTracks：资源加载异常.");
                    return;
                }
                this.addChild(timelineModel);
                this.fps = timelineAsset.fps;
                this.version = timelineAsset.version;
                this.calclEndTime();
                this.createTrack(CinemachineTrack, timelineAsset.cinemachineTrackList);
                this.createTrack(ControlTrack, timelineAsset.controlTrackList);
                this.createTrack(ActivationTrack, timelineAsset.activationTrackList);
                this.createTrack(AnimationTrack, timelineAsset.animationTrackList);
            }
            calclEndTime() {
                let maxTime = 0;
                function getMaxTime(list) {
                    if (!list)
                        return;
                    for (var i = 0; i < list.length; i++) {
                        maxTime = Math.max(maxTime, list[i].end);
                    }
                }
                let data = this.timelineAsset;
                for (let i = 0; i < data.animationTrackList.length; i++) {
                    getMaxTime(data.animationTrackList[i].clipList);
                }
                for (let i = 0; i < data.cinemachineTrackList.length; i++) {
                    getMaxTime(data.cinemachineTrackList[i].clipList);
                }
                for (let i = 0; i < data.controlTrackList.length; i++) {
                    getMaxTime(data.controlTrackList[i].clipList);
                }
                for (let i = 0; i < data.activationTrackList.length; i++) {
                    getMaxTime(data.activationTrackList[i].clipList);
                }
                this.endTime = maxTime;
            }
            createTrack(trackClass, dataList) {
                for (let i = 0; i < dataList.length; i++) {
                    let data = dataList[i];
                    let track = new trackClass(this, data);
                    track.createClip();
                    track.reset();
                    this.trackList.push(track);
                }
            }
            getDepRes() {
                if (!this.timelineAsset) {
                    console.warn("PlayableDirector.getDepRes: 资源还未加载");
                    return [];
                }
                let resList = [];
                for (var i = 0; i < this.timelineAsset.animationTrackList.length; i++) {
                    let item = this.timelineAsset.animationTrackList[i];
                    for (var j = 0; j < item.clipList.length; j++) {
                        let clip = item.clipList[j];
                        if (clip.assetPath) {
                            resList.push({ url: clip.assetPath, type: Laya.Loader.ANIMATIONCLIP });
                        }
                    }
                }
                for (var i = 0; i < this.timelineAsset.controlTrackList.length; i++) {
                    let item = this.timelineAsset.controlTrackList[i];
                    for (var j = 0; j < item.clipList.length; j++) {
                        let clip = item.clipList[j];
                        if (clip.assetPath) {
                            resList.push({ url: clip.assetPath, type: Laya.Loader.HIERARCHY });
                        }
                    }
                }
                return resList;
            }
            addChildToRoot(child) {
                if (this.timelineModel) {
                    this.timelineModel.addChild(child);
                }
            }
            findChildPath(childPath) {
                return TimelineTools.findChildPath(this.timelineModel, childPath);
            }
            getChildPath(child, root) {
                if (root == child)
                    return "";
                root = root || this.timelineModel;
                if (!root)
                    return null;
                var path = child.name;
                var parent = child.parent;
                while (parent != root) {
                    if (!parent) {
                        console.error("getChildPath 节点不在根节点上.");
                        return null;
                    }
                    else {
                        path = parent.name + "/" + path;
                        parent = parent.parent;
                    }
                }
                return path;
            }
            findChild(childName) {
                return TimelineTools.findChild(this.timelineModel, childName);
            }
            getGenericBinding(trackName) {
                for (let i = 0; i < this.trackList.length; i++) {
                    if (this.trackList[i].name == trackName) {
                        return this.trackList[i].bindObject;
                    }
                }
            }
            setGenericBinding(trackName, obj) {
                for (let i = 0; i < this.trackList.length; i++) {
                    if (this.trackList[i].name == trackName) {
                        this.trackList[i].genericBinding(obj);
                    }
                }
            }
            getTrack(trackType) {
                let arr = [];
                for (let i = 0; i < this.trackList.length; i++) {
                    if (this.trackList[i] instanceof trackType) {
                        arr.push(this.trackList[i]);
                    }
                }
                return arr;
            }
            replaceNode(nodePath, newNode, destroyOld) {
                let oldNode = this.findChildPath(nodePath);
                if (!oldNode) {
                    console.error("changeNode 找不到替换节点:", nodePath);
                    return;
                }
                function isParent(child, parent) {
                    if (!child || !child.parent)
                        return false;
                    if (child.parent == parent)
                        return true;
                    return isParent(child.parent, parent);
                }
                let allBindObjInfo = [];
                for (let i = 0; i < this.trackList.length; i++) {
                    let bindObj = this.trackList[i].bindObject;
                    if (bindObj) {
                        let node;
                        if (bindObj instanceof Laya.Animator) {
                            node = bindObj.owner;
                        }
                        else {
                            node = bindObj;
                        }
                        if (isParent(node, oldNode)) {
                            let parentPath = this.getChildPath(node.parent, oldNode);
                            let nodePath = parentPath + "/" + node.name;
                            if (!parentPath || parentPath.length == 0) {
                                nodePath = node.name;
                            }
                            allBindObjInfo.push({ parentPath: parentPath, nodePath: nodePath, node: node });
                        }
                    }
                }
                for (let i = allBindObjInfo.length - 1; i >= 0; i--) {
                    if (TimelineTools.findChildPath(newNode, allBindObjInfo[i].nodePath)) {
                        TimelineTools.debugLog("发现相同的节点:", allBindObjInfo[i].nodePath);
                        allBindObjInfo.splice(i, 1);
                    }
                }
                for (let i = allBindObjInfo.length - 1; i >= 0; i--) {
                    let child = allBindObjInfo[i];
                    for (let j = allBindObjInfo.length - 1; j >= 0; j--) {
                        if (i == j)
                            continue;
                        let parent = allBindObjInfo[j];
                        if (~child.nodePath.indexOf(parent.nodePath)) {
                            TimelineTools.debugLog("发现子节点", child.nodePath);
                            allBindObjInfo.splice(i, 1);
                            break;
                        }
                    }
                }
                for (let i = 0; i < allBindObjInfo.length; i++) {
                    let parent = TimelineTools.findChildPath(newNode, allBindObjInfo[i].parentPath);
                    if (parent) {
                        allBindObjInfo[i].newParent = parent;
                    }
                    else {
                        console.error("changeNode 找不到节点:", allBindObjInfo[i].parentPath);
                        return;
                    }
                }
                newNode.name = oldNode.name;
                function moveNode(node, newParent) {
                    let idx = node.parent.getChildIndex(node);
                    newParent.addChildAt(node, idx);
                }
                oldNode.parent.addChildAt(newNode, oldNode.parent.getChildIndex(oldNode));
                newNode.transform.position = oldNode.transform.position;
                oldNode.removeSelf();
                for (let i = 0; i < allBindObjInfo.length; i++) {
                    moveNode(allBindObjInfo[i].node, allBindObjInfo[i].newParent);
                }
                if (destroyOld)
                    oldNode.destroy();
                this.reset();
                return allBindObjInfo;
            }
            play() {
                if (!this.timelineAsset) {
                    console.error("PlayableDirector.start: 资源尚未加载.");
                    return;
                }
                this.elapsedTime = 0;
                this.reset();
                this.update();
                Laya.timer.frameLoop(1, this, this.update, null, true);
                this.event("START");
                TimelineTools.debugLog("PlayableDirector.play");
            }
            reset() {
                for (let i = 0; i < this.trackList.length; i++) {
                    this.trackList[i].reset();
                }
            }
            update() {
                let deltaTime = Laya.timer.delta / 1000;
                this.elapsedTime += deltaTime;
                if (this.elapsedTime >= this.endTime) {
                    if (this.stopUpdateOnlyWhenFinish) {
                        this.clearTime();
                        this.event("STOPPED");
                        return;
                    }
                }
                if (this.loopEndFrame > 0) {
                    if (this.elapsedTime >= TimelineTools.roundFloat(this.loopEndFrame / this.fps)) {
                        this.elapsedTime = TimelineTools.roundFloat(this.loopStartFrame / this.fps);
                        let list = this.trackList;
                        for (let i = 0; i < list.length; i++) {
                            let track = list[i];
                            track.loopStart(this.elapsedTime);
                        }
                        this.event("LOOP_START");
                    }
                }
                this.updateTrack(false, false);
            }
            updateTrack(isJump, bCrossAnim) {
                let list = this.trackList;
                for (let i = 0; i < list.length; i++) {
                    let track = list[i];
                    track.update(this.elapsedTime, isJump, bCrossAnim);
                }
                if (this.elapsedTime >= this.endTime) {
                    this.stop();
                }
            }
            stop() {
                this.clearTime();
                for (let i = 0; i < this.trackList.length; i++) {
                    this.trackList[i].stop();
                }
                this.event("STOPPED");
                TimelineTools.debugLog("PlayableDirector.stop");
            }
            clearTime() {
                Laya.timer.clearAll(this);
            }
            pause() {
            }
            setLoopFrame(startFrame, endFrame) {
                if (startFrame < 0) {
                    console.error("PlayableDirector.setLoop: startFrame < 0!");
                    return;
                }
                if (endFrame <= startFrame) {
                    console.error("PlayableDirector.setLoop: endFrame <= startFrame!");
                    return;
                }
                this.loopStartFrame = startFrame;
                this.loopEndFrame = endFrame;
            }
            jumpTo(frame, bCrossAnim = true) {
                this.loopStartFrame = -1;
                this.loopEndFrame = -1;
                this.elapsedTime = TimelineTools.roundFloat(frame / this.fps);
                this.updateTrack(true, bCrossAnim);
            }
            createLight(lightColor) {
                let tracks = this.getTrack(CinemachineTrack);
                for (let i = 0; i < tracks.length; i++) {
                    let track = tracks[i];
                    let clips = track.clips;
                    for (let i = 0; i < clips.length; i++) {
                        let camera = clips[i].camera;
                        if (camera) {
                            let light = camera.getChildByName("auto_create_light");
                            if (light) {
                                console.warn("PlayableDirector.createLight：灯光已存在.");
                            }
                            else {
                                light = camera.addChild(new Laya.DirectionLight());
                                light.name = "auto_create_light";
                            }
                            light.color = lightColor || new Laya.Vector3(1, 1, 1);
                        }
                    }
                }
            }
        }

        class vEditorTimelineTestScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vEditorTimelineTestScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                let params = {
                    roleId: mgrRole.showingRoleId
                };
                this.avatar = new RoleAvatar(params);
                this.add3DEffectAtBack(this.avatar, 0);
                this.avatar.fillByPartIds(mgrPart.getLastClothes(mgrRole.showingRoleId));
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.reuseListSpine = new ReuseList(1, 0, 20);
                this.reuseListSpine.size(this.boxSpineList.width, this.boxSpineList.height);
                this.boxSpineList.addChild(this.reuseListSpine);
                this.reuseListSpine.setItemClass(vEditorTimelineCheckItem);
                this.reuseListSpine.setVerticalMoveEnable(true);
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                let datas = [];
                mgrCfg.forDb_from_timeline_template_db((k, v) => {
                    datas.push({
                        id: v.id,
                        onClickSpine: this.onClickSpine.bind(this),
                    });
                });
                this.reuseListSpine.setDatas(datas);
            }
            onClickSpine(id) {
                this.playTimeline(null);
            }
            playTimeline(callback) {
                let director = new PlayableDirector();
                director.setLoopFrame(242, 243);
                director.load(`res/_3d_v1/res/Conventional/dengchang.json`, () => {
                    this.add3DEffectAtBack(director);
                    this.cameraBack.active = false;
                    let replaceNodes = director.replaceNode("Director/role", this.avatar, true);
                    director.play();
                    director.on("STOPPED", this, () => {
                        for (let i = 0; i < replaceNodes.length; i++) {
                            const element = replaceNodes[i];
                            element.node.destroy();
                        }
                        this.cameraBack.active = true;
                        this.add3DEffectAtBack(this.avatar);
                        director.removeSelf();
                        director.destroy();
                        callback && callback();
                    });
                    director.on("LOOP_START", this, () => {
                        Tools.registerTouchHander(this, (e) => {
                            if (e.isBegin) {
                                Tools.unRegisterTouchHander(this);
                                director.jumpTo(244, false);
                            }
                        });
                    });
                });
            }
        }
        class vEditorTimelineCheckItem extends ReuseListItem {
            constructor() {
                super();
                let width = 500;
                let height = 30;
                this.size(width, height);
                this.anchorX = 0;
                this.anchorY = 0;
                this.label = new Laya.Label;
                this.label.fontSize = 24;
                this.label.color = `#ffffff`;
                this.addChild(this.label);
                this.button = this.label.addComponent(ScaleButton);
                this.button.fOnClick = this.onTouchButton.bind(this);
            }
            onTouchButton() {
                if (!this.data)
                    return;
                this.data.onClickSpine(this.data.id);
            }
            fillByData(data) {
                this.data = data;
                let template = mgrCfg.get_from_timeline_template_db(data.id);
                this.label.text = `id：${data.id}-名字:${template.name || ""}}`;
            }
        }

        class vGridAd extends ViewBase {
            constructor(context) {
                super(context);
                this.crossRecommendState = false;
                this._bRadioPass = false;
                this._bShow = false;
                this.context = context;
                let ratio = mgrSdk.getCopNumberValueByKey(this.context.copStr);
                this._bRadioPass = Mathf.random(0, 100) <= ratio;
                this.onCreateComplete();
            }
            destroy() {
                super.destroy();
                this.closeGridAd();
            }
            onCreateComplete() {
                Timer.callLoop(0.1, () => {
                    this.refreshState();
                }, this);
            }
            refreshState() {
                if (this.destroyed)
                    return;
                if (DialogBase.ShowingDialog.length > 0) {
                    if (this.crossRecommendState) {
                        this.crossRecommendState = false;
                        this.closeGridAd();
                    }
                }
                else {
                    if (!this.crossRecommendState) {
                        this.crossRecommendState = true;
                        this.openGridAd();
                    }
                }
            }
            openGridAd() {
                if (!this._bRadioPass) {
                    return;
                }
                if (this._bShow) {
                    return;
                }
                this._bShow = true;
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/openAdv",
                    data: {
                        advId: this.context.advId,
                    },
                });
            }
            closeGridAd() {
                if (!this._bRadioPass) {
                    return;
                }
                if (!this._bShow) {
                    return;
                }
                this._bShow = false;
                mgrSdk.sendMsgToSdk({
                    cmd: "/c/closeAdv",
                    data: {
                        advId: this.context.advId,
                    },
                });
            }
        }

        const CAMERA_PRARAM_INIT$3 = {
            fov: 30,
            position: new Laya.Vector3(0, 1.17, 2.674),
            rotation: new Laya.Vector3(-2.5),
            lerpValue: 0.1,
        };
        class vFreedomRoomScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vFreedomRoomScene";
                this.exportNodeNames = [];
                this.BODY_IDLE_ANI = "hz_idle-hz_idle";
                this.context.roleId = this.context.roleId || mgrRole.showingRoleId;
            }
            onOpened() {
                super.onOpened();
                mgrSound.play(4);
                this.spriteBg.zOrder = -5;
                mgrTip.showLoadingTip("vRoomDialog_loadingAvatar", null, null, true);
                this.buildScene(() => {
                    this.roleAvatar.registerAllLoadEndCallback(() => {
                        Timer.callLater(0.1, () => {
                            if (!this || this.destroyed) {
                                return;
                            }
                            this.roleAvatar.playDefaultIdleAnimation();
                            let panel = new vRoomDialog({
                                avatar: this.roleAvatar,
                                cameraFollow: this.cameraFollow,
                                stageId: this.context.stageId,
                                backSceneName: this.context.backSceneName,
                                nextDialogName: this.context.nextDialogName,
                                roleId: this.context.roleId,
                                cardId: this.context.cardId,
                                partIds: this.context.partIds,
                                bRemakeCardResult: this.context.bRemakeCardResult,
                                fOnClose: this.context.fOnClose,
                                fOnSure: this.context.fOnSure,
                                fromSystemModel: this.context.fromSystemModel
                            });
                            panel.name = "vRoomDialog";
                            this.nodeResource.addChild(panel);
                            panel.x = this.nodeResource.width / 2;
                            panel.y = this.nodeResource.height / 2;
                            panel.zOrder = 10;
                            panel.manualSendAnimationFinished();
                            mgrTip.tryShowFullScreenMoreGameFixed("b_fsmgfs_free_dress");
                        }, this);
                    });
                });
                this.addGridAd();
            }
            onClosed() {
                super.onClosed();
                mgrTip.hideLoadingTip("vRoomDialog_loadingAvatar");
            }
            getPreLoadModelIds() {
                let arr = ["huanzhuang_bg"];
                let lastDressPartIds = mgrPart.getLastClothes(mgrRole.showingRoleId, true);
                for (let k in lastDressPartIds) {
                    let partId = lastDressPartIds[k];
                    let partData = mgrCfg.get_from_part_db(partId);
                    if (!!partData && !!partData.modelId) {
                        arr.push(partData.modelId);
                    }
                }
                return arr;
            }
            getPreLoadAnimationIds() {
                return [
                    this.BODY_IDLE_ANI
                ];
            }
            buildScene(callback) {
                let mapBg = mgrLoader.Pool.getModel("huanzhuang_bg");
                this.add3DEffectAtBack(mapBg);
                let cf = this.cameraBack.getComponent(CameraFollow);
                cf.lookMode = E_CAMERA_MODE.fixMode;
                cf.fov = CAMERA_PRARAM_INIT$3.fov;
                cf.position = CAMERA_PRARAM_INIT$3.position;
                cf.endRotation = CAMERA_PRARAM_INIT$3.rotation;
                cf.lerpValue = 1;
                cf.onLateUpdate();
                this.roleAvatar = new RoleAvatar({ roleId: this.context.roleId });
                this.roleAvatar.setIdleId(this.BODY_IDLE_ANI);
                this.add3DEffectAtBack(this.roleAvatar, 0);
                let lastDressPartIds = mgrPart.getLastClothes(mgrRole.showingRoleId, true);
                this.roleAvatar.fillByPartIds(lastDressPartIds);
                let holdPartData = null;
                for (let k in lastDressPartIds) {
                    let tId = lastDressPartIds[k];
                    let tPartData = mgrCfg.get_from_part_db(tId);
                    if (tPartData.type == PartType.handHold) {
                        holdPartData = tPartData;
                        break;
                    }
                }
                if (!!holdPartData) {
                    this.roleAvatar.setIdleId(holdPartData.holdIdleAnimation);
                }
                else {
                    this.roleAvatar.setIdleId(this.BODY_IDLE_ANI);
                }
                this.cameraFollow = this.cameraBack.getComponent(CameraFollow);
                this.roleAvatar.registerLoadEndCallback(() => {
                    callback();
                });
            }
            addGridAd() {
                let gridAd = new vGridAd({ advId: "20001", copStr: "grid_ad_ratio2" });
                this.addChild(gridAd);
            }
        }

        const DEBUG$3 = false;
        class vGridAdNode extends Laya.Sprite {
            constructor(index, panelName) {
                super();
                this.bOpened = false;
                this.bEnabled = true;
                this.msgHandler = new MsgHandler();
                this.index = 0;
                this.bShowGrid = true;
                this.size(140, 200);
                this.index = index;
                this.panelName = panelName;
                let ratios = mgrSdk.getCopByKey("grid_ad_ratio").split(";");
                if (!Mathf.randomEnable(parseInt(ratios[this.index]))) {
                    this.bEnabled = false;
                }
                this.onCreateComplete();
            }
            onCreateComplete() {
                this.msgHandler.registerListeners({
                    "PANEL_STACK_CHANGED": this.onMsgPanelStackChanged.bind(this),
                });
                this.msgHandler.startProcMsg();
                this.refreshState();
            }
            destroy() {
                this.msgHandler.stopProcMsg();
                super.destroy();
                this.closeGridAd();
            }
            setshowGrid(bShow) {
                this.bShowGrid = bShow;
                this.refreshState();
            }
            refreshState() {
                if (!this.bEnabled)
                    return;
                if (this.destroyed)
                    return;
                if (DEBUG$3)
                    console.log("vGridAdNode.refreshState", this.panelName);
                let topViewName = this.getTopViewName();
                let bFocus = (this.panelName == topViewName) && this.bShowGrid;
                if (DialogBase.ShowingDialog.length > 0)
                    bFocus = false;
                this.onFocus(bFocus);
            }
            getTopViewName() {
                let panelName = mgrDirector.getCur2DSceneName();
                return panelName;
            }
            onFocus(focus) {
                if (DEBUG$3)
                    console.log("vGridAdNode.onFocus", focus, this.panelName);
                if (!this.bEnabled)
                    return;
                if (focus) {
                    if (!mgrGuide.isAllGuideFinished() || mgrGuide.isGuiding()) {
                        if (DEBUG$3)
                            console.log("  guiding, skip.");
                    }
                    else {
                        this.openGridAd();
                    }
                }
                else {
                    this.closeGridAd();
                }
            }
            openGridAd() {
                if (DEBUG$3)
                    console.log("vGridAdNode.openGridAd", this.panelName, this.bOpened);
                if (this.bOpened)
                    return;
                this.bOpened = true;
                Timer.callLoop(0.1, (timer) => {
                    if (this.destroyed || !this.bOpened) {
                        timer.stop();
                        return;
                    }
                    if (DEBUG$3)
                        console.log("vGridAdNode.on call loop");
                    if (this._tryOpenGridAd()) {
                        timer.stop();
                    }
                }, this);
            }
            closeGridAd() {
                if (DEBUG$3)
                    console.log("vGridAdNode.closeGridAd", this.panelName, this.bOpened);
                if (!this.bOpened)
                    return;
                this.bOpened = false;
                if (DEBUG$3)
                    console.log("  call /c/closeGridAd");
                mgrSdk.closeGridAd();
            }
            _tryOpenGridAd() {
                if (DEBUG$3)
                    console.log("vGridAdNode._tryOpenGridAd", this.panelName);
                if (this.destroyed)
                    return true;
                let point = new Laya.Point(this.x, this.y);
                if (DEBUG$3)
                    console.log("vGridAdNodes.initPos");
                let outPoint = point;
                if (this.parent) {
                    outPoint.setTo(this.x, this.y);
                    this.parent.localToGlobal(outPoint, false);
                }
                if (DEBUG$3)
                    console.log("  outPoint", outPoint.x, outPoint.y);
                let sw = Laya.stage.width;
                let sh = Laya.stage.height;
                if (DEBUG$3)
                    console.log("  stage.size", sw, sh);
                let ccx = outPoint.x / sw;
                let ccy = 1 - outPoint.y / sh;
                if (DEBUG$3)
                    console.log("  ccx, ccy", ccx, ccy);
                if (ccx < 0)
                    ccx = 0;
                if (ccy < 0)
                    ccy = 0;
                if (ccx > 1)
                    ccx = 1;
                if (ccy > 1)
                    ccy = 1;
                if (ccy == 1) {
                    if (DEBUG$3)
                        console.log("ccy is 1!return");
                    return false;
                }
                if (DEBUG$3)
                    console.log("  call /c/openGridAd", ccx, ccy);
                mgrSdk.openGrid(ccx, ccy, this.panelName);
                return true;
            }
            onMsgPanelStackChanged() {
                Laya.timer.frameOnce(1, this, this.refreshState, null, true);
            }
        }

        var HUB_ROLE_STATE;
        (function (HUB_ROLE_STATE) {
            HUB_ROLE_STATE[HUB_ROLE_STATE["idle"] = 1] = "idle";
            HUB_ROLE_STATE[HUB_ROLE_STATE["interacting"] = 2] = "interacting";
            HUB_ROLE_STATE[HUB_ROLE_STATE["show"] = 3] = "show";
        })(HUB_ROLE_STATE || (HUB_ROLE_STATE = {}));
        class vHubScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vHubScene";
                this.exportNodeNames = [];
                this.avatarPosRotDict = {
                    [0]: { pos: new Laya.Vector3, rot: new Laya.Vector3 },
                };
                this.CAMERA_PARAM_FROM_LOADING = {
                    fov: 30,
                    pos: new Laya.Vector3(0, 1.5, 1.55),
                    rot: new Laya.Vector3(-5)
                };
                this.CAMERA_PARAM_FROM_OTHER = {
                    fov: 30,
                    pos: new Laya.Vector3(0, 1.38, 5.8),
                    rot: new Laya.Vector3(-5)
                };
                this.CAMERA_PARAM_END = {
                    fov: 30,
                    pos: new Laya.Vector3(0, 1.38, 5),
                    rot: new Laya.Vector3(-5)
                };
                this.crossRecommendState = false;
                this.bBuildUiEnded = false;
                this.avatar = null;
                this.canShake = true;
                vHubScene.hubScene = this;
            }
            onOpened() {
                super.onOpened();
                if (mgrChannel.isSupportGridAd) {
                    let viewName = this.sourceName.substr(this.sourceName.lastIndexOf("/") + 1, 100);
                    this.gridNode = new vGridAdNode(0, viewName);
                    this.spriteGridAd.addChild(this.gridNode);
                }
                mgrSound.play(1);
                console.log("进入主界面", mgrGuide.isGuiding(), mgrGuide.isAllGuideFinished());
                mgrSdk.getFollowOfficialAccountState();
                Tools.registerTouchHander(this.boxBackMask, this.onTouchSpriteBg.bind(this));
                mgrSdk.getShortcutState();
                mgrDesign.deleteTempDesignPart();
                this.init();
                this.fillData();
                this.widget();
                this.registerListeners({
                    MSG_DEBUG_KEY_DOWN: this.onKeyDown.bind(this),
                    MSG_ACHIEVEMENT_STATE_CHANGED: this.onAchievementStateChanged.bind(this),
                    MSG_GUIDE_HUB_NODE: this.onMsgGuideHubNode.bind(this)
                });
                this.refresh();
                Timer.callLoop(1, this.refresh.bind(this), this);
                this.buttonMoreGameBox.__node.visible = mgrAd.showMoreGameBox(0);
                this.addGridAd();
            }
            refreshCrossRecommend() {
                if (mgrChannel._isSupportRecommendationBtn) {
                    if (DialogBase.ShowingDialog.length > 0) {
                        if (this.crossRecommendState) {
                            mgrSdk.closeCrossRecommend();
                            this.crossRecommendState = false;
                            console.log("=======>>>>>>>> close Recommend");
                        }
                    }
                    else {
                        if (!this.crossRecommendState) {
                            let worldPos = this.boxContainerMC.localToGlobal(new Laya.Point(this.spriteChannelR0.x, this.spriteChannelR0.y));
                            mgrSdk.openCrossRecommend(worldPos.x / Laya.stage.width * Laya.Browser.clientWidth, worldPos.y / Laya.stage.height * Laya.Browser.clientHeight, 0);
                            this.crossRecommendState = true;
                            console.log("=======>>>>>>>> open Recommend");
                        }
                    }
                }
            }
            onClosed() {
                if (this.avatar) {
                    this.avatar.destroy();
                }
                this.avatar = null;
                super.onClosed();
                vHubScene.hubScene = null;
                mgrSdk.closeCrossRecommend();
                mgrVideoRecorder.stopRecord();
            }
            getPreLoadAnimationIds() {
                return [
                    ANIMATION_ID.idle,
                    "zjm_bixin_yuandian-zjm_bixin02_yuandian",
                    "zjm_maimeng_yuandian-zjm_maimeng_yuandian"
                ];
            }
            getPreLoadModelIds() {
                let arr = [
                    "map01",
                    "map01zq",
                    "map01xinnian",
                    Const.ROLE_LUCKY_FULL_EFFECT_NAME
                ];
                return arr;
            }
            getPreLoadImagePaths() {
                return [];
            }
            customWait(endCallback) {
                Timer.callLoop(0.016, (timer) => {
                    if (this.bBuildUiEnded) {
                        timer.stop();
                        endCallback();
                    }
                }, this);
            }
            init() {
                this.buildUi(() => {
                    this.spineUiEffect = ULSkeleton.create("cj_zjm_xinnian");
                    this.spineUiEffect.playAnimation("idle");
                    this.spineUiEffect.pos(mgrDirector.width / 2, mgrDirector.height / 2 + 100);
                    this.spriteEffectHolder.addChild(this.spineUiEffect);
                    Timer.callLater(Tools.random(2, 8), () => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        this.spineHudie1 = ULSkeleton.create("cj_hudie1", () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            let modelId = "117_ui_loop_hdparticle_01";
                            mgrLoader.loadModeWithModeId(modelId, () => {
                                if (!this.nodeResource || this.nodeResource.destroyed) {
                                    return;
                                }
                                let mode = mgrLoader.Pool.getModel(modelId);
                                this.resetTrail(mode);
                                this.initScene3DFront();
                                this.scene3DFront.addChild(mode);
                                Timer.callLoop(0.016, () => {
                                    let bonePos = this.spineHudie1.getBoneLocalPosByName("hudie1");
                                    let _temp = this.spineHudie1.localToGlobal(new Laya.Point(bonePos.x, bonePos.y));
                                    let outPos = new Laya.Vector3;
                                    this.cameraFront.convertScreenCoordToOrthographicCoord(new Laya.Vector3(_temp.x, _temp.y, 0), outPos);
                                    mode.transform.position = outPos;
                                }, this);
                            }, this, 1);
                        });
                        let doPlayHudie1 = () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.spineHudie1.y = mgrDirector.height / 2 - Tools.random(100);
                            this.spineHudie1.playAnimation("idle", false, () => {
                                Timer.callLater(Tools.random(100) / 100 * 15, () => {
                                    doPlayHudie1();
                                }, this);
                            });
                        };
                        doPlayHudie1();
                        this.spineHudie1.pos(mgrDirector.width / 2, mgrDirector.height / 2);
                        this.spriteEffectHolder.addChild(this.spineHudie1);
                    }, this);
                    Timer.callLater(Tools.random(2, 8), () => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        this.spineHudie2 = ULSkeleton.create("cj_hudie2", () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            let modelId = "117_ui_loop_hdparticle_02";
                            mgrLoader.loadModeWithModeId(modelId, () => {
                                if (!this.nodeResource || this.nodeResource.destroyed) {
                                    return;
                                }
                                let mode = mgrLoader.Pool.getModel(modelId);
                                this.resetTrail(mode);
                                this.initScene3DFront();
                                this.scene3DFront.addChild(mode);
                                Timer.callLoop(0.016, () => {
                                    let bonePos = this.spineHudie2.getBoneLocalPosByName("hudie2");
                                    let _temp = this.spineHudie2.localToGlobal(new Laya.Point(bonePos.x, bonePos.y));
                                    let outPos = new Laya.Vector3;
                                    this.cameraFront.convertScreenCoordToOrthographicCoord(new Laya.Vector3(_temp.x, _temp.y, 0), outPos);
                                    mode.transform.position = outPos;
                                }, this);
                            }, this, 1);
                        });
                        let doPlayHudie2 = () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.spineHudie2.y = mgrDirector.height / 2 - Tools.random(100);
                            this.spineHudie2.playAnimation("idle", false, () => {
                                Timer.callLater(Tools.random(100) / 100 * 15, () => {
                                    doPlayHudie2();
                                }, this);
                            });
                        };
                        doPlayHudie2();
                        this.spineHudie2.pos(mgrDirector.width / 2, mgrDirector.height / 2);
                        this.spriteEffectHolder.addChild(this.spineHudie2);
                    }, this);
                    if (this.context.fromSystemModel == SYSTEM_MODEL.loading) {
                        this.spineUiEffect.scale(1.3, 1.3);
                    }
                    else {
                    }
                    cc.tween(this.buttonClothDesign.__node).repeatForever(cc.tween()
                        .delay(2)
                        .by(0.1, { rotation: -10 })
                        .by(0.2, { rotation: 20 })
                        .by(0.1, { rotation: -10 })).start();
                    cc.tween(this.buttonQuest.__node).repeatForever(cc.tween()
                        .by(0.1, { rotation: -10 })
                        .by(0.2, { rotation: 20 })
                        .by(0.1, { rotation: -10 })
                        .delay(2)).start();
                    if (this.buttonMidAutumn.__node.visible) {
                        cc.tween(this.buttonMidAutumn.__node).repeatForever(cc.tween()
                            .by(0.1, { rotation: -10 })
                            .by(0.2, { rotation: 20 })
                            .by(0.1, { rotation: -10 })
                            .delay(2)).start();
                    }
                    if (mgrSdk.getCopNumberValueByKey("b_show_hub_quest_new_tip") == 1) {
                        this.imageQuestNewTip.visible = true;
                        mgrEffect.shineNode(this.imageQuestNewTip, 0.4);
                    }
                    else {
                        this.imageQuestNewTip.visible = false;
                    }
                    this.bBuildUiEnded = true;
                    this.roleStManager = new FSMObject;
                    this.roleStManager.registerState(HUB_ROLE_STATE.idle, this.inIdle.bind(this), this.exeIdle.bind(this), this.outIdle.bind(this));
                    this.roleStManager.registerState(HUB_ROLE_STATE.show, this.inShow.bind(this), this.exeShow.bind(this), this.outShow.bind(this));
                    this.roleStManager.registerState(HUB_ROLE_STATE.interacting, this.inInteraction.bind(this), this.exeInteraction.bind(this), this.outInteraction.bind(this));
                    this.roleStManager.startUpdate(this, this.onTimerLoop.bind(this));
                    let cf = this.cameraBack.getComponent(CameraFollow);
                    cf.lookMode = E_CAMERA_MODE.fixMode;
                    if (this.context.fromSystemModel == SYSTEM_MODEL.loading) {
                        cf.fov = this.CAMERA_PARAM_FROM_LOADING.fov;
                        cf.position = this.CAMERA_PARAM_FROM_LOADING.pos;
                        cf.endRotation = this.CAMERA_PARAM_FROM_LOADING.rot;
                    }
                    else {
                        cf.fov = this.CAMERA_PARAM_FROM_OTHER.fov;
                        cf.position = this.CAMERA_PARAM_FROM_OTHER.pos;
                        cf.endRotation = this.CAMERA_PARAM_FROM_OTHER.rot;
                    }
                    cf.lerpValue = 1;
                    cf.onLateUpdate();
                    let aniArr = null;
                    if (Tools.random(100) > 50) {
                        aniArr = ["zjm_bixin_yuandian-zjm_bixin02_yuandian", "zjm_maimeng-zjm_maimeng"];
                    }
                    else {
                        aniArr = ["zjm_maimeng_yuandian-zjm_maimeng_yuandian", "zjm_bixin-zjm_bixin02"];
                    }
                    this.avatar.playAnimation(aniArr, 0, () => {
                        this.avatar.hideShouChi();
                    }, () => {
                        this.avatar.showShouChi();
                    });
                    this.roleStManager.setNextState(HUB_ROLE_STATE.idle);
                    this.registerGuideNode();
                    this.showSomeDialogOther();
                    this.playInUi();
                });
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
                mgrLayout.widgetRightTopMC(this.spriteJumpOtherGame);
                mgrLayout.widgetLeftTopMC(this.spriteJumpOtherGameDrag);
                mgrLayout.widgetLeftTopMC(this.spriteChannelR0);
                mgrLayout.widgetRightTopMC(this.buttonHotActivity.__node);
                mgrLayout.widgetRightTopMC(this.boxTopRight);
                mgrLayout.widgetBottomMC(this.boxBottomCenter);
                mgrLayout.widgetLeftBottomMC(this.boxBottomLeft);
                mgrLayout.widgetRightBottomMC(this.boxRightListFuncBase);
            }
            registerGuideNode() {
                mgrGuide.registerGuideNode("vHubScene.buttonQuest", this.buttonQuest.__node);
                mgrGuide.registerGuideNode("vHubScene.buttonFreeDress", this.buttonFreeDress.__node);
                if (!mgrGuide.isFinished(200)) {
                    mgrGuide.startGuide(200);
                }
                else if (!mgrGuide.isFinished(1800)) {
                    mgrGuide.startGuide(1800);
                }
            }
            onTimerLoop(dt) {
            }
            playInUi(delayTime = 1) {
                let upAction = (node, yOffset, delay, dur) => {
                    node.alpha = 0;
                    node["_originPos"] = node["_originPos"] || new Laya.Vector2(node.x, node.y);
                    node.y += yOffset;
                    cc.tween(node)
                        .delay(delay)
                        .parallel(cc.tween().toAlpha(Math.max(0, dur * 0.5), 1), cc.tween().toPos(dur, node["_originPos"].x, node["_originPos"].y, cc.Ease.backOut))
                        .start();
                };
                upAction(this.buttonCardFight.__node, 300, delayTime + 0.4, 0.6);
                upAction(this.buttonChangeRole.__node, 300, delayTime + 0.2, 0.6);
                upAction(this.buttonFreeDress.__node, 300, delayTime, 0.6);
                upAction(this.buttonClothDesign.__node, 300, delayTime + 0.2, 0.6);
                upAction(this.buttonQuest.__node, 300, delayTime + 0.4, 0.6);
                mgrEffect.playComebackAction([this.spriteTopBarHolder], -400, 0, delayTime, 0.3, null, cc.Ease.backOut);
                mgrEffect.playComebackAction([this.boxTopRight], 300, 0, delayTime, 0.3, null, cc.Ease.backOut);
                mgrEffect.playComebackAction([this.boxRightListFuncBase], 100, 0, delayTime + 0.5, 1.2);
                mgrEffect.playComebackAction([this.boxBottomLeft], -300, 0, delayTime + 0.5, 0.6, () => {
                    let cf = this.cameraBack.getComponent(CameraFollow);
                    cf.lerpValue = 0.04;
                    cf.fov = this.CAMERA_PARAM_END.fov;
                    cf.position = this.CAMERA_PARAM_END.pos;
                    cf.endRotation = this.CAMERA_PARAM_END.rot;
                    cc.tween(this.spineUiEffect).toScale(0.6, 1)
                        .call(() => {
                    })
                        .start();
                    this.add3DEffectAtFront("117_ui_loop_bgparticle_01", { x: mgrDirector.width / 2, y: mgrDirector.height / 2 });
                }, cc.Ease.backOut);
                Timer.callLater(delayTime + 0.5, () => {
                    mgrEffect.scalePop(this.buttonNewYear.__node, 0.3, () => {
                        if (this.buttonNewYear.__node.visible) {
                            cc.tween(this.buttonNewYear.__node).repeatForever(cc.tween()
                                .by(0.1, { rotation: -10 })
                                .by(0.2, { rotation: 20 })
                                .by(0.1, { rotation: -10 })
                                .delay(2)).start();
                        }
                    });
                });
            }
            onMsgGuideHubNode(e) {
                let nodeName = e.nodeName;
                if (!nodeName || nodeName == "") {
                    return;
                }
                let node = this[nodeName];
                if (!node || node.destroyed) {
                    return;
                }
                let useNode = null;
                if (node instanceof ScaleButton) {
                    useNode = node.__node;
                }
                else {
                    useNode = node;
                }
                this.add3DEffectAtFront("eff_ui_xsyd", useNode, 5);
            }
            showSomeDialogOther() {
                if (!mgrGuide.isAllForceGuideFinished())
                    return;
                mgrChannel.tipAddMyFavorite();
                let cd = mgrSdk.getCopNumberValueByKey("hub_scene_alert_dialog_cd");
                let bOverCd = Tools.time() - mgrAlertRouter.getHubSceneTipDialogShowTime() >= cd;
                if (this.context.fromSystemModel != SYSTEM_MODEL.loading && bOverCd && mgrSdk.getCopNumberValueByKey("b_show_hub_scene_alert_dialog") == 1) {
                    mgrTip.alertPrompt1("提示", "还有更多精彩等你来探索哦~", "确定", () => { });
                    mgrAlertRouter.setHubSceneTipDialogShowTime(Tools.time());
                }
                if (this.context.fromSystemModel != SYSTEM_MODEL.loading) {
                    mgrTip.tryShowFullScreenMoreGameFixed("b_fsmgfs_back_hub");
                }
                console.log("新手引导全部完成，则主界面尝试触发评分弹出框");
                let ratio = mgrSdk.getCopNumberValueByKey("pop_review_ratio") || 0;
                if (!!ratio && Tools.random(100) <= ratio) {
                    mgrReview.tryShowReviewDialog();
                }
                else {
                    console.log("  概率不满足");
                }
            }
            buildUi(loadEndCallback) {
                this.buttonNewYear.__node.scale(0, 0);
                this.showRightFuncList(true);
                this.boxContainerMC.mouseThrough = true;
                this.topBar = new vTopBar({ bDisableGold: true });
                this.spriteTopBarHolder.addChild(this.topBar);
                let taskManager = new TaskManager;
                let taskSamples = [];
                let idleNameConfigCenter = this.getCenterAvatarIdleName(0);
                let params = {
                    fBoneBindedCallback: (serialNumber) => {
                        this.mainAvatarBoneBindSerialNumber = serialNumber;
                    },
                    defaultBodyIdleName: idleNameConfigCenter.defaultBodyIdleName,
                    defaultFaceIdleName: idleNameConfigCenter.defaultFaceIdleName,
                    roleId: mgrRole.showingRoleId
                };
                this.avatar = new RoleAvatar(params);
                this.add3DEffectAtBack(this.avatar, 0);
                let lastDressPartIds = mgrPart.getLastClothes(mgrRole.showingRoleId);
                this.avatar.fillByPartIds(lastDressPartIds);
                if (!mgrGuide.isFinished(303)) {
                    this.avatar.fillByPartIds([13000]);
                }
                let holdPartData = null;
                for (let k in lastDressPartIds) {
                    let tId = lastDressPartIds[k];
                    let tPartData = mgrCfg.get_from_part_db(tId);
                    if (tPartData.type == PartType.handHold) {
                        holdPartData = tPartData;
                        break;
                    }
                }
                if (!!holdPartData) {
                    this.avatar.setIdleId(holdPartData.holdIdleAnimation);
                }
                else {
                    this.avatar.setIdleId(Tools.random(100) > 50 ? "zjm_idle-zjm_idle01" : "zjm_idle-zjm_idle02");
                }
                this.avatar.tryShowLuckEffect();
                taskSamples.push((endCallback) => {
                    this.avatar.registerLoadEndCallback(() => {
                        this.avatar.transform.position = this.avatarPosRotDict[0].pos;
                        this.avatar.transform.rotationEuler = this.avatarPosRotDict[0].rot;
                        endCallback();
                    });
                });
                taskManager.push(taskSamples);
                taskManager.start(() => {
                    loadEndCallback();
                });
                this.add3DBg();
            }
            add3DBg() {
                let mapModelName = "map01xinnian";
                let offsetZ = 0.001;
                let map01 = mgrLoader.Pool.getModel(mapModelName);
                this.add3DEffectAtBack(map01);
                let yun = map01.getChildByName("zhujiemian_yun");
                let render = Tools.getMeshRender(yun);
                let material = render.sharedMaterial;
                Timer.callLoop(0.016, () => {
                    material.tilingOffsetZ -= offsetZ / 6;
                }, this);
            }
            addGridAd() {
                let gridAd = new vGridAd({ advId: "40001", copStr: "grid_ad_ratio4" });
                this.addChild(gridAd);
            }
            randomGetLeftAvatarIdleName(index) {
                let defaultBodyIdleName = null;
                let defaultFaceIdleName = null;
                let datas = mgrCfg.get_from_hub_role_standby_feedback_db(1);
                if (datas) {
                    let data = datas[index] || datas[0];
                    defaultBodyIdleName = data.animationId;
                    defaultFaceIdleName = data.faceAnimaitonId;
                }
                return {
                    defaultBodyIdleName: defaultBodyIdleName,
                    defaultFaceIdleName: defaultFaceIdleName
                };
            }
            randomGetRightAvatarIdleName(index) {
                let defaultBodyIdleName = null;
                let defaultFaceIdleName = null;
                let datas = mgrCfg.get_from_hub_role_standby_feedback_db(2);
                if (datas) {
                    let data = datas[index] || datas[0];
                    defaultBodyIdleName = data.animationId;
                    defaultFaceIdleName = data.faceAnimaitonId;
                }
                return {
                    defaultBodyIdleName: defaultBodyIdleName,
                    defaultFaceIdleName: defaultFaceIdleName
                };
            }
            getCenterAvatarIdleName(index) {
                let defaultBodyIdleName = null;
                let defaultFaceIdleName = null;
                let datas = mgrCfg.get_from_hub_role_standby_feedback_db(3);
                if (datas) {
                    let data = datas[index] || datas[0];
                    defaultBodyIdleName = data.animationId;
                    defaultFaceIdleName = data.faceAnimaitonId;
                }
                return {
                    defaultBodyIdleName: defaultBodyIdleName,
                    defaultFaceIdleName: defaultFaceIdleName
                };
            }
            fillData() {
            }
            setLeafletMaxGameVersionButtonTexture(enterBtn, sprite, dbName, bShake = false) {
                let db = mgrCfg.getDbArr(dbName, (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    return true;
                });
                let labelTip = null;
                let imageTip = enterBtn.__node.getChildByName("imageTip");
                if (imageTip) {
                    labelTip = imageTip.getChildByName("labelTip");
                    if (labelTip) {
                        imageTip.visible = false;
                    }
                }
                let bContainValidVersion = false;
                if (db && db.length != 0) {
                    db = Tools.sortArrayByField(db, ["-gameResVersion", "-id"]);
                    if (db && db[0]) {
                        bContainValidVersion = true;
                        if (db[0].hubBtnTexture) {
                            Tools.loadImg(sprite, db[0].hubBtnTexture);
                        }
                        if (db[0].desc && imageTip && labelTip) {
                            labelTip.text = db[0].desc;
                            while (labelTip.width > 72) {
                                labelTip.fontSize--;
                            }
                            Tools.layoutH(imageTip);
                            imageTip.visible = true;
                        }
                    }
                }
                enterBtn.__node.visible = !!bContainValidVersion;
                if (enterBtn.__node.visible && bShake) {
                    cc.tween(enterBtn.__node).repeatForever(cc.tween()
                        .delay(1)
                        .by(0.1, { rotation: -10 })
                        .by(0.2, { rotation: 20 })
                        .by(0.1, { rotation: -10 })).start();
                }
            }
            onKeyDown(k) {
            }
            onAchievementStateChanged() {
            }
            _doLayout(parent, dir, gap = 2) {
                gap = gap || 0;
                let x = 0;
                let y = 0;
                let totalDis = 0;
                let validCount = 0;
                let count = parent.numChildren;
                for (let i = 0; i < count; i++) {
                    var node = parent.getChildAt(i);
                    if (node.visible) {
                        if (dir == "left") {
                            node.x = x;
                            x = x - node.width - gap;
                            totalDis += (node.width + gap);
                        }
                        else if (dir == "right") {
                            node.x = x;
                            x = x + node.width + gap;
                            totalDis += (node.width + gap);
                        }
                        else if (dir == "up") {
                            if (validCount == 0) {
                                node.y = 0;
                                y -= (node.height / 2);
                                totalDis += (node.height);
                            }
                            else {
                                y -= (gap + (node.height) / 2);
                                node.y = y;
                                y -= (node.height / 2);
                                totalDis += (node.height + gap);
                            }
                        }
                        else if (dir == "down") {
                            if (validCount == 0) {
                                node.y = 0;
                                y += (node.height / 2);
                                totalDis += (node.height);
                            }
                            else {
                                y += (gap + (node.height) / 2);
                                node.y = y;
                                y += (node.height / 2);
                                totalDis += (node.height + gap);
                            }
                        }
                        validCount += 1;
                    }
                }
                return totalDis;
            }
            refresh() {
                this.refreshCrossRecommend();
                this.sprite4399.visible = mgrChannel.isChannel4399();
                this.buttonMoreGame.__node.visible = mgrChannel.canGameInterPushMoreGame();
                this.buttonRewardMoreGame.__node.visible = mgrChannel.canGameInterPushRewardMoreGame();
                this.buttonNotice.__node.visible = !!mgrSdk.getCopByKey("url_nortice");
                this.buttonFindMe.__node.visible = mgrChannel.canShowFindMe();
                this.buttonShortCut.__node.visible = mgrChannel._isSupportInstallShortcut && !mgrChannel.isTakedInstallShortCutReward();
                this.buttonShare.__node.visible = mgrChannel.getShareRewardAmount() > 0 && mgrShare.isCanShare("share_dialog");
                this.buttonDouyinDesktop.__node.visible = false;
                this.buttonDouyinSmallGame.__node.visible = false;
                this.buttonFollowDouyin.__node.visible = !!mgrChannel._isSupportFollowOfficialAccount;
                let bAdvanceHub = mgrSdk.getCopNumberValueByKey("b_advanced_hub");
                this.buttonAuthority.__node.visible = (bAdvanceHub == 1 || bAdvanceHub == 2);
                this.buttonBlessingBag.__node.visible = mgrSdk.getCopNumberValueByKey("b_fu_dai") == 1 ? true : false;
                this.buttonMidAutumn.__node.visible = mgrMidAutumn.isEnable();
                this.buttonMoreWonderful.__node.visible = !!mgrChannel._isJumpLeisureEnabled;
                this.buttonHotActivity.__node.visible = mgrSdk.getCopNumberValueByKey("b_hot_actity") == 1 ? true : false;
                let b_button_ios_comment = mgrSdk.getCopNumberValueByKey("b_button_ios_comment") == 1 ? true : false;
                this.buttonIosComment.__node.visible = b_button_ios_comment;
                this.spriteMidAutumnFlag.visible = mgrMidAutumn.isEnable();
                if (this.buttonIosComment.__node.visible && this.canShake) {
                    this.canShake = false;
                    cc.tween(this.buttonIosComment.__node).repeatForever(cc.tween()
                        .delay(1)
                        .by(0.1, { rotation: -10 })
                        .by(0.2, { rotation: 20 })
                        .by(0.1, { rotation: -10 })).start();
                }
                mgrTip.showBadgeWithNumber(this.buttonSign.__node, mgrSign.getBadgeCout(), new Laya.Point(40, 5));
                mgrTip.showBadgeWithNumber(this.buttonSuit.__node, mgrPart.getBadgeCount(), new Laya.Point(12, 12));
                if (mgrSdk.getCopNumberValueByKey("b_show_reward_more_game_red_point") == 1) {
                    mgrTip.showBadgeWithNumber(this.buttonRewardMoreGame.__node, 1, new Laya.Point(12, 12));
                }
                this.buttonAdH5.__node.visible = mgrChannel._isShowUrlAdIcon && mgrCop.getNumberValue("for_ad_h5") == 1;
                this._doLayout(this.boxBottomLeft, "up", 12);
                let tmpDis = this._doLayout(this.boxRightListFuncContainer, "up", 12);
                this.imageRightListFuncBaseBg.height = tmpDis + 10;
                this.buttonMoreGameBox.__node.visible = mgrAd.showMoreGameBox(0);
            }
            changeRightFuncListStatus() {
                if (!!this.panelRightList["_bShow"]) {
                    this.hideRightFuncList();
                }
                else {
                    this.showRightFuncList();
                }
            }
            showRightFuncList(bImmi) {
                this.spriteRightListFuncOpened.visible = true;
                this.spriteRightListFuncClosed.visible = false;
                this.panelRightList["_bShow"] = true;
                if (bImmi) {
                    this.panelRightList.scale(1, 1, true);
                }
                else {
                    cc.tween(this.panelRightList, true).toScale(0.2, 1, cc.Ease.backOut)
                        .call(() => {
                    })
                        .start();
                }
            }
            hideRightFuncList(bImmi) {
                this.spriteRightListFuncOpened.visible = false;
                this.spriteRightListFuncClosed.visible = true;
                this.panelRightList["_bShow"] = false;
                if (bImmi) {
                    this.panelRightList.scale(0, 0, true);
                }
                else {
                    cc.tween(this.panelRightList, true).to(0.2, { scaleY: 0 }, cc.Ease.backIn)
                        .call(() => {
                    })
                        .start();
                }
            }
            onTouchButtonSign() {
                if (!this.avatar) {
                    return;
                }
                mgrDirector.openDialog("vSignDialog");
            }
            onTouchButtonShare() {
                mgrDirector.openDialog(`vShareDilaog`);
            }
            onTouchButtonFindMe() {
                if (mgrChannel.isChannelBaidu()) {
                    mgrDirector.openDialog(`vFindMeDialogBaidu`);
                }
                else if (mgrChannel.isChannelWeixin()) {
                    mgrDirector.openDialog(`vFindMeDialogWeixin`);
                }
                else if (mgrChannel.isChannelHeadline()) {
                    mgrDirector.openDialog(`vFindMeDialogToutiao`);
                }
                else if (mgrChannel.isChannelPlatformDouyin()) {
                    mgrDirector.openDialog(`vFindMeDialogDouyin`);
                }
            }
            onTouchButtonRank() {
                mgrDirector.warpSceneWidthEffect(`vRankScene`, {
                    backSceneName: `vHubScene`,
                });
            }
            onTouchButtonMoreGame() {
                if (!window[`conch`]) {
                    mgrDirector.openDialog(`vMoreGameDialog`);
                }
                else {
                    mgrSdk.openULMoreGame();
                }
            }
            onTouchButtonRewardMoreGame() {
                mgrDirector.openDialog(`vRewardMoreGame`);
            }
            onTouchButtonNotice() {
                if (!window[`conch`]) {
                }
                else {
                    vWebViewDialog.openWebView(mgrCop.get("url_nortice"));
                }
            }
            onTouchButtonShortCut() {
                mgrSdk.installShortcut();
            }
            onTouchButtonDouyinSmallGame() {
                mgrDirector.openDialog(`vDouyinSmallGame`);
            }
            onTouchButtonDouyinDesktop() {
                mgrDirector.openDialog(`vDouyinDesktop`);
            }
            onTouchButtonAdH5() {
                mgrAd.triggerAdEvent("ad_h5");
            }
            onTouchButtonSuit() {
                mgrDirector.warpSceneWidthEffect("vSuitTypeScene", {});
            }
            onTouchButtonSetting() {
                mgrDirector.openDialog("vSettingDialog");
            }
            onTouchButtonFollowDouyin() {
                mgrSdk.getFollowOfficialAccountState();
                mgrDirector.openDialog("vDouyinFollow");
            }
            onTouchButtonMoreWonderful() {
                mgrSdk.openMoreWonderful();
            }
            onTouchButtonMaxLevel() {
                mgrTip.showMsgTip("角色已经达到满级了哦");
            }
            onTouchButtonBlessingBag() {
                mgrDirector.openDialog("vCdkDialog");
                mgrSdk.statisCommonEvent(70000);
            }
            onTouchButtonAmazeFShoe() {
                mgrDirector.openDialog("vAmuseFashionShoeLeafletDialog");
            }
            onTouchButtonHotActivity() {
                mgrDirector.openDialog("vHotActivityDialog");
            }
            onTouchButtonIosComment() {
                mgrDirector.openDialog("vIosInvateReview");
            }
            onTouchButtonAmazeLessonMusic() {
                mgrDirector.openDialog("vAmuseLessonMusicLeafletDialog");
            }
            onTouchButtonCardFight() {
                mgrDirector.warpSceneWidthEffect(`vAmuseCardStartScene`, {
                    backSceneName: `vHubScene`
                });
            }
            onTouchButtonFreeDress() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vHubScene.clickButtonFreeDress` });
                mgrDirector.warpSceneWidthEffect(`vFreedomRoomScene`, {
                    stageId: 2001,
                    backSceneName: `vHubScene`,
                    fromSystemModel: SYSTEM_MODEL.hub,
                });
            }
            onTouchButtonClothDesign() {
                mgrDirector.warpSceneWidthEffect(`vDesignRoomScene`, {
                    backSceneName: `vHubScene`,
                });
            }
            onTouchButtonRightListFunc() {
                this.changeRightFuncListStatus();
            }
            onTouchButtonChangeRole() {
                mgrDirector.warpSceneWidthEffect("vRoleChangeScene", {});
            }
            onTouchButtonQuest() {
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vHubScene.clickButtonQuest` });
                mgrDirector.warpSceneWidthEffect("vWorldDailyQuestMainScene");
            }
            onTouchButtonCardCollect() {
                mgrDirector.openDialog("vAmuseCardModeDialog");
            }
            onTouchButtonMidAutumn() {
                mgrDirector.openDialog("vMidAutumnActivityDialog");
            }
            onTouchButtonMoreGameBox() {
                mgrSdk.opentChannelMoreGameBox();
            }
            onTouchButtonNewYear() {
                mgrDirector.openDialog(`vNewYearPreviewDialog`);
            }
            onTouchButtonAuthority() {
                let mode = mgrSdk.getCopNumberValueByKey("b_advanced_hub");
                if (mode == 1) {
                    mgrSdk.openAdvancedSetting();
                }
                else if (mode == 2) {
                    mgrDirector.openDialog("vAdvancedSettingDialog");
                }
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    this.lastTouchBgPos = e.pos;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, deltaX, 0), true, false);
                }
                if (e.isClick) {
                    let screenWorldPos = new Laya.Vector2(e.pos.x, e.pos.y);
                    let ray = Tools.createRayFromScreenPos(this.cameraBack, screenWorldPos);
                    let bClicked = this.checkMainAvatarClick(ray);
                }
            }
            checkMainAvatarClick(ray) {
                if (DialogBase.ShowingDialog.length > 0 || !this.avatar || this.avatar.destroyed || !this.avatar.isIdling()) {
                    return false;
                }
                for (let colliderName in this.avatar.avatarColliderSprite3dDict) {
                    let sprite3d = this.avatar.avatarColliderSprite3dDict[colliderName];
                    if (!sprite3d) {
                        continue;
                    }
                    let result = UVPickerByMesh.pick(ray, sprite3d);
                    if (result && result.bHit) {
                        let type = this.avatar.avatarColliderName2TypeDict[colliderName];
                        let datas = mgrCfg.get_from_center_role_click_feedback_db(type);
                        if (!datas) {
                            return false;
                        }
                        this.sendMsg(`MSG_CLICK_ROLE`, {
                            pos: type,
                        });
                        this.roleStManager.setNextState(HUB_ROLE_STATE.interacting);
                        let data = Tools.randomGotOneArrayData(datas);
                        if (data.soundId) {
                            mgrSound.play(data.soundId);
                        }
                        this.avatar.playAnimation(data.animationId, 0.05, () => {
                            this.avatar.hideShouChi();
                        }, () => {
                            this.roleStManager.setNextState(HUB_ROLE_STATE.idle);
                            this.avatar.showShouChi();
                        });
                        return true;
                    }
                }
                return false;
            }
            inIdle() {
                this.idleTimer = Timer.callLater(5, () => {
                    this.roleStManager.setNextState(HUB_ROLE_STATE.show);
                }, this);
            }
            exeIdle() {
            }
            outIdle() {
                this.idleTimer.stop();
                this.idleTimer = null;
            }
            inInteraction() {
            }
            exeInteraction() {
            }
            outInteraction() {
            }
            inShow() {
                let aniIds = [
                    "zjm_bixin-zjm_bixin01",
                    "zjm_bixin-zjm_bixin02",
                    "zjm_maimeng-zjm_maimeng"
                ];
                let aniId = Tools.randomGotOneArrayData(aniIds);
                this.avatar.playAnimation(aniId, 0.05, () => {
                    this.avatar.hideShouChi();
                }, () => {
                    this.roleStManager.setNextState(HUB_ROLE_STATE.idle);
                    this.avatar.showShouChi();
                });
            }
            exeShow() { }
            outShow() {
            }
        }

        class vPrestartScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vPrestartScene";
            }
            onOpened() {
                super.onOpened();
                let node = Laya.stage.getChildByName(Const.CUSTOM_LAYA_STAGE_BASE_BG_NAME);
                if (!!node) {
                    node.alpha = 0;
                }
                this.sprite01.alpha = 0;
                this.sprite02.alpha = 0;
                this.sprite03.alpha = 0;
                this.sprite04.alpha = 0;
                this.spriteWord02.alpha = 0;
                this.startAction();
            }
            onClosed() {
                super.onClosed();
                let node = Laya.stage.getChildByName(Const.CUSTOM_LAYA_STAGE_BASE_BG_NAME);
                if (!!node) {
                    node.alpha = 1;
                }
            }
            startAction() {
                mgrTip.hideLoadingTip("prestart_scene_load");
                let doShowFunc = (index, callback) => {
                    let spriteRole = this[`sprite0${index}`];
                    cc.tween(spriteRole)
                        .toAlpha(0.1, 1)
                        .delay(1)
                        .call(() => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        callback && callback();
                    })
                        .start();
                };
                cc.tween(this.sprite01)
                    .delay(0.3)
                    .toAlpha(0.1, 1)
                    .delay(1)
                    .call(() => {
                    cc.tween(this.sprite02)
                        .toAlpha(0.1, 1)
                        .delay(1)
                        .call(() => {
                        mgrEffect.filterGray(this.sprite01);
                    })
                        .call(() => {
                        cc.tween(this.spriteWord02)
                            .toAlpha(0.05, 1)
                            .delay(0.1)
                            .call(() => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            doShowFunc(2, () => {
                                doShowFunc(3, () => {
                                    doShowFunc(4, () => {
                                        this.onPlayCompleted();
                                    });
                                });
                            });
                        })
                            .start();
                    })
                        .start();
                })
                    .start();
            }
            onPlayCompleted() {
                let nodes = [
                    this.nodeResource,
                    this.sprite01,
                    this.spriteWord02,
                    this.sprite02,
                    this.sprite03,
                    this.sprite04,
                ];
                for (let k in nodes) {
                    let node = nodes[k];
                    if (!node || node.destroyed) {
                        continue;
                    }
                    cc.tween(node).removeAllActions();
                }
                this.buttonGetNormal.__node.visible = false;
                if (!!mgrGuide.isAllForceGuideFinished()) {
                    mgrDirector.warpSceneWidthEffect("vHubScene", { fromSystemModel: SYSTEM_MODEL.loading });
                }
                else {
                    mgrDirector.warpSceneWidthEffect(`vFreedomRoomScene`, {
                        stageId: 2001,
                        fromSystemModel: SYSTEM_MODEL.loading,
                    });
                }
            }
            onTouchButtonGetNormal() {
                this.onPlayCompleted();
            }
        }

        class vRankScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vRankScene";
                this.exportNodeNames = [];
            }
            onOpened() {
                super.onOpened();
                mgrOfflinePvp.refreshPlayerData();
                this.buildUi();
                this.widget();
                this.fadeIn();
                this.fillDataPvp();
                this.registerListeners({
                    MSG_PVP_RANK_UPDATE: this.onMsgPvpRankUpdate.bind(this),
                    MSG_PLAYER_NAME_CHANGED: this.onMsgPlayerNameChanged.bind(this),
                });
                let myPlayerData = mgrOfflinePvp.getPlayerData();
                if (myPlayerData && myPlayerData.rank > 3) {
                    mgrSound.play(410);
                }
            }
            onClosed() {
                super.onClosed();
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
                mgrLayout.widgetRightMC(this.spriteJumpOtherGameDrag);
            }
            fadeIn() {
                Timer.callLater(0.8, () => {
                    this.add3DEffectAtFront("eff_ui_php_star", this.spriteEffect1);
                }, this);
            }
            buildUi() {
                mgrLoader.loadFont("card_power", this.labelScore);
                mgrLoader.loadFont("card_power", this.labelScore1);
                mgrLoader.loadFont("card_power", this.labelScore2);
                mgrLoader.loadFont("card_power", this.labelScore3);
                this.reusePvpList = new ReuseList(1, 0, 10);
                this.reusePvpList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reusePvpList);
                this.reusePvpList.setItemClass(vRankItem);
                this.reusePvpList.setVerticalMoveEnable(true);
                this.reusePvpList.setSpaceY(5);
            }
            fillDataPvp() {
                this.labelName.text = mgrPlayer.getName();
                let myPlayerData = mgrOfflinePvp.getPlayerData();
                if (myPlayerData) {
                    this.spriteRank.visible = true;
                    this.labelRank.text = `${myPlayerData.rank.toString()}`;
                    this.labelUnRank.visible = false;
                    this.labelScore.visible = true;
                    this.labelScore.text = `${myPlayerData.score}`;
                }
                else {
                    this.spriteRank.visible = false;
                    this.labelUnRank.visible = true;
                    this.labelScore.visible = false;
                }
                let pvpDatas = mgrOfflinePvp.getPvpDatas();
                let datas = [];
                for (let index = 0; index < pvpDatas.length; index++) {
                    const player = pvpDatas[index];
                    if (index <= 2) {
                        this.fillTopRankInfo(player);
                        continue;
                    }
                    datas.push({
                        player: player,
                        fOnClick: this.onClickEnemy.bind(this),
                    });
                }
                this.reusePvpList.setDatas(datas);
                this.reusePvpList.setScroll(0);
            }
            fillTopRankInfo(player) {
                let labelName = this[`labelName${player.rank}`];
                if (!labelName) {
                    return;
                }
                let labelScore = this[`labelScore${player.rank}`];
                let spriteShowingPhoto = this[`spriteShowingPhoto${player.rank}`];
                labelName.text = player.name;
                labelScore.text = `${Math.floor(player.score)}`;
                if (mgrPlayer.getUid() == player.uid) {
                    let playerPhotoInfo = mgrOfflinePvp.getPlayerPhotoInfo() || {};
                    let tex2dSaved = mgrRole.getPhotoTexture2D(playerPhotoInfo.textureKey);
                    if (!!tex2dSaved) {
                        spriteShowingPhoto.texture = new Laya.Texture(tex2dSaved);
                    }
                }
                else {
                    Tools.loadImg(spriteShowingPhoto, player.texture);
                }
            }
            onClickEnemy(data) {
                if (data.uid == mgrPlayer.getUid()) {
                    mgrTip.showMsgTip("不能挑战自己喔！");
                    return;
                }
                let enemyCardPosInfo = [];
                let roleCardDataDict = data.datas || {};
                for (let k in roleCardDataDict) {
                    let cardData = roleCardDataDict[k];
                    let roleData = mgrCfg.get_from_role_db(cardData.roleId);
                    enemyCardPosInfo[cardData.cardPosIndex] = { roleId: cardData.roleId, tagId: roleData.roleTagId, styleId: cardData.cardId, texturePath: cardData.texture, power: cardData.power, hp: cardData.hp };
                }
                mgrTip.alertPrompt2("提示", `是否挑战${data.name}？`, "不了", "好的", () => {
                }, () => {
                    console.log("查看enemyCardPosInfo", enemyCardPosInfo);
                    mgrDirector.warpSceneWidthEffect(`vAmuseCardTeamSetScene`, {
                        bPvp: true,
                        stageId: 301,
                        enemyCardPosInfo: enemyCardPosInfo
                    });
                });
            }
            onTouchButtonBack() {
                let scenaName = this.context.backSceneName || `vHubScene`;
                mgrDirector.warpSceneWidthEffect(scenaName, this.context.backSceneContext);
            }
            onTouchButtonRank1() {
                let pvpDatas = mgrOfflinePvp.getPvpDatas();
                this.onClickEnemy(pvpDatas[0]);
            }
            onTouchButtonRank2() {
                let pvpDatas = mgrOfflinePvp.getPvpDatas();
                this.onClickEnemy(pvpDatas[1]);
            }
            onTouchButtonRank3() {
                let pvpDatas = mgrOfflinePvp.getPvpDatas();
                this.onClickEnemy(pvpDatas[2]);
            }
            onMsgPvpRankUpdate() {
                this.fillDataPvp();
            }
            onMsgPlayerNameChanged() {
                this.fillDataPvp();
            }
        }

        class vRoleChangeScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vRoleChangeScene";
                this.exportNodeNames = [];
            }
            getPreLoadModelIds() {
                return [];
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                mgrSound.play(2);
                this.buildUi();
                this.playOutUi();
                this.playInUi();
                mgrSound.play(561);
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                let db = mgrCfg.getDbArr("role_db", (data) => {
                    if (data && data.gameResVersion && !mgrGameResVersion.isValidGameResVersion(data.gameResVersion)) {
                        return false;
                    }
                    if (data.bNpc) {
                        return false;
                    }
                    return true;
                });
                let arr = [];
                for (let key in db) {
                    arr.push(db[key]);
                }
                arr = Tools.sortArrayByField(arr, "sort");
                let bAdStatis = false;
                arr.forEach((v, i) => {
                    v["fOnClick"] = this.selectRole.bind(this);
                    v["fIsSelected"] = this.isSelected.bind(this);
                    v["fIsUsing"] = this.isUsing.bind(this);
                    let roleData = mgrCfg.get_from_role_db(v.id);
                    let jumpData = mgrCfg.get_from_role_collect_jump_db(v.id);
                    let bJump = jumpData && jumpData.jumpTargetScene;
                    if (!bJump && mgrPlayer.getItemAmount(roleData.unlockItemId) < roleData.unlockItemAmount && mgrPlayer.getItemAmount(v.id) <= 0 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vRoleChangeScene_fragment)) {
                        bAdStatis = true;
                        v["bAd"] = true;
                    }
                    else {
                        v["bAd"] = false;
                    }
                    v["index"] = i;
                });
                if (bAdStatis) {
                    let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vRoleChangeScene_fragment);
                    adEventData.pointEventId && mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                }
                this.arr = db;
                this.reuseList = new ReuseList(3, 0, 4);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vRoleChangeItem);
                if (arr.length > 9) {
                    this.reuseList.setVerticalMoveEnable(true);
                }
                else {
                    this.reuseList.setVerticalMoveEnable(false);
                    this.reuseList.setTouchEnable(false);
                }
                this.reuseList.setSpaceX(0);
                this.reuseList.setSpaceY(0);
                this.reuseList.setDatas(arr);
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            playOutUi() {
                this.buttonChange.__node.scale(0, 0);
            }
            playInUi() {
                let delayTime = 0.6;
                let timeGap = 0.2;
                let nodes = [];
                nodes.forEach(v => {
                    cc.tween(v)
                        .delay(delayTime)
                        .call(() => {
                        if (v.destroyed)
                            return;
                        v.scaleX = -0.2;
                    })
                        .to(0.3, { scaleX: 1 })
                        .start();
                    delayTime += timeGap;
                });
            }
            selectRole(roleId, bAd) {
                let collectJumpData = mgrCfg.get_from_role_collect_jump_db(roleId);
                if (collectJumpData && mgrPlayer.getItemAmount(roleId) <= 0) {
                    let scene = collectJumpData.jumpTargetScene;
                    let backScene = collectJumpData.jumpBackScene || null;
                    switch (collectJumpData.jumpWay) {
                        case "open2DScene":
                            mgrDirector.open2DScene(scene, {
                                backSceneName: backScene
                            });
                            break;
                        case "warpSceneWidthEffect":
                            mgrDirector.warpSceneWidthEffect(scene, {
                                backSceneName: backScene
                            });
                            break;
                        default:
                            mgrDirector.openDialog(scene);
                            break;
                    }
                    return;
                }
                if (bAd) {
                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vRoleChangeScene_fragment, { roleId }, true);
                    return;
                }
                let roleData = mgrCfg.get_from_role_db(roleId);
                let curFragmentNum = mgrPlayer.getItemAmount(roleData.unlockItemId);
                let needFragmentNum = roleData.unlockItemAmount;
                if (mgrPlayer.getItemAmount(roleId) <= 0) {
                    let doUnlockFunc = () => {
                        let callback = () => {
                            this.reuseList.refresh();
                        };
                        mgrDirector.openDialog("vGotNewRoleDialog", { roleId, fOnClose: callback });
                    };
                    if (curFragmentNum >= needFragmentNum) {
                        doUnlockFunc();
                    }
                    else {
                        let coinAmount = 400 * needFragmentNum;
                        let coinTemplate = mgrCfg.get_from_item_template_db(Const.ITEM_ID_DIAMONDS);
                        mgrTip.alertPrompt2("提示", `是否花费${coinAmount}${coinTemplate.name}【解锁${roleData.name}】？`, "取消", "确定", null, () => {
                            if (mgrShop.tryConsumeItem(Const.ITEM_ID_DIAMONDS, coinAmount, "解锁角色")) {
                                mgrPlayer.addItemAmount(roleData.unlockItemId, needFragmentNum, "购买解锁角色碎片");
                                doUnlockFunc();
                            }
                        });
                    }
                    return;
                }
                this.selectedRoleId = roleId;
                if (mgrPlayer.getItemAmount(roleId) > 0) {
                    this.buttonChange.__node.visible = true;
                    cc.tween(this.buttonChange.__node)
                        .to(0.2, { scaleX: 1, scaleY: 1 }, cc.Ease.backOut)
                        .start();
                    Timer.callLater(0.2, () => {
                        cc.clearTween(this.buttonChange.__node);
                        cc.tween(this.buttonChange.__node)
                            .repeatForever(cc.tween().to(0.8, { scaleX: 1.1, scaleY: 1.1 }).to(0.8, { scaleX: 1, scaleY: 1 })).start();
                    });
                }
                else {
                    this.buttonChange.__node.visible = false;
                }
            }
            isSelected(id) {
                return (id && this.selectedRoleId && this.selectedRoleId == id) ? true : false;
            }
            isUsing(id) {
                return mgrRole.showingRoleId == id ? true : false;
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(`vHubScene`);
            }
            onTouchButtonChange() {
                if (!this.selectedRoleId) {
                    mgrTip.showMsgTip("请选择角色");
                    return;
                }
                if (mgrRole.showingRoleId == this.selectedRoleId) {
                    mgrTip.showMsgTip("已设置为当前角色，无需更换");
                    return;
                }
                let doExcFunc = () => {
                    let roleData = mgrCfg.get_from_role_db(this.selectedRoleId);
                    if (mgrSdk.getCopNumberValueByKey("b_statistics_part_click_count") == 1) {
                        !!roleData.statisPointId && mgrSdk.statisCommonEvent(roleData.statisPointId);
                    }
                    let oldRoleId = mgrRole.showingRoleId;
                    mgrRole.changeShowingRoleId(this.selectedRoleId);
                    let oldRolePartIds = mgrPart.getLastClothes(oldRoleId);
                    let newRolePartIds = [];
                    newRolePartIds = roleData.centerPartIds || [];
                    mgrPart.setLastClothes(newRolePartIds);
                    mgrDirector.warpSceneWidthEffect("vRoleChangeShowScene", {
                        oldRoleId: oldRoleId,
                        oldRolePartIds: oldRolePartIds,
                        newRoleId: mgrRole.showingRoleId,
                        newRolePartIds: newRolePartIds,
                        goNextSceneFunc: () => {
                            mgrDirector.warpSceneWidthEffect("vHubScene");
                            return true;
                        }
                    });
                };
                if (mgrSdk.getCopNumberValueByKey("b_alert_unnecessary_prompt") == 1) {
                    mgrTip.alertPrompt2("提示", `确定更换吗?`, "再想想", "确定", null, () => {
                        doExcFunc();
                    });
                }
                else {
                    doExcFunc();
                }
            }
            onMsgAdEventSuccessd(e) {
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vRoleChangeScene_fragment) {
                    let roleId = e.userData.roleId;
                    let callback = () => {
                        this.reuseList.refresh();
                    };
                    mgrDirector.openDialog("vGotNewRoleDialog", { roleId, bVip: true, fOnClose: callback });
                }
            }
        }

        class vRoleChangeShowScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vRoleChangeShowScene";
                this.exportNodeNames = [];
                this.CAMERA_PARAM_END = {
                    fov: 30,
                    pos: new Laya.Vector3(0, 1.38, 5),
                    rot: new Laya.Vector3(-5)
                };
            }
            getPreLoadModelIds() {
                let arr = [
                    "eff_ui_xsyd",
                    "tailuo",
                    "men_dengchang",
                    "shouchi014_dengchang"
                ];
                if (this.context.oldRoleId) {
                    arr.push("eff_ui_hzc_glow");
                }
                if (this.context.oldRolePartIds) {
                    for (let k in this.context.oldRolePartIds) {
                        let partData = mgrCfg.get_from_part_db(this.context.oldRolePartIds[k]);
                        arr.push(partData.modelId);
                    }
                }
                if (this.context.newRolePartIds) {
                    for (let k in this.context.newRolePartIds) {
                        let partData = mgrCfg.get_from_part_db(this.context.newRolePartIds[k]);
                        arr.push(partData.modelId);
                    }
                }
                return arr;
            }
            getPreLoadAnimationIds() {
                let arr = [
                    "face_huanren_dengchang-face_dengchang_show",
                    "huanren_dengchang-dengchang_show",
                    "men_dengchang-men_dc_come",
                    "men_dengchang-men_dc_idle",
                    "men_dengchang-men_dc_show",
                    "shouchi014_dengchang-shouchi014_dc_come",
                    "shouchi014_dengchang-shouchi014_dc_idle",
                    "shouchi014_dengchang-shouchi014_dc_show",
                    "shouchi014_dengchang-tpose",
                    "tailuo_dengchang-tailuo_dc_come",
                    "tailuo_dengchang-tailuo_dc_idle",
                    "tailuo_dengchang-tailuo_dc_show",
                ];
                if (this.context.oldRoleId) {
                    arr.concat([
                        "face_huanren_lichang-face_huanren_lichang",
                        "huanren_lichang-huanren_lichang",
                        "men_lichang-men_lichang",
                        "tailuo_lichang-tailuo_lc",
                        "tailuo_lichang-tailuo_lc_shifa",
                    ]);
                }
                return arr;
            }
            getPreLoadImagePaths() {
                let arr = [];
                let oldRoleData = mgrCfg.get_from_role_db(this.context.oldRoleId);
                if (oldRoleData && oldRoleData.roleYanqiuTexture && oldRoleData.roleYanqiuTexture != "") {
                    arr.push(oldRoleData.roleYanqiuTexture);
                }
                let newRoleData = mgrCfg.get_from_role_db(this.context.newRoleId);
                if (newRoleData && newRoleData.roleYanqiuTexture && newRoleData.roleYanqiuTexture != "") {
                    arr.push(newRoleData.roleYanqiuTexture);
                }
                return arr;
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.widget();
                this.avatar.registerAllLoadEndCallback(() => {
                    if (this.context.oldRoleId) {
                        this.playLiChangTimeline(() => {
                            mgrTip.showLoadingTip("role_show_tm_loading");
                            this.avatar.changeRoleId(this.context.newRoleId);
                            this.avatar.fillByPartIds(this.context.newRolePartIds, true);
                            this.avatar.registerAllLoadEndCallback(() => {
                                mgrTip.hideLoadingTip("role_show_tm_loading");
                                this.playDengChangTimeline(() => {
                                    let roleData = mgrCfg.get_from_role_db(this.context.newRoleId);
                                    mgrSound.play(roleData.soundId);
                                    this.goHub();
                                });
                            });
                        });
                    }
                    else {
                        this.playDengChangTimeline(() => {
                            let roleData = mgrCfg.get_from_role_db(this.context.newRoleId);
                            mgrSound.play(roleData.soundId);
                            this.goHub();
                        });
                    }
                });
            }
            goHub() {
                if (!!this.bGone) {
                    return;
                }
                this.bGone = true;
                mgrVideoRecorder.stopRecord();
                let roleData = mgrCfg.get_from_role_db(this.context.newRoleId);
                mgrSound.stopAll();
                if (this.bUserStoped) {
                    if (!this.context.goNextSceneFunc || !this.context.goNextSceneFunc()) {
                        mgrDirector.warpSceneWidthEffect(`vHubScene`);
                    }
                }
                else {
                    mgrTip.tryShowPhotoShare("vRoleChangeShowScene", roleData.defaultCardTexture, null, () => {
                        if (!this.context.goNextSceneFunc || !this.context.goNextSceneFunc()) {
                            mgrDirector.warpSceneWidthEffect(`vHubScene`);
                        }
                    });
                }
            }
            onClosed() {
                mgrTip.hideLoadingTip("role_show_tm_loading");
                if (this.avatar) {
                    this.avatar.destroy();
                }
                super.onClosed();
            }
            buildUi() {
                this.spriteBg.zOrder = -5;
                if (this.context.oldRoleId) {
                    let params = {
                        roleId: this.context.oldRoleId,
                        bDisableDynamic: true
                    };
                    this.avatar = new RoleAvatar(params);
                    this.add3DEffectAtBack(this.avatar, 0);
                    this.avatar.changeRoleId(this.context.oldRoleId);
                    this.avatar.fillByPartIds(this.context.oldRolePartIds, true);
                }
                else {
                    let params = {
                        roleId: this.context.newRoleId,
                        bDisableDynamic: true
                    };
                    this.avatar = new RoleAvatar(params);
                    this.add3DEffectAtBack(this.avatar, 0);
                    this.avatar.changeRoleId(this.context.newRoleId);
                    this.avatar.fillByPartIds(this.context.newRolePartIds, true);
                }
                let cf = this.cameraBack.getComponent(CameraFollow);
                cf.lookMode = E_CAMERA_MODE.fixMode;
                cf.fov = this.CAMERA_PARAM_END.fov;
                cf.position = this.CAMERA_PARAM_END.pos;
                cf.endRotation = this.CAMERA_PARAM_END.rot;
                cf.lerpValue = 1;
                cf.onLateUpdate();
            }
            widget() {
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            playDengChangTimeline(callback) {
                if (this.bUserStoped) {
                    return;
                }
                let template = mgrCfg.get_from_timeline_template_db("dengchang");
                let director = new PlayableDirector();
                this.currentDirector = director;
                director.setLoopFrame(220, 280);
                director.stopUpdateOnlyWhenFinish = true;
                mgrTip.showLoadingTip("role_show_tm_loading");
                director.load(template.path, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    mgrTip.hideLoadingTip("role_show_tm_loading");
                    this.add3DEffectAtBack(director);
                    this.cameraBack.active = false;
                    let tailuo = director.findChild("tailuo");
                    mgrMaterial.setCustomMaterial(tailuo, "tailuo");
                    let menModel = director.findChild("men_dengchang");
                    mgrMaterial.setCustomMaterial(menModel, "men_dengchang");
                    let shouchiModel = director.findChild("shouchi014_dengchang");
                    mgrMaterial.setCustomMaterial(shouchiModel, "shouchi014_dengchang");
                    let replaceNodes = director.replaceNode("Director/role", this.avatar, true);
                    director.on("STOPPED", this, () => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        if (!!replaceNodes) {
                            for (let i = 0; i < replaceNodes.length; i++) {
                                const element = replaceNodes[i];
                                element.node.destroy();
                            }
                        }
                        this.avatar.removeSelf();
                        this.add3DEffectAtBack(this.avatar);
                        director.removeSelf();
                        director.destroy();
                        callback && callback();
                    });
                    director.on("LOOP_START", this, () => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        Tools.registerTouchHander(this, (e) => {
                            if (e.isBegin) {
                                Tools.unRegisterTouchHander(this);
                                director.jumpTo(281, false);
                                Timer.callLater(5 / 30, () => {
                                    if (!this.nodeResource || this.nodeResource.destroyed) {
                                        return;
                                    }
                                    mgrSound.play(575);
                                }, this);
                                Timer.callLater(16 / 30, () => {
                                    if (!this.nodeResource || this.nodeResource.destroyed) {
                                        return;
                                    }
                                    mgrSound.play(576);
                                }, this);
                                Timer.callLater(49 / 30, () => {
                                    if (!this.nodeResource || this.nodeResource.destroyed) {
                                        return;
                                    }
                                    mgrSound.play(577);
                                }, this);
                            }
                        });
                    });
                    director.once("START", this, () => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        if (!this.context.oldRoleId) {
                            mgrVideoRecorder.startRecord();
                        }
                        Timer.callLater(280 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.avatar.playRoleFaceAnimation(ROLE_FACE_MOV.chijing);
                        }, this);
                        Timer.callLater(310 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.avatar.playRoleFaceAnimation(ROLE_FACE_MOV.haixiu);
                        }, this);
                        Timer.callLater(340 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.avatar.playRoleFaceAnimation(ROLE_FACE_MOV.biyan);
                        }, this);
                        Timer.callLater(417 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.avatar.playRoleFaceAnimation(ROLE_FACE_MOV.biyan);
                        }, this);
                        Timer.callLater(488 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.avatar.playRoleFaceAnimation(ROLE_FACE_MOV.idle);
                        }, this);
                        Timer.callLater(20 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            mgrSound.play(571);
                        }, this);
                        Timer.callLater(95 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            mgrSound.play(572);
                        }, this);
                        Timer.callLater(120 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            mgrSound.play(573);
                        }, this);
                        Timer.callLater(210 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            mgrSound.play(574);
                        }, this);
                    });
                    director.play();
                });
            }
            playLiChangTimeline(callback) {
                let template = mgrCfg.get_from_timeline_template_db("lichang");
                let director = new PlayableDirector();
                this.currentDirector = director;
                mgrTip.showLoadingTip("role_show_tm_loading");
                director.load(template.path, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    mgrTip.hideLoadingTip("role_show_tm_loading");
                    this.add3DEffectAtBack(director);
                    this.cameraBack.active = false;
                    let tailuo = director.findChild("tailuo");
                    mgrMaterial.setCustomMaterial(tailuo, "tailuo");
                    let menModel = director.findChild("men_dengchang");
                    mgrMaterial.setCustomMaterial(menModel, "men_dengchang");
                    let shouchiModel = director.findChild("shouchi014_dengchang");
                    mgrMaterial.setCustomMaterial(shouchiModel, "shouchi014_dengchang");
                    let replaceNodes = director.replaceNode("Director/role", this.avatar, true);
                    director.on("STOPPED", this, () => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        if (!!replaceNodes) {
                            for (let i = 0; i < replaceNodes.length; i++) {
                                const element = replaceNodes[i];
                                element.node.destroy();
                            }
                        }
                        this.cameraBack.active = true;
                        this.avatar.removeSelf();
                        this.add3DEffectAtBack(this.avatar);
                        director.removeSelf();
                        director.destroy();
                        callback && callback();
                    });
                    director.once("START", this, () => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        mgrVideoRecorder.startRecord();
                        Timer.callLater(46 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.avatar.playRoleFaceAnimation(ROLE_FACE_MOV.idle);
                        }, this);
                        Timer.callLater(85 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.avatar.playRoleFaceAnimation(ROLE_FACE_MOV.chijing);
                        }, this);
                        Timer.callLater(121 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.avatar.playRoleFaceAnimation(ROLE_FACE_MOV.nanguo);
                        }, this);
                        Timer.callLater(60 / 30, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            mgrSound.play(578);
                        });
                    });
                    director.play();
                });
            }
            onTouchButtonGetNormal() {
                this.bUserStoped = true;
                this.currentDirector.destroy();
                this.currentDirector = null;
                this.buttonGetNormal.__node.visible = false;
                this.goHub();
            }
        }

        class vRoomStageResultScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vRoomStageResultScene";
                this.avatarPosRotDict = {
                    [-1]: { pos: new Laya.Vector3(-0.82, 0, -1.82), rot: new Laya.Vector3 },
                    [0]: { pos: new Laya.Vector3(0, 0, 0.1), rot: new Laya.Vector3 },
                    [1]: { pos: new Laya.Vector3(0.57, 0, -0.96), rot: new Laya.Vector3 },
                };
                this.preInitData();
            }
            onOpened() {
                super.onOpened();
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.buildUi();
                this.widget();
                this.fillData();
            }
            onClosed() {
                super.onClosed();
            }
            getPreLoadModelIds() {
                return [];
            }
            getPreLoadAnimationIds() {
                return [
                    "jiesuan_ruchang-jiesuan_ruchang",
                    "jiesuan_shibai-jiesuan_shibai",
                    "jiesuan_teshu-jiesuan_teshu",
                    "dangao-dg_gq",
                ];
            }
            getPreLoadImagePaths() {
                let arr = [];
                if (this.stageData.textureResultBg && this.stageData.textureResultBg != "") {
                    arr.push(this.stageData.textureResultBg);
                }
                return arr;
            }
            preInitData() {
                this.stageData = mgrCfg.get_from_stage_db(this.context.stageId);
                this.bSuccess = this.context.result.score > 60 ? true : false;
            }
            buildUi() {
                if (this.stageData.textureResultBg && this.stageData.textureResultBg != "") {
                    Tools.loadImg(this.spriteBg, this.stageData.textureResultBg);
                }
                this.spriteBg.zOrder = -4;
                this.spriteTitle.visible = false;
                let params = {
                    roleId: mgrRole.showingRoleId
                };
                this.avatar = new RoleAvatar(params);
                this.add3DEffectAtBack(this.avatar, 0);
                this.avatar.fillByPartIds(mgrPart.getLastClothes(mgrRole.showingRoleId));
                this.avatar.registerLoadEndCallback(() => {
                    this.playAvatarComeIn(() => {
                        let aniId = null;
                        if (!!this.context.bDressedLuckyPart) {
                            aniId = "jiesuan_teshu-jiesuan_teshu";
                        }
                        else {
                            aniId = this.bSuccess ? "dangao-dg_gq" : "jiesuan_shibai-jiesuan_shibai";
                        }
                        this.avatar.playAnimation(aniId);
                        this.playJudgeAction(() => {
                            this.colorPointHandler();
                        });
                    });
                });
                let cf = this.cameraBack.getComponent(CameraFollow);
                cf.lookMode = E_CAMERA_MODE.fixMode;
                cf.fov = 30;
                cf.position = new Laya.Vector3(0, 1.39, 4.4);
                cf.endRotation = new Laya.Vector3(-8);
                cf.lerpValue = 1;
                cf.onLateUpdate();
                this.spriteRateWord1.scale(0, 0, true);
                this.spriteRateEmoj.scale(0, 0, true);
                this.spriteRateWord2.scale(0, 0, true);
                this.spriteRateLike.scale(0, 0, true);
            }
            widget() {
            }
            fillData() {
                if (!this.bSuccess) {
                    this.labelRateWord1.text = `加油加油`;
                    this.labelRateWord2.text = `再接再厉`;
                }
            }
            playAvatarComeIn(callback) {
                this.avatar.transform.position = this.avatarPosRotDict[0].pos;
                this.avatar.transform.rotationEuler = this.avatarPosRotDict[0].rot;
                callback && callback();
            }
            playJudgeAction(callback) {
                cc.tween(this.spriteRateWord1).delay(0.1).toScale(0.15, 1, cc.Ease.backOut).start();
                cc.tween(this.spriteRateEmoj).delay(0.2).toScale(0.15, 1, cc.Ease.backOut).start();
                cc.tween(this.spriteRateWord2).delay(0.2).toScale(0.15, 1, cc.Ease.backOut).start();
                cc.tween(this.spriteRateLike).delay(0.15).toScale(0.15, 1, cc.Ease.backOut).start();
                Timer.callLater(0.4, () => {
                    callback && callback();
                }, this);
            }
            colorPointHandler() {
                let rewardRatio = !!this.context.bDressedLuckyPart ? 2 : 1;
                let gameWorldDailyData = mgrCfg.get_from_cloth_daily_quest_config(mgrWorldDaily.getWorldDay()) || mgrCfg.get_from_cloth_daily_quest_config(1);
                mgrPlayer.addItemAmount(gameWorldDailyData.rewardItemId, gameWorldDailyData.rewardItemAmount * rewardRatio, "换装结算奖励");
                let rewardColorPoint = (!!this.bSuccess ? this.stageData.bestRewardColorPoint : this.stageData.goodRewardColorPoint) * rewardRatio;
                this.oldColorPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_ROOM_COLOR);
                this.currGotColorPoint = rewardColorPoint;
                mgrPlayer.addItemAmount(Const.ITEM_ID_ROOM_COLOR, rewardColorPoint, "换装结算奖励");
                this.spriteTitleSuccess.visible = !!this.bSuccess;
                this.spriteTitleFaild.visible = !this.spriteTitleSuccess.visible;
                this.spriteTitle.visible = true;
                this.spriteTitle.scale(3, 3, true);
                if (this.bSuccess) {
                    mgrSound.play(Tools.random(321, 323));
                }
                else {
                    mgrSound.play(Tools.random(331, 332));
                }
                cc.tween(this.spriteTitle).toScale(0.1, 1)
                    .call(() => {
                    if (!!this.bSuccess) {
                        mgrSound.play(312);
                    }
                    else {
                        mgrSound.play(313);
                    }
                })
                    .delay(0.4)
                    .call(() => {
                    let gotCoinFunc = () => {
                        let rewardRmb = (!!this.bSuccess ? this.stageData.bestRewardRmbAmount : this.stageData.goodRewardRmbAmount) * rewardRatio;
                        mgrPlayer.addItemAmount(Const.ITEM_ID_DIAMONDS, rewardRmb, "换装结算奖励");
                        mgrTip.addGotItemTip(Const.ITEM_ID_DIAMONDS, rewardRmb, null, {
                            fOnClose: () => {
                                let callback = () => {
                                    let onSelected = (bMake) => {
                                        if (bMake) {
                                            mgrDirector.warpSceneWidthEffect(`vAmuseCardPhotoMakeScene`, {
                                                fromViewDesc: "换装关卡",
                                                backSceneName: this.context.backSceneName || `vWorldDailyQuestMainScene`,
                                            });
                                        }
                                        else {
                                            let cameraFollow = this.cameraBack.getComponent(CameraFollow);
                                            let oldPos = cameraFollow.position.clone();
                                            let oldFov = cameraFollow.fov;
                                            let oldRot = cameraFollow.endRotation.clone();
                                            cameraFollow.position = new Laya.Vector3(0, 1.2, 2);
                                            cameraFollow.fov = 30;
                                            cameraFollow.lerpValue = 1;
                                            cameraFollow.endRotation = new Laya.Vector3(-2.5);
                                            cameraFollow.onLateUpdate();
                                            Tools.takeAPhoto(512, 512, this.cameraBack, (tex2d) => {
                                                cameraFollow.position = oldPos;
                                                cameraFollow.fov = oldFov;
                                                cameraFollow.endRotation = oldRot;
                                                mgrVideoRecorder.stopRecord();
                                                mgrTip.tryShowPhotoShare("vRoomDialog", tex2d, null, () => {
                                                    mgrDirector.warpSceneWidthEffect(`vWorldDailyQuestMainScene`, {
                                                        bSuccess: this.bSuccess,
                                                        dailyGameType: DailyGameType.cloth,
                                                        bFromGameResult: true
                                                    });
                                                });
                                            }, Laya.RenderTextureFormat.R8G8B8A8);
                                        }
                                    };
                                    onSelected(false);
                                };
                                let bGotAllSuitPart = true;
                                let data = mgrCfg.get("ad_suit_config_db", 1);
                                let suitIds = data.suitIds || [];
                                for (let i = 0; i < suitIds.length; i++) {
                                    if (!mgrPart.isSuitCollectionCompleted(suitIds[i])) {
                                        bGotAllSuitPart = false;
                                        break;
                                    }
                                }
                                if (!bGotAllSuitPart && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vHubScene_warp)) {
                                    mgrDirector.openDialog("vAdSuitDialog", {
                                        fOnClose: () => {
                                            callback();
                                        }
                                    });
                                }
                                else {
                                    callback();
                                }
                            }
                        });
                    };
                    if (!this.bSuccess) {
                        gotCoinFunc();
                    }
                    else {
                        let rewardPartId = mgrWorldDaily.getNextRewardPartId(DailyGameType.cloth);
                        if (!rewardPartId) {
                            gotCoinFunc();
                            return;
                        }
                        mgrDirector.openDialog("vAmuseCakeResultDialog", {
                            colorItemId: Const.ITEM_ID_ROOM_COLOR,
                            oldColorPoint: this.oldColorPoint,
                            currGotColorPoint: this.currGotColorPoint,
                            dailyGameType: DailyGameType.cloth,
                            bSuccess: this.bSuccess,
                            rewardPartId: rewardPartId,
                            fOnClose: () => {
                                gotCoinFunc();
                            }
                        });
                    }
                })
                    .start();
            }
            onMsgAdEventSuccessd(e) {
            }
        }

        class vSuitTypeScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vSuitTypeScene";
            }
            onOpened() {
                super.onOpened();
                this.buildUi();
                this.fillData();
                this.playUiAction();
                mgrSound.play(502);
                this.addGridAd();
            }
            onClosed() {
                super.onClosed();
            }
            buildUi() {
                this.add3DEffectAtFront("eff_ui_shop_glow", this.boxContainerMC, 0, 1);
                let db = mgrCfg.getDbArr("suit_type_db", (data) => {
                    if (data && data.bHandwork && mgrDesign.getDesignPartCount() <= 0) {
                        return false;
                    }
                    return true;
                });
                let arr = [];
                for (let key in db) {
                    arr.push(db[key]);
                }
                arr.forEach((v, i) => {
                    v["fOnClick"] = this.selectSuitType.bind(this);
                    v["index"] = i;
                });
                this.reuseList = new ReuseList(1, 0, 4);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vSuitTypeListItem);
                if (arr.length > 3) {
                    this.reuseList.setVerticalMoveEnable(true);
                }
                else {
                    this.reuseList.setVerticalMoveEnable(false);
                    this.reuseList.setTouchEnable(false);
                }
                this.reuseList.setSpaceX(0);
                this.reuseList.setSpaceY(0);
                this.reuseList.setDatas(arr);
                this.widget();
                this.refresh();
                Timer.callLoop(1, this.refresh.bind(this), this);
            }
            fillData() {
                let max = mgrPart.getMaxPartNum();
                let cur = mgrPart.getAllHavedPartIds().length;
                this.labelSuitNum.text = `${cur}/${max}`;
                this.labelDesc.text = `超过${Math.floor(cur / (max || 1) * 100)}%的玩家`;
            }
            selectSuitType(categoryId) {
                let categoryData = mgrCfg.get_from_suit_type_db(categoryId);
                if (categoryData.bHandwork) {
                    mgrDirector.warpSceneWidthEffect("vDesignCollectScene", { bFromTypeScene: true });
                }
                else {
                    mgrDirector.openDialog("vSuitShowingDialog", { categoryId, fOnClose: this.onShowingClosed.bind(this) });
                }
            }
            refresh() {
            }
            widget() {
                mgrLayout.widgetLeftBottomMC(this.boxLeftBottom);
                mgrLayout.widgetBottomMC(this.spriteMySuitNum);
                mgrLayout.widgetRightBottomMC(this.spriteJumpOtherGame);
            }
            playUiAction() {
                this.buttonBack.__node.alpha = 0;
                this.spriteMySuitNum.alpha = 0;
                cc.tween(this.buttonBack.__node).delay(1.0).toAlpha(0.5, 1).start();
                cc.tween(this.spriteMySuitNum).delay(1.0).toAlpha(0.5, 1).start();
            }
            onShowingClosed() {
                Timer.callLater(0.5, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    this.fillData();
                });
            }
            addGridAd() {
                let gridAd = new vGridAd({ advId: "30001", copStr: "grid_ad_ratio3" });
                this.addChild(gridAd);
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect(`vHubScene`);
            }
        }

        var WaveDirection;
        (function (WaveDirection) {
            WaveDirection[WaveDirection["X"] = 0] = "X";
            WaveDirection[WaveDirection["Y"] = 1] = "Y";
            WaveDirection[WaveDirection["Z"] = 2] = "Z";
        })(WaveDirection || (WaveDirection = {}));
        class vTestModelDeformScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vTestModelDeformScene";
                this.exportNodeNames = [];
                this.reuseList = null;
                this.avatar = null;
                this._weight = 0;
                this._2PI = Math.PI * 2;
                this.Direction = WaveDirection.Y;
                this.IsFlat = false;
                this.WavePower = 1;
                this.WaveSpeed = 1;
                this._isGenerate = false;
            }
            canOperateCamera() {
                return false;
            }
            onOpened() {
                super.onOpened();
                mgrDirector.adaptStageSize(2304, 1580);
                Laya.stage.on(Laya.Event.MOUSE_WHEEL, this, (e) => {
                    this.avatar.transform.localPositionZ += e.delta / 20;
                });
                let rightDown = false;
                let lastX = 0;
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_DOWN, this, (e) => {
                    rightDown = true;
                    lastX = e.stageX;
                });
                Laya.stage.on(Laya.Event.RIGHT_MOUSE_UP, this, (e) => {
                    rightDown = false;
                });
                Laya.stage.on(Laya.Event.MOUSE_MOVE, this, (e) => {
                    if (!rightDown)
                        return;
                    let delta = e.stageX - lastX;
                    lastX = e.stageX;
                    this.avatar && this.avatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                    this.roleAvatar && this.roleAvatar.transform.rotate(new Laya.Vector3(0, delta, 0), false, false);
                });
                Tools.registerTouchHander(this.spriteBg, this.onTouchSpriteBg.bind(this));
                this.spriteBg.zOrder = -4;
                this.buildUi();
                this.fillData();
                this.buttonSearch.fOnClick = () => {
                    this.fillData();
                };
                this.buttonShowAllModel.fOnClick = () => {
                };
                this.buttonShowPartModel.fOnClick = () => {
                };
                this.buttonClose.fOnClick = () => {
                    mgrDirector.warpSceneWidthEffect("vHubScene");
                };
                this.registerListeners({
                    MSG_DEBUG_KEY_DOWN: (k) => {
                        if (k == `escape`) {
                            this.curModel = null;
                            this.avatar.removeChildren();
                        }
                    }
                });
            }
            onClosed() {
                super.onClosed();
            }
            onTouchSpriteBg(e) {
                if (e.isBegin) {
                    this.bTouchBg = true;
                    this.lastTouchBgPos = e.pos;
                    this.lastBeginPos = e.pos;
                }
                if (e.isCancel || e.isEnd) {
                    this.bTouchBg = false;
                }
                if (this.bTouchBg) {
                    let deltaX = e.pos.x - this.lastTouchBgPos.x;
                    let deltaY = e.pos.y - this.lastTouchBgPos.y;
                    this.lastTouchBgPos = e.pos;
                    this.avatar
                        && this.avatar.transform
                            .translate(new Laya.Vector3(deltaX / mgrDirector.width, -deltaY / mgrDirector.height, 0), true);
                }
            }
            buildUi() {
                this.reuseList = new ReuseList(1, 0, 20);
                this.reuseList.size(this.boxList.width, this.boxList.height);
                this.boxList.addChild(this.reuseList);
                this.reuseList.setItemClass(vEditorCartonMaterialPart);
                this.reuseList.setVerticalMoveEnable(true);
                this.avatar = new Laya.Sprite3D;
                this.add3DEffectAtBack(this.avatar);
                let cf = this.directitonLight.getComponent(CameraFollow);
                cf.endRotation = new Laya.Vector3(-5, 27, -17.27);
            }
            fillData() {
                let regexp = null;
                if (this.inputText.text.length != 0) {
                    regexp = new RegExp(this.inputText.text);
                }
                if (!this.allPartModelDict) {
                    let partModelDict = {};
                    mgrCfg.forDb_from_part_db((k, v) => {
                        partModelDict[v.modelId] = v.id;
                    });
                    this.allPartModelDict = partModelDict;
                }
                let datas = [];
                mgrCfg.forDb_from_model_db((k, v) => {
                    if (v.id.startsWith("eff_") || v.id.startsWith("e_")) {
                        return;
                    }
                    if (this.bOnlyPart && !this.allPartModelDict[v.id]) {
                        return;
                    }
                    if (!regexp) {
                        datas.push({
                            modelId: v.id,
                            fOnClickModel: this.onSelectModel.bind(this),
                            skinName: null,
                            fOnClickSkinName: null,
                        });
                    }
                    else {
                        if (regexp.test(v.id)) {
                            datas.push({
                                modelId: v.id,
                                fOnClickModel: this.onSelectModel.bind(this),
                                skinName: null,
                                fOnClickSkinName: null,
                            });
                        }
                    }
                });
                this.reuseList.setDatas(datas);
            }
            onSelectModel(modelId) {
                mgrLoader.loadModeWithModeId(modelId, () => {
                    this.curModel = mgrLoader.Pool.getModel(modelId);
                    this.curModel.transform.localRotationY = 90;
                    this.curModel.transform.localRotationY = 180;
                    this.curModel.transform.localRotationZ = -180;
                    this.avatar.addChild(this.curModel);
                    let meshData;
                    let posMeshArr = [];
                    let vertices;
                    let normals = [];
                    let render = Tools.getMeshRender(this.curModel);
                    let indexies;
                    if (render) {
                        let meshFilter = this.curModel["_meshFilter"];
                        if (meshFilter) {
                            meshData = meshFilter.sharedMesh;
                            meshData.getPositions(posMeshArr);
                            vertices = meshData.getVertices();
                            meshData.getNormals(normals);
                            indexies = meshData.getIndices();
                        }
                    }
                    if (!meshData) {
                        let numChildren = this.curModel.numChildren;
                        for (let i = 0; i < numChildren; i++) {
                            let node = this.curModel.getChildAt(i);
                            render = Tools.getMeshRender(node);
                            if (!render) {
                                continue;
                            }
                            let meshFilter = node["_meshFilter"];
                            if (!meshFilter) {
                                continue;
                            }
                            meshData = meshFilter.sharedMesh;
                            meshData.getPositions(posMeshArr);
                            vertices = meshData.getVertices();
                            meshData.getNormals(normals);
                            break;
                        }
                    }
                    let rotateModelMeshY = (positionArr, rot) => {
                        let arr = [];
                        for (let i = 0; i < positionArr.length; i++) {
                            let posModel = positionArr[i];
                            let r = Math.sqrt(Math.abs(posModel.x * posModel.x) + Math.abs(posModel.z * posModel.z));
                            if (!r) {
                                arr.push(posModel);
                                continue;
                            }
                            let tmpCircleCenterPos = new Laya.Vector2(0, 0);
                            let oRot = Tools.getAngle(posModel.x, posModel.z);
                            let posBorder = Tools.getCircleBorderPosPoint(tmpCircleCenterPos, r, oRot + rot);
                            let cPos = new Laya.Vector3(posModel.x + posBorder.y, posModel.y, posModel.z + posBorder.x);
                            arr.push(cPos);
                        }
                        return arr;
                    };
                    Timer.callLater(3, () => {
                        let arr = rotateModelMeshY(posMeshArr, 45);
                        meshData.setPositions(arr);
                    }, this);
                    return;
                    Timer.callLater(3, () => {
                        this.WavePower = 1;
                        let heightModel = 3.2;
                        let newPosArr = [];
                        for (let i = 0; i < posMeshArr.length; i++) {
                            let pos = posMeshArr[i].clone();
                            let posScaled = new Laya.Vector3();
                            let scaleDis = 0.2;
                            let scale = 1;
                            if (pos.y < scaleDis) {
                                scale = pos.y / scaleDis;
                            }
                            else if (pos.y > (heightModel - scaleDis)) {
                                scale = (scaleDis - (heightModel - pos.y)) / scaleDis;
                            }
                            else {
                            }
                            Laya.Vector3.scale(pos, scale, posScaled);
                            newPosArr.push(new Laya.Vector3(posScaled.x, pos.y, posScaled.z));
                        }
                        meshData.setPositions(newPosArr);
                        Timer.callLater(3, () => {
                            let r = 0.5;
                            let s = 2 * Math.PI * r;
                            let centerPos3d = new Laya.Vector3(0, 0, 0);
                            let startBorderPos = new Laya.Vector3(0, r, 0);
                            let tmpCircleCenterPos = new Laya.Vector2(0, 0);
                            let circledPosArr = [];
                            for (let i = 0; i < newPosArr.length; i++) {
                                let posModel = newPosArr[i];
                                let useR = r + Math.abs(posModel.z);
                                let cl = Math.abs(posModel.y);
                                let rot = (cl / (2 * Math.PI * r)) * 360;
                                let soffset = Math.sin(rot * 36) * 0.05;
                                let posBorder = Tools.getCircleBorderPosPoint(tmpCircleCenterPos, useR, rot);
                                let cPos = new Laya.Vector3(posModel.x + soffset, posBorder.y, posBorder.x);
                                circledPosArr.push(cPos);
                            }
                            meshData.setPositions(circledPosArr);
                        }, this);
                    }, this);
                }, this, 1);
            }
            OnBeginEffect(meshData) {
                switch (this.Direction) {
                    case WaveDirection.X:
                        if (this.IsFlat)
                            this._applyWave = this.ApplyWaveFlatX;
                        else
                            this._applyWave = this.ApplyWaveX;
                        break;
                    case WaveDirection.Y:
                        if (this.IsFlat)
                            this._applyWave = this.ApplyWaveFlatY;
                        else
                            this._applyWave = this.ApplyWaveY;
                        break;
                    case WaveDirection.Z:
                        if (this.IsFlat)
                            this._applyWave = this.ApplyWaveFlatZ;
                        else
                            this._applyWave = this.ApplyWaveZ;
                        break;
                }
                if (!this._isGenerate) {
                    this._isGenerate = true;
                    this._positions = new Laya.Vector3[meshData.vertices.length];
                    for (let i = 0; i < meshData.vertices.length; i++) {
                        console.log("----TODO");
                    }
                }
            }
            OnUpdateEffect(meshData) {
                this.UpdateWeight();
                for (let i = 0; i < meshData.vertices.length; i++) {
                    let vertex = meshData.vertices[i];
                    vertex.Position = this._applyWave(this._positions[i]);
                }
            }
            OnEndEffect(meshData) {
            }
            UpdateWeight() {
                if (this._weight < this._2PI) {
                    this._weight += 0.01 * this.WaveSpeed;
                }
                else {
                    this._weight = 0;
                }
            }
            ApplyWaveX(vertex) {
                vertex.y += this.WavePower * Math.sin(vertex.x + this._weight);
                return vertex;
            }
            ApplyWaveY(vertex) {
                vertex.x += this.WavePower * Math.sin(vertex.y + this._weight);
                return vertex;
            }
            ApplyWaveZ(vertex) {
                vertex.y += this.WavePower * Math.sin(vertex.z + this._weight);
                return vertex;
            }
            ApplyWaveFlatX(vertex) {
                vertex.y = this.WavePower * Math.sin(vertex.x + this._weight);
                return vertex;
            }
            ApplyWaveFlatY(vertex) {
                vertex.x = this.WavePower * Math.sin(vertex.y + this._weight);
                return vertex;
            }
            ApplyWaveFlatZ(vertex) {
                vertex.y = this.WavePower * Math.sin(vertex.z + this._weight);
                return vertex;
            }
        }

        var WORLD_DAILY_QUEST_MAIN_STATE;
        (function (WORLD_DAILY_QUEST_MAIN_STATE) {
            WORLD_DAILY_QUEST_MAIN_STATE[WORLD_DAILY_QUEST_MAIN_STATE["init"] = 1] = "init";
            WORLD_DAILY_QUEST_MAIN_STATE[WORLD_DAILY_QUEST_MAIN_STATE["gotDayPoint"] = 2] = "gotDayPoint";
            WORLD_DAILY_QUEST_MAIN_STATE[WORLD_DAILY_QUEST_MAIN_STATE["changeDay"] = 3] = "changeDay";
            WORLD_DAILY_QUEST_MAIN_STATE[WORLD_DAILY_QUEST_MAIN_STATE["inDay"] = 4] = "inDay";
            WORLD_DAILY_QUEST_MAIN_STATE[WORLD_DAILY_QUEST_MAIN_STATE["cardFight"] = 5] = "cardFight";
        })(WORLD_DAILY_QUEST_MAIN_STATE || (WORLD_DAILY_QUEST_MAIN_STATE = {}));
        class vWorldDailyQuestMainScene extends SceneBase {
            constructor(context) {
                super(context);
                this.sourceName = "scene/vWorldDailyQuestMainScene";
                this.DAY_2_GAME_BG_DICT = {
                    [0]: "res/ui/world_daily_quest_zz/game_bg/sprite_item_bg7.png",
                    [1]: "res/ui/world_daily_quest_zz/game_bg/sprite_item_bg1.png",
                    [2]: "res/ui/world_daily_quest_zz/game_bg/sprite_item_bg2.png",
                    [3]: "res/ui/world_daily_quest_zz/game_bg/sprite_item_bg3.png",
                    [4]: "res/ui/world_daily_quest_zz/game_bg/sprite_item_bg4.png",
                    [5]: "res/ui/world_daily_quest_zz/game_bg/sprite_item_bg5.png",
                    [6]: "res/ui/world_daily_quest_zz/game_bg/sprite_item_bg6.png",
                };
                this.DAY_BG_ITEM_COUNT = 7;
            }
            getPreLoadModelIds() {
                return [];
            }
            getPreLoadAnimationIds() {
                return [];
            }
            getPreLoadImagePaths() {
                return [];
            }
            onOpened() {
                super.onOpened();
                Tools.registerTouchHander(this.boxEventFront, () => { });
                mgrSound.play(3);
                mgrSound.play(601);
                this.buildUi();
                this.widget();
                this.stManager = new FSMObject;
                this.stManager.registerState(WORLD_DAILY_QUEST_MAIN_STATE.init, this.inInit.bind(this), this.exeInit.bind(this), this.outInit.bind(this));
                this.stManager.registerState(WORLD_DAILY_QUEST_MAIN_STATE.gotDayPoint, this.inGotDayPoint.bind(this), this.exeGotDayPoint.bind(this), this.outGotDayPoint.bind(this));
                this.stManager.registerState(WORLD_DAILY_QUEST_MAIN_STATE.changeDay, this.inChangeDay.bind(this), this.exeChangeDay.bind(this), this.outChangeDay.bind(this));
                this.stManager.registerState(WORLD_DAILY_QUEST_MAIN_STATE.inDay, this.inDay.bind(this), this.exeDay.bind(this), this.outDay.bind(this));
                this.stManager.registerState(WORLD_DAILY_QUEST_MAIN_STATE.cardFight, this.inCardFight.bind(this), this.exeCardFight.bind(this), this.outCardFight.bind(this));
                this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.init);
                this.stManager.startUpdate(this);
                this.boxPartList.alpha = 0;
                this.boxWarnLockContainer.visible = false;
                this.buttonBack.__node.visible = false;
                mgrTip.tryShowFullScreenMoreGameFixed("b_fsmgfs_world_daily");
                this.uiActionIn(() => {
                    this.boxPartList.alpha = 1;
                    this.doItemRouterHandler();
                    if (!!this.callbackAfterUiAction) {
                        this.callbackAfterUiAction();
                    }
                });
                this.registerListeners({
                    MSG_AD_EVENT_SUCCESSD: this.onMsgAdEventSuccessd.bind(this)
                });
                this.addGridAd();
            }
            onClosed() {
                super.onClosed();
            }
            doItemRouterHandler() {
                if (!this.context.bFromItemRouter) {
                    return;
                }
                if (this.context.dailyGameType) {
                    switch (this.context.dailyGameType) {
                        case DailyGameType.cake:
                        case DailyGameType.cloth:
                        case DailyGameType.custom_made:
                        case DailyGameType.parkour:
                        case DailyGameType.clothcrossing:
                            this.onClickItem(this.context.dailyGameType);
                            break;
                        default:
                            break;
                    }
                }
            }
            buildUi() {
                this.buttonMidAutumn.__node.visible = mgrMidAutumn.isEnable();
                if (this.buttonMidAutumn.__node.visible) {
                    cc.tween(this.buttonMidAutumn.__node).repeatForever(cc.tween()
                        .by(0.1, { rotation: -10 })
                        .by(0.2, { rotation: 20 })
                        .by(0.1, { rotation: -10 })
                        .delay(2)).start();
                }
                this.spriteUpgradeMask.visible = false;
                this.topBar = new vTopBar({});
                this.spriteTopBarHolder.addChild(this.topBar);
                this.boxPartList["_originPos"] = new Laya.Vector2(this.boxPartList.x, this.boxPartList.y);
                this.panelCurrDay1["_originHeight"] = this.panelCurrDay1.height;
                this.panelCurrDay2["_originHeight"] = this.panelCurrDay2.height;
                this.panelOldDay1["_originHeight"] = this.panelOldDay1.height;
                this.panelOldDay2["_originHeight"] = this.panelOldDay2.height;
                mgrLoader.loadFont("world_daily_progress", this.labelDailyDay1);
                mgrLoader.loadFont("world_daily_progress", this.labelDailyDay2);
                mgrLoader.loadFont("world_daily_progress", this.labelDailyDayOld1);
                mgrLoader.loadFont("world_daily_progress", this.labelDailyDayOld2);
                this.reuseList = new ReuseList(3, 0, 6);
                this.reuseList.size(this.boxPartList.width, this.boxPartList.height);
                this.boxPartList.addChild(this.reuseList);
                this.reuseList.setItemClass(vWorldDailyGameItem);
                this.reuseList.setVerticalMoveEnable(false);
                this.reuseList.setSpaceX(40);
                this.reuseList.setSpaceY(0);
                this.reuseList.setTouchEnable(false);
                this.spineDay1 = ULSkeleton.create("cj_xuanguan");
                this.spineDay1.playAnimation("idle2");
                this.spriteHolderSpineDay1.addChild(this.spineDay1);
                this.spineDay2 = ULSkeleton.create("cj_xuanguan");
                this.spineDay2.playAnimation("idle2");
                this.spriteHolderSpineDay2.addChild(this.spineDay2);
                this.progressBar.barName = this.progressBar.owner.name;
                this.progressBar.style = ULPROGRESSBAR_STYLE.hor;
                this.progressBar.progress = 0;
            }
            fillData() {
                this.refreshGameList();
                this.refreshDayProgress(true);
                this.refreshDayReward();
                this.refreshDayUi(true);
            }
            widget() {
                mgrLayout.widgetLeftTopMC(this.spriteTopBarHolder);
            }
            doGameItemEffect(callback) {
                this.boxPartList.alpha = 1;
                let cells = this.reuseList.getAllCells();
                let count = cells.length;
                for (let i = 0; i < count; i++) {
                    let cell = cells[i];
                    cell.scale(0, 0, true);
                    cc.tween(cell).delay(i * 0.05).toScale(0.1, 1.1).toScale(0.05, 1).start();
                }
                Timer.callLater(count * 0.05 + 0.15, () => {
                    if (!this.nodeResource || this.nodeResource.destroyed) {
                        return;
                    }
                    callback && callback();
                }, this);
            }
            addGridAd() {
                let gridAd = new vGridAd({ advId: "10001", copStr: "grid_ad_ratio1" });
                this.addChild(gridAd);
            }
            uiActionIn(callback) {
                let startProgress = 0.0001;
                let targetProgress = this.progressBar.progress;
                this.progressBar.progress = 0;
                this.labelProgress.scale(0, 0, true);
                this.spriteProgressContainer.scale(0, 0, true);
                mgrEffect.playComebackAction([this.spriteTitleWord01], 0, -200, 0, 0.3);
                mgrEffect.playComebackAction([this.spriteTitleWord02], 0, -200, 0.1, 0.3, () => {
                    this.doGameItemEffect();
                    this.progressBar.progressTweenTo(0.05, targetProgress, startProgress, 0.6, () => {
                        cc.tween(this.spriteProgressContainer)
                            .toScale(0.05, 2)
                            .call(() => {
                            this.labelProgress.scale(1, 1, true);
                        })
                            .toScale(0.05, 1)
                            .call(() => {
                            this.add3DEffectAtFront("117_ui_once_flash_03", this.labelProgress, 1);
                            callback && callback();
                        }).start();
                    });
                });
                mgrEffect.playComebackAction([this.spriteTopBarHolder], -400, 0, 1.2, 0.3, null, cc.Ease.backOut);
            }
            startGuide() {
                mgrGuide.registerGuideNode(`vWorldDailyQuestMainScene.spriteGuide1`, this.spriteGuide1);
                mgrGuide.registerGuideNode(`vWorldDailyQuestMainScene.spriteGuideWarnNpc`, this.spriteGuideWarnNpc);
                if (!mgrGuide.isFinished(201)) {
                    mgrGuide.startGuide(201);
                }
                else if (!mgrGuide.isFinished(500)) {
                    mgrGuide.startGuide(500);
                }
            }
            inInit() {
                this.refreshGameList();
                this.refreshDayProgress(true);
                this.refreshDayReward();
                this.refreshDayUi(true);
                let callback = null;
                if (!!this.context.bFromGameResult && !!this.context.bSuccess) {
                    callback = () => {
                        this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.gotDayPoint);
                    };
                }
                else {
                    let worldDay = mgrWorldDaily.getWorldDay();
                    let template = mgrCfg.get_from_world_daily_quest(worldDay);
                    if (!!template) {
                        let currPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_WORLD_DAILY_POINT);
                        if (currPoint >= template.dailyPoint) {
                            this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.changeDay);
                        }
                        else {
                            callback = () => {
                                this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.inDay);
                            };
                        }
                    }
                    else {
                        callback = () => {
                            this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.inDay);
                        };
                    }
                }
                this.callbackAfterUiAction = callback;
            }
            exeInit() { }
            outInit() { }
            inGotDayPoint() {
                let callback = () => {
                    mgrSound.play(602);
                    this.refreshDayProgress(false, 0.5, 0.5, () => {
                        let worldDay = mgrWorldDaily.getWorldDay();
                        let template = mgrCfg.get_from_world_daily_quest(worldDay);
                        if (!!template) {
                            let currPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_WORLD_DAILY_POINT);
                            if (currPoint >= template.dailyPoint) {
                                this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.changeDay);
                            }
                            else {
                                this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.inDay);
                            }
                        }
                    });
                };
                let flyToProgressEff = () => {
                    let startPos = new Laya.Point(mgrDirector.width / 2, mgrDirector.height * 0.75);
                    let targetPos = new Laya.Point(this.spriteDailyIcon.x, this.spriteDailyIcon.y);
                    let cells = this.reuseList.getAllCells();
                    let count = cells.length;
                    for (let i = 0; i < count; i++) {
                        let cell = cells[i];
                        if (cell["data"] && cell["data"].id == this.context.dailyGameType) {
                            let tmpStartWorldPos = cell.getDailyIconWorldPos();
                            startPos = this.spriteProgressContainer.globalToLocal(tmpStartWorldPos);
                            break;
                        }
                    }
                    let centerPoint = new Laya.Point(targetPos.x + (startPos.x - targetPos.x) / 2, targetPos.y + (startPos.y - targetPos.y) / 2);
                    if (targetPos.x > startPos.x) {
                        centerPoint.x += 100;
                    }
                    else {
                        centerPoint.x -= 100;
                    }
                    let spriteHolder = new Laya.Sprite();
                    spriteHolder.size(128, 128);
                    spriteHolder.pivot(64, 64);
                    spriteHolder.scale(0.3, 0.3);
                    Tools.loadImg(spriteHolder, mgrPlayer.getIcon(Const.ITEM_ID_WORLD_DAILY_POINT));
                    this.spriteProgressContainer.addChild(spriteHolder);
                    spriteHolder.pos(startPos.x, startPos.y);
                    this.add3DEffectAtFront("117_ui_loop_trailparticle_yellow", spriteHolder, 0.5);
                    cc.tween(spriteHolder)
                        .then(cc.bezierTo(0.5, [startPos.x, startPos.y, centerPoint.x, centerPoint.y, targetPos.x, targetPos.y], 3))
                        .call(() => {
                        this.add3DEffectAtFront("117_ui_once_flash_01", this.spriteProgressContainer);
                        mgrEffect.shakeNodeXOnce(this.spriteProgressContainer);
                    })
                        .call(() => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            return;
                        }
                        callback();
                    })
                        .removeSelf()
                        .start();
                };
                if (!!this.context.dailyGameType) {
                    flyToProgressEff();
                }
                else {
                    callback();
                }
            }
            exeGotDayPoint() { }
            outGotDayPoint() { }
            inChangeDay() {
                this.spriteUpgradeMask.visible = true;
                mgrSound.play(604);
                this.add3DEffectAtFront("117_ui_once_flash_02", this.spriteRewardRoleIcon);
                cc.tween(this.spriteRoleIconContainer)
                    .delay(0.3)
                    .toScale(0.3, 1.1).toScale(0.05, 1)
                    .delay(0.2)
                    .call(() => {
                    this.receiveDayilyReward(() => {
                        Timer.callLater(0.3, () => {
                            if (!this.nodeResource || this.nodeResource.destroyed) {
                                return;
                            }
                            this.refreshDayUi(false, () => {
                                this.refreshDayReward();
                                this.showDayReward(() => {
                                    this.add3DEffectAtFront("117_ui_loop_xkparticle01", this.spriteRewardRoleIcon);
                                    Timer.callLater(0.3, () => {
                                        if (!this.nodeResource || this.nodeResource.destroyed) {
                                            return;
                                        }
                                        this.spriteUpgradeMask.visible = false;
                                        this.doGameItemEffect(() => {
                                            this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.inDay);
                                        });
                                    }, this);
                                });
                            });
                        }, this);
                    });
                })
                    .start();
            }
            exeChangeDay() { }
            outChangeDay() {
                this.spriteUpgradeMask.visible = false;
            }
            inDay() {
                if (mgrGuide.isAllForceGuideFinished()) {
                    mgrEffect.playComebackAction([this.buttonBack.__node], -150, 0);
                }
                else {
                    this.buttonBack.__node.visible = false;
                }
                this.fillData();
                this.tryTipCardFight();
                if (!this.boxWarnLockContainer.visible) {
                }
                this.startGuide();
                this.boxEventFront.visible = false;
            }
            exeDay() { }
            outDay() { }
            inCardFight() {
                mgrSound.play(605);
                let worldDay = mgrWorldDaily.getWorldDay();
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                this.warnCardStageData = mgrCfg.get_from_amaze_card_stage_db(template.cardFightStageId);
                let bossNpcData = null;
                let npcIdArr = this.warnCardStageData.npcIdArr || [];
                for (let k in npcIdArr) {
                    let npcId = npcIdArr[k];
                    let npcData = mgrCfg.get_from_amuse_card_npc_db(npcId);
                    if (!npcData) {
                        continue;
                    }
                    bossNpcData = npcData;
                    break;
                }
                this.labelWarnTotalPower.text = `${bossNpcData.fightPower}`;
                if (!!bossNpcData.imgWarn && bossNpcData.imgWarn != "") {
                    Tools.loadImg(this.spriteWarnNpcImg, bossNpcData.imgWarn);
                }
                let tagTemplate = mgrCfg.get_from_part_tag_db(bossNpcData.roleTagId);
                Tools.loadImg(this.spriteWarnRoleTagIcon, tagTemplate.icon);
                this.boxWarnLockContainer.visible = true;
                Tools.unRegisterTouchHander(this.boxWarnLockContainer);
                Tools.registerTouchHander(this.boxWarnLockContainer, (e) => {
                    if (!e.isClick) {
                        return;
                    }
                    this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vWorldDailyQuestMainScene.clickGuideWarnNpc` });
                    this.boxWarnLockContainer.visible = false;
                    mgrDirector.openDialog("vAmuseCardWorldDailyStartDialog", {
                        stageId: this.warnCardStageData.id,
                    }, true);
                });
                mgrEffect.shineNode(this.spriteWarnNpcImg);
            }
            exeCardFight() { }
            outCardFight() { }
            tryTipCardFight() {
                let worldDay = mgrWorldDaily.getWorldDay();
                if (mgrWorldDaily.isCardFightShowedDay(worldDay)) {
                    this.boxWarnLockContainer.visible = false;
                    return;
                }
                mgrWorldDaily.markCardFightShowed(worldDay);
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                if (!!template.cardFightStageId && !!mgrCfg.get_from_amaze_card_stage_db(template.cardFightStageId)) {
                    this.stManager.setNextState(WORLD_DAILY_QUEST_MAIN_STATE.cardFight);
                }
                else {
                    this.boxWarnLockContainer.visible = false;
                }
            }
            refreshDayUi(bImmi, completeCallback) {
                let currDay = mgrWorldDaily.getWorldDay();
                let dayStr = currDay.toString();
                if (dayStr.length == 1) {
                    this.labelDailyDay1.text = "0";
                }
                else if (dayStr.length == 2) {
                    this.labelDailyDay1.text = dayStr.substr(0, 1);
                }
                if (dayStr.length == 1) {
                    this.labelDailyDay2.text = dayStr.substr(0, 1);
                }
                else if (dayStr.length == 2) {
                    this.labelDailyDay2.text = dayStr.substr(1, 1);
                }
                let preDay = currDay - 1;
                let preDayStr = preDay.toString();
                if (preDayStr.length == 1) {
                    this.labelDailyDayOld1.text = "0";
                }
                else if (preDayStr.length == 2) {
                    this.labelDailyDayOld1.text = preDayStr.substr(0, 1);
                }
                if (preDayStr.length == 1) {
                    this.labelDailyDayOld2.text = preDayStr.substr(0, 1);
                }
                else if (preDayStr.length == 2) {
                    this.labelDailyDayOld2.text = preDayStr.substr(1, 1);
                }
                this.spriteLeftDay.visible = (21 - currDay) > 0 ? true : false;
                this.labelLeftDay.text = `${21 - currDay}`;
                if (!!bImmi) {
                    this.panelCurrDay1.height = this.panelCurrDay1["_originHeight"];
                    this.panelCurrDay2.height = this.panelCurrDay2["_originHeight"];
                    this.panelOldDay1.height = 0;
                    this.panelOldDay2.height = 0;
                    completeCallback && completeCallback();
                    return;
                }
                this.panelCurrDay1.height = 0;
                this.panelCurrDay2.height = 0;
                this.panelOldDay1.height = this.panelOldDay1["_originHeight"];
                this.panelOldDay2.height = this.panelOldDay2["_originHeight"];
                let doChangePageFunc = (index, callback) => {
                    mgrSound.play(603);
                    let doLerpPosFunc = (percent) => {
                        this[`panelCurrDay` + index].height = this[`panelCurrDay` + index]["_originHeight"] * percent;
                        this[`panelOldDay` + index].height = this[`panelOldDay` + index]["_originHeight"] * (1 - percent);
                        if (percent >= 1) {
                            callback && callback();
                        }
                    };
                    let startTime = Tools.time();
                    let dur = 0.83;
                    Timer.callLoop(0.016, (timer) => {
                        if (!this.nodeResource || this.nodeResource.destroyed) {
                            timer.stop();
                            return;
                        }
                        let passTime = Tools.time() - startTime;
                        if (passTime >= dur) {
                            doLerpPosFunc(1);
                            timer.stop();
                            return;
                        }
                        doLerpPosFunc(passTime / dur);
                    }, this);
                    this[`spineDay` + index].playAnimation("idle", false);
                };
                if (this.labelDailyDay1.text != this.labelDailyDayOld1.text) {
                    this.spineDay1.playAnimation("idle2");
                    this.spineDay2.playAnimation("idle2");
                    doChangePageFunc(1, () => {
                        doChangePageFunc(2, () => {
                            completeCallback && completeCallback();
                        });
                    });
                }
                else {
                    this.spineDay2.playAnimation("idle2");
                    doChangePageFunc(2, () => {
                        completeCallback && completeCallback();
                    });
                }
            }
            hideDayReward() {
                this.spriteRewardRoleIcon.alpha = 0;
                this.spriteRewardItemIcon.alpha = 0;
                this.labelRewardName.alpha = 0;
            }
            showDayReward(callback) {
                cc.tween(this.spriteRewardRoleIcon).toAlpha(0.3, 1).start();
                cc.tween(this.spriteRewardItemIcon).toAlpha(0.3, 1).start();
                cc.tween(this.labelRewardName)
                    .toAlpha(0.3, 1)
                    .call(() => {
                    callback && callback();
                })
                    .start();
            }
            refreshDayReward() {
                let rewardData = mgrWorldDaily.getWorldDayRoleReward();
                let rewardRoleData = null;
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (rewardData.itemId == v.unlockItemId) {
                        rewardRoleData = v;
                    }
                });
                let scalrRoleIcon = !!rewardRoleData ? 1 : 0;
                this.spriteRewardRoleIcon.scale(scalrRoleIcon, scalrRoleIcon, true);
                this.spriteRewardItemIcon.scale(1 - scalrRoleIcon, 1 - scalrRoleIcon, true);
                this.labelRewardName.scale(1, 1, true);
                this.buttonRoleIconContainer.__node.visible = !!rewardRoleData;
                if (!!rewardRoleData) {
                    this.labelRewardName.text = "角色";
                    Tools.loadImg(this.spriteRewardRoleIcon, rewardRoleData.dailyRewardIcon, true);
                    Tools.loadImg(this.spriteRoleFragment, mgrPlayer.getIcon(rewardRoleData.unlockItemId));
                    let curFragmentNum = mgrPlayer.getItemAmount(rewardRoleData.unlockItemId);
                    let needFragmentNum = rewardRoleData.unlockItemAmount;
                    this.labelRoleFragmentCurNum.text = `${curFragmentNum}`;
                    this.labelRoleFragmentAllNum.text = `/${needFragmentNum}`;
                    this.buttonRoleIconContainer.__node.visible = curFragmentNum < needFragmentNum ? true : false;
                }
                else {
                    let templateItem = mgrCfg.get_from_item_template_db(rewardData.itemId);
                    Tools.loadImg(this.spriteRewardItemIcon, templateItem.icon);
                    this.labelRewardName.text = `*${rewardData.amount}`;
                }
            }
            refreshDayProgress(bInit, dur, delay, callback) {
                let worldDay = mgrWorldDaily.getWorldDay();
                let template = mgrCfg.get_from_world_daily_quest(worldDay);
                if (!!template) {
                    let currPoint = mgrPlayer.getItemAmount(Const.ITEM_ID_WORLD_DAILY_POINT);
                    let dailyPoint = template.dailyPoint;
                    this.labelProgress.text = `${Math.min(currPoint, dailyPoint)}/${dailyPoint}`;
                    if (!!bInit) {
                        this.progressBar.progress = Math.min(currPoint / dailyPoint, 1);
                        callback && callback();
                    }
                    else {
                        this.progressBar.progressTweenTo(dur || 0.3, Math.min(currPoint / dailyPoint, 1), 0, delay || 0, callback);
                    }
                }
            }
            refreshGameList() {
                let worldDay = mgrWorldDaily.getWorldDay();
                let index = worldDay % this.DAY_BG_ITEM_COUNT;
                Tools.loadImg(this.spriteDayGameBg, this.DAY_2_GAME_BG_DICT[index]);
                let dbArr = mgrCfg.getDbAndSortByField("world_game_db", "id");
                let arr = [];
                for (let k in dbArr) {
                    let data = dbArr[k];
                    if (data.id == DailyGameType.dailyFightEvent) {
                        if (!!mgrWorldDaily.isCardFightedDay(worldDay)) {
                            continue;
                        }
                    }
                    if (data.id == DailyGameType.dailyTurntable) {
                    }
                    arr.push({
                        id: data.id,
                        fOnClick: this.onClickItem.bind(this),
                        bAd: false
                    });
                }
                this.reuseList.setTouchEnable(arr.length >= 6);
                this.reuseList.setDatas(arr);
                this.reuseList.scrollTo(0);
            }
            receiveDayilyReward(rewardCallback) {
                let rewardData = mgrWorldDaily.getWorldDayRoleReward();
                let rewardRoleData = null;
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (rewardData.itemId == v.unlockItemId) {
                        rewardRoleData = v;
                    }
                });
                mgrPlayer.addItemAmount(Const.ITEM_ID_WORLD_DAILY_POINT, -mgrPlayer.getItemAmount(Const.ITEM_ID_WORLD_DAILY_POINT), "");
                mgrWorldDaily.addWorldDay();
                this.hideDayReward();
                if (!!rewardRoleData) {
                    mgrDirector.openDialog("vGotNewRoleDialog", { roleId: rewardRoleData.id, bVip: true, fOnClose: rewardCallback });
                }
                else {
                    mgrPlayer.addItemAmount(rewardData.itemId, rewardData.amount, "日程奖励");
                    mgrTip.addGotItemTip(rewardData.itemId, rewardData.amount, null, {
                        fOnClose: rewardCallback
                    });
                }
            }
            getRoleExceptShowingRole(gameType, muteRoleId) {
                let roleId = mgrWorldDaily.getGameTempParms(gameType);
                if (!!roleId && roleId != muteRoleId && roleId != mgrRole.showingRoleId) {
                    return mgrCfg.get_from_role_db(roleId);
                }
                let arr = [];
                let roleDataShowing = mgrCfg.get_from_role_db(mgrRole.showingRoleId);
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (!!muteRoleId && v.id == muteRoleId) {
                        return;
                    }
                    if (!v.rootRoleId || v.rootRoleId != roleDataShowing.rootRoleId) {
                        arr.push(v);
                    }
                });
                return Tools.randomGotOneArrayData(arr);
            }
            onClickItem(id) {
                this.boxEventFront.visible = false;
                this.sendMsg(`MSG_GUIDE_EVENT`, { id: `vWorldDailyQuestMainScene.clickGuide1` });
                let worldDay = mgrWorldDaily.getWorldDay();
                let template = mgrCfg.get_from_world_game_db(id);
                switch (template.id) {
                    case DailyGameType.cake: {
                        let config = mgrCfg.get_from_cake_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.cake, config.maxStageId);
                        let stageData = mgrCfg.get_from_cake_stage_db(stageId);
                        let commonCustomerFunc = () => {
                            let roleData = this.getRoleExceptShowingRole(DailyGameType.cake, stageData.cakeHumanMuteRoleId);
                            mgrWorldDaily.setGameTempParms(DailyGameType.cake, roleData.id);
                            mgrDirector.openDialog("vAmuseCakePreviewDialog", { stageId: stageId, roleId: roleData.id, bVip: false });
                        };
                        if (stageData.id > 3 && Tools.random(100) < 50 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAmuseCakePreviewVipDialog_vip)) {
                            mgrWorldDaily.addVipShowCountByGameType(DailyGameType.cake);
                            if (!mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.cake)) {
                                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vAmuseCakePreviewVipDialog_vip);
                                if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                                    mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                                }
                            }
                            mgrWorldDaily.cleanGameTempParms(DailyGameType.cake);
                            let roleData = this.getRoleExceptShowingRole(DailyGameType.cake, stageData.cakeHumanMuteRoleId);
                            mgrDirector.openDialog("vAmuseCakePreviewVipDialog", { stageId: stageId, roleId: roleData.id, bVip: true, fOnGiveUp: commonCustomerFunc });
                        }
                        else {
                            commonCustomerFunc();
                        }
                        break;
                    }
                    case DailyGameType.pen: {
                        let config = mgrCfg.get_from_pen_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.pen, config.maxStageId);
                        let roleId = null;
                        if (!roleId) {
                            mgrCfg.forDb_from_amaze_pen_select_role_db((k, v) => {
                                if (v.bDefaultOwn && !roleId) {
                                    roleId = v.id;
                                }
                            });
                        }
                        mgrDirector.openDialog("vAmusePenPreviewDialog", { stageId: stageId, roleId: roleId || mgrRole.showingRoleId });
                        break;
                    }
                    case DailyGameType.cloth: {
                        let config = mgrCfg.get_from_cloth_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.cloth, config.maxStageId);
                        let roleData = this.getRoleExceptShowingRole(DailyGameType.cloth);
                        mgrWorldDaily.setGameTempParms(DailyGameType.cloth, roleData.id);
                        mgrDirector.openDialog("vFreedomRoomPreviewDialog", {
                            targetRoleId: roleData.id,
                            stageId: stageId,
                            backSceneName: `vWorldDailyQuestMainScene`,
                        }, true);
                        break;
                    }
                    case DailyGameType.custom_made: {
                        let config = mgrCfg.get_from_custom_made_cloth_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.custom_made, config.maxStageId);
                        let commonCustomerFunc = () => {
                            let roleData = this.getRoleExceptShowingRole(DailyGameType.custom_made);
                            mgrWorldDaily.setGameTempParms(DailyGameType.custom_made, roleData.id);
                            mgrDirector.openDialog("vCustomMadeClothesPreviewDialog", { stageId: stageId, roleId: roleData.id, bVip: false });
                        };
                        if (stageId > 3 && Tools.random(100) < 50 && mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesPreviewVipDialog_vip)) {
                            mgrWorldDaily.addVipShowCountByGameType(DailyGameType.custom_made);
                            if (!mgrWorldDaily.canFreePlayVipByGameType(DailyGameType.custom_made)) {
                                let adEventData = mgrCfg.get_from_ad_event_db(AD_EVENT_ID.VIDEO.video_vCustomMadeClothesPreviewVipDialog_vip);
                                if (adEventData.pointEventId && adEventData.pointEventId.length > 0) {
                                    mgrSdk.statisVideoPointEvent(adEventData.pointEventId, 1);
                                }
                            }
                            mgrWorldDaily.cleanGameTempParms(DailyGameType.custom_made);
                            let roleData = this.getRoleExceptShowingRole(DailyGameType.custom_made);
                            mgrDirector.openDialog("vCustomMadeClothesPreviewVipDialog", { stageId: stageId, roleId: roleData.id, bVip: true, fOnGiveUp: commonCustomerFunc });
                        }
                        else {
                            commonCustomerFunc();
                        }
                        break;
                    }
                    case DailyGameType.parkour: {
                        let config = mgrCfg.get_from_parkour_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.parkour, config.maxStageId);
                        mgrDirector.openDialog("vAmuseParkourPreviewDialog", { stageId: stageId });
                        break;
                    }
                    case DailyGameType.clothcrossing: {
                        let config = mgrCfg.get_from_cloth_crossing_daily_quest_config(worldDay);
                        let stageId = mgrWorldDaily.getStageIdByGameTypeAndMaxStageId(DailyGameType.clothcrossing, config.maxStageId);
                        mgrDirector.openDialog("vAmuseClothCrossingPreviewDialog", { stageId: stageId });
                        break;
                    }
                    case DailyGameType.dailyTurntable: {
                        if (mgrPlayer.getItemAmount(Const.ITEM_ID_TURNTABLE_COUNT) > 0 || mgrAd.preCheckCanTriggerAdEvent(AD_EVENT_ID.VIDEO.video_vAdTurntableDialog_free)) {
                            mgrDirector.openDialog("vAdTurntableDialog");
                        }
                        else {
                            mgrTip.showMsgTip("今日次数已用完，请明天再来吧");
                        }
                        break;
                    }
                    case DailyGameType.dailyFightEvent: {
                        let worldDay = mgrWorldDaily.getWorldDay();
                        let template = mgrCfg.get_from_world_daily_quest(worldDay);
                        this.warnCardStageData = mgrCfg.get_from_amaze_card_stage_db(template.cardFightStageId);
                        mgrDirector.openDialog("vAmuseCardWorldDailyStartDialog", {
                            stageId: this.warnCardStageData.id,
                        }, true);
                        break;
                    }
                    default:
                        break;
                }
            }
            onMsgAdEventSuccessd(e) {
                let userData = e.userData || {};
                let roleId = userData.roleId;
                let bDailyMain = userData.bDailyMain;
                if (e.adEventId == AD_EVENT_ID.VIDEO.video_vGotNewRoleDialog_fragment && !!roleId && !!bDailyMain) {
                    mgrDirector.openDialog("vGotNewRoleDialog", {
                        roleId: roleId, bVip: true, fOnClose: () => {
                            this.refreshDayReward();
                        }
                    });
                }
            }
            onTouchButtonBack() {
                mgrDirector.warpSceneWidthEffect("vHubScene");
            }
            onTouchButtonFrontEvent() {
            }
            onTouchButtonRoleIconContainer() {
                let rewardData = mgrWorldDaily.getWorldDayRoleReward();
                let rewardRoleData = null;
                mgrCfg.forDb_from_role_db((k, v) => {
                    if (rewardData.itemId == v.unlockItemId) {
                        rewardRoleData = v;
                    }
                });
                let scalrRoleIcon = !!rewardRoleData ? 1 : 0;
                this.spriteRewardRoleIcon.scale(scalrRoleIcon, scalrRoleIcon, true);
                this.spriteRewardItemIcon.scale(1 - scalrRoleIcon, 1 - scalrRoleIcon, true);
                this.labelRewardName.scale(1, 1, true);
                if (!!rewardRoleData) {
                    mgrAd.triggerAdEvent(AD_EVENT_ID.VIDEO.video_vGotNewRoleDialog_fragment, { roleId: rewardRoleData.id, bDailyMain: true }, true);
                }
            }
            onTouchButtonMidAutumn() {
                mgrDirector.openDialog("vMidAutumnActivityDialog");
            }
        }

        class vGuideMaskDialog extends DialogBase {
            constructor(context) {
                super(context);
                this.sourceName = null;
                this.exportNodeNames = [];
                this.MASK_ALPHA_FACTOR = 0.45;
                this.name = "vGuideMaskDialog";
                this.imageMaskContent = new Laya.Image;
                this.imageMaskContent.size(768, 1280);
                this.imageMaskContent.texture = new Laya.Texture(Laya.Texture2D.blackTexture);
                this.addChild(this.imageMaskContent);
                this.imageMaskContent.alpha = 0;
                this.imageMaskTop = new Laya.Image;
                this.imageMaskTop.size(1, 1);
                this.imageMaskTop.texture = new Laya.Texture(Laya.Texture2D.blackTexture);
                this.addChild(this.imageMaskTop);
                this.imageMaskTop.alpha = 0;
                this.imageMaskBottom = new Laya.Image;
                this.imageMaskBottom.size(1, 1);
                this.imageMaskBottom.texture = new Laya.Texture(Laya.Texture2D.blackTexture);
                this.addChild(this.imageMaskBottom);
                this.imageMaskBottom.alpha = 0;
                this.imageMaskLeft = new Laya.Image;
                this.imageMaskLeft.size(1, 1);
                this.imageMaskLeft.texture = new Laya.Texture(Laya.Texture2D.blackTexture);
                this.addChild(this.imageMaskLeft);
                this.imageMaskLeft.alpha = 0;
                this.imageMaskRight = new Laya.Image;
                this.imageMaskRight.size(1, 1);
                this.imageMaskRight.texture = new Laya.Texture(Laya.Texture2D.blackTexture);
                this.addChild(this.imageMaskRight);
                this.imageMaskRight.alpha = 0;
                this.imageMaskCenter = new Laya.Image;
                this.imageMaskCenter.skin = "res/ui/common/mask_01.png";
                this.addChild(this.imageMaskCenter);
                this.imageMaskCenter.sizeGrid = "10,10,10,10,0";
                this.imageMaskCenter.alpha = 0;
                this.size(Laya.stage.width, Laya.stage.height);
                Tools.registerTouchHander(this, this.onTouchNodeBg.bind(this));
            }
            onOpened() {
                super.onOpened();
                this.nodeResource = this;
                Tools.registerTouchHander(this.imageMaskTop, (e) => {
                    if (!e.isClick)
                        return;
                    this.onTouchMask();
                });
                Tools.registerTouchHander(this.imageMaskLeft, (e) => {
                    if (!e.isClick)
                        return;
                    this.onTouchMask();
                });
                Tools.registerTouchHander(this.imageMaskRight, (e) => {
                    if (!e.isClick)
                        return;
                    this.onTouchMask();
                });
                Tools.registerTouchHander(this.imageMaskBottom, (e) => {
                    if (!e.isClick)
                        return;
                    this.onTouchMask();
                });
                this.target = this.context.target;
                this.dragTarget = this.context.dragTarget;
                this.extraArena = this.context.extraArena;
                this.content = this.context.content;
                this.widget = this.context.widget;
                if (this.context.bScene) {
                    this.__dialogRoot.zOrder = 0;
                }
                this.parent.hitArea = new Laya.HitArea();
                this.parent.hitArea.hit.drawRect(0, 0, Laya.stage.width, Laya.stage.height, "#000000");
                this.hitArea = new Laya.HitArea();
                this.hitArea.hit.drawRect(0, 0, Laya.stage.width, Laya.stage.height, "#000000");
                let guideTipNode = null;
                if (this.context.content) {
                    guideTipNode = new vGuideTipNode({
                        content: this.content,
                        widget: this.widget,
                        type: this.context.type,
                        tipDelayTime: this.context.tipDelayTime,
                    });
                    this.addChild(guideTipNode);
                }
                if (this.target && this.target.width > 0) {
                    if (!this.dragTarget) {
                        let guideHhand = new Laya.Image;
                        guideHhand.size(1, 1);
                        guideHhand.anchorX = 0.5;
                        guideHhand.anchorY = 0.5;
                        this.addChild(guideHhand);
                        let xsydSprite3d = mgrLoader.Pool.getModel("eff_ui_xsyd");
                        this.add3DEffectAtFront(xsydSprite3d, guideHhand, 0);
                        if (!!this.context.fingerDir) {
                            if (this.context.fingerDir == 1) {
                                xsydSprite3d.transform.rotationEuler = new Laya.Vector3(0, 180, 0);
                            }
                            else if (this.context.fingerDir == 2) {
                                xsydSprite3d.transform.rotationEuler = new Laya.Vector3(0, 0, 90);
                            }
                            else if (this.context.fingerDir == 3) {
                                xsydSprite3d.transform.rotationEuler = new Laya.Vector3(0, 180, 90);
                            }
                        }
                        this.skeleton = guideHhand;
                    }
                    else {
                        let guideHhand = new Laya.Image;
                        guideHhand.size(1, 1);
                        guideHhand.anchorX = 0.5;
                        guideHhand.anchorY = 0.5;
                        this.addChild(guideHhand);
                        this.add3DEffectAtFront(`eff_ui_xsyd_hand`, guideHhand, 0);
                        let localPosStart = this.globalToLocal(this.target.parent.localToGlobal(new Laya.Point(this.target.x, this.target.y)));
                        let localPosEnd = this.globalToLocal(this.dragTarget.parent.localToGlobal(new Laya.Point(this.dragTarget.x, this.dragTarget.y)));
                        guideHhand.pos(localPosStart.x, localPosStart.y);
                        CustomTween.to(guideHhand, { x: localPosEnd.x, y: localPosEnd.y }, 1000)
                            .callback(() => {
                            guideHhand.pos(localPosStart.x, localPosStart.y);
                        })
                            .start(0);
                    }
                }
                else if (guideTipNode) {
                    let guideHhand = new Laya.Image;
                    guideHhand.size(1, 1);
                    guideHhand.anchorX = 0.5;
                    guideHhand.anchorY = 0.5;
                    this.addChild(guideHhand);
                    this.add3DEffectAtFront("eff_ui_xsyd", guideHhand, 0);
                    this.skeleton = guideHhand;
                    guideTipNode.context.fPosUpdateFunc = () => {
                        if (!this || this.destroyed || !this.skeleton || this.skeleton.destroyed) {
                            return;
                        }
                        this.skeleton.pos(guideTipNode.x + guideTipNode.width / 2 - 70, guideTipNode.y + guideTipNode.height / 2 - 50);
                    };
                }
                this.refresh();
                Timer.callLoop(0.016, () => { this.refresh(); }, this);
            }
            onClosed() {
                super.onClosed();
            }
            refresh() {
                if (this.context.maskType == 2 || this.context.maskType == 3 || this.context.maskType == 4) {
                    this.MASK_ALPHA_FACTOR = 0;
                }
                this.imageMaskContent.visible = !this.target;
                this.imageMaskContent.alpha = 0.75 * this.MASK_ALPHA_FACTOR;
                if (!this.target || this.target.destroyed)
                    return;
                let minX = 0;
                let minY = 0;
                let maxX = 0;
                let maxY = 0;
                if (this.dragTarget) {
                    let globalPos = this.target.localToGlobal(new Laya.Point(0, 0));
                    let localPos = this.globalToLocal(globalPos);
                    let globalDragPos = this.dragTarget.localToGlobal(new Laya.Point(0, 0));
                    let localDragPos = this.globalToLocal(globalDragPos);
                    minX = Math.min(localPos.x, localDragPos.x);
                    minY = Math.min(localPos.y, localDragPos.y);
                    maxX = Math.max(localPos.x + this.target.width * this.target.scaleX, localDragPos.x + this.dragTarget.width * this.dragTarget.scaleX);
                    maxY = Math.max(localPos.y + this.target.height * this.target.scaleY, localDragPos.y + this.dragTarget.height * this.dragTarget.scaleY);
                }
                else {
                    let globalPos = this.target.localToGlobal(new Laya.Point(0, 0));
                    let localPos = this.globalToLocal(globalPos);
                    minX = localPos.x;
                    minY = localPos.y;
                    maxX = minX + this.target.width * this.target.scaleX;
                    maxY = minY + this.target.height * this.target.scaleY;
                }
                let startX = ul.clamp(minX, 1, Laya.stage.width - 2);
                let startY = ul.clamp(minY, 1, Laya.stage.height - 2);
                let realWidth = Math.max(1, maxX - minX);
                let realHeight = Math.max(maxY - minY);
                this.imageMaskTop.pivot(0, 0);
                this.imageMaskTop.x = 0;
                this.imageMaskTop.y = 0;
                this.imageMaskTop.width = Laya.stage.width;
                this.imageMaskTop.height = startY;
                this.imageMaskBottom.pivot(0, 0);
                this.imageMaskBottom.x = 0;
                this.imageMaskBottom.y = startY + realHeight;
                this.imageMaskBottom.width = Laya.stage.width;
                this.imageMaskBottom.height = Laya.stage.height - startY - realHeight;
                this.imageMaskLeft.pivot(0, 0);
                this.imageMaskLeft.x = 0;
                this.imageMaskLeft.y = startY;
                this.imageMaskLeft.width = startX;
                this.imageMaskLeft.height = realHeight;
                this.imageMaskRight.pivot(0, 0);
                this.imageMaskRight.x = startX + realWidth;
                this.imageMaskRight.y = startY;
                this.imageMaskRight.width = Laya.stage.width - (startX + realWidth);
                this.imageMaskRight.height = realHeight;
                this.imageMaskCenter.pivot(0, 0);
                this.imageMaskCenter.pos(startX, startY);
                this.imageMaskCenter.size(realWidth, realHeight);
                this.imageMaskCenter.alpha = 1 * this.MASK_ALPHA_FACTOR;
                this.imageMaskTop.alpha = 0.75 * this.MASK_ALPHA_FACTOR;
                this.imageMaskBottom.alpha = 0.75 * this.MASK_ALPHA_FACTOR;
                this.imageMaskLeft.alpha = 0.75 * this.MASK_ALPHA_FACTOR;
                this.imageMaskRight.alpha = 0.75 * this.MASK_ALPHA_FACTOR;
                if (this.context.maskType == 0 || this.context.maskType == 3) {
                    this.parent.hitArea.unHit.clear();
                    this.parent.hitArea.unHit.drawRect(startX, startY, realWidth, realHeight, "#000000");
                    this.hitArea.unHit.clear();
                    this.hitArea.unHit.drawRect(startX, startY, realWidth, realHeight, "#000000");
                }
                else if (this.context.maskType == 4) {
                    this.imageMaskCenter.visible = false;
                    this.imageMaskTop.visible = false;
                    this.imageMaskBottom.visible = false;
                    this.imageMaskLeft.visible = false;
                    this.imageMaskRight.visible = false;
                    this.parent.hitArea.unHit.clear();
                    this.parent.hitArea.unHit.drawRect(0, 0, Laya.stage.width, Laya.stage.height, "#000000");
                    this.hitArea.unHit.clear();
                    this.hitArea.unHit.drawRect(0, 0, Laya.stage.width, Laya.stage.height, "#000000");
                }
                this.skeleton && this.skeleton.pos(startX + realWidth / 2, startY + realHeight / 2);
            }
            onTouchMask() {
                if (this.__bClosing)
                    return;
                console.log("onTouchGuideMask");
                this.sendMsg("MSG_GUIDE_EVENT", { id: `clickGuideMask` });
            }
            isShadowBlock() {
                return false;
            }
            isShowShadow() {
                return false;
            }
            closeDialog() {
                if (this._bChildClosing)
                    return;
                this._bChildClosing = true;
                if (this.context.maskType != 2 && this.context.maskType != 3) {
                    CustomTween.to(this.imageMaskTop, { alpha: 0 }, 300).start(1);
                    CustomTween.to(this.imageMaskBottom, { alpha: 0 }, 300).start(1);
                    CustomTween.to(this.imageMaskLeft, { alpha: 0 }, 300).start(1);
                    CustomTween.to(this.imageMaskRight, { alpha: 0 }, 300).start(1);
                    CustomTween.to(this.imageMaskCenter, { alpha: 0 }, 300).start(1);
                    if (this.imageMaskContent.visible) {
                        CustomTween.to(this.imageMaskContent, { alpha: 0 }, 300).start(1);
                    }
                }
                Timer.callLater(0.3, () => {
                    super.closeDialog(true);
                });
            }
            onTouchNodeBg(e) {
                if (e.isClick && (!this.target || (this.context.maskType == 1 || this.context.maskType == 2))) {
                    this.onTouchMask();
                }
                if (e.isBegin) {
                    this["_b_drag_to_right"] = true;
                    this["_turn_count"] = 0;
                    this["_b_poped"] = false;
                    this[`_v_start_pos`] = e.pos;
                }
                else if (e.isMove) {
                    let p0 = this[`_v_start_pos`];
                    let p = e.pos;
                    if (this["_b_drag_to_right"]) {
                        if (p.x < p0.x - 20) {
                            this["_b_drag_to_right"] = false;
                            this["_turn_count"]++;
                            console.log("turn left", this["_turn_count"]);
                        }
                    }
                    else {
                        if (p.x > p0.x + 20) {
                            this["_b_drag_to_right"] = true;
                            this["_turn_count"]++;
                            console.log("turn right", this["_turn_count"]);
                        }
                    }
                    if (!this["_b_poped"]) {
                        if (this["_turn_count"] >= 20) {
                            mgrGuide.endGuide();
                            this["_b_poped"] = true;
                        }
                    }
                }
            }
        }
        vGuideMaskDialog.Statis29Flag = false;

        class require {
            static requireModule(moduleName) {
                switch (moduleName) {
                    case "vAdFreeTrialPartDialog":
                        return vAdFreeTrialPartDialog;
                    case "vAdFreeTrialSuccesDialog":
                        return vAdFreeTrialSuccesDialog;
                    case "vAdGetMoreUnlockItemDialog":
                        return vAdGetMoreUnlockItemDialog;
                    case "vAdPopMachineDialog":
                        return vAdPopMachineDialog;
                    case "vAdSuitDialog":
                        return vAdSuitDialog;
                    case "vAdTurntableDialog":
                        return vAdTurntableDialog;
                    case "vAdvancedSettingDialog":
                        return vAdvancedSettingDialog;
                    case "vAgeTipDialog":
                        return vAgeTipDialog;
                    case "vAmuseCakePreviewDialog":
                        return vAmuseCakePreviewDialog;
                    case "vAmuseCakePreviewVipDialog":
                        return vAmuseCakePreviewVipDialog;
                    case "vAmuseCakeResultDialog":
                        return vAmuseCakeResultDialog;
                    case "vAmuseCardAlbumDialog":
                        return vAmuseCardAlbumDialog;
                    case "vAmuseCardChooseChangeDialog":
                        return vAmuseCardChooseChangeDialog;
                    case "vAmuseCardDoubleNpcAlbumDialog":
                        return vAmuseCardDoubleNpcAlbumDialog;
                    case "vAmuseCardExtractDialog":
                        return vAmuseCardExtractDialog;
                    case "vAmuseCardFightSelectDialog":
                        return vAmuseCardFightSelectDialog;
                    case "vAmuseCardModeDialog":
                        return vAmuseCardModeDialog;
                    case "vAmuseCardPreviewExtractDialog":
                        return vAmuseCardPreviewExtractDialog;
                    case "vAmuseCardTipDialog":
                        return vAmuseCardTipDialog;
                    case "vAmuseCardTrialDialog":
                        return vAmuseCardTrialDialog;
                    case "vAmuseCardWorldDailyStartDialog":
                        return vAmuseCardWorldDailyStartDialog;
                    case "vAmuseClothCrossingCardSaveDialog":
                        return vAmuseClothCrossingCardSaveDialog;
                    case "vAmuseClothCrossingPreviewDialog":
                        return vAmuseClothCrossingPreviewDialog;
                    case "vAmuseParkourPreviewDialog":
                        return vAmuseParkourPreviewDialog;
                    case "vAmusePenChooseDialog":
                        return vAmusePenChooseDialog;
                    case "vAmusePenPreviewDialog":
                        return vAmusePenPreviewDialog;
                    case "vAmusePenRevivalDialog":
                        return vAmusePenRevivalDialog;
                    case "vAmusePenRoleTrialDialog":
                        return vAmusePenRoleTrialDialog;
                    case "vAmusePenSuperDialog":
                        return vAmusePenSuperDialog;
                    case "vAmusePenSuperDialog1":
                        return vAmusePenSuperDialog1;
                    case "vCardNewYearPreviewItem":
                        return vCardNewYearPreviewItem;
                    case "vCdkDialog":
                        return vCdkDialog;
                    case "vCollectWorldColorDialog":
                        return vCollectWorldColorDialog;
                    case "vCustomMadeClothesPreviewDialog":
                        return vCustomMadeClothesPreviewDialog;
                    case "vCustomMadeClothesPreviewVipDialog":
                        return vCustomMadeClothesPreviewVipDialog;
                    case "vDebugDialog":
                        return vDebugDialog;
                    case "vDesktopIconDilaog":
                        return vDesktopIconDilaog;
                    case "vDouyinDesktop":
                        return vDouyinDesktop;
                    case "vDouyinFollow":
                        return vDouyinFollow;
                    case "vDouyinSmallGame":
                        return vDouyinSmallGame;
                    case "vEditorColorDialog":
                        return vEditorColorDialog;
                    case "vEditorMaterialImgSelectDialog":
                        return vEditorMaterialImgSelectDialog;
                    case "vEditorUiTipInfoDialog":
                        return vEditorUiTipInfoDialog;
                    case "vFindMeDialogBaidu":
                        return vFindMeDialogBaidu;
                    case "vFindMeDialogDouyin":
                        return vFindMeDialogDouyin;
                    case "vFindMeDialogToutiao":
                        return vFindMeDialogToutiao;
                    case "vFindMeDialogWeixin":
                        return vFindMeDialogWeixin;
                    case "vFreedomRoomPreviewDialog":
                        return vFreedomRoomPreviewDialog;
                    case "vFullScreenMoreGame":
                        return vFullScreenMoreGame;
                    case "vFullScreenMoreGame2":
                        return vFullScreenMoreGame2;
                    case "vGiftOpenDialog":
                        return vGiftOpenDialog;
                    case "vGotItemDialog":
                        return vGotItemDialog;
                    case "vGotNewDoubleRoleDialog":
                        return vGotNewDoubleRoleDialog;
                    case "vGotNewRoleDialog":
                        return vGotNewRoleDialog;
                    case "vGotPartDialog":
                        return vGotPartDialog;
                    case "vHotActivityDialog":
                        return vHotActivityDialog;
                    case "vIntitleDialog":
                        return vIntitleDialog;
                    case "vIosInvateReview":
                        return vIosInvateReview;
                    case "vItemGotEffectDialog":
                        return vItemGotEffectDialog;
                    case "vLuckDiamondDialog":
                        return vLuckDiamondDialog;
                    case "vLuckEnergyDialog":
                        return vLuckEnergyDialog;
                    case "vMallDialog":
                        return vMallDialog;
                    case "vMidAutumnActivityDialog":
                        return vMidAutumnActivityDialog;
                    case "vMoreGameDialog":
                        return vMoreGameDialog;
                    case "vMoreGameFriendHotPlayDialog":
                        return vMoreGameFriendHotPlayDialog;
                    case "vNativeDialogBig":
                        return vNativeDialogBig;
                    case "vNativeDialogSmall":
                        return vNativeDialogSmall;
                    case "vNewYearPreviewDialog":
                        return vNewYearPreviewDialog;
                    case "vOfflineDialog":
                        return vOfflineDialog;
                    case "vPartDetailDialog":
                        return vPartDetailDialog;
                    case "vPromptDialog":
                        return vPromptDialog;
                    case "vRewardMoreGame":
                        return vRewardMoreGame;
                    case "vRoomDialog":
                        return vRoomDialog;
                    case "vSettingDialog":
                        return vSettingDialog;
                    case "vShareDilaog":
                        return vShareDilaog;
                    case "vSharePromptDilaog":
                        return vSharePromptDilaog;
                    case "vShareWithPhotoDialog":
                        return vShareWithPhotoDialog;
                    case "vSignDialog":
                        return vSignDialog;
                    case "vStagePreResultDialog":
                        return vStagePreResultDialog;
                    case "vStoryDialog":
                        return vStoryDialog;
                    case "vSuitShowingDialog":
                        return vSuitShowingDialog;
                    case "vSurpriseRewardDialog":
                        return vSurpriseRewardDialog;
                    case "vTakePhotoDialog":
                        return vTakePhotoDialog;
                    case "vTestDialog":
                        return vTestDialog;
                    case "vWebViewDialog":
                        return vWebViewDialog;
                    case "vEditorSelectDialog":
                        return vEditorSelectDialog;
                    case "vEditorTDEffDialog":
                        return vEditorTDEffDialog;
                    case "vAmuseCardAlbumSelectItem":
                        return vAmuseCardAlbumSelectItem;
                    case "vAmuseCardDoubleNpcAlbumItem":
                        return vAmuseCardDoubleNpcAlbumItem;
                    case "vAmuseCardExtractItem":
                        return vAmuseCardExtractItem;
                    case "vAmuseCardFightBloodTip":
                        return vAmuseCardFightBloodTip;
                    case "vAmuseCardFightSelectItem":
                        return vAmuseCardFightSelectItem;
                    case "vAmuseCardPhotoMakeListItem":
                        return vAmuseCardPhotoMakeListItem;
                    case "vAmusePenChooseListItem":
                        return vAmusePenChooseListItem;
                    case "vCakePart":
                        return vCakePart;
                    case "vCakeTypeBtn":
                        return vCakeTypeBtn;
                    case "vCardPreviewItem":
                        return vCardPreviewItem;
                    case "vDesignCollectCell":
                        return vDesignCollectCell;
                    case "vEditorCartonMaterialPart":
                        return vEditorCartonMaterialPart;
                    case "vEditorDynamicBoneAnimationItem":
                        return vEditorDynamicBoneAnimationItem;
                    case "vEditorDynamicBoneChild":
                        return vEditorDynamicBoneChild;
                    case "vEditorDynamicBonePart":
                        return vEditorDynamicBonePart;
                    case "vEditorDynamicBoneSearchRouterItem":
                        return vEditorDynamicBoneSearchRouterItem;
                    case "vFreedomRoomPreviewTalkItem":
                        return vFreedomRoomPreviewTalkItem;
                    case "vFullScreenMoreGameItem":
                        return vFullScreenMoreGameItem;
                    case "vFullScreenMoreGameItem2":
                        return vFullScreenMoreGameItem2;
                    case "vGuideTipNode":
                        return vGuideTipNode;
                    case "vHotActivityListItem":
                        return vHotActivityListItem;
                    case "vItemTip":
                        return vItemTip;
                    case "vJumpOtherDragLeft":
                        return vJumpOtherDragLeft;
                    case "vJumpOtherDragRight":
                        return vJumpOtherDragRight;
                    case "vJumpOtherGameBanner":
                        return vJumpOtherGameBanner;
                    case "vJumpOtherGameBannerVertical":
                        return vJumpOtherGameBannerVertical;
                    case "vMallItem":
                        return vMallItem;
                    case "vMidAutumnActItem":
                        return vMidAutumnActItem;
                    case "vMidAutumnPart":
                        return vMidAutumnPart;
                    case "vMsgTip":
                        return vMsgTip;
                    case "vNativeBanner":
                        return vNativeBanner;
                    case "vRankItem":
                        return vRankItem;
                    case "vRewardMoreGameItem":
                        return vRewardMoreGameItem;
                    case "vRoleChangeItem":
                        return vRoleChangeItem;
                    case "vRoomDesignPart":
                        return vRoomDesignPart;
                    case "vRoomPart":
                        return vRoomPart;
                    case "vRoomPartType":
                        return vRoomPartType;
                    case "vRoomRoleCell":
                        return vRoomRoleCell;
                    case "vStarLevelItem":
                        return vStarLevelItem;
                    case "vSuitShowingListItem":
                        return vSuitShowingListItem;
                    case "vSuitTypeListItem":
                        return vSuitTypeListItem;
                    case "vTestReuseListItem":
                        return vTestReuseListItem;
                    case "vTopBar":
                        return vTopBar;
                    case "vWarpSceneNode":
                        return vWarpSceneNode;
                    case "vWarpSceneNodeWhite":
                        return vWarpSceneNodeWhite;
                    case "vWorldDailyGameItem":
                        return vWorldDailyGameItem;
                    case "vAmuseCakeMakeScene":
                        return vAmuseCakeMakeScene;
                    case "vAmuseCardFightScene":
                        return vAmuseCardFightScene;
                    case "vAmuseCardPhotoMakeScene":
                        return vAmuseCardPhotoMakeScene;
                    case "vAmuseCardStartNewYearStageScene":
                        return vAmuseCardStartNewYearStageScene;
                    case "vAmuseCardStartScene":
                        return vAmuseCardStartScene;
                    case "vAmuseCardTeamSetScene":
                        return vAmuseCardTeamSetScene;
                    case "vAmuseClothCrossingScene":
                        return vAmuseClothCrossingScene;
                    case "vAmuseFashionPenScene":
                        return vAmuseFashionPenScene;
                    case "vAmuseParkourScene":
                        return vAmuseParkourScene;
                    case "vCustomMadeClothesScene":
                        return vCustomMadeClothesScene;
                    case "vDesignCollectScene":
                        return vDesignCollectScene;
                    case "vDesignRoomScene":
                        return vDesignRoomScene;
                    case "vEditorAnimationCheckScene":
                        return vEditorAnimationCheckScene;
                    case "vEditorCakeStageScene":
                        return vEditorCakeStageScene;
                    case "vEditorCardStageScene":
                        return vEditorCardStageScene;
                    case "vEditorClothCrossingStageScene":
                        return vEditorClothCrossingStageScene;
                    case "vEditorClothStageScene":
                        return vEditorClothStageScene;
                    case "vEditorDesignStageScene":
                        return vEditorDesignStageScene;
                    case "vEditorDynamicBone":
                        return vEditorDynamicBone;
                    case "vEditorHumanBone":
                        return vEditorHumanBone;
                    case "vEditorParkourStageScene":
                        return vEditorParkourStageScene;
                    case "vEditorPartCheck":
                        return vEditorPartCheck;
                    case "vEditorPartIconShotScene":
                        return vEditorPartIconShotScene;
                    case "vEditorPartSuitShotScene":
                        return vEditorPartSuitShotScene;
                    case "vEditorPBRHairShaderScene":
                        return vEditorPBRHairShaderScene;
                    case "vEditorPenStageScene":
                        return vEditorPenStageScene;
                    case "vEditorShaderCartonScene":
                        return vEditorShaderCartonScene;
                    case "vEditorShaderClothScene":
                        return vEditorShaderClothScene;
                    case "vEditorShaderHairScene":
                        return vEditorShaderHairScene;
                    case "vEditorShaderSkinScene":
                        return vEditorShaderSkinScene;
                    case "vEditorSpineCheckScene":
                        return vEditorSpineCheckScene;
                    case "vEditorStagePassCheck":
                        return vEditorStagePassCheck;
                    case "vEditorTimelineTestScene":
                        return vEditorTimelineTestScene;
                    case "vFreedomRoomScene":
                        return vFreedomRoomScene;
                    case "vHubScene":
                        return vHubScene;
                    case "vLoadingScene":
                        return vLoadingScene;
                    case "vPrestartScene":
                        return vPrestartScene;
                    case "vRankScene":
                        return vRankScene;
                    case "vRoleChangeScene":
                        return vRoleChangeScene;
                    case "vRoleChangeShowScene":
                        return vRoleChangeShowScene;
                    case "vRoomStageResultScene":
                        return vRoomStageResultScene;
                    case "vSuitTypeScene":
                        return vSuitTypeScene;
                    case "vTestModelDeformScene":
                        return vTestModelDeformScene;
                    case "vWorldDailyQuestMainScene":
                        return vWorldDailyQuestMainScene;
                    case "vGuideMaskDialog":
                        return vGuideMaskDialog;
                    case "SceneBase":
                        return SceneBase;
                    case "DialogBase":
                        return DialogBase;
                }
            }
        }

        class Start extends Laya.Script {
            constructor() { super(); }
            onAwake() {
                console.log("--->>:onAwake");
                Const.require = require;
                mgrNative.init();
                mgrDirector.adaptStageSize();
                Tools.gameStartTime = Laya.timer.currTimer;
                TweenSystem.create();
            }
            onEnable() {
                console.log("--->>:onEnable");
            }
            onStart() {
                console.log("--->>:onStart");
                mgrLayout.widget(0.5, 0.5, this.owner, { x: 0.5, y: 0.5 });
                mgrDirector.initScene();
                Laya.loader.load("url_path.json", new Laya.Handler(this, (urlConfig) => {
                    if (urlConfig.path && !Laya.Browser.onPC) {
                        // Laya.URL.basePath = urlConfig.path;

                        let self = this;
                        let loaded = Laya.LocalStorage.getItem("Loaded");
                        if (loaded != 1) {
                            var downloadTask = qg$1.download({
                                url: "http://res.njmobaike.com/CDN/ZhuZhuZhuangBanWuYu/LuoLiTianShiHuanZhuang/1.1.0/bin.zip",
                                success: function (data) {
                                    console.log(`handling success, tempFilePath = ${data.tempFilePath}`);
                                    qg$1.unzipFile({
                                        srcUri: data.tempFilePath,
                                        dstUri: qg$1.env.USER_DATA_PATH + "/bin/",
                                        success: function (uri) {
                                            console.log(`handling success: ${uri}`);
                                            Laya.URL.basePath = qg$1.env.USER_DATA_PATH + "/bin/";
                                            Laya.LocalStorage.setItem("Loaded",1);
                                        },
                                        fail: function (data, code) {
                                            console.log(`handling fail, code = ${code}`);
                                        }
                                    });
                                },
                                fail: function (data, code) {
                                    console.log(`handling fail, code = ${code}`);
                                }
                            });
        
                            downloadTask.onProgressUpdate(function (msg) {
                                console.log('SSSSSSSSSSSSSSSSS');
                                var progress = msg["progress"];
                                console.log(progress + "%");
                            });
                        }
                        else {
                            Laya.URL.basePath = qg$1.env.USER_DATA_PATH + "/bin/";
                        }
                    }
                    new UpdaterScript(this.owner, (msg) => {
                        if (msg == UPDATER_UI_MSG.ENTER_NEXT_SCENE) {
                            this.owner.getChildAt(0).visible = false;
                            this.loadFont(() => {
                                mgrDirector.open2DScene("vLoadingScene");
                            });
                        }
                    }).startUpdate();
                }));
            }
            loadFont(callback) {
                let path = `res/ui/font/font.ttf`;
                let stage = window["tt"] || window["wx"] || window["qg"];
                if (stage && stage.loadFont) {
                    try {
                        window["font"] = stage.loadFont(path);
                    }
                    catch (error) {
                        console.warn("Start loadFont error", error);
                    }
                    callback();
                }
                else {
                    callback();
                    Laya.loader.load(path, Laya.Handler.create(this, callback), null, Laya.Loader.TTF);
                }
            }
            onUpdate() {
                Tools.autoIncrementRuingTime();
                let failedRess = Laya.loader["_failRes"] || {};
                let totalCount = 0;
                let resList = "";
                Tools.forEachMap(failedRess, (url, count) => {
                    totalCount += count;
                    resList += url;
                });
                if (totalCount > 15) {
                }
                else {
                }
            }
            onLateUpdate() {
            }
            onDisable() {
                console.log("--->>:onDisable");
            }
        }

        class CustomLayout extends Laya.Script {
            constructor() {
                super();
                this.bHorizontalCenter = true;
                this.bFrameRefresh = true;
                this.space = 30;
                this.anchor = 0.5;
            }
            onEnable() {
                if (this.bHorizontalCenter)
                    Tools.layoutH(this.owner, this.space, this.anchor);
                if (!this.bHorizontalCenter)
                    Tools.layoutV(this.owner, this.space, this.anchor);
            }
            onUpdate() {
                if (!this.bFrameRefresh)
                    return;
                if (this.bHorizontalCenter)
                    Tools.layoutH(this.owner, this.space, this.anchor);
                if (!this.bHorizontalCenter)
                    Tools.layoutV(this.owner, this.space, this.anchor);
            }
            onDisable() {
            }
        }

        class GameConfig {
            constructor() {
            }
            static init() {
                var reg = Laya.ClassUtils.regClass;
                reg("Start.ts", Start);
                reg("script/ulframework/component/CustomLayout.ts", CustomLayout);
            }
        }
        GameConfig.width = 768;
        GameConfig.height = 1280;
        GameConfig.scaleMode = "fixedwidth";
        GameConfig.screenMode = "none";
        GameConfig.alignV = "top";
        GameConfig.alignH = "left";
        GameConfig.startScene = "MainScene.scene";
        GameConfig.sceneRoot = "";
        GameConfig.debug = false;
        GameConfig.stat = false;
        GameConfig.physicsDebug = true;
        GameConfig.exportSceneToJson = true;
        GameConfig.init();

        /**
         * - 时间: 2020年3月11日15:27:29
         * - by: Liuwei
         * - cause: 在魅族上有文字错乱的bug.
         * - 修改方式:  在文本构造函数中 修改 cacheAs = "bitmap";
         * 
         * - 本适配文件需要放在Laya.ResourceVersion.enable调用之前创建
         */
        const B_ALL_TEXT_RENDER_CACHE_AS_BITMAP = false;
        class ULAdapter {
            constructor() {
                Laya = window.Laya;
                window.Stage = window.Laya.Stage;

                this.adaptChannel();
                this.adaptVersinCompress();
                this.adpatLaya();

                this.adaptLoader();

                //刘亮说window["hbs"]这样会报错，只能下面这样
                let huaweType = 'hbs';
                // window[huaweType]
                if (window["qg"] || window["kwaigame"] || window[huaweType]) {
                    //do nothing
                }
                else {
                    // this.adaptFrameRate();
                }

                // this.adpatFgui();
                // this.adaptLoader();
            }



            /**
             * - 适配渠道bug
             * - 在发布中, 一部分渠道会有一些bug
             * - 适配渠道, 文件缓存
             */
            adaptChannel() {
                //1.即刻玩华为花屏问题
                window._setupVertexArrayObject = function (gl) {
                    var original_getSupportedExtensions = gl.getSupportedExtensions;
                    gl.getSupportedExtensions = function getSupportedExtensions() {
                        var list = original_getSupportedExtensions.call(this) || [];
                        if (list.indexOf("OES_vertex_array_object") < 0) {
                            list.push("OES_vertex_array_object");
                        }
                        return list;
                    };
                    var original_getExtension = gl.getExtension;
                    gl.getExtension = function getExtension(name) {
                        var ext = original_getExtension.call(this, name);
                        //ul runtime bug start
                        if (typeof loadRuntime !== "undefined" && name === "OES_vertex_array_object") {
                            ext = undefined;
                        }
                        //ul runtime bug end
                        if (ext) {
                            return ext;
                        }
                        if (name !== "OES_vertex_array_object") {
                            return null;
                        }
                        if (!this.__OESVertexArrayObject) {
                            console.log("Setup OES_vertex_array_object polyfill");
                            this.__OESVertexArrayObject = new OESVertexArrayObject(this);
                        }
                        return this.__OESVertexArrayObject;
                    };
                };

                //解决魅族文字花屏问题
                class ULText extends Laya.Text {
                    constructor() {
                        super();
                        if (B_ALL_TEXT_RENDER_CACHE_AS_BITMAP) {
                            this.cacheAs = "bitmap";
                            this.font = "Arial";
                        }
                    }
                }

                class ULLabel extends Laya.Label {
                    constructor(text = "") {
                        super(text);
                        if (B_ALL_TEXT_RENDER_CACHE_AS_BITMAP) {
                            this.cacheAs = "bitmap";
                            this.font = "Arial";
                        }
                    }
                }
                Laya.Label = ULLabel;
                Laya.Text = ULText;

                //适配启用(头条 微信 oppo  vivo  百度 qq)
                // wx/
                Laya.MiniAdpter && (Laya.MiniAdpter.autoCacheFile = true);
                Laya.MiniAdpter && (Laya.MiniAdpter.AutoCacheDownFile = true);
                //headline
                Laya.TTMiniAdapter && (Laya.TTMiniAdapter.autoCacheFile = true);
                Laya.TTMiniAdapter && (Laya.TTMiniAdapter.AutoCacheDownFile = true);
                //qq
                Laya.QQMiniAdapter && (Laya.QQMiniAdapter.autoCacheFile = true);
                Laya.QQMiniAdapter && (Laya.QQMiniAdapter.AutoCacheDownFile = true);
                // qg
                Laya.QGMiniAdapter && (Laya.QGMiniAdapter.autoCacheFile = true);
                Laya.QGMiniAdapter && (Laya.QGMiniAdapter.AutoCacheDownFile = true);
                // vivo
                Laya.VVMiniAdapter && (Laya.VVMiniAdapter.autoCacheFile = true);
                Laya.VVMiniAdapter && (Laya.VVMiniAdapter.AutoCacheDownFile = true);
                // baidu
                Laya.BMiniAdapter && (Laya.BMiniAdapter.autoCacheFile = true);
                Laya.BMiniAdapter && (Laya.BMiniAdapter.AutoCacheDownFile = true);
                // xiaomi
                Laya.KGMiniAdapter && (Laya.KGMiniAdapter.autoCacheFile = true);
                Laya.KGMiniAdapter && (Laya.KGMiniAdapter.AutoCacheDownFile = true);
            }

            /**
             * - 适配version 文件压缩
             */
            adaptVersinCompress() {
                //version 解压问题
                Laya.ResourceVersion.enable = (manifestFile, callback, type = 2) => {
                    Laya.ResourceVersion.type = type;
                    Laya.ResourceVersion[`__callback__`] = callback;
                    Laya.ResourceVersion[`__manifestFile__`] = manifestFile;

                    Laya.ILaya.loader.load(manifestFile, Laya.Handler.create(null, Laya.ResourceVersion.onManifestLoaded, [callback]), null, Laya.Loader.BUFFER);
                };
                Laya.ResourceVersion.onManifestLoaded = (callback, data) => {
                    let pako = window['pako'];
                    //先压缩, 再用文本的方式解压
                    data = pako.gzip(data);
                    let text = pako.ungzip(data, { to: "string" });
                    data = JSON.parse(text);

                    Laya.ResourceVersion.manifest = data;
                    Laya.URL.customFormat = Laya.ResourceVersion.addVersionPrefix;
                    callback.run();
                    if (!data) {
                        console.warn("资源版本清单文件不存在，不使用资源版本管理。忽略ERR_FILE_NOT_FOUND错误。");
                    }
                };
            }


            // 适配Laya
            adpatLaya() {
                //     var Config3D = Laya.Config3D;
                //     var Scene3D = Laya.Scene3D;
                //     var Scene3DShaderDeclaration = Laya.Scene3DShaderDeclaration;
                //     var Vector3 = Laya.Vector3;
                //     var Cluster = Laya.Cluster;
                //     //解决多光源下, spotLight没有参数的问题
                //     class ULScene3D extends Laya.Scene3D {
                //         _prepareSceneToRender() {
                //             var shaderValues = this._shaderValues;
                //             var multiLighting = Config3D._config._multiLighting;
                //             if (multiLighting) {
                //                 var ligTex = Scene3D._lightTexture;
                //                 var ligPix = Scene3D._lightPixles;
                //                 const pixelWidth = ligTex.width;
                //                 const floatWidth = pixelWidth * 4;
                //                 var curCount = 0;
                //                 var dirCount = this._directionLights._length;
                //                 var dirElements = this._directionLights._elements;
                //                 if (dirCount > 0) {
                //                     var sunLightIndex = this._directionLights.getBrightestLight();
                //                     this._mainDirectionLight = dirElements[sunLightIndex];
                //                     this._directionLights.normalLightOrdering(sunLightIndex);
                //                     for (var i = 0; i < dirCount; i++, curCount++) {
                //                         var dirLight = dirElements[i];
                //                         var dir = dirLight._direction;
                //                         var intCor = dirLight._intensityColor;
                //                         var off = floatWidth * curCount;
                //                         Vector3.scale(dirLight.color, dirLight._intensity, intCor);
                //                         dirLight.transform.worldMatrix.getForward(dir);
                //                         Vector3.normalize(dir, dir);
                //                         ligPix[off] = intCor.x;
                //                         ligPix[off + 1] = intCor.y;
                //                         ligPix[off + 2] = intCor.z;
                //                         ligPix[off + 4] = dir.x;
                //                         ligPix[off + 5] = dir.y;
                //                         ligPix[off + 6] = dir.z;
                //                         if (i == 0) {
                //                             shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, intCor);
                //                             shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dir);
                //                         }
                //                     }
                //                     shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
                //                 }
                //                 else {
                //                     shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
                //                 }
                //                 var poiCount = this._pointLights._length;
                //                 if (poiCount > 0) {
                //                     var poiElements = this._pointLights._elements;
                //                     var mainPointLightIndex = this._pointLights.getBrightestLight();
                //                     this._mainPointLight = poiElements[mainPointLightIndex];
                //                     this._pointLights.normalLightOrdering(mainPointLightIndex);
                //                     for (var i = 0; i < poiCount; i++, curCount++) {
                //                         var poiLight = poiElements[i];
                //                         var pos = poiLight.transform.position;
                //                         var intCor = poiLight._intensityColor;
                //                         var off = floatWidth * curCount;
                //                         Vector3.scale(poiLight.color, poiLight._intensity, intCor);
                //                         ligPix[off] = intCor.x;
                //                         ligPix[off + 1] = intCor.y;
                //                         ligPix[off + 2] = intCor.z;
                //                         ligPix[off + 3] = poiLight.range;
                //                         ligPix[off + 4] = pos.x;
                //                         ligPix[off + 5] = pos.y;
                //                         ligPix[off + 6] = pos.z;
                //                     }
                //                     shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
                //                 }
                //                 else {
                //                     shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
                //                 }
                //                 var spoCount = this._spotLights._length;
                //                 if (spoCount > 0) {
                //                     var spoElements = this._spotLights._elements;
                //                     var mainSpotLightIndex = this._spotLights.getBrightestLight();
                //                     this._mainSpotLight = spoElements[mainSpotLightIndex];
                //                     this._spotLights.normalLightOrdering(mainSpotLightIndex);
                //                     for (var i = 0; i < spoCount; i++, curCount++) {
                //                         var spoLight = spoElements[i];
                //                         var dir = spoLight._direction;
                //                         var pos = spoLight.transform.position;
                //                         var intCor = spoLight._intensityColor;
                //                         var off = floatWidth * curCount;
                //                         Vector3.scale(spoLight.color, spoLight._intensity, intCor);
                //                         spoLight.transform.worldMatrix.getForward(dir);
                //                         Vector3.normalize(dir, dir);
                //                         ligPix[off] = intCor.x;
                //                         ligPix[off + 1] = intCor.y;
                //                         ligPix[off + 2] = intCor.z;
                //                         ligPix[off + 3] = spoLight.range;
                //                         ligPix[off + 4] = pos.x;
                //                         ligPix[off + 5] = pos.y;
                //                         ligPix[off + 6] = pos.z;
                //                         ligPix[off + 7] = spoLight.spotAngle * Math.PI / 180;
                //                         ligPix[off + 8] = dir.x;
                //                         ligPix[off + 9] = dir.y;
                //                         ligPix[off + 10] = dir.z;
                //                     }
                //                     shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
                //                 }
                //                 else {
                //                     shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
                //                 }
                //                 (curCount > 0) && (ligTex.setSubPixels(0, 0, pixelWidth, curCount, ligPix, 0));
                //                 shaderValues.setTexture(Scene3D.LIGHTBUFFER, ligTex);
                //                 shaderValues.setInt(Scene3D.DIRECTIONLIGHTCOUNT, this._directionLights._length);
                //                 shaderValues.setTexture(Scene3D.CLUSTERBUFFER, Cluster.instance._clusterTexture);

                //                 if (this._spotLights._length > 0) {
                //                     var spotLight = this._spotLights._elements[0];
                //                     this._mainSpotLight = spotLight;
                //                     Vector3.scale(spotLight.color, spotLight._intensity, spotLight._intensityColor);
                //                     shaderValues.setVector3(Scene3D.SPOTLIGHTCOLOR, spotLight._intensityColor);
                //                     shaderValues.setVector3(Scene3D.SPOTLIGHTPOS, spotLight.transform.position);
                //                     spotLight.transform.worldMatrix.getForward(spotLight._direction);
                //                     Vector3.normalize(spotLight._direction, spotLight._direction);
                //                     shaderValues.setVector3(Scene3D.SPOTLIGHTDIRECTION, spotLight._direction);
                //                     shaderValues.setNumber(Scene3D.SPOTLIGHTRANGE, spotLight.range);
                //                     shaderValues.setNumber(Scene3D.SPOTLIGHTSPOTANGLE, spotLight.spotAngle * Math.PI / 180);
                //                     shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
                //                 }
                //                 else {
                //                     shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
                //                 }
                //             }
                //             else {
                //                 if (this._directionLights._length > 0) {
                //                     var dirLight = this._directionLights._elements[0];
                //                     this._mainDirectionLight = dirLight;
                //                     Vector3.scale(dirLight.color, dirLight._intensity, dirLight._intensityColor);
                //                     dirLight.transform.worldMatrix.getForward(dirLight._direction);
                //                     Vector3.normalize(dirLight._direction, dirLight._direction);
                //                     shaderValues.setVector3(Scene3D.LIGHTDIRCOLOR, dirLight._intensityColor);
                //                     shaderValues.setVector3(Scene3D.LIGHTDIRECTION, dirLight._direction);
                //                     shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, dirLight._intensityColor);
                //                     shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dirLight._direction);
                //                     shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
                //                 }
                //                 else {
                //                     shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
                //                 }
                //                 if (this._pointLights._length > 0) {
                //                     var poiLight = this._pointLights._elements[0];
                //                     this._mainPointLight = poiLight;
                //                     Vector3.scale(poiLight.color, poiLight._intensity, poiLight._intensityColor);
                //                     shaderValues.setVector3(Scene3D.POINTLIGHTCOLOR, poiLight._intensityColor);
                //                     shaderValues.setVector3(Scene3D.POINTLIGHTPOS, poiLight.transform.position);
                //                     shaderValues.setNumber(Scene3D.POINTLIGHTRANGE, poiLight.range);
                //                     shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
                //                 }
                //                 else {
                //                     shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
                //                 }
                //                 if (this._spotLights._length > 0) {
                //                     var spotLight = this._spotLights._elements[0];
                //                     this._mainSpotLight = spotLight;
                //                     Vector3.scale(spotLight.color, spotLight._intensity, spotLight._intensityColor);
                //                     shaderValues.setVector3(Scene3D.SPOTLIGHTCOLOR, spotLight._intensityColor);
                //                     shaderValues.setVector3(Scene3D.SPOTLIGHTPOS, spotLight.transform.position);
                //                     spotLight.transform.worldMatrix.getForward(spotLight._direction);
                //                     Vector3.normalize(spotLight._direction, spotLight._direction);
                //                     shaderValues.setVector3(Scene3D.SPOTLIGHTDIRECTION, spotLight._direction);
                //                     shaderValues.setNumber(Scene3D.SPOTLIGHTRANGE, spotLight.range);
                //                     shaderValues.setNumber(Scene3D.SPOTLIGHTSPOTANGLE, spotLight.spotAngle * Math.PI / 180);
                //                     shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
                //                 }
                //                 else {
                //                     shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
                //                 }
                //             }
                //         }
                //     }

                //    Laya.Scene3D = ULScene3D;

                //   class ULSprite extends Laya.Sprite {
                //       setXY(x, y) {
                //           this.pos(x, y);
                //       }
                //   }
                //   Laya.Sprite = ULSprite;

                /******** 因为这部分代码, 不会生效,  因为所有的初始化和引用都在laya内部, 这里做备份 */
                class ULInput3D extends Laya.Input3D {
                    constructor() {
                        super();
                        this._pushEventList = ((e) => {
                            (e.cancelable) && (e.preventDefault());
                            (e.cancelable) && this._eventList.push(e);
                        }).bind(this);
                    }
                }
                Laya.Input3D = ULInput3D;

                class ULAnimatorControllerLayer extends Laya.AnimatorControllerLayer {
                    addState(state) {
                        var stateName = state.name;
                        if (this._statesMap[stateName]) {
                            console.warn("AnimatorControllerLayer:this stat's name has exist.");
                        }
                        else {
                            this._statesMap[stateName] = state;
                            this._states.push(state);
                            if (this._animator) {
                                state._clip._addReference();
                                this._animator._getOwnersByClip(state);
                            }
                        }
                    }
                }
                Laya.AnimatorControllerLayer = ULAnimatorControllerLayer;

                class ULSimpleSingletonList extends Laya.SimpleSingletonList {
                    add(element) {
                        var index = element._getIndexInList();
                        if (index !== -1) return;
                        // throw "SimpleSingletonList:" + element + " has  in  SingletonList.";
                        this._add(element);
                        element._setIndexInList(this.length++);
                    }
                    remove(element) {
                        var index = element._getIndexInList();
                        /**
                         * - 2020年1月8日14:50:51
                         * - by 刘伟
                         * - cause: 在疯狂点击, 可能会造成lenght < 0的情况 导致crash
                         */
                        if (this.length <= 0) return;
                        this.length--;
                        if (index !== this.length) {
                            var end = this.elements[this.length];
                            this.elements[index] = end;
                            end._setIndexInList(index);
                        }
                        element._setIndexInList(-1);
                    }
                }
                Laya.SimpleSingletonList = ULSimpleSingletonList;



                class ULScene3D extends Laya.Scene3D {

                    renderSubmit() {
                        if (!this._directionLights || !this._cameraPool) {
                            return 1;
                        }
                        var gl = Laya.LayaGL.instance;
                        this._prepareSceneToRender();
                        var i, n, n1;
                        for (i = 0, n = this._cameraPool.length, n1 = n - 1; i < n; i++) {
                            if (Laya.Render.supportWebGLPlusRendering)
                                ShaderData.setRuntimeValueMode((i == n1) ? true : false);
                            var camera = this._cameraPool[i];
                            camera.enableRender && camera.render();
                        }
                        Laya.Context.set2DRenderConfig();
                        return 1;
                    }
                }
                Laya.Scene3D = ULScene3D;
            }

            //适配帧率
            adaptFrameRate() {

                Laya.stage.frameRate = Laya.Stage.FRAME_SLOW;

                let oldrender = Laya.Stage.prototype.render;
                this._frameStartTime = 0;
                let frameDuration = 20;
                let totalTime = 0;
                let startTime = 0;
                let frameCount = 0;

                Laya.Stage.prototype.render = (context, x, y) => {
                    if (Laya.Browser.now() - this._frameStartTime <= frameDuration) {
                        return;
                    }
                    this._frameStartTime = Laya.Browser.now();

                    startTime = Laya.Browser.now();
                    oldrender.apply(Laya.stage, [context, x, y]);
                    totalTime += Laya.Browser.now() - startTime;
                    frameCount++;
                    frameDuration = Math.min(totalTime / frameCount, 20);
                };
            }


            // // 适配fgui
            // adpatFgui() {
            //     // 阻止fgui列表的touch down事件继续冒泡
            //     // by LDW 2020-11-20
            //     var scroll_panel_mouseDown = fgui.ScrollPane.prototype["__mouseDown"];
            //     fgui.ScrollPane.prototype["__mouseDown"] = function (e) {
            //         e.stopPropagation();
            //         scroll_panel_mouseDown.apply(this);
            //     }


            //     // 定义Image的width和height，使得Image被点击时可以进行hit判定
            //     // by LDW 2020-11-22
            //     Object.defineProperty(fgui.Image.prototype, "width", {
            //         configurable: true,
            //         enumerable: true,
            //         get: function () {
            //             return this._width;
            //         },
            //         set: function (value) {
            //             if (this["_width"] !== value) {
            //                 this.set_width(value);
            //                 this.markChanged(1);
            //             }
            //         }
            //     })

            //     Object.defineProperty(fgui.Image.prototype, "height", {
            //         configurable: true,
            //         enumerable: true,
            //         get: function () {
            //             return this._height;
            //         },
            //         set: function (value) {
            //             if (this["_height"] !== value) {
            //                 this.set_height(value);
            //                 this.markChanged(1);
            //             }
            //         }
            //     })


            //     // 将按钮的缩放效果改为tween动画
            //     // by LDW 2020-11-23
            //     var GButton = fgui.GButton;
            //     var button_setState = GButton.prototype["setState"];
            //     GButton.prototype["setState"] = function (val) {
            //         if (this._downEffect == 2) {
            //             if (this._buttonController)
            //                 this._buttonController.selectedPage = val;

            //             if (val == GButton.DOWN || val == GButton.SELECTED_OVER || val == GButton.SELECTED_DISABLED) {
            //                 if (!this._downScaled) {
            //                     if (this["_originScaleX"] == null) {
            //                         this["_originScaleX"] = this.scaleX;
            //                         this["_originScaleY"] = this.scaleY;
            //                     }

            //                     Laya.Tween.to(this, { scaleX: this["_originScaleX"] * this._downEffectValue, scaleY: this["_originScaleY"] * this._downEffectValue }, 50);
            //                     this._downScaled = true;
            //                 }
            //             }
            //             else {
            //                 if (this._downScaled) {
            //                     Laya.Tween.to(this, { scaleX: this["_originScaleX"], scaleY: this["_originScaleY"] }, 50, Laya.Ease.backOut);
            //                     this._downScaled = false;
            //                 }
            //             }
            //         } else {
            //             button_setState.apply(this, arguments);
            //         }
            //     }
            // }


            //适配资源加载
            adaptLoader() {
                class ULLoader extends Laya.Loader {
                    onLoaded(data = null) {
                        var type = this._type;
                        var url = this._url;
                        //需要对二进制文件进行解压操作
                        if (type == Laya.Loader.BUFFER) {
                            let isMatch = (data) => {
                                let array = new Uint8Array(data);
                                let matchArr = [31, 139, 8, 0];
                                for (let i = 0; i < matchArr.length; i++) {
                                    const element = matchArr[i];
                                    if (element !== array[i]) {
                                        return false;
                                    }
                                }
                                return true;
                            };

                            //压缩头判定版本
                            if (isMatch(data)) {
                                //匹配到了压缩头
                                data = pako.ungzip(data);
                                // console.error(`${url}: 已压缩`);
                            }

                            // // try 版本  效率低
                            // let pako = window['pako'];
                            // try {
                            //     let newData = pako.ungzip(data);
                            //     data = newData;
                            //     console.error(`${url}: 已压缩`);
                            // } catch (error) {
                            //     console.error(`${url}: 未压缩`);
                            // }
                        }
                        super.onLoaded(data);
                    }
                }
                Laya.ILaya.Loader = Laya.Loader = ULLoader;

                let oldLoad = ULLoader.prototype[`load`];
                ULLoader.prototype[`load`] = function (...args) {
                    let url = args[0];
                    if (!!url) {
                        let idx = url.indexOf(".jpg");
                        let idx1 = url.indexOf(".png");
                        if (idx >= 0) {
                            url = url.substring(0, idx + 4);
                        }
                        else if (idx1 >= 0) {
                            url = url.substring(0, idx1 + 4);
                        }
                    }
                    args[0] = url;
                    oldLoad.call(this, ...args);
                };
                /**
                 * - 自定义加载管理器
                 */
                class ULLoaderManager extends Laya.LoaderManager {
                    _doLoad(resInfo) {
                        this._loaderCount++;
                        var loader = this._loaders.length ? this._loaders.pop() : new Laya.Loader();
                        loader.on(Laya.Event.COMPLETE, null, onLoaded);
                        loader.on(Laya.Event.PROGRESS, null, function (num) {
                            resInfo.event(Laya.Event.PROGRESS, num);
                        });
                        loader.on(Laya.Event.ERROR, null, function (msg) {
                            onLoaded(null);
                        });
                        var _me = this;
                        function onLoaded(data = null) {
                            loader.offAll();
                            loader._data = null;
                            loader._customParse = false;
                            _me._loaders.push(loader);
                            _me._endLoad(resInfo, data instanceof Array ? [data] : data);
                            _me._loaderCount--;
                            _me._next();
                        }
                        loader._constructParams = resInfo.createConstructParams;
                        loader._propertyParams = resInfo.createPropertyParams;
                        loader._createCache = resInfo.createCache;
                        loader.load(resInfo.url, resInfo.type, resInfo.cache, resInfo.group, resInfo.ignoreCache, resInfo.useWorkerLoader);
                    }
                }
                Laya.ILaya.loader = Laya.loader = new ULLoaderManager();
                Laya3D._innerFirstLevelLoaderManager = new ULLoaderManager();
                Laya3D._innerSecondLevelLoaderManager = new ULLoaderManager();
                Laya3D._innerThirdLevelLoaderManager = new ULLoaderManager();
                Laya3D._innerFourthLevelLoaderManager = new ULLoaderManager();
            }
        }

        const B_ALL_TEXT_RENDER_CACHE_AS_BITMAP$1 = false;
        class Main {
            constructor() {
                window[`notCacheList`] = [];
                if (window["Laya3D"])
                    Laya3D.init(GameConfig.width, GameConfig.height);
                else
                    Laya.init(GameConfig.width, GameConfig.height, Laya["WebGL"]);
                Laya["Physics"] && Laya["Physics"].enable();
                Laya["DebugPanel"] && Laya["DebugPanel"].enable();
                Laya.stage.scaleMode = GameConfig.scaleMode;
                Laya.stage.screenMode = GameConfig.screenMode;
                Laya.stage.alignV = GameConfig.alignV;
                Laya.stage.alignH = GameConfig.alignH;
                Laya.URL.exportSceneToJson = GameConfig.exportSceneToJson;
                Laya.MouseManager.multiTouchEnabled = false;
                if (GameConfig.debug || Laya.Utils.getQueryString("debug") == "true")
                    Laya.enableDebugPanel();
                if (GameConfig.physicsDebug && Laya["PhysicsDebugDraw"])
                    Laya["PhysicsDebugDraw"].enable();
                if (GameConfig.stat)
                    Laya.Stat.show();
                Laya.Shader3D.debugMode = false;
                Laya.PBRMaterial.renderQuality = Laya.PBRRenderQuality.Low;
                if (!B_ALL_TEXT_RENDER_CACHE_AS_BITMAP$1) {
                    Laya.TextRender.forceSplitRender = true;
                }
                new ULAdapter();

                Laya.ResourceVersion.enable("version.json", Laya.Handler.create(this, this.onVersionLoaded), Laya.ResourceVersion.FILENAME_VERSION);

                Advertisement.initVal();
            }
            onVersionLoaded() {
                // Laya.AtlasInfoManager.enable("fileconfig.json", Laya.Handler.create(this, this.onConfigLoaded));

                let self = this;
                Laya.loader.create("prefab/jkgg.prefab", Laya.Handler.create(this, prefab => {
                    let jkgg = Laya.Pool.getItemByCreateFun("jkgg", prefab.create, prefab);
                    jkgg.width = Laya.stage.width;
                    jkgg.height = Laya.stage.height;
                    Laya.stage.addChild(jkgg);
                    Laya.timer.once(3 * 1000, this, function () {
                        jkgg.visible = false;

                        // Laya.loader.load("prefab/fwtk.json", Laya.Handler.create(this, function (pref) {
                        //     var fwtkp = new Laya.Prefab();
                        //     fwtkp.json = pref;
                        //     var fwtks = Laya.Pool.getItemByCreateFun("fwtk", fwtkp.create, fwtkp);
                        //     fwtks.pos(Laya.stage.width / 2, Laya.stage.height / 2);
                        //     fwtks.scaleX = 1;
                        //     fwtks.scaleY = 1;
                        //     fwtks.getChildByName('btn_yes').on(Laya.Event.MOUSE_DOWN, this, function () {
                        //         Laya.LocalStorage.setItem('ycys', JSON.parse('true'));
                        //         fwtks.removeSelf();

                        Laya.AtlasInfoManager.enable("fileconfig.json", Laya.Handler.create(self, self.onConfigLoaded));

                        //     })
                        //     fwtks.getChildByName('btn_no').on(Laya.Event.MOUSE_DOWN, this, function () {
                        //         qg.exitApplication({
                        //             success: function () {
                        //                 console.log("exitApplication success");
                        //             },
                        //             fail: function () {
                        //                 console.log("exitApplication fail");
                        //             },
                        //             complete: function () {
                        //                 console.log("exitApplication complete");
                        //             }
                        //         });
                        //     })
                        //     Laya.stage.addChild(fwtks);
                        // }))

                    });
                }));
            }
            onConfigLoaded() {
                GameConfig.startScene && Laya.Scene.open(GameConfig.startScene);

                Advertisement.insertAdverV3();
            }
        }
        new Main();

}());
