
/** 
 * @description 互推数据类
 * @author kaka
 */

import { Data } from "../../../mk/data/Data";
import JsbSystem from "../../../mk/system/JsbSystem";

export class MoreGameData extends Data {
    /**推荐游戏信息 */
    private _moreGameList = null

    set moreGameList(value) {
        this._moreGameList = value;
        this.init_moreGameList = true;
    }

    get moreGameList() {
        return this._moreGameList;
    }

    /** 刷新标志位 */
    init_moreGameList = false;

    /** 下载中列表 */
    private static downLoadTaskMap: Map<string, DownloadTaskClazz> = new Map<string, any>()

    /** 测试数据 */
    private testData = {
        "normal": [
            {
                "nebulaAppId": "wxd2e694c55d457ded",
                "title": "爱上切水果",
                "introduction": "切水果、切水果、切、切、切！",
                "downloadUrl": "https://xcx-box.oss-cn-hangzhou.aliyuncs.com/hotgame/haocheyijia/hutui/CutFruit.apk",
                "packageName": "com.aries.asqsg.mz",
                "icon": "https://oss.duiweize.com/fission/5vp7CPeadkABlgIe.png",
                "banner": "https://oss.duiweize.com/fission/EXrqiYF6BkC1ZsZf.png",
            },
            {
                "nebulaAppId": "wx74fee17e08a29836",
                "title": "炮火掠夺",
                "introduction": "大炮一响，黄金万两！",
                "downloadUrl": "https://xcx-box.oss-cn-hangzhou.aliyuncs.com/hotgame/haocheyijia/hutui/FirePillage.apk",
                "packageName": "com.aries.firepillage.mz",
                "icon": "https://oss.duiweize.com/fission/BZ9ZUicxgCbWb33D.png",
                "banner": "https://oss.duiweize.com/fission/vGPWCE2tuGZwLSJH.png",
            }
        ],
        "banner": [
            {
                "nebulaAppId": "wx07895e2f78748daf",
                "title": "豪车大富翁",
                "introduction": "豪车、金钱、美女，你要的这里都有！",
                "downloadUrl": "https://xcx-box.oss-cn-hangzhou.aliyuncs.com/hotgame/haocheyijia/hutui/HundredsOfMillions.apk",
                "packageName": "org.cocos2d.hundredsofmillion.mk.mz",
                "icon": "https://oss.duiweize.com/fission/fviQN9OpUmmqpTjU.png",
                "banner": "https://oss.duiweize.com/fission/eWUxr3OySHIohqtB.png",
                "banner2": "https://oss.duiweize.com/fission/eWUxr3OySHIohqtB.png",
            },
            {
                "nebulaAppId": "wx22b3f0f8005f0e51",
                "title": "航海传奇",
                "introduction": " 战舰、短裙、红包，你想要的都有！",
                "downloadUrl": "https://xcx-box.oss-cn-hangzhou.aliyuncs.com/hotgame/haocheyijia/hutui/LegendOfNavigation.apk",
                "packageName": "com.aries.hhcq.mz",
                "icon": "https://oss.duiweize.com/fission/ZqDsgbj9PT94RcG0.png",
                "banner": "https://oss.duiweize.com/fission/goS05API8LtqB0QH.png",
                "banner2": "https://oss.duiweize.com/fission/goS05API8LtqB0QH.png",
            }
        ]
    }

    /** 初始化数据 */
    init() {
        this.sendRecommendList();
    }

    async sendRecommendList() {
        if (this._moreGameList == null || this._moreGameList == undefined) {
            let data = {};
            let response = await mk.http.sendData('/fission/recommendList', data);

            if (response.errcode != 0) {
                return;
            }
            this.moreGameList = response.data;
        }
        else {
            this.init_moreGameList = true;
        }

        // //test
        // this.moreGameList = this.testData;
    }

    /**上报 */
    sendAppDownloadLog(downLoadAppId: string) {
        let data = { "downloadAppId": downLoadAppId };
        let response = mk.http.sendRequest('/fission/appDownloadLog', 'POST', JSON.stringify(data));
    }

