/*
 * @Author: YeeChan
 * @Date: 2020-12-17 20:07:37
 * @Description: 信息展示 清除存档
 */

import AppConfig from "../Config/AppConfig";
import AppSwitchConfig from "../Config/AppSwitchConfig";
import { ryw_Event } from "../Event/EventEnum";
import EventMgr from "../Event/EventMgr";
import HttpUnit from "../NetWork/HttpUnit";
import AppPlatform from "../Util/AppPlatform";
import { DateUtils } from "../Util/DateUtils";
import Utilit from "../Util/Utilit";
import WudianMgr from "./WudianMgr";

export default class DebugInfoMgr {
    //debug 根节点
    private static debugNode_custom: cc.Node = null;
    //展示页面
    private static debugPanel_custom: cc.Node = null;

    private static scrollview_custom: cc.ScrollView = null;
    private static content_custom: cc.Node = null;

    //debug 消息集合 
    private static debugInfoList_custom: Array<string> = new Array();
    private static debugFrameInfoList_custom: Array<string> = new Array();
    private static debugLabelList_custom: Array<cc.Label> = new Array();
    private static debugUmengInfoList_custom: { [key: string]: number } = {};

    private static showInfoNode_custom: cc.Node = null;
    private static showInfoLabel_custom: cc.Label = null;

    //是否启动了debug模式
    private static isOpenDebug_custom: boolean = false;
    //是否正常点击
    private static isOpenStartClick_custom: boolean = false;
    //次数
    private static touchClickSum_custom: number = 0;
    //间隔时间
    private static clickTime_custom: number = 0;

    //ip屏蔽接口是否调用成功
    private static isNetIpBlockState_custom: boolean = false;

