import { Node, UIOpacity, _decorator, tween } from 'cc';
import BaseAppInit from '../../../extensions/app/assets/base/BaseAppInit';
import { httpRequest, LOGIN_TOKEN } from '../../res-native/network/HttpRequest';
import { Tools } from '../../res-native/tools/Tools';
const { ccclass, property } = _decorator;

@ccclass('AppInit')
export class AppInit extends BaseAppInit {
    @property(Node)
    private logo: Node;

    /**
    * 获得用户资源总量，这里返回几，就需要用户自行调用几次nextInit
    */
    protected getUserAssetNum(): number {
        return 1;
    }

    protected onLoad() {
        //this.initToken();

        // if (LOGIN_TOKEN.access_token == "" || LOGIN_TOKEN.access_token == undefined) {
        //     return
        // }

        let str = window.location.search.slice(1)
        const pairs = str.split('&');
        const params: { [key: string]: string } = {};
        pairs.forEach(pair => {
            const [key, value] = pair.split('=');
            params[decodeURIComponent(key)] = decodeURIComponent(value || '');
        });

        Tools.httpReq("mini-games/auth/login", {token:params.token}, (res:any) => {
            LOGIN_TOKEN.setToken(res.token, res.token, "https://www.tab66aud.com", "en")
            //USERDATA.setUserData(res);
            this.nextInit();
        })

        // Tools.httpReq("login", {token:"devtestaud", password:"password123"}, (res:any) => {
        //     //USERDATA.setUserData(res);
        //     LOGIN_TOKEN.setToken(res.token, res.token, "https://www.tab66aud.com", "en")
        //     httpRequest.get("/api/me/profile" , (res:any) => {
        //         let token = res.sso_url.mini_game_angpau
        //         token = token.match(/token=([^&]*)/)?.[1];
        //         Tools.httpReq("mini-games/auth/login", {token:token}, (res:any) => {
        //             //USERDATA.setUserData(res);
        //             this.nextInit();
        //         })
        //     })
        // })

        // // 执行初始化操作
        // const opacity = this.logo.getComponent(UIOpacity);
        // opacity.opacity = 0;

        // tween(opacity)
        //     .to(0.5, { opacity: 255 })
        //     .delay(1)
        //     .to(0.5, { opacity: 0 })
        //     .call(() => {
        //         Tools.httpReq("login", {username:"devtestaud", password:"password123"}, (res:any) => {
        //             //USERDATA.setUserData(res);
        //             LOGIN_TOKEN.setToken(res.token, res.token, "https://www.tab66aud.com", "en")
        //             httpRequest.get("/api/me/profile" , (res:any) => {
        //                 let token = res.sso_url.mini_game_angpau
        //                 token = token.match(/token=([^&]*)/)?.[1];
        //                 Tools.httpReq("mini-games/auth/login", {token:token}, (res:any) => {
        //                     //USERDATA.setUserData(res);
        //                     this.nextInit();
        //                 })
        //             })
        //         })

        //         //this.nextInit();
        //     })
        //     .start();
    }

    /** 根据参数初始化TOKEN */
    initToken(){
        let str = window.location.search.slice(1)
        const pairs = str.split('&');
        const params: { [key: string]: string } = {};
        pairs.forEach(pair => {
            const [key, value] = pair.split('=');
            params[decodeURIComponent(key)] = decodeURIComponent(value || '');
        });

        const at = Tools.parseJWT(params.access_token)
        const actualKey = 'xyxfz83d'.substring(0, 8); // 取前8个字符
        // 解密appkey
        const appkey = Tools.desEcbDecrypt(at.extend.channel, actualKey);
        
        // 如果解密失败，尝试原始值
        if (!appkey) {
            console.log('Failed to decrypt token, using original value');
        }

        LOGIN_TOKEN.setToken(params.access_token, params.refresh_token, at.extend.app_id, appkey)
    }

    // BaseAppInit中使用start方法作为初始化入口，如果重写start方法，请注意调用父类方法
    // protected start() {  }

    protected onFinish() {
        // 执行完成操作
        this.node.destroy();
    }
}