import LoadingView from "./View/Logo/LoadingView";
import AppPlatform from "./Util/AppPlatform";
import AppConfig from "./Config/AppConfig";
import { LogUtils } from "./Util/LogUtils";
import BundleMgr from "./Mgr/BundleMgr";
import GameMgr from "./Mgr/GameMgr";
import User from "./User/User";
import EventMgr from "./Event/EventMgr";
import { ryw_Event } from "./Event/EventEnum";
import Common5 from "../Platform/th/Common5";
import CommonDefine from "../Platform/th/CommonDefine";
import GameReport, { ENTERTYPE } from "./Report/ZyZyReport";
const { ccclass, property } = cc._decorator;

/**
 * 主页场景
 */

@ccclass
export default class Main extends cc.Component {

    public static isBack_custom: boolean = false; //是否从后台回到前台
    //加载页面
    @property({ tooltip: "加载页面预支", type: cc.Node })
    private loadingPrefab: cc.Node = null;

    //-----------------
    private loadView_custom: LoadingView;

    //加载分包的进度最终位置
    private readonly loadSubpackageTotal_custom: number = 0.8;
    //网络加载的最终位置
    private readonly loadHttpNetworkTotal_custom: number = 1;

    //当前加载的分包下标
    private subpackageIndex_custom: number = 0;
    //公共的包大小
    private subpackageSum_custom: number = 0;
    //下一步要到达的进度最大值(0-1)
    private needProcessNum_custom: number = 0;

    //加载的状态 0未开始 1加载正常进度 2加载慢慢速度 3结束,进度条快速完成  4等待加载场景
    private loadingState_custom: number = 0;
    //速度
    private loadingSpeed_custom: number = 0;

