import { RES } from "../module/RES";
import { layers } from "../module/views/layers";
import { sendTbNet, TbNetName } from "./TaoBaoNet";
import { PropType } from "./something/enum/PropType";
import { showPanel } from "../module/ctrls";
import { FailedPanel } from "./panels/FailedPanel";
import { SuccessPrizePanel } from "./panels/SuccessPrizePanel";
import { SuccessNoPrizePanel } from "./panels/SuccessNoPrizePanel";
import Tween = FYGE.Tween;
import Ease = FYGE.Ease;

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

    public static openTask() {
        sendTbNet(TbNetName.openTask);
    }

    public static addSteps = 5;
    public static maxLevel = 99;
    public static musicOn = true;

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

    public static isMember: boolean;

    /**
     * 全局数据，重要数据
     */
    public static globalData: {
        avatar: string,
        nickName: string,
        activityId: string,
        openId: string,
        inviteId: string,
        oldInviteId: string,
        isFollow: boolean,
        isFirstLogin: boolean,  // 当日是否第一次登录
        loginAddPower: number,  // 赠送体力值
        isNewUser: boolean, // 是否新用户
    }

    public static gameData: {
        prizeLevels: number[],
        rule: string,
        currentLevel: any,
        topLevelVisitSuccess: boolean,
        isDrawTopLevelPrize: boolean,
        power: number,
        tools: {
            steps: number,
            booms: number,
            hammers: number,
        },
        records: {
            score: number,
            level: number,
            isVisitSuccess: boolean,
            stars: number,
            createTime: number,
            updateTime: number,
        },
        levelPrize: {
            level50: string,
            level99: string,
        }
        tasks: any,
    };// 活动基本信息

    static actEnd = false;

    /**
     * 进入地图页面刷新
     */
    public static getGameInfo() {
        return new Promise((r) => {
            sendTbNet(TbNetName.getActivityBaseInfoById, {}, (s, res) => {
                if (s) {
                    this.gameData = res.data;
                    sendTbNet(TbNetName.updateActivityInfo, { data: JSON.parse(JSON.stringify(res.data)) });
                    Tools.gameData.prizeLevels = [];
                    for (let k in Tools.gameData.levelPrize) {
                        Tools.gameData.prizeLevels.push(+k.split('level')[1]);
                    }
                    Tools.gameData.prizeLevels.sort((a, b) => a - b);

                    // @ts-ignore
                    if (my && my.getServerTime) {
                        // @ts-ignore
                        my.getServerTime({
                            success: (t) => {
                                Tools.actEnd = (+res.data.endTime <= +t.time);
                            },
                            failed: () => {
                                Tools.actEnd = (+res.data.endTime <= Date.now());
                            }
                        });
                    } else {
                        Tools.actEnd = (+res.data.endTime <= Date.now());
                    }

                }
                r(s);
            })
        })
    }

    /**
     * 消耗道具
     */
    public static consumerTools(type: PropType): Promise<boolean> {
        return new Promise((resolve, reject) => {
            sendTbNet(TbNetName.consumerTools, { type }, async (s, res) => {
                if (s) {
                    await Tools.updateTools();
                    resolve(true);
                } else {
                    resolve(false);
                }
            })
        })
    }

    /**
     * 更新道具
     */
    public static updateTools() {
        return new Promise((resolve, reject) => {
            sendTbNet(TbNetName.getToolsInfo, {}, (s, res) => {
                if (s) {
                    //修改道具数量
                    this.gameData.tools = res.data.tools;
                    resolve(true);
                } else {
                    resolve(false);
                }
            });
        });
    }

    /**
     * 更新体力
     */
    public static updatePower() {
        return new Promise((resolve, reject) => {
            sendTbNet(TbNetName.getRemainTimes, {}, (s, res) => {
                if (s) {
                    //修改体力数量
                    this.gameData.power = res.data.power;
                    resolve(true);
                } else {
                    resolve(false);
                }
            });
        });
    }

    public static gameOver(data) {
       if (!data.isVisitSuccess) {   // 闯关失败
           showPanel(FailedPanel, data);
       } else if (data.level == Tools.maxLevel) { // 99肯定是抽奖机会
           showPanel(SuccessNoPrizePanel, data);
       } else if (data.prize && data.prize.type != 5) {  // 闯关成功，奖励关卡
           showPanel(SuccessPrizePanel, data);
       } else {    // 闯关成功，不是奖励关卡
           showPanel(SuccessNoPrizePanel, data);
       }
    }

    /**
     * 询问权限用
     */
    public static async checkPermission() {
        //@ts-ignore
        var tbMy = my
        if (!tbMy) return;
        //@ts-ignore
        const { cloud } = getApp();
        //测试地址//到时云存储传一个小json，，改路径
        var url = "cloud://B4F0300E5148F478B506DEDC26EA4C6C//butterfly0.svga";
        //获取临时地址
        var urls = await cloud.file.getTempFileURL({ fileId: [url] })
        url = urls[0].url.replace('-internal', '');
        tbMy.downloadFile({
            url: url,
            success(res) {
                var i = res.apFilePath;
                tbMy.getFileSystemManager().readFile({
                    filePath: i,
                    // encoding: "utf8",
                    success: function (r) {

                    },
                    fail: function (res) {

                    }
                })
            },
            fail(res) {

            },
        });
    }

    public static getSprite(imageName: string, x: number = 0, y: number = 0) {
        var sprite = new FYGE.Sprite(RES.getRes(imageName));
        sprite.x = x;
        sprite.y = y
        return sprite
    }

    /**
     *
     * @param txt
     * @param size
     * @param color
     * @param textWidth
     * @param align
     * @param x
     * @param y
     */
    public static getText(
        txt: string,
        size: number,
        color: string = "#000000",
        align: FYGE.TEXT_ALIGN = FYGE.TEXT_ALIGN.LEFT,
        textWidth: number = 0,
        x: number = 0,
        y: number = 0
    ): FYGE.TextField {
        var text = new FYGE.TextField();
        text.fillColor = color;
        text.size = size;
        text.textWidth = textWidth;
        text.textAlign = align;
        text.x = x;
        text.y = y;
        text.text = txt;
        return text
    }

    /**
     * 左上角原点
     * @param width
     * @param height
     * @param color
     * @param alpha
     * @param radius
     * @param x
     * @param y
     */
    public static getRect(
        width: number,
        height: number,
        color: number = 0xff0000,
        alpha: number = 1,
        radius: number = 0,
        x: number = 0,
        y: number = 0,
    ): FYGE.Graphics {
        var g = new FYGE.Graphics();
        g.beginFill(color);
        g.alpha = alpha;
        if (!radius) {
            g.drawRect(0, 0, width, height)
        } else {
            g.drawRoundedRect(0, 0, width, height, radius)
        }
        g.endFill();
        g.position.set(x, y);
        return g
    }

    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;
        if (!textWidth) return;
        //修改位置
        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
     */
    public static btnDelay(target, delay = 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 } {
        const arr = {};
        for (let i = 0; i <= 9; i++) arr[i] = RES.getRes(name + i + ".png")
        return arr
    }
}
