import { _decorator, Component, Node, SpriteFrame, sys } from 'cc';
import { config } from './config';
import { settingData } from './data';
import { http } from './http';
import { userDataManager } from './manager/userDataManager';
import { SdkUtil } from './sdkUtil';
import { uiManager } from './manager/uiManager';
import { restart_view } from './ui/restart_view';
import { tools } from './tools';
import { gameSocket } from './socket/gameSocket';
import { exchange_car_view } from './ui/exchange_car_view/exchange_car_view';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
    public static settingData:settingData = null

    // 延时请求数据
    public static requestDelay(cb,timeout:number=330) {
        setTimeout(()=>{
            cb && cb()
        },timeout)
    }

    // 开启webscoket
    public static openWebScoket() {
        gameSocket.Instance.connect(config.websocket_domain)
    }
    
    // 检查玩游戏
    public static checkPlayGame(parent_node:Node,play_cb) {
        let call_back = (()=>{
            play_cb()
        })
        if(userDataManager.getUserIsFreeAds()) {
            call_back()
            return
        }
        if(userDataManager.isTodayCanFreePlayGame()) {
            userDataManager.addTodayPlayGameNumber()
            call_back()
            return
        }

        uiManager.Instance().showUi(config.UI.ui_restart_view, parent_node, (node:Node)=>{
            node.getComponent(restart_view).initView((v:restart_view)=>{
                GameManager.showVideoAd(config.ADS_TYPE.GAME_RESTART, ()=>{
                    v.closeSelf()
                    call_back()
                })
            },(v:restart_view)=>{
                if(userDataManager.isTodayCanShare()==false) {
                    v.closeSelf()
                    call_back()
                    return
                }
                SdkUtil.shareGame('',tools.sys_config.share_des,(r)=>{
                    if(r==true) {
                        userDataManager.addTodayShareNumber()
                        v.closeSelf()
                        call_back()
                    }
                })
            })
        })
    }

    // 展示兑换车视图
    public static showExchangeCarView(car_id:number,sp_icon:string,sp_count:number, cb) {
        let data = {'car_id':car_id,'sp_icon':sp_icon,'sp_count':sp_count}
        uiManager.Instance().showUi(config.UI.ui_exchange_car_view, null, (node:Node)=>{
            node.getComponent(exchange_car_view).initView(data,cb)
        })
    }

    // 游戏开始
    public static gameStart() {
        SdkUtil.ttStartScreenRecording()
    }

    // 游戏结束
    public static gameOver() {
        setTimeout(()=>{
            SdkUtil.ttStopScreenRecording()
        },1700)
    }

    // 设置
    public static getSettingData():settingData {
        if(GameManager.settingData!=null) {
            return GameManager.settingData
        }
        let str = sys.localStorage.getItem(config.LOCAL_STORAGE.SETTING_DATA)
        if(str==undefined||str==""||str==null){
            GameManager.settingData = new settingData
        } else {
            let data:settingData = JSON.parse(str)
            GameManager.settingData = data
        }
        return GameManager.settingData;
    }

    public static saveSettingData(data:settingData) {
        sys.localStorage.setItem(config.LOCAL_STORAGE.SETTING_DATA, JSON.stringify(data));
    }

    // 震动
    public static vibrateShort() {
        if(GameManager.getSettingData().isOpenZhendong) {
            SdkUtil.vibrateShort()
        }
    }

    // 游戏结束结算页分享
    public static gameOverResultsShare() {
        if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            SdkUtil.shareGameVideo()
        } else if(sys.platform == sys.Platform.WECHAT_GAME) {
            SdkUtil.shareGame('',tools.sys_config.share_des)
        }
    }

    //请求广播
    public static requestGuangbo(cb=null) {
        http.post(config.API.msg, null, (err,d)=>{
            if(!err){
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    // console.log("system_msg", nd.content)
                    if(cb!=null){
                        cb(nd.content)
                    }
                }   
            }
        }, 'GET')
    }

    //请求用户车列表
    public static requestUserCarList(cb=null) {
        http.post(config.API.user_car_list,null,(err,d)=>{
            if(!err){
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    // console.log("user_car_list", nd.content)
                    if(cb!=null){
                        cb(nd.content)
                    }
                }   
            }
        },'GET')
    }

    // 请求用户注册/设置地区 stype 1:注册 2:重新设置
    public static requestUserSetRegion(region_id:number,stype:number,cb, show_loading:boolean=false) {
        if(show_loading) {uiManager.Instance().showLoading()}
        let opt = {'region_id':region_id, 'stype':stype}
        http.post(config.API.user_set_region, opt, (err,d)=>{
            if(show_loading) {uiManager.Instance().hideLoading()}
            let nd = JSON.parse(d)
            if(nd.code === config.status.SUCCESS){
                if(cb!=null){
                    cb(nd.content)
                }
            }  
        })
    }
    
    // 请求我的排行 stype 0:全国 1:省 2:市
    public static requestMineRank(stype:number, cb) {
        let opt = {'stype': stype}
        http.post(config.API.user_ranking, opt, (err,d)=>{
            if(!err){
                let data = JSON.parse(d)
                if(data.code===config.status.SUCCESS){
                    if(cb!=null) {
                        cb(data.content)
                    }
                }
            } else{
                console.log("user rank Data err",err)
            }
        })
    }

    // 请求排行列表
    public static requestRankList(region_id:number, cb, show_loading:boolean=false) {
        if(show_loading) {uiManager.Instance().showLoading()}
        http.post(config.API.rankings(region_id),null, (err,d)=>{
            if(show_loading) {uiManager.Instance().hideLoading()}
            if(!err){
                let data = JSON.parse(d)
                if(data.code===config.status.SUCCESS){
                    // console.log('data=',data.content)
                    cb && cb(data.content)
                }
            } else{
                console.log("rankList err",err)
            }
        },'GET')
    }

    // 背包列表
    public static requestBagList(stype_id:number, cb, show_loading:boolean=false) {
        if(show_loading) {uiManager.Instance().showLoading()}
        let opt = {'stype_id':stype_id}
        http.post(config.API.bag_list, opt, (err,d)=>{
            if(show_loading) {uiManager.Instance().hideLoading()}
            if(!err){
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    // console.log("bag_list", nd.content)
                    cb && cb(nd.content)
                }
            }
        })
    }

    // 兑换车辆  
    public static requestExchangeCar(car_id:number, cb, show_loading:boolean=false) {
        if(show_loading) {uiManager.Instance().showLoading()}
        let opt = {'car_id':car_id}
        http.post(config.API.exchange_car, opt, (err,d)=>{
            if(show_loading) {uiManager.Instance().hideLoading()}
            if(!err){
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    // console.log("兑换车辆", nd.content)
                    cb && cb()
                }
            }
        })
    }

    // 设置用户已读小红点
    public static requestUserSetReadRedDot(stype:number, cb) {
        let opt = {'stype': stype}
        http.post(config.API.user_up_red_dot, opt, (err,d)=>{
            if(!err){
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    // console.log("设置小红点", nd.content)
                    cb && cb()
                }
            }
        })
    }

    // 请求tt侧边栏用户奖励
    public static requestTTSidebarUserReward(status=config.USER_TT_SIDEBAR_REWARD.GET, success_cb, fail_cb=null) {
        if(sys.platform != sys.Platform.BYTEDANCE_MINI_GAME) {
            success_cb(null)
            return
        }
        if(status != config.USER_TT_SIDEBAR_REWARD.GET) {
            uiManager.Instance().showLoading()
        }
        http.post(config.API.unlock_number_status,{'stype':status}, (err,data)=>{
            if(status!= config.USER_TT_SIDEBAR_REWARD.GET) {
                uiManager.Instance().hideLoading()
            }
            if(!err) {
                let _data = JSON.parse(data)
                if(_data.code==config.status.SUCCESS) {
                    if(success_cb) {
                        success_cb(_data.content)
                    }
                } else {
                    if(fail_cb) {
                        fail_cb()
                    }
                }
            } else {
                if(fail_cb) {
                    fail_cb()
                }
            }
        })
    }

    // 请求同步数据
    public static requestSyncNumber(opt,success_cb=null,fail_cb=null) {
        http.post(config.API.sync_free_number, opt, (err,data)=>{
            if(!err) {
                let _data = JSON.parse(data)
                if(_data.code==config.status.SUCCESS) {
                    if(success_cb) {
                        success_cb(_data.content)
                    }
                } else {
                    if(fail_cb) {
                        fail_cb(_data.code)
                    }
                }
            } else {
                if(fail_cb) {
                    fail_cb(err)
                }
            }
        })
    }

    // 显示视频广告
    public static showVideoAd(ads_type=config.ADS_TYPE.UNKNOWN, success_cb, err_cb=null) {
        let ad_id = SdkUtil.getAdId(ads_type)
        SdkUtil.showVideoAd(ad_id,(res)=>{
            if(res.isEnded) {
                success_cb(res)
            } else {
                err_cb(res)
            }
        })
    }

}