    async onLoad() {
        this.wdyjrjsdkInit();
        this.checkDoubleTexture();
        if (AppPlatform.is_TT_GAME_custom()) {

            console.log = ()=>{}
            console.warn = ()=>{}
            // console.error = ()=>{}
            Common5.ISSHOWGM = false
            AppConfig.AppID_custom = AppConfig.TT_APP_ID_custom;
            AppConfig.state_custom = AppConfig.TT_state_custom;
            AppConfig.gameid_custom = AppConfig.TT_gameid_custom;
            AppConfig.ResServer_custom = AppConfig.TT_ResServer_custom;
            AppConfig.Versions_custom = AppConfig.TT_Versions_custom;
            AppConfig.UseRYSDK_custom = false;

            AppConfig.LoopAdLocationID_custom = AppConfig.TT_LoopAdLocationID_custom;
            AppConfig.BannerAdLocationID_custom = AppConfig.TT_BannerAdLocationID_custom;
            AppConfig.InsertAdLocationID_custom = AppConfig.TT_InsertAdLocationID_custom;
            AppConfig.AniAdLocationID_custom = AppConfig.TT_AniAdLocationID_custom;
            AppConfig.HistoryLocationID_custom = AppConfig.TT_HistoryLocationID_custom;
            AppConfig.MoreGameLocationID_custom = AppConfig.TT_MoreGameLocationID_custom;

        } else if (AppPlatform.is_WECHAT_GAME_custom()) {
            Common5.ISSHOWGM = false
            AppConfig.AppID_custom = AppConfig.WX_APP_ID_custom;
            AppConfig.state_custom = AppConfig.WX_state_custom;
            AppConfig.gameid_custom = AppConfig.WX_gameid_custom;
            AppConfig.ResServer_custom = AppConfig.WX_ResServer_custom;
            AppConfig.Versions_custom = AppConfig.WX_Versions_custom;
            AppConfig.UseRYSDK_custom = true;
            if (AppConfig.closeUseRYSDK_custom) {//强制关闭的情况
                AppConfig.UseRYSDK_custom = false;
            }

            AppConfig.LoopAdLocationID_custom = AppConfig.WX_LoopAdLocationID_custom;
            AppConfig.BannerAdLocationID_custom = AppConfig.WX_BannerAdLocationID_custom;
            AppConfig.InsertAdLocationID_custom = AppConfig.WX_InsertAdLocationID_custom;
            AppConfig.AniAdLocationID_custom = AppConfig.WX_AniAdLocationID_custom;
            AppConfig.HistoryLocationID_custom = AppConfig.WX_HistoryLocationID_custom;
            AppConfig.MoreGameLocationID_custom = AppConfig.WX_MoreGameLocationID_custom;
        } else if (AppPlatform.is_QQ_PLAY_custom()) {
            Common5.ISSHOWGM = false
            AppConfig.AppID_custom = AppConfig.QQ_APP_ID_custom;
            AppConfig.state_custom = AppConfig.QQ_state_custom;
            AppConfig.gameid_custom = AppConfig.QQ_gameid_custom;
            AppConfig.ResServer_custom = AppConfig.QQ_ResServer_custom;
            AppConfig.Versions_custom = AppConfig.QQ_Versions_custom;
            AppConfig.UseRYSDK_custom = false;

            AppConfig.LoopAdLocationID_custom = AppConfig.QQ_LoopAdLocationID_custom;
            AppConfig.BannerAdLocationID_custom = AppConfig.QQ_BannerAdLocationID_custom;
            AppConfig.InsertAdLocationID_custom = AppConfig.QQ_InsertAdLocationID_custom;
            AppConfig.AniAdLocationID_custom = AppConfig.QQ_AniAdLocationID_custom;
            AppConfig.HistoryLocationID_custom = AppConfig.QQ_HistoryLocationID_custom;
            AppConfig.MoreGameLocationID_custom = AppConfig.QQ_MoreGameLocationID_custom;
        } else if (AppPlatform.is_OPPO_GAME_custom()) {
            Common5.ISSHOWGM = false
            AppConfig.AppID_custom = AppConfig.OPPO_APP_ID_custom;
            AppConfig.state_custom = AppConfig.OPPO_state_custom;
            AppConfig.gameid_custom = AppConfig.OPPO_gameid_custom;
            AppConfig.ResServer_custom = AppConfig.OPPO_ResServer_custom;
            AppConfig.Versions_custom = AppConfig.OPPO_Versions_custom;
            AppConfig.UseRYSDK_custom = false;

            AppConfig.LoopAdLocationID_custom = AppConfig.OPPO_LoopAdLocationID_custom;
            AppConfig.BannerAdLocationID_custom = AppConfig.OPPO_BannerAdLocationID_custom;
            AppConfig.InsertAdLocationID_custom = AppConfig.OPPO_InsertAdLocationID_custom;
            AppConfig.AniAdLocationID_custom = AppConfig.OPPO_AniAdLocationID_custom;
            AppConfig.HistoryLocationID_custom = AppConfig.OPPO_HistoryLocationID_custom;
            AppConfig.MoreGameLocationID_custom = AppConfig.OPPO_MoreGameLocationID_custom;

        } else if (AppPlatform.is_VIVO_GAME_custom()) {
            Common5.ISSHOWGM = false
            AppConfig.AppID_custom = AppConfig.VIVO_APP_ID_custom;
            AppConfig.state_custom = AppConfig.VIVO_state_custom;
            AppConfig.gameid_custom = AppConfig.VIVO_gameid_custom;
            AppConfig.ResServer_custom = AppConfig.VIVO_ResServer_custom;
            AppConfig.Versions_custom = AppConfig.VIVO_Versions_custom;
            AppConfig.UseRYSDK_custom = false;

            AppConfig.LoopAdLocationID_custom = AppConfig.VIVO_LoopAdLocationID_custom;
            AppConfig.BannerAdLocationID_custom = AppConfig.VIVO_BannerAdLocationID_custom;
            AppConfig.InsertAdLocationID_custom = AppConfig.VIVO_InsertAdLocationID_custom;
            AppConfig.AniAdLocationID_custom = AppConfig.VIVO_AniAdLocationID_custom;
            AppConfig.HistoryLocationID_custom = AppConfig.VIVO_HistoryLocationID_custom;
            AppConfig.MoreGameLocationID_custom = AppConfig.VIVO_MoreGameLocationID_custom;
        } else if (AppPlatform.is_Android_custom() || AppPlatform.is_Iphone_custom()) {//android
            Common5.ISSHOWGM = false
            AppConfig.AppID_custom = AppConfig.APK_APP_ID_custom;
            AppConfig.state_custom = AppConfig.APK_state_custom;
            AppConfig.gameid_custom = AppConfig.APK_gameid_custom;
            AppConfig.ResServer_custom = AppConfig.APK_ResServer_custom;
            AppConfig.Versions_custom = AppConfig.APK_Versions_custom;
            AppConfig.UseRYSDK_custom = false;

        } else {//其他开发 用微信的
            AppConfig.AppID_custom = AppConfig.Web_APP_ID_custom;
            AppConfig.state_custom = AppConfig.TT_state_custom;
            AppConfig.gameid_custom = AppConfig.TT_gameid_custom;
            AppConfig.ResServer_custom = AppConfig.TT_ResServer_custom;
            AppConfig.Versions_custom = AppConfig.TT_Versions_custom;
            AppConfig.UseRYSDK_custom = false;//开发模式不支持

            AppConfig.LoopAdLocationID_custom = AppConfig.TT_LoopAdLocationID_custom;
            AppConfig.BannerAdLocationID_custom = AppConfig.TT_BannerAdLocationID_custom;
            AppConfig.InsertAdLocationID_custom = AppConfig.TT_InsertAdLocationID_custom;
            AppConfig.AniAdLocationID_custom = AppConfig.TT_AniAdLocationID_custom;
            AppConfig.HistoryLocationID_custom = AppConfig.TT_HistoryLocationID_custom;
            AppConfig.MoreGameLocationID_custom = AppConfig.TT_MoreGameLocationID_custom;
        }

        this.loadView_custom = this.loadingPrefab.getComponent(LoadingView);
        this.subpackageSum_custom = AppConfig.subResArray_custom.length;
        this.loadView_custom.setProcess_custom(0);

		// GameReport.EnterReport(ENTERTYPE.TIAOZHUAN, '加载本地json')

        AppPlatform.checkUpdate_custom();
        Common5.loadConfigLocal_custom(()=>{
            this.loadSubpackage_custom();
        });
    }

