import Common5 from "../../Platform/th/Common5";
import CommonDefine from "../../Platform/th/CommonDefine";

import HttpUnit from "../NetWork/HttpUnit";
import {requestData} from "../NetWork/HttpUnit";
import User from "../User/User";
import AppPlatform from "../Util/AppPlatform";
import { DateUtils } from "../Util/DateUtils";

   /*
        打点数据类型
        广告:AD
        加载时长:LoadTime
        停留时长:StayTime
        切换后台:OnHide
        普通按钮合集:Btns
        离开当前界面:Out
        进入界面:Enter
    */
export enum  ENTERTYPE {
    XUANGUAN,
    TONGGUAN,
    TIAOZHUAN,
    CHONGWAN,
}
export enum  OUTTYPE {
    CHENGGONG,
    TIAOZHUAN,
    FANHUI,
    SHIBAI,
}
export const OPER_TYPE = {
    AD:"AD",
    LoadTime:"LoadTime",
    StayTime:"StayTime",
    OnHide:"OnHide",
    Out:"Out",
    Enter:"Enter",
    Btns:"Btns",
}
const { ccclass, property } = cc._decorator;
@ccclass
export default class GameReport{
    
    public static loadingTime = 0;
    public static loadingFinishTime = 0
    public static GamePlatform = "OTHER";
    public static GameVersion = "1.0.0";

    public static GameName = "WDZCRJNEW"; //手动配置

    public static UserUuid = null;
    public static SubGame = 'default';
    public static SubGameRemake = 'default';
    public static OperType:string = OPER_TYPE.AD;

    public static OperRemake:string|number = null;
        //OperRemake 
    /*
    操作备注OperType
	OperType==LoadTime 必填--秒 例如:30
	OperType==StayTime 必填--秒 例如:3000
	OperType==OUT 必填 例如:重玩离开
	OperType==ENTER 必填 例如:重玩进入
	OperType==onHide 选择填 例如:hide
	OperType==BTNS 选择填 例如:普通点击
	OperType==AD 选择填 例如:钓鱼
    */


    public static OperTypeResult:number = 1;

    public static onHideState = {
        gold:0, //金币
        strength:0,  //体力
        sendCardTimes:0, //发牌次数
        unlockLevel:0, //已经解锁关卡
        removeTimes:0, //消除次数
        default1:0, //默认字段1
        default2:0, //默认字段2
        default3:0 //默认字段3
    }
    public static OperateName = 'default';
    public static CustomClicks = '';

    //
    public static tmpUserid = "";
    public static PostTime = '';
    public static AllowGamePlatform = "OTHER";
    public static ReportConfig = null;
    public static ReportUrl = null;
    public static getReqData = null;
    public static postReqData = null;
    public static GameTable = "";
    
    public static isReport = false;
    public static isRequest = false;
    public static checkSendData(){
        if(!this.UserUuid){
            //重新获取useruuid
            if(AppPlatform.is_WECHAT_GAME_custom()){
                ZYSDK.ZYSDK.getUserId().then((uid)=>{
                    console.log('zyzy report getuserid 11============================')
                    let tmpUserid = uid;//ZYSDK.ZYSDK.getUserId()
                    //this.getTempUserId()
                    console.warn(tmpUserid, '获取微信userid++++======')
                    this.SetUserUuid(tmpUserid)
                })
           
                return false;
                // if(tmpUserid){
                //     return true
                // }else{
                //     return false
                // }
            }else{
                
                if(this.isRequest){
                    return
                }
                this.isRequest = true
                let successcall = (code)=>{
                    CommonDefine.loginCode = code;
                    this.getUserId()
                    this.isRequest = false
                }

                let failcall = ()=>{
                    this.isRequest = false
                }
                AppPlatform.loginPlatform_custom( successcall, failcall)
                console.log('没有useruuid重新获取useruuid')
                return false
            }

        }

        if(this.OperateName == 'default'){
            //重新获取useruuid
            console.log('OperateName需要设置')
            return false
        }

        return true
    }

    //游戏加载
    public static FirstInitGameTimeReport(time:number){
        GameReport.LoadTimeReport(time, '游戏登录')
    }



    //关卡加载



