import { showToast } from "../module/ctrls";
import { RES } from "../module/RES";
import { GTool } from "../module/tools/GTool";
import { layers } from "../module/views/layers";
import { sendTbNet, TbNetName } from "./TaoBaoNet";
import Tween = FYGE.Tween;
import Ease = FYGE.Ease;

export function goMyPrize() {
    sendTbNet(
        TbNetName.navigateTo,
        { url: '/pages/myprize/myprize' },
        null,
        true
    );
}

export function goTask() {
    sendTbNet(TbNetName.openTask);
}

export async function sleep(time: number): Promise<void> {
    return new Promise((resolve) => {
        Tween.get(FYGE)
            .wait(time)
            .call(resolve)
    });
}

type AppType = {
    musicStatus: boolean
}

export const myApp:AppType = getApp()

/**
 * 定制，记录一些全局量和通用方法
 */
export class Tools {

    public static PAGE;

    /**
     * 缓存key
     */
    public static cacheKey: string = "guideThreeSquirrels"

    public static isMember: boolean;

    /**
     * 全局数据，重要数据
     */
    public static globalData: {
        avatar: string,
        nickName: string,
        activityId: string,
        inviteId: string,
        old_inviteId: string,
        isFollow: boolean

        openId: string,
        newUser: boolean
        newUser1: boolean
        firstLoginToday: boolean
        shop: string,
        startId: string,
        completed: boolean,
        shopId: number | string
    }

    public static async getGlobalData() {
        const { data } = await sendTbNet(TbNetName.getAppData);
        Tools.globalData = data;
    }

    static indexMask = {}

    /**
     * activityBaseInfo
     * @member openId openId
     * @member rule 规则
     * @member startTime 开始时间
     * @member endTime 结束时间
     */
    public static activityBaseInfo: {
        rule: string,
        startTime: number,
        endTime: number,
        showPrizeImg: {     // 弹窗奖品图
            image_1: string,
            image_2: string,
            image_3: string,
        }
    } = {
        rule: "",
        startTime: 0,
        endTime: 0,
        showPrizeImg: {
            image_1: "",
            image_2: "",
            image_3: "",
        }
    }

    public static async getActivityBaseInfo() {
        const { success, data } = await sendTbNet(TbNetName.getActivityBaseInfoById);
        if (data) {
            Tools.activityBaseInfo = data;
        }
        return success;
    }

    public static gameInfo: {
        maxLevel: number,
        gameTimes: number,
        inviteTotalCount: number,
        invitePrize: {
            inviteCount: number,
            receiveStatus: number,  // 领取状态（1 待解锁  待领取 3已领取）
            type: string    // type： 档位（level1 邀请8人 level2 邀请16入 level3邀请28入 level4邀请40人）
        }[],
        inviteRemainTimes: {    // inviteRemainTimes：有值则弹助力反馈弹窗 {rewards: 0,remainNumber: 0},
            rewards: number,
            remainNumber: number
        },
        accessMaxLevelCount: number,
        hasAccessMaxLevel: boolean, // 是否通关
        cardTotalCount: number, // 第几位获得
        hasTakeTotalTimesPrize: boolean, // 是否领取618大奖
    } = {
        maxLevel: 1,
        gameTimes: 0,
        inviteTotalCount: 0,
        invitePrize: [{
            inviteCount: 0,
            receiveStatus: 0,
            type: "level1"
        }],
        inviteRemainTimes: null,
        accessMaxLevelCount: 0,
        hasAccessMaxLevel: false,
        cardTotalCount: 0,
        hasTakeTotalTimesPrize: false,
    }

    public static async getGameInfo() {
        const { success, data } = await sendTbNet(TbNetName.getGameInfo);
        if (data) {
            Tools.gameInfo = data;
        }
        return success;
    }


    public static async queryVip() {
        const { success, data } = await sendTbNet(TbNetName.getVipInfo);
        return success && data.isVip;
    }


    public static async getPrize(prize, callFun: Function = () => 0) {
        console.log(prize)
        const call = async () => {
            await sleep(500);
            callFun();
        }
        const { type, id } = prize;
        switch (type) {
            case 1: // 权益
                await sendTbNet(TbNetName.receiveEnamePrize, { id },
                    async (success, res) => {
                        if (!success || !res) {
                            showToast('奖品发放失败\n请前往我的奖品处进行处理');
                            await call();
                            return;
                        }
                        if (res.data && res.data.drawStatus == 3) {
                            showToast('奖品发放成功\n请前往我的奖品处查看');
                        } else {
                            showToast('奖品发放失败\n请前往我的奖品处进行处理');
                        }
                        await call();
                    }, true
                );
                break;
            case 3: // 实物
                await sendTbNet(TbNetName.getUserAddress, { prizeId: id },
                    async (success, res) => {
                        if (!success) {
                            // showToast('奖品发放失败\n请前往我的奖品处进行处理');
                            return;
                        }
                        showToast('奖品发放成功\n请前往我的奖品处查看');
                        await call();
                    }, true
                );
                break;

            case 2: // 积分
            case 5: // 谢谢参与
                await call();
                break;
        }
    }