    /**
     * 下载
     * @param data 
     * @returns 下载任务
     */
    createNewTask(data): DownloadTaskClazz {
        let name = data.nebulaAppId + ".apk"
        let url = data.downloadUrl
        let packageName = data.packageName

        if (packageName != "") {
            let isExist = JsbSystem.ifCanStartGame(packageName, true)
            if (isExist) {
                // JsbSystem.sendEvent('hutuiEventLaunch_' + data.nebulaAppId, "互推启动" + data.title, 'hutuiEventLaunch')
                //判断在原生环境下存在就直接启动
                return null
            }
        }

        if (JsbSystem.isFileExist(name)) {
            JsbSystem.installApk(name);
            return null;
        }

        if (MoreGameData.downLoadTaskMap[data.nebulaAppId]) {
            mk.tip.pop('正在下载中...');
            return null
        }

        mk.tip.pop('开始下载...');

        let downLoadTask = new DownloadTaskClazz(0, 0, data.nebulaAppId, null)
        let curTask = JsbSystem.downFile2Local(url, data.nebulaAppId + ".apk", (locaPath) => {
            // LogUtil.logV("sendAppDownloadLog", "success")
            downLoadTask.progress = -2
            this.sendAppDownloadLog(data.nebulaAppId)
            setTimeout(() => {
                JsbSystem.installApk(name)
            }, 1)
        }, () => {
            downLoadTask.progress = -1
            MoreGameData.downLoadTaskMap[data.nebulaAppId] = null
            mk.tip.pop('下载失败，请稍后再试');
        }, (task: jsb.DownloaderTask, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) => {
            downLoadTask.progress = bytesReceived
            downLoadTask.totalBytesReceives = totalBytesReceived
        })
        downLoadTask.downloadTask = curTask
        MoreGameData.downLoadTaskMap[data.nebulaAppId] = downLoadTask
        // AdM.onSendEvent('hutuiEventDown_' + data.nebulaAppId, "互推下载" + data.title, 'hutuiEventDown')
        return downLoadTask
    }

    getTaskInfo(appId): DownloadTaskClazz {
        return MoreGameData.downLoadTaskMap[appId]
    }

    // /** 随机获取推荐位游戏  展示在更多游戏界面中部 可能是空*/
    // getRandomBanner() {
    //     if (!this.moreGameList.banner || this.moreGameList.banner.length <= 0) {
    //         return null
    //     }

    //     let index = Utils.rnd(0, this.moreGameList.banner.length - 1)
    //     let data = this.moreGameList.banner[index]
    //     return data
    // }

    /** 随机获取信息流位游戏  展示在十倍领取*/
    getRandomSteam() {
        if (!this.moreGameList) {
            return null
        }
        let index = mk.math.random(0, this.moreGameList.stream.length - 1)
        let data = this.moreGameList.stream[index]
        return data
    }

    /** 随机获取底部位游戏  展示在更多游戏界面列表小图*/
    getRandomNormal() {
        if (!this.moreGameList) {
            return null
        }
        let index = mk.math.random(0, this.moreGameList.normal.length - 1)
        let data = this.moreGameList.normal[index]
        return data
    }

    /** 弹出互推红包弹窗 */
    popMoreGamePopNode() {
        if (Math.random() <= gData.gameData.configs.globalCfg.popMoreGame) {
            mk.ui.openPanel('module/moreGame/moreGamePopNode');
        }
    }
}

/** 下载任务 */
class DownloadTaskClazz {
    private _progress = 0
    private _totalBytesReceives = 0
    private _nebulaAppId = ""
    private _downloadTask = null
    constructor(progress, totalBytesReceives, nebulaAppId, downloadTask) {
        this._progress = progress
        this._totalBytesReceives = totalBytesReceives
        this._nebulaAppId = nebulaAppId
        this._downloadTask = downloadTask
    }

    public get progress(): number {
        return this._progress
    }
    public set progress(progress: number) {
        this._progress = progress
    }

    public get totalBytesReceives(): number {
        return this._totalBytesReceives
    }
    public set totalBytesReceives(totalBytesReceives: number) {
        this._totalBytesReceives = totalBytesReceives
    }

    public get downloadTask(): any {
        return this._downloadTask
    }
    public set downloadTask(downloadTask: any) {
        this._downloadTask = downloadTask
    }
}