    public static ReportSend(OperType, OperRemake,OperTypeResult){
        return
        let isCheck = this.checkSendData()
        if(!isCheck){
            return
        }
        let content = {
            "GamePlatform": this.GamePlatform, //登录获取
            "GameVersion":this.GameVersion, //登录获取
            "GameName":this.GameName, //手动配置
            "UserUuid":this.UserUuid, //需要添加代码登录获取
            "SubGame":this.SubGame, //setSubGame
            "SubGameRemake":this.SubGameRemake,//setSubGameRemake
            "OperType":OperType,//
            "OperRemake":OperRemake, //当前操作的备注 例如:钓鱼
            "OperTypeResult":OperTypeResult, //0或者1
            "onHideState":this.onHideState, //如果有需要传参数请设置SetOnHideState
            "OperateName":this.OperateName, //请设置SetCurOperateName
            "TempUserID":this.tmpUserid,
            "CustomClicks":'',  
        }
        
        if(OperType == OPER_TYPE.Btns){
            content.CustomClicks =  this.CustomClicks
        }else{
            content.CustomClicks = ''
        }
        console.log('打点数据++ReportSend====',content.OperateName+content.OperType+content.OperRemake)
        // console.log('打点数据++ReportSend=json===',JSON.stringify(content))

        this.ReportContent(JSON.stringify(content))
        if(OperType == OPER_TYPE.Btns){
            this.CustomClicks = ''
        }
        
    }

    public static ADReport(OperRemake:string,OperateName?,OperTypeResult=1){
        if(OperateName){
          
            this.OperateName = OperateName;
        }



        this.ReportSend(OPER_TYPE.AD, OperRemake, OperTypeResult)
    }

    public static LoadTimeReport(OperRemake:number, OperateName?){
        if(OperateName){
          
            this.OperateName = OperateName;
        }
   

        let OperTypeResult = 1
        this.ReportSend(OPER_TYPE.LoadTime, OperRemake, OperTypeResult)
    }

    public static StayTimeReport(OperRemake:number, OperateName?){
        if(OperateName){
           
            this.OperateName = OperateName;
        }


        let OperTypeResult = 1
        this.ReportSend(OPER_TYPE.StayTime, OperRemake, OperTypeResult)


    }

    public static OUTReport(enterType:OUTTYPE, OperateName?){
        //OperRemake 离开备注
        let OperRemake = '返回离开'
        if(enterType == OUTTYPE.FANHUI){
            OperRemake = '返回离开'
        }else if(enterType == OUTTYPE.CHENGGONG){
            OperRemake = '成功离开'
        }else if(enterType == OUTTYPE.TIAOZHUAN){
            OperRemake = '跳转离开'
        }else if(enterType == OUTTYPE.SHIBAI){
            OperRemake = '失败离开'
        }


        if(OperateName){
   
            this.OperateName = OperateName;
        }
        this.checkSendBtnsReport()
 
 
        let OperTypeResult = 1
        this.ReportSend(OPER_TYPE.Out, OperRemake, OperTypeResult)

    }

    public static EnterReport(enterType:ENTERTYPE, OperateName?){
        //OperRemake进入备注
        let OperRemake = '选关'
        if(enterType == ENTERTYPE.TIAOZHUAN){
            OperRemake = '跳转'
        }else if(enterType == ENTERTYPE.XUANGUAN){
            OperRemake = '选关'
        }else if(enterType == ENTERTYPE.TONGGUAN){
            OperRemake = '通关'
        }else if(enterType == ENTERTYPE.CHONGWAN){
            OperRemake = '重玩'
        }

  
        if(OperateName){
            
            this.OperateName = OperateName;
        }
    
   
        let OperTypeResult = 1
        this.ReportSend(OPER_TYPE.Enter, OperRemake, OperTypeResult)

    }

    public static BtnsReport( CustomClicks:string, OperRemake ='普通按钮点击集合', OperateName?){
        this.CustomClicks =  this.CustomClicks+CustomClicks+','

        let arr1=this.CustomClicks.split(",");
  
        if(arr1.length>=13){
            if(OperateName){
                this.OperateName = OperateName;
            }
            let OperTypeResult = 1
    
            this.ReportSend(OPER_TYPE.Btns, OperRemake, OperTypeResult)
        }
    }

    public static checkSendBtnsReport(){
        let OperRemake ='普通按钮点击集合'
        if(this.CustomClicks.length==0 ){

        }else{
            let OperTypeResult = 1
            this.ReportSend(OPER_TYPE.Btns, OperRemake, OperTypeResult)
        }
    }