    /**
     * 通过res里的名字生成一个sprite
     * @param imageName
     * @param x
     * @param y
     */
    public static getSprite(imageName: string, x: number = 0, y: number = 0): FYGE.Sprite {
        const sprite = new FYGE.Sprite(RES.getRes(imageName));
        sprite.x = x;
        sprite.y = y;
        return sprite
    }

    /**
     * 中心原点
     * @param radius
     * @param color
     * @param alpha
     * @param x
     * @param y
     */
    public static getCircle(
        radius: number = 10,
        color: number = 0xff0000,
        alpha: number = 1,
        x: number = 0,
        y: number = 0
    ): FYGE.Graphics {
        var g = new FYGE.Graphics();
        g.beginFill(color);
        g.alpha = alpha;
        g.drawCircle(0, 0, radius)
        g.endFill();
        g.position.set(x, y);
        return g
    }

    /**
     * 高度适配
     * 遮挡上面的情况
     * 顶部部ui要适配
     * @param maxDis 最大距离
     * @param minDis 最小距离
     * @param type 页面适配类型
     * @return y值
     */
    public static getAdjustHeight(maxDis: number, minDis: number, type: "top" | "mid" | "bot" = "bot"): number {
        //图层偏移量
        var offsetY: number = (() => {
            //顶部适配。layers会被置顶，返回0
            if (type == "top") return 0;
            //底部适配。layers会置底，返回两倍的
            if (type == "bot") return layers.stageOffsetY * 2;
            return layers.stageOffsetY;
        })()
        //小于1206时固定距离顶部高度
        if (layers.stageHeight <= 1206) return minDis + offsetY;
        //大于1206时取插值
        return (layers.stageHeight - 1206) / (1624 - 1206) * (maxDis - minDis) + minDis + offsetY;
    }

    /**
     * 修改皮肤上的文本对齐方式，原先默认是左的，多汗行的时候计算有误，待查
     * @param text
     * @param align
     * @param textWidth
     */
    public static changeTextAlign(text: FYGE.TextField, align: FYGE.TEXT_ALIGN, textWidth?: number) {
        if (align == FYGE.TEXT_ALIGN.LEFT) return;
        text.textAlign = align;
        //没有就原先的
        textWidth = textWidth || text.textWidth;
        //修改位置
        if (align == FYGE.TEXT_ALIGN.CENTER) text.x -= (textWidth - text.textWidth) / 2;
        if (align == FYGE.TEXT_ALIGN.RIGHT) text.x -= textWidth - text.textWidth
        text.textWidth = textWidth;
    }


    public static customToast(
        target: FYGE.DisplayObject,
        call: Function = () => 0,
        time: number = 2000,
        showTime: number = 300
    ) {
        Tween.get(target)
            .set({ alpha: 0, visible: true })
            .to({ alpha: 1 }, showTime, Ease.quadIn)
            .wait(time)
            .to({ alpha: 0 }, showTime, Ease.quadOut)
            .set({ alpha: 0, visible: false })
            .call(() => {
                call();
            });
    }

    /**
     * 延时防连点
     * @param target
     * @param {number} delay 默认2000毫秒
     */
    public static btnDelay(target: FYGE.Container, delay: number = 2000) {
        target.mouseEnable = false;
        target.mouseChildren = false;
        setTimeout(() => {
            target.mouseEnable = true;
            target.mouseChildren = true;
        }, delay);
    }

    /**
     * 根据名字获取0到9的贴图
     * 位图字每次都写太烦了
     * @param name
     */
    public static getNumTextures(name: string): { [key: number]: FYGE.Texture } {
        var arr = {}
        for (var i = 0; i <= 9; i++) arr[i] = RES.getRes(name + i + ".png")
        return arr
    }

    /**
     * 获得距离底部的百分比高度，还要减个自身的高度，自行处理
     * @param {number} percent  百分比
     * @returns {number}
     */
    static getAdjustBottomHeight(percent: number): number {
        return layers.stageHeight - layers.stageHeight * percent + layers.stageOffsetY;//stageOffsetY加不加取决于页面适配类型
    }

    /**
     * 获得距离顶部的百分比高度
     * @param {number} percent  百分比
     * @returns {number}
     */
    static getAdjustTopHeight(percent: number): number {
        return layers.stageHeight * percent + layers.stageOffsetY;//stageOffsetY加不加取决于页面适配类型
    }

}


/**
 * 从数组里随机取元素
 * @param arr
 * @param count
 */
export function getRandomArrayElements(arr, count) {
    if (arr.length <= count) return arr;

    let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
        index = (i + 1) * Math.random() >> 0;
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}


/**
 * 数字补0
 * @param num 数字
 * @param length 位数
 */
export function prefixInteger(num: number, length: number) {
    return (Array(length).join('0') + num).slice(-length);
}