    /**
     * 启动debug
     */
    public static setDebug_custom() {

        if (AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().debuginfo_custom == 1) {
            this.isOpenDebug_custom = true;

            //监听ip屏蔽
            EventMgr.onEvent_custom(ryw_Event.ryw_App_OnUpdateIpBlockState_custom, () => {
                this.isNetIpBlockState_custom = true;
                if (this.debugPanel_custom.active) {
                    this.updateFrameInfo_custom();
                    this.updateItem_custom();
                }
            }, this);

            //平台登录的状态
            EventMgr.onEvent_custom(ryw_Event.ryw_PlatformLoginState_custom, (tab) => {
                let state_custom = tab.state
                let info_custom = tab.info
                this.addDebugInfo_custom(info_custom);
            }, this);
            //登录的状态
            EventMgr.onEvent_custom(ryw_Event.ryw_NetLoginState_custom, (tab) => {
                let state_custom = tab.state
                let info_custom = tab.info
                this.addDebugInfo_custom(info_custom);
            }, this);
            //获取用户数据
            EventMgr.onEvent_custom(ryw_Event.ryw_NetUserDataState_custom, (tab) => {
                let state_custom = tab.state
                let info_custom = tab.info
                this.addDebugInfo_custom(info_custom);
            }, this);
            //友盟打点
            EventMgr.onEvent_custom(ryw_Event.ryw_Umeng_custom, (tab) => {
                let event = tab.event
                if (this.debugUmengInfoList_custom[event]) {
                    this.debugUmengInfoList_custom[event] = this.debugUmengInfoList_custom[event] + 1;
                } else {
                    this.debugUmengInfoList_custom[event] = 1;
                }
                this.updateItem_custom();
            }, this);

            let sizeView = cc.view.getVisibleSize();

            let size = cc.view.getFrameSize();
            // console.log(size)
            // console.log(sizeView)
            console.log("启动了debug展示")

            //根节点
            this.debugNode_custom = new cc.Node();
            cc.game.addPersistRootNode(this.debugNode_custom);
            this.debugNode_custom.width = sizeView.width;
            this.debugNode_custom.height = sizeView.height;
            this.debugNode_custom.anchorX = 0;
            this.debugNode_custom.anchorY = 0;
            this.debugNode_custom.x = 0;
            this.debugNode_custom.y = 0;

            let butSize_custom = cc.size(180, 120);
            let butNode_custom = this.createNode_custom(this.debugNode_custom, cc.v2(0, sizeView.height - butSize_custom.height), cc.Color.WHITE);
            butNode_custom.setContentSize(butSize_custom);
            // butNode.addComponent(cc.Sprite).spriteFrame = this.createSpriteFrame_custom(butSize);
            // this.createLabel_custom(butNode, cc.v2(0, 0), "打开", cc.Color.RED);

            // butNode_custom.on(cc.Node.EventType.TOUCH_START, (touch: cc.Event, event) => { }, this)
            // butNode_custom["_touchListener"].onTouchBegan = (touch, event) => {
            //     let pos_custom = butNode_custom.convertToNodeSpaceAR(touch.getLocation());
            //     if (pos_custom.x < 0 || pos_custom.y < 0 || pos_custom.x > butSize_custom.width || pos_custom.y > butSize_custom.height) {//超出按钮范围
            //         return;
            //     }
            //     if (!this.isOpenStartClick_custom) {
            //         let time_custom = DateUtils.getNowTime_custom();
            //         //console.log(this.touchClickSum_custom)
            //         if (time_custom - this.clickTime_custom <= 500) {
            //             this.touchClickSum_custom = this.touchClickSum_custom + 1;
            //             if (this.touchClickSum_custom > 10) {
            //                 this.isOpenStartClick_custom = true;
            //             }
            //         } else {
            //             this.touchClickSum_custom = 0;
            //         }
            //         this.clickTime_custom = time_custom
            //     } else {
            //         if (!this.debugPanel_custom.active) {
            //             this.updateFrameInfo_custom();
            //             this.updateItem_custom();
            //             this.debugPanel_custom.active = true;
            //         }
            //     }
            //     return true;
            // };
            // butNode_custom["_touchListener"].setSwallowTouches(false);


            let showSize_custom = cc.size(sizeView.width * 0.98, sizeView.height * 0.7);
            //背景色
            this.debugPanel_custom = this.createNode_custom(this.debugNode_custom, cc.v2((sizeView.width - showSize_custom.width) / 2, (sizeView.height - showSize_custom.height) / 2), cc.Color.WHITE, showSize_custom);
            this.debugPanel_custom.active = false;
            this.debugPanel_custom.addComponent(cc.Button);

            //滚动容器
            let snode_custom = this.createNode_custom(this.debugPanel_custom, cc.v2(0, 0), cc.Color.GRAY, showSize_custom);
            this.scrollview_custom = snode_custom.addComponent(cc.ScrollView);
            this.scrollview_custom.horizontal = false;
            this.scrollview_custom.vertical = true;
            this.scrollview_custom.inertia = true;
            this.scrollview_custom.brake = 0.75;
            //遮罩
            let viewMask_custom = this.createNode_custom(snode_custom, cc.v2(0, 0), cc.Color.WHITE);
            viewMask_custom.setContentSize(showSize_custom);
            viewMask_custom.addComponent(cc.Mask)
            viewMask_custom.anchorY = 1;
            viewMask_custom.y = showSize_custom.height;
            //content
            this.content_custom = this.createNode_custom(viewMask_custom, cc.v2(0, 0), cc.Color.GRAY, showSize_custom);
            this.content_custom.anchorY = 1;
            this.scrollview_custom.content = this.content_custom;

            //关闭按钮
            this.createButton_custom(this.debugPanel_custom, cc.v2(0, showSize_custom.height), "关闭", cc.color(255, 180, 180), cc.Color.RED, cc.size(100, 70), () => {
                this.debugPanel_custom.active = false;
            });
            //清除缓存按钮
            this.createButton_custom(this.debugPanel_custom, cc.v2(showSize_custom.width - 170, showSize_custom.height), "清理缓存", cc.color(255, 180, 180), cc.Color.RED, cc.size(170, 70), () => {
                HttpUnit.saveGameData_custom("{}", (res) => {
                    if (res.code == 1) { console.log("存档成功") }
                    else { console.log("存档失败") }
                }, (res) => { console.log("存档失败") })
                this.showToast_custom("清理用户数据,并提交!请重启")
            });

            //提示框
            let cshowToastSize_custom = cc.size(showSize_custom.width * 0.9, 100);
            this.showInfoNode_custom = this.createNode_custom(this.debugNode_custom, cc.v2((sizeView.width) / 2, (sizeView.height) / 2), cc.color(175, 100, 170), cshowToastSize_custom);
            this.showInfoNode_custom.anchorX = 0.5;
            this.showInfoNode_custom.anchorY = 0.5;
            this.showInfoLabel_custom = this.createLabel_custom(this.showInfoNode_custom, cc.v2(0, 0), "", cc.Color.RED).getComponent(cc.Label);
            this.showInfoLabel_custom.node.anchorX = 0.5;
            this.showInfoLabel_custom.node.anchorY = 0.5;
            this.showInfoNode_custom.active = false;


        }
    }

    /**
     * 增加一条需要展示的debug信息
     * @param info 需要展示的信息
     */
    public static addDebugInfo_custom(info: string) {
        if (this.isOpenDebug_custom) {
            this.debugInfoList_custom.push(info);
        }
    }