    public static OnHideReport(OperRemake, OperateName? , gold=0, strength=0, sendCardTimes=0, unlockLevel=0, removeTimes=0,default1=0, default2=0,default3=0){
        if(OperateName){
            
            this.OperateName = OperateName;
        }
 
        this.onHideState.gold = gold
        this.onHideState.strength = strength
        this.onHideState.sendCardTimes = sendCardTimes
        this.onHideState.unlockLevel = unlockLevel
        this.onHideState.removeTimes = removeTimes
        this.onHideState.default1 = default1
        this.onHideState.default2 = default2
        this.onHideState.default3 = default3


  
        let OperTypeResult = 1
        this.ReportSend(OPER_TYPE.OnHide, OperRemake, OperTypeResult)
    }

    public static OnHideReport2(OperRemake, onHideState, OperateName?){
        if(OperateName){
           
            this.OperateName = OperateName;
        }
        
 
        let OperTypeResult = 1
        this.ReportSend(OPER_TYPE.OnHide, OperRemake, OperTypeResult)
    }



    public static ReportContent(content,typeInput?){

        console.log('this.isReport+++++++++=====111',this.isReport)
        if (!this.isReport){
            return;
        }

        console.log('this.isReport+++++++++====222',this.isReport)

        if (null != this.postReqData){
            if (!(this.AllowGamePlatform.indexOf(this.GamePlatform) > -1)){
                return;
            }
       
            let headers = {};
            let type = "";
            let enable = "0";
            let find = false;
            
            type = this.OperateName;
            if (typeInput){
                type = typeInput;
            }
            if (this.ReportConfig.KeyList[0].Type[0] == "ALL"){
                enable = "1";
            }
            else {                
                if (type != ""){
                    for (let i = 0; i < this.ReportConfig.KeyList.length; i++){
                        if (this.ReportConfig.KeyList[i].Type.length>0){
                            for (let j = 0; j < this.ReportConfig.KeyList[i].Type.length; j++){
                                if (type == this.ReportConfig.KeyList[i].Type[j]){
                                    enable = "1";
                                    find = true;
                                    break;
                                }
                            }
                            if (find){
                                break;
                            }
                        }
                    }
                }
                else{
                    return;
                }
            }
            if (enable == "0"){
                return;
            }
            let data = {
                            "GameTable":this.GameTable,
                            "Content":content,
                            "PostTime":DateUtils.getNowTime_custom()
                        }
            // console.log(data);
            HttpUnit.sendHttpUrl_custom(this.postReqData,JSON.stringify(data),(res)=>{
                if (res){
                    console.log("success");
                }
                else{
                    console.log("false");
                }
            },(err)=>{
                console.log(err);
            },headers);       
        }
    }
    public static init(){
        return
        if (AppPlatform.is_TT_GAME_custom()){
            this.GamePlatform = "TT";            
            let tt =window["tt"];
            const envInfo = tt.getEnvInfoSync();
            this.GameVersion = envInfo.microapp.mpVersion;
            console.warn("GameVersion:", this.GameVersion);
        }
        else if (AppPlatform.is_WECHAT_GAME_custom()){
            this.GamePlatform = "WECHAT";
            let wx =window["wx"];
            const envInfo = wx.getAccountInfoSync();
            this.GameVersion = envInfo.miniProgram.version;
            console.warn("GameVersion:", this.GameVersion); 

            GameReport.GameName = 'WDZCRJNEW_WX'
        }
        else{
            this.GamePlatform = "OTHER";
        }
        // console.log("PlatForm:",this.GamePlatform);
        this.getReqData = new requestData();
        this.getReqData.meth_custom = "GET";
       
        this.getReqData.url_custom = "https://report1.ioe-times.com/api/getconfig?GameName="+this.GameName+"&GamePlatform="+this.GamePlatform;
        this.getReqData.onSuccess_custom = (res)=>{
            // console.log(res);
        }
        let headers = {};
        let time = "time=" + String(Date.now());
        // headers["Access-Control-Allow-Origin"] = "*";
        // headers["Content-Type"] = "application/jsonp";
        // headers["sign"] = AesTools.encrypt_custom(time); 
        HttpUnit.sendHttpUrl_custom(this.getReqData,"{}",(res)=>{
            if (res){

                console.log('打点基础配置请求完成')
                if(res.data && res.data!=''){
                    let tmpRes = JSON.parse(res.data);
                    this.ReportConfig = JSON.parse(tmpRes.GameConfig);
                    this.ReportUrl = tmpRes.GameReportUrl;
                    this.GameTable = tmpRes.GameTable;
                    let Gailv = this.ReportConfig.Gailv;
    
                    console.log('打点基础配置请求完成',Gailv)
    
                    if (Common5.getRandomNum(0,100) <= Gailv){
                        this.isReport = true;
                    }
                    this.AllowGamePlatform = tmpRes.GamePlatform;
      
                    this.initPostReq(this.ReportUrl);
                    this.initOtherPlatformUser();
                    GameReport.SetCurOperateName("游戏登录");
                    if(this.loadingFinishTime-this.loadingTime>0){
                        GameReport.LoadTimeReport((this.loadingFinishTime-this.loadingTime)/1000)
                    }
                }

             
                
            }
            else{
                console.log("false");
            }
        },(err)=>{
            console.log(err);
        },headers);   
        
        
        //获取userID
        // this.getUserId()
    }
    public static initPostReq(reqUrl){
        this.postReqData = new requestData();
        this.postReqData.meth_custom = "POST";
        this.postReqData.url_custom = reqUrl;
    }
   

