import { RES } from "../module/RES";
import { layers } from "../module/views/layers";
import Tween = FYGE.Tween;
import Ease = FYGE.Ease;
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";

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

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

    public static isMember: boolean;

    /**
     * 全局数据，重要数据
     */
    public static globalData: {
        "avatar": string,
        "nickName": string,
        "activityId": string,
        "openId": string,
        "inviteId": string,
        "isFollow": boolean,
        "isFirstLogin": boolean,
        "loginAddPower": boolean,
    }

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

    public static propInfo: {
        hammers: number,
        steps: number,
        booms: number,
        power: number,
    } = {
        hammers: 0,
        steps: 0,
        booms: 0,
        power: 0,
    }

    // public getPower() {
    //     sendTbNet(TbNetName.getPower, {},
    //         (success, res) => {


    //         });
    // }

    public static actEnd: boolean = false;
    public static actStart: boolean = true;

    public static baseInfo: {
        inviteFriends: any,
        rule: string,
        updateTime: number,
        title: string,
        toolsProbability: any,
        currentLevel: 1,
        records: {
            score: number,
            level: number,
            isVisitSuccess: boolean,
            stars: number,
        }[],

        levelPrize: {
            level50: string,
            level100: string,
            level120: string
        },
    };// 活动基本信息

    public static getBaseInfo() {
        // 游戏基本信息
        return new Promise((r) => {
            sendTbNet(TbNetName.getActivityBaseInfoById, {}, (s, res) => {
                if (s && res && res.data) {
                    const data = Tools.baseInfo = res.data;
                    if (res.data.tools) {
                        Tools.propInfo.booms = data.tools.booms || 0;
                        Tools.propInfo.steps = data.tools.steps || 0;
                        Tools.propInfo.hammers = data.tools.hammers || 0;
                    }
                    Tools.propInfo.power = data.power || 0;

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


                }
                r(s);
            })
        })
    }

    /**
     * 消耗道具
     */
    public static consumerTools(type: PropType): Promise<boolean> {
        return new Promise((resolve, reject) => {
            sendTbNet(TbNetName.consumerTools, {type}, (s, res) => {
                if (s) {
                    //修改道具数量
                    this.propInfo[type] -= 1;
                    sendTbNet(TbNetName.getToolsInfo, {},
                        (st, rt) => {
                            if (!st) {
                                resolve(true);
                                return;
                            }
                            this.propInfo.booms = Tools.propInfo.booms = +rt.data.tools.booms;
                            this.propInfo.steps = Tools.propInfo.steps = +rt.data.tools.steps;
                            this.propInfo.hammers = Tools.propInfo.hammers = +rt.data.tools.hammers;
                            resolve(true);
                        }
                    );
                } else {
                    // reject()
                    resolve(false)
                }
            })
        })
    }

    public static gameOver(data) {
        if (!data.isVisitSuccess) {   // 闯关失败
            showPanel(FailedPanel, data);
        } else if (
            (data.prize && data.prize.image)
            || (data.tool && data.tool.type)
        ) {  // 闯关成功，奖励关卡
            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 } {
        var arr = {}
        for (var i = 0; i <= 9; i++) arr[i] = RES.getRes(name + i + ".png")
        return arr
    }
}
