import { _decorator, Button, Component, game, Label, log, Node, ProgressBar, sys } from 'cc';
import { http } from '../http/http';
import { config } from '../config';
import { gameManager } from '../gameManager';
import { ClientEvent } from '../framework/clientEvent';
import { StorageManager } from '../framework/storageManager';
const { ccclass, property } = _decorator;
@ccclass('launch_view')
export class launch_view extends Component {
    @property(Node) progress;
    @property(Node) lab_progress;
    private isStop = false;
    private PageList = [null,1,1,1];
    start() {
        this.progress.getComponent(ProgressBar).progress = 0;
        // this.Interval_id=setInterval(this.setupLoading.bind(this),200);
        gameManager.havNoAllAd = config.hav_no_allAd
        this.schedule(this.setupLoading,0.05)
    }

    setupLoading(){
        let self = this;
        let progress_number = Math.floor(this.progress.getComponent(ProgressBar).progress *100);
        if(self.isStop){
            return;
        }
       
        if(progress_number==10){
            self.isStop = true;
            http.get(config.static_url.category,(err,data)=>{
                if(!err){
                    self.isStop = false;
                    let _data = JSON.parse(data);
                    if(_data.code==config.MSG_CODE.SUCCESS){
                        gameManager.set_server_play_list_data( _data.content);
                    }
                }
            })
        }

   
        if(progress_number==20){
            this.isStop = true;
            let login_call_back = ()=>{
                http.post(config.api_url.login,formData,(err,data)=>{
                    if(!err){
                        let _data = JSON.parse(data);
                        // console.log("config.api_url.login",data)
                        if(_data.code==config.MSG_CODE.SUCCESS){
                            gameManager.set_server_user_data(_data.content)
                            if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
                                gameManager.request_sign_status(config.SIGN_STATUS_TYPE.GET,(sign_status_data)=> {
                                    gameManager.set_server_user_sign_status(sign_status_data)
                                    this.isStop = false;
                                }, (err)=> { })
                            } else {
                                this.isStop = false;
                            }
                        }
                        return
                    }
              
                })
            }
            let formData = null;
            let user_id =gameManager.getUserId();
            if(sys.platform==sys.Platform.BYTEDANCE_MINI_GAME){
                if(user_id==""||user_id==null||user_id==undefined){
                    console.log("本地没有数据")
                    tt.login({
                        force: true,
                        success(res) {
                            let code = res.code;
                            let anonymousCode = res.anonymousCode;
                            console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
                            // console.log("code==",code);
                            // console.log("anonymousCode==",anonymousCode);
        
                            
                            http.post(config.api_url.get_open_id,{"code":code,"anonymous_code":anonymousCode},(err,data)=>{
                                if(!err){
                                    let _data = JSON.parse(data);
                                    if(_data.code==config.MSG_CODE.SUCCESS){
                                        gameManager.setUserId( _data.content.openid)
                                        // StorageManager.instance.setUserId(_data.content.openid);
                                        formData = {"openid":gameManager.getUserId(),"avatarUrl": ""}
                                        login_call_back();
                                        // console.log("_data.content.data.openid",_data.content.openid)
                                    }
                                    return
                                }
                          
                            })
    
                        },
                        fail(res) {
                          console.log(`login 调用失败`);
                        },
                      });
                }else{
                    console.log("本地有数据")
                    formData = {"openid":gameManager.getUserId(),"avatarUrl": ""}
                    login_call_back();
                }
            }else{
                formData = new FormData();
                formData.append("openid", "123");
                formData.append("avatarUrl", "");
                login_call_back();
            }
    
        }

        if(progress_number===30){
            if(gameManager.userInfo.unlock_levels==""){
                gameManager.init_unlock_levels();
                this.isStop = true;
                let form_Data = null;
                if(sys.platform==sys.Platform.BYTEDANCE_MINI_GAME){
                    form_Data = {"coin": gameManager.userInfo.coin+"","unlock_levels": gameManager.get_unlock_levels()}
                }else{
                    form_Data = new FormData();
                    form_Data.append("coin", gameManager.userInfo.coin+"");
                    form_Data.append("unlock_levels", gameManager.get_unlock_levels());
                }
                http.post(config.api_url.sync_data,form_Data,(_err,c_data)=>{
                    console.log("c__data _err:",_err)
                    if(!_err){
                        let c__data = JSON.parse(c_data);
                        console.log("c__data",c__data)
                        if(c__data.code==config.MSG_CODE.SUCCESS){
                            this.isStop = false;
                        }
                    }
                 
                })
            }else{
                gameManager.update_unlock_levels()
            }
        }