    /**
     * 添加框架的信息
     */
    private static updateFrameInfo_custom() {
        this.debugFrameInfoList_custom = [];
        let addVersion_custom = () => {
            let cur_custom = Utilit.checkVersions_custom();
            let versionSwitch_custom = "[]"
            if (AppPlatform.is_TT_GAME_custom())//抖音,字节跳动
            {
                versionSwitch_custom = "ttcfg:<" + AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().ttcfg_custom.ttversions_custom + ">";
            }
            else if (AppPlatform.is_OPPO_GAME_custom())//oppo小游戏
            {
                versionSwitch_custom = "oppocfg:<" + AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().oppocfg_custom.oppoversions_custom + ">";
            }
            else if (AppPlatform.is_QQ_PLAY_custom())//qq小游戏
            {
                versionSwitch_custom = "qqcfg:<" + AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().qqcfg_custom.qqversions_custom + ">";
            }
            else if (AppPlatform.is_WECHAT_GAME_custom()) //VIVO 小游戏
            {
                versionSwitch_custom = "vivocfg:<" + AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().vivocfg_custom.vivoversions_custom + ">";
            }
            else//微信小游戏
            {
                versionSwitch_custom = "version:<" + AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().version_custom + ">";
            }
            let str_custom = "游戏名字:[" + AppConfig.GameName_custom + "],gameid:[" + AppConfig.gameid_custom + "]\n";
            str_custom = str_custom + AppConfig.ResServer_custom + "\n"
            str_custom = str_custom + "本地版本号:[" + AppConfig.Versions_custom + "]\n远端版本号:[" + versionSwitch_custom + "]\n版本比较结果:" + (cur_custom ? "true" : "false");
            this.debugFrameInfoList_custom.push(str_custom);
        }

        let cwudian_custom = () => {
            let mainSwitch_custom = AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().wudian_custom == 1;
            let isOpenTime_custom = AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().wudianTimeAvaliable_custom;
            let ipnotBlock_custom = WudianMgr.ryw_GetIpBlocked_custom();
            let launchScene_custom_custom = AppPlatform.getLaunchOptionsSync_custom().scene;

            if (AppPlatform.is_TT_GAME_custom()) {
                mainSwitch_custom = true;
                isOpenTime_custom = true;
            }

            let noEnterBySearch_custom: boolean = true;
            var wudianSceneList_custom = AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().wudianSceneList_custom;
            for (let index = 0; index < wudianSceneList_custom.length; index++) {
                var wudianSceneValue_custom = wudianSceneList_custom[index];
                if (launchScene_custom_custom == wudianSceneValue_custom) {
                    noEnterBySearch_custom = false;
                }
            }
            let cwd_custom = mainSwitch_custom && noEnterBySearch_custom && ipnotBlock_custom && isOpenTime_custom;

            let str = "ip屏蔽接口调用:" + (this.isNetIpBlockState_custom ? "成功" : "失败") + "\n"
                + "误点最终结果:[" + (cwd_custom ? "有" : "没有") + "]\n"
                + "当前场景值:[" + launchScene_custom_custom + "]\n"
                + "ip没有屏蔽:[" + (ipnotBlock_custom ? "是" : "不是") + "]\n"
                + "场景没有屏蔽:[" + (noEnterBySearch_custom ? "是" : "不是") + "]\n"
                + "误点开关:[" + (mainSwitch_custom ? "打开" : "关闭") + "],\n"
                + "时间开关:[" + (isOpenTime_custom ? "打开" : "关闭") + "]"

            this.debugFrameInfoList_custom.push(str);
        }

        addVersion_custom();
        cwudian_custom();
    }



    /**
     * 设置提示语
     * @param info 
     */
    private static showToast_custom(info: string) {
        cc.Tween.stopAllByTarget(this.showInfoNode_custom);
        this.showInfoLabel_custom.string = info;
        this.showInfoNode_custom.active = true;
        this.showInfoNode_custom.opacity = 0;
        this.showInfoNode_custom.scale = 0.75;
        cc.tween(this.showInfoNode_custom)
            .to(0.25, { opacity: 255, scale: 1 }, { easing: "backOut" })
            .delay(2)
            .call(() => {
                this.showInfoNode_custom.active = false;
            })
            .start();
    }