    public static setLoadingTime(loadingTime){
        this.loadingTime = loadingTime
    }

    public static setLoadingFinishTime(FinishTime){
        this.loadingFinishTime = FinishTime
    }


    public static getLoadingTime(){
        return this.loadingTime
    }
    public static  getUserId(){
        return
        let onFail = ()=>{

        }

        let onSuccess = (response)=>{
            console.log(response, '获取userID+++=====')
            if(response.msg == 'OK'){
                this.SetUserUuid(response.openid)
                User.setUserId(response.openid)
                if (!this.isReport){
                    return;
                }
                GameReport.LoadTimeReport((this.loadingFinishTime-this.loadingTime)/1000)
            }        
        }
        if(!AppPlatform.is_TT_GAME_custom()){
          
            //
            if(AppPlatform.is_WECHAT_GAME_custom()){
                ZYSDK.ZYSDK.getUserId().then((uid)=>{
                    console.log('zyzy report getuserid 00============================')
                    let tmpUserid = uid //ZYSDK.ZYSDK.getUserId()
                    //this.getTempUserId()
                    console.warn(tmpUserid, '获取微信userid++++======')
                    this.SetUserUuid(tmpUserid)
                })
            }else{
                this.SetUserUuid("_000s3U9CckmoiK8inaKu2qohzNujHrbdpaS")
            }
          
        }else{ 
            if(AppPlatform.is_TT_GAME_custom()){
                let userid = User.getUserId()

                console.log(userid,'userid+++zyzy+++++++++++======')
                if(userid == ''){
    
                    console.log('+++登录++++++zyzy+++++++++++====11==')
    
                    if(CommonDefine.loginCode){
    
                        console.log('+++登录++++++zyzy+++++++++++====222==')
                        CommonDefine.getLoginInfo(CommonDefine.loginCode, onFail, onSuccess)
                    }
                }else{
                    console.log('已经有了zyzyuserid')
                  
                    this.SetUserUuid(userid)
                    if (!this.isReport){
                        return;
                    }
                    GameReport.LoadTimeReport((this.loadingFinishTime-this.loadingTime)/1000)
                }
            }
 
       
          
        }
    }


    public static SetCurOperateName(OperateName){
        this.OperateName = OperateName;
    }

    public static setSubGame(SubGame){
        this.SubGame = SubGame;
    }
    
    public static setSubGameRemake(SubGameRemake){
        this.SubGameRemake = SubGameRemake;
    }
    
    public static SetCurGame(OperateName){
        this.OperateName = OperateName;
    }

    public static SetUserUuid(UserUuid){
        this.UserUuid = UserUuid;
    }
    
    public static getGameVersion(){
        return this.GameVersion
    }

    public static initOtherPlatformUser(){
        let tmpUserid = this.getTempUserId()

        console.log(tmpUserid, 'tmpUserid+++====')
        //this.tmpUserid = tmpUserid.toString();
        this.tmpUserid = tmpUserid

    }



    public static SetOnHideState(onHideState){
        this.onHideState = onHideState;
    }
    
    
    public static getTempUserId(){
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    
    }




}