        if(progress_number==40){
            // this.isStop = true;
            // let all = 0;
            // const element = gameManager.get_play_list_item_by_categoryid(config.PLAY_TYPE.MEI_NV_ZHAO_XI_JIE);
            // let item = gameManager.get_cur_level_by_categoryid(element.id);
            // let key = `${element.id}_${item.level}`;
            // let str = StorageManager.instance.getGlobalData(key);
            // if(str===""||str===undefined||str===null){
            //     all++;
            //     gameManager.loadLevelImg(element.id,item.level,()=>{
            //         this.isStop = false;
            //     })
            // }
            // if(all===0){
            //     this.isStop = false;
            // }
            // gameManager.loadLevelImg(element.id,item.level,()=>{
            //     this.isStop = false;
            // })
        }

        if(progress_number==50){
            this.isStop = true;
            let all = 0;
            const element = gameManager.get_play_list_item_by_categoryid(config.PLAY_TYPE.HAN_ZI_ZHAO_BU_TONG);
            let item = gameManager.get_cur_level_by_categoryid(element.id);
            // let key = `${element.id}_${item.level}`;
            // let str = StorageManager.instance.getGlobalData(key);
            // if(str===""||str===undefined||str===null){
            //     all++;
            //     gameManager.loadLevelImg(element.id,item.level,()=>{
            //         this.isStop = false;
            //     })
            // }
            // if(all===0){
            //     this.isStop = false;
            // }
            gameManager.loadLevelImg(element.id,item.level,()=>{
                this.isStop = false;
            })
        }

        if(progress_number==60){
            this.isStop = true;
            let all = 0;
            const element = gameManager.get_play_list_item_by_categoryid(config.PLAY_TYPE.YI_QI_ZHAO_CHA);
            let item = gameManager.get_cur_level_by_categoryid(element.id);
            // let key = `${element.id}_${item.level}`;
            // let str = StorageManager.instance.getGlobalData(key);
            // if(str===""||str===undefined||str===null){
            //     all++;
            //     gameManager.loadLevelImg(element.id,item.level,()=>{
            //         this.isStop = false;
            //     })
            // }
            // if(all===0){
            //     this.isStop = false;
            // }
            gameManager.loadLevelImg(element.id,item.level,()=>{
                this.isStop = false;
            })
        }


        if(progress_number==70){
            this.isStop = true;
            let call = ()=>{
                this.isStop = false;
            }
            gameManager.loadSysMusic(call);

        }

        if(progress_number==75){
            this.isStop = true;
            let call = ()=>{
                this.isStop = false;
            }
            gameManager.loadPlayMusicByCategoryId(config.PLAY_TYPE.YI_QI_ZHAO_CHA,call);
        }

        if(progress_number==80){
            self.isStop = true;
            http.get(config.static_url.user_test,(err,data)=>{
                if(!err){
                    self.isStop = false;
                    let _data = JSON.parse(data);
                    if(_data.code==config.MSG_CODE.SUCCESS){
                        gameManager.init_test_user_list( _data.content);
                    }
                }
            })
        }

        if(progress_number==85){
            this.isStop = true;
            let call = ()=>{
                this.isStop = false; 
            }
            gameManager.loadPlayMusicByCategoryId(config.PLAY_TYPE.MEI_NV_ZHAO_XI_JIE,call);

        }
        if(progress_number==85){
            this.isStop = true;
            let call = ()=>{
                this.isStop = false; 
            }
            gameManager.loadPlayMusicByCategoryId(config.PLAY_TYPE.HAN_ZI_ZHAO_BU_TONG,call);

        }
 
        if(progress_number==90){
            this.isStop = true;
            let call = ()=>{
                this.isStop = false; 
            }
            gameManager.loadPlayMusicByCategoryId(config.PLAY_TYPE.YI_QI_ZHAO_CHA,call);

        }
        if(progress_number>=100){
            this.finishLoading();
            this.unschedule(this.setupLoading)
            progress_number = 100;
            gameManager.isFinishLoad = true;
        }

        this.lab_progress.getComponent(Label).string = `加载中... ${progress_number} %`;
        this.progress.getComponent(ProgressBar).progress += 0.025;
     
    }

    finishLoading(){
        console.log("finish");
        ClientEvent.dispatchEvent(config.EVENT_MSG.ON_BACK_HOME_VIEW);
        ClientEvent.dispatchEvent(config.EVENT_MSG.ON_CHANGE_COIN_NUMBER);
        ClientEvent.dispatchEvent(config.EVENT_MSG.ON_USER_LOGIN_SUCCESS);
        this.node.removeFromParent();
    }
}