    start() {
        
    }


    /**
     * 加载分包
     */
    private loadSubpackage_custom() {
        var self = this;
        //有分包没有加载完成
        if (this.subpackageIndex_custom < this.subpackageSum_custom) {
            let platform = "";
            let subpackageName = AppConfig.subResArray_custom[this.subpackageIndex_custom];

            if (AppPlatform.is_TT_GAME_custom()) {
                platform = "tt";
            } else if (AppPlatform.is_WECHAT_GAME_custom()) {
                platform = "wx";
            }
            else if (AppPlatform.is_OPPO_GAME_custom()) {
                platform = "qg";
            }
            else if (AppPlatform.is_QQ_PLAY_custom()) {
                platform = "qq";
            }
            LogUtils.log_custom("加载分包 " + subpackageName + "  platform " + platform);

            let proSum = ((this.subpackageIndex_custom + 1) / this.subpackageSum_custom) * self.loadSubpackageTotal_custom;
            this.setStartLoadingPerNum_custom(proSum)
            BundleMgr.loadBundleByName_custom(subpackageName, handleFM_custom((err, bundle) => {
                if (err) {
                    console.error('加载分包失败'+err);
                } else {
                    self.subpackageIndex_custom = self.subpackageIndex_custom + 1;
                    AppPlatform.loadSubpackageFinish_custom(subpackageName);
                    self.loadSubpackage_custom();
                    
                }
            }, this));
            // }
        } else {//加载完成了
            //this.setStartLoadingPerNum(this.loadSubpackageTotal)
            console.log('加载完成+++===全部bundle')
			// GameReport.EnterReport(ENTERTYPE.TIAOZHUAN, 'loading加载完毕')
            this.onLoadResComplate_custom();//预加载完成

        }
    }

