import { GDispatcher } from "../engine/2d/events";
import { showToast } from "../module/ctrls";

//接口枚举，包括需要调用淘宝的api，用是否含有兑吧区分，或者单独区分
export enum TbNetName {

    /**
     * 查询积分
     * activityId
     */
    getCredits = "getCredits",
    /**
     * 开始接口
     * activityId,nickName
     */
    startGame = "startGame",
    /**
     * 提交分数接口
     * activityId,grade,score,type(0:解锁 1:提交),	playId
     */
    submit = "submit",
    /**
     * 查询道具数量
     * actitvityId
     */
    getTools = "getTools",
    /**
     * 获取任务列表
     * activityId
     */
    getTaskList = "getTaskList",
    /**
     * 领取道具
     * activityId，toolType
     */
    getToolsByType = "getToolsByType",
    /**
     * 消耗道具
     * activityId,type,playId
     */
    useTools = "useTools",

    /**
     * 单纯接收来自小程序的信息，事件自行绑定
     */
    returnGame = "returnGame",


    //前端自己调用小程序的方法

    /**
     * 获取参数
     */
    getAppData = "mine.getAppData",
    /**
     * 小程序内跳到其他页面
     * url
     */
    navigateToOutside = "mine.navigateToOutside",
    /**
     * 跳转到小程序的其他页面
     * url
     */
    navigateTo = "mine.navigateTo",
    /**
     * 返回上一页或多页
     * delta，页面数，不传默认1
     */
    navigateBack = "mine.navigateBack",
    /**
     * 显示分享面板
     * openId
     */
    invite = "mine.showSharePanel",
    /**
     * 单纯接收来自小程序的信息，事件自行绑定
     */
    // returnGame = "mine.returnGame",
}
//返回数据类型，到时再调整
interface dataIn {
    netName: TbNetName
    data: any
}
//记录数据
const data = {};

//淘宝小程序全局
const my = window["my"];

if (!window["develop"]) {
    //接收数据
    my.onMessage = function (e: dataIn) {
        //记录数据
        console.log("返回数据", e.netName, e.data)
        data[e.netName] = e.data;
        //触发事件，会考虑单独发过来的事件
        GDispatcher.dispatchEvent(e.netName, e.data)
    }
}

/**
 * 发送接口
 * @param netName 
 * @param parameter 
 * @param callback 
 */
export function sendTbNet(netName: TbNetName, parameter: any, callback: Function, hideMsg: boolean = false) {
    //本地开发，直接取数据
    if (window["develop"]) {
        // var url = "../../mock/miniTb/" + netName + ".json"
        // fetchAsync(url)
        //     .then((data) => {
        //         //记录数据
        //         data[name] = data;
        //         //回调
        //         callback(data.success, data);
        //     },()=>{})
        //直接用变量，方便注释
        setTimeout(() => {
            var returnData = mockData[netName];
            //记录数据
            data[netName] = returnData;
            if (returnData) {
                // if (!hideMsg && !returnData.success) showToast(codeMsg[returnData.code] || "网络异常")
                if (!hideMsg && !returnData.success) showToast(returnData.message || "网络异常")
                callback(returnData.success, returnData);
            } else {
                if (!hideMsg) showToast("网络异常")
                callback(false)
            }

        }, 500)
        return
    }
    console.log("发送数据", netName, parameter)
    //向小程序发信息
    my.postMessage({
        netName: netName,
        parameter: parameter
    });
    let timeId: any;
    //事件回调
    let fun = function (d) {
        // if (!hideMsg && !d.success) showToast(codeMsg[d.code] || "网络异常")
        if (!hideMsg && !d.success) showToast(d.message || "网络异常")
        GDispatcher.removeEvent(netName, fun);
        callback(d.success, d);
        clearTimeout(timeId);
    }
    //加事件
    GDispatcher.addEvent(netName, fun, null);
    //设置超时，意味着无返回数据
    timeId = setTimeout(() => {
        if (!hideMsg) showToast("网络超时")
        fun({ success: false })
    }, 5000)
}