    /**
     * 更新item
     */
    private static updateItem_custom() {
        let infoList = [];
        //先加框架的
        for (let index = 0; index < this.debugFrameInfoList_custom.length; index++) {
            const element_custom = this.debugFrameInfoList_custom[index];
            infoList.push(element_custom);
        }

        let umengInfo = "友盟统计开始:\n"
        for (const key in this.debugUmengInfoList_custom) {
            if (Object.prototype.hasOwnProperty.call(this.debugUmengInfoList_custom, key)) {
                const element = this.debugUmengInfoList_custom[key];
                umengInfo = "事件:" + umengInfo + key + ",次数: " + element + "\n"
            }
        }
        umengInfo = umengInfo + "友盟统计结束!"
        infoList.push(umengInfo);

        //再加自定义的
        for (let index = 0; index < this.debugInfoList_custom.length; index++) {
            const element_custom = this.debugInfoList_custom[index];
            infoList.push(element_custom);
        }


        let sizeInfo = infoList.length;
        let sizeLabel = this.debugLabelList_custom.length;
        let num = sizeInfo - sizeLabel;
        //增加新的
        if (num > 0) {
            for (let index = 0; index < num; index++) {
                let label = this.createLabel_custom(this.content_custom, cc.v2(0, 0), "", cc.Color.BLACK).getComponent(cc.Label);
                label.node.width = this.content_custom.width;
                label.overflow = cc.Label.Overflow.RESIZE_HEIGHT;
                label.horizontalAlign = cc.Label.HorizontalAlign.LEFT;
                label.node.anchorY = 1;
                this.debugLabelList_custom.push(label);
            }
        }
        //关闭
        for (let index = 0; index < this.debugLabelList_custom.length; index++) {
            const element_custom = this.debugLabelList_custom[index];
            element_custom.node.active = false;
        }
        //更新
        let maxHeight_custom: number = 0;
        let temp_custom: boolean = false;
        for (let index = 0; index < infoList.length; index++) {
            const element_custom = infoList[index];
            let label = this.debugLabelList_custom[index];
            label.string = element_custom;
            label.node.y = -maxHeight_custom;
            label.node.active = true;
            label["_forceUpdateRenderData"]();
            maxHeight_custom = maxHeight_custom + label.node.height + 5
            if (temp_custom) {
                temp_custom = false;
                label.node.color = cc.color(0, 0, 0);
            } else {
                temp_custom = true;
                label.node.color = cc.color(122, 22, 22);
            }
        }
        this.content_custom.height = maxHeight_custom;
    }

    /**
     * 创建一个 label
     * @param info 
     * @param color 
     */
    private static createLabel_custom(parent: cc.Node, pos: cc.Vec2, info: string, color: cc.Color) {
        let node = this.createNode_custom(parent, pos, color)
        let label = node.addComponent(cc.Label);
        label.fontSize = 30;
        label.lineHeight = 32;
        label.string = info;
        return node;
    }

    /**
     * 创建一个 节点
     * @param color 
     * @param size 
     */
    private static createNode_custom(parent: cc.Node, pos: cc.Vec2, color: cc.Color, size?: cc.Size) {
        let node = new cc.Node();
        if (size) {
            node.setContentSize(size);
            node.addComponent(cc.Sprite).spriteFrame = this.createSpriteFrame_custom(size);
        }
        node.color = color;
        parent.addChild(node);
        node.x = pos.x;
        node.y = pos.y;
        node.anchorX = 0;
        node.anchorY = 0;
        return node;
    }


    /**
     * 创建一个button
     * @param info 
     * @param color 
     * @param labelColor 
     * @param size 
     * @param listener 
     */
    private static createButton_custom(parent: cc.Node, pos: cc.Vec2, info: string, color: cc.Color, labelColor: cc.Color, size: cc.Size, listener?: Function) {
        let node = this.createNode_custom(parent, pos, color, size);
        node.addComponent(cc.Button);
        node.color = color;
        if (listener) {
            node.on("click", listener, this);
        }
        this.createLabel_custom(parent, pos, info, labelColor);
        return node;
    }


    /**
     * 创建纯色的spriteframe
     * @param size 
     */
    private static createSpriteFrame_custom(size: cc.Size): cc.SpriteFrame {
        let texture = new cc.Texture2D();
        let spriteFrame = new cc.SpriteFrame();
        let count = size.width * size.height * 4;
        let imgData = new Uint8Array(count);
        for (let j = 0; j < count; j += 4) {
            imgData[j] = 255;
            imgData[j + 1] = 255;
            imgData[j + 2] = 255;
            imgData[j + 3] = 255;
        }
        texture.initWithData(imgData, cc.Texture2D.PixelFormat.RGBA8888, size.width, size.height);
        spriteFrame.setTexture(texture);
        spriteFrame.setRect(cc.rect(0, 0, size.width, size.height));
        return spriteFrame;
    }
}