    /**
     * 设置下一个加载步骤可以到的位置
     * @param preNum 
     */
    private setStartLoadingPerNum_custom(preNum: number) {
        this.setLoadingState_custom(1, preNum);
    }


    /**
     * 设置加载的进度状态
     * @param state 
     */
    private setLoadingState_custom(state: number, preNum: number) {
        this.loadingState_custom = state;
        this.needProcessNum_custom = preNum;
        switch (state) {
            case 0:
                break;
            case 1:
                this.loadingSpeed_custom = 1 / 80;
                break;
            case 2:
                this.loadingSpeed_custom = 1 / 200;
                break;
            case 3://下载完成了
                {
                    let precess = this.loadView_custom.getProcess_custom();
                    let psum = 1 - precess;
                    if (psum > 0) {
                        this.loadingSpeed_custom = psum / 20;
                    } else {
                        this.loadingSpeed_custom = 1 / 2;
                    }

                }
                break;
            default:
                break;
        }
    }



    /**
     * 假的进度
     * @param dt 
     */
    protected update(dt: number): void {
        if (this.loadView_custom) {
            let precess = this.loadView_custom.getProcess_custom();
            let nextPrecess = precess + this.loadingSpeed_custom;

            switch (this.loadingState_custom) {
                case 0:
                    break;
                case 1://正常速度
                    if (nextPrecess >= this.needProcessNum_custom * 0.7) {
                        //nextPrecess = this.needProcessNum * 0.7;
                        if (nextPrecess >= this.needProcessNum_custom) {
                            nextPrecess = this.needProcessNum_custom;
                        }
                        //进入慢速度
                        this.setLoadingState_custom(2, this.needProcessNum_custom);
                    }
                    break;
                case 2://慢速度
                    if (nextPrecess >= this.needProcessNum_custom) {
                        nextPrecess = this.needProcessNum_custom;
                    }
                    break;
                case 3://急速进度
                    if (nextPrecess >= 1) {
                        nextPrecess = 1;
                        this.loadingState_custom = 4;

                    }
                    break;
                default:
                    break;
            }

            if (precess != nextPrecess) {
                this.loadView_custom.setProcess_custom(nextPrecess);
            }
        }
    }

    /**
     * 设置下载全部完成,可以进游戏了
     */
    private setDownloadOver_custom() {
        this.initGame_custom();
        this.setLoadingState_custom(3, 1);
    }


    /**
     * 登录失败
     */
    private Login_fail_custom(res?: any) {
        console.log("登陆失败!!!" + res);
        EventMgr.emitEvent_custom(ryw_Event.ryw_PlatformLoginState_custom, { state: 1, info: "平台登录失败" })
        
        let data = cc.sys.localStorage.getItem("data" + AppConfig.AppID_custom);
        if (data) {
            console.log("登录失败+++++++++  有存档");

            User.initiUser_custom(JSON.parse(data));
        } else {
            console.log("登录失败+++++++++  无存档");

            User.initiUser_custom(null);
        }
        this.setDownloadOver_custom();
    }

    /**
     * 各个平台登录成功后 来自己服务器登录
     * @param code 
     */
    private go_Login_custom(code: any) {
        User.code_custom = code
        EventMgr.emitEvent_custom(ryw_Event.ryw_PlatformLoginState_custom, { state: 0, info: "平台登录成功" })
        console.log("准备登陆自己的平台")

        // if (AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().isNetWorkGame_custom != 1) {
        //存本地
        let data = cc.sys.localStorage.getItem("data" + AppConfig.AppID_custom);
        if (data) {
            console.log("登录成功+++++++++  有存档");

            User.initiUser_custom(JSON.parse(data));
        } else {
            console.log("登录成功+++++++++  无存档");

            User.initiUser_custom(null);
        }
        this.setDownloadOver_custom();
        // }
        // else {
        //     //登录公司服务器
        //     this.login_custom();
        // }

    }