/**
 * 获取数据
 * @param netName 
 */
export function getTbData(netName: TbNetName): { code?: string, success: boolean, data?: any } {
    return data[netName] || null;
}
//webview里调用无效，用postMessage去调
// export const navigateToOutside = (url) => {
//     my.call("navigateToOutside", {
//         url
//     }, (res) => {
//         // my.alert({ content: "success - " + JSON.stringify(res)})
//     });
// }

async function fetchAsync(url: string) {
    // await response of fetch call
    let response = await fetch(url);
    // only proceed once promise is resolved
    let data = await response.json();
    // only proceed once second promise is resolved
    return data;
}


// const { cloud } = window["getApp"]();
// const { function: fc } = cloud;
// fc.invoke("duiba.sign.doJoin", { signActivityId: 1 })
//     .then(res => {
//         console.log(res);
//     })

//模拟数据
const mockData = {
    //获取数据
    "mine.getAppData": {
        "success": true,
        "data": {
            "activityId": "111",
            "nickName": "开发环境",
            "avatar": "//yun.duiba.com.cn/developer/img/activityTool/slotMachine/virtual.png",
            "joinNeedsCredits": 20,
            "openSound": true,
            "gameObj": {
                "maxScore": 600,
                "bombCount": 1,
                "exchangeCount": 2,
                "netCount": 3,
                "unlockGrade": 128,
                "id": "asdqweqwe"
            },
        }
    },
    //登录
    "getCredits": {
        "code": 0,
        "data": {
            "credits": 20,
        },
        "success": true,
        "message": "ok"
    },
    //开始游戏
    "startGame": {
        "code": 0,
        "data": {
            "maxScore": 2048,
            "bombCount": 3,
            "exchangeCount": 0,
            "netCount": 0,
            "unlockGrade": 256,
            "id": "asdasd456"
        },
        "success": true,
        "message": "ok"
    },
    //提交分数
    "submit": {
        "success": true,
        "data": {
            "creditsTimesToday": 2,
            "credits": 300,
            "score": 24567,
            "grade": 1024,
            "playDuration": 4567
        }
    },
    //获取道具数量
    "getTools": {
        "code": 0,
        "data": {
            "bombCount": 2,
            "exchangeCount": 1,
            "netCount": 0
        },
        "success": true,
        "message": "ok"
    },
    //获取任务列表
    "getTaskList": {
        "success": true,
        "data": {
            "list": [
                {
                    "taskName": "doFollowShop",
                    "isComplete": true,
                    "taskDrawStatus": 0
                },
                {
                    "taskName": "doInvite",
                    "isComplete": false,
                    "taskDrawStatus": 0
                },
                {
                    "taskName": "doCollect",
                    "isComplete": false,
                    "taskDrawStatus": 0
                },
                {
                    "taskName": "doOrder",
                    "isComplete": false,
                    "taskDrawStatus": 0
                }
            ]
        }
    },
    //领取道具
    "getToolsByType": {
        "success": true,
        "data": {
            "inviteSuccessCount": 2
        }
    },
    //消耗道具
    "useTools": {
        "success": true,
    }
}

/**
 * 错误码列表，字段不设枚举了
 */
export const codeMsg = {
    "210001": "服务器异常",
    "210002": "用户不存在",
    "210003": "邀请已达上限",
    "210004": "无法邀请自己",
    "210006": "该活动ID无效",
    "210009": "该活动暂未开始",
    "210010": "该分享ID不存在",
    "210012": "该用户暂未获奖",
    "210013": "领取失败",
    "210015": "该活动已删除",
    "210016": "该活动已经结束",
    "210017": "该奖品已达领取上线",
    "210018": "请先分享好友",
    "210019": "暂有奖品未领取",
    "210020": "暂有奖品未完成",
    "210021": "请先玩一局游戏",
    "210022": "请先选择奖品",
    "210023": "领取失败，库存不足",
    "210024": "请先成为会员",
    "210025": "奖品已经过期",
    "210026": "不能重复助力",
    "210028": "请至我的奖品页重新领取",//重新领取
}