    /**
     * 分包等相关资源全部加载完成了
     */
    private onLoadResComplate_custom() {
        // cc.sys.localStorage.clear()

        
        var self = this;
        this.setStartLoadingPerNum_custom(this.loadHttpNetworkTotal_custom);
        //预加载用到的场景
        GameMgr.getInstance_custom().preloadScene_custom();
        AppPlatform.loginPlatform_custom(function (code) {

          	// GameReport.EnterReport(ENTERTYPE.TIAOZHUAN, '平台登录code')
            CommonDefine.loginCode = code
            self.go_Login_custom(code)
            
        }, () => {
            self.Login_fail_custom();

        }, () => {
            // console.log("pc登录,数据存本地");
            //存本地
            let data = cc.sys.localStorage.getItem("data" + AppConfig.AppID_custom);
            if (data) {
                console.log("分包等相关资源全部加载完成了+++++++++  有存档");

                User.initiUser_custom(JSON.parse(data));
            } else {
                console.log("分包等相关资源全部加载完成了+++++++++  无存档");

                User.initiUser_custom(null);
            }
            
            self.setDownloadOver_custom();
        });
        
        GameReport.setLoadingTime((new Date()).getTime());
        GameReport.setStayTime((new Date()).getTime());

        //GameReport.init();
    }



    //初始游戏
    public initGame_custom() {

        if (AppPlatform.is_WECHAT_GAME_custom()) {
            console.log("小游戏设置转发按钮");
            window["wx"].showShareMenu({
                withShareTicket: true,
                menus:['shareAppMessage','shareTimeline'],
                success: () => {

                },
                fail: () => {

                },
                complete: () => {

                }
            });
            window["wx"].onShareAppMessage(function () {
                return {
                    title: "失败不是终点,而是逆袭的起点,勇往直前,无所畏惧",
                    imageUrlId: '34MEvHptTqaWXBeERMZOCQ==',
                    imageUrl: 'https://mmocgame.qpic.cn/wechatgame/gUGyibricTBrq4SibbbFwNLZ4dX5G4uAcCOkRHgW3KvEzyywMib2uVfqConCdibpFJ4ZS/0'
                }
            });

            // window["wx"].onShow(function () {
            //     console.log('微信 显示在前台');
            //     AppPlatform.isBackGameWX = true;
            // });


            //初始化放到后面
            let self = this;
            AppPlatform.loginPlatform_custom(function (code) {
                //初始 ry sdk
                console.log('登陆成功,进行初始化');
                GameMgr.getInstance_custom().onLoadToWorldScene_custom();
                
            }, null)
        } else {
            GameMgr.getInstance_custom().onLoadToWorldScene_custom();
        }

        // this.reportLaunchOptions_custom();

        AppPlatform.initGame_custom();
    }


    wdyjrjsdkInit(){
        ZYSDK.ZYSDK.initSdk()
        console.log('sdk init success')
    }
    
    checkDoubleTexture(){
        //web包需要注释掉
        cc.game.once(cc.game.EVENT_ENGINE_INITED, ()=>{
            let oldHandleLoadedTexture = cc.Texture2D.prototype.handleLoadedTexture;
            let optimizedHandleLoadedTexture = function (premultiplied) {
                oldHandleLoadedTexture.call(this,premultiplied);
                this._image.src="";
            };
            //for cocos creator 1.4
            //this. htmlElementObj.src=";
            cc.Texture2D.prototype.handleLoadedTexture = optimizedHandleLoadedTexture;
        })
       
    }
}