import { Decorator } from "../Decorator/Decorator";
import { setShareImg, clearShareImg } from "../utils";
import SceneCtrl from "../ctrls/SceneCtrl";
import AnswerScene from "./AnswerScene";
import Scene from "../views/Scene";
import MainScene from "./MainScene";
import { MUtils } from "../MUtils";

@Decorator.OnDestroy
export default class ResultScene extends Scene {
    get skinKey() { return "ResultScene" }
    get groupName() { return "result_scene" }
    public btnRestart: eui.Button;
    public img: eui.Image;

    async onSkinComplete() {
        super.onSkinComplete();
        this.btnRestart.onTap(this, () => {
            MUtils.doClickBuried("6");
            SceneCtrl.instance.change(MainScene);
        });

        let score = this.data["score"];
        let level = "";
        if (score <= 7) {
            level = "1";
        } else if (score > 7 && score <= 10) {
            level = "2";
        } else if (score > 10 && score <= 13) {
            level = "3";
        } else if (score > 13) {
            level = "4";
        } else {
            console.error("invalid score");
        }
        console.log("score", score);
        this.img.source = await RES.getResAsync(`result_${level}_png`);

        this.createShareImg(level);

        MUtils.doShowBuried("5");
    }

    private shareImgUrl: string = null;

    async createShareImg(level: string) {
        this.shareImgUrl = `share${level}_jpg`;
        let mainTex = await RES.getResAsync(this.shareImgUrl) as egret.Texture;
        let qrcodeTex = await RES.getResAsync("share_qrcode_png") as egret.Texture;
        //创建显示对象
        let shareImg = new egret.DisplayObjectContainer();
        let mainImg = new egret.Bitmap(mainTex);
        shareImg.addChild(mainImg);
        let qrcode = new egret.Bitmap(qrcodeTex);
        qrcode.x = 94;
        qrcode.y = 1000;
        qrcode.width = 100;
        qrcode.height = 100;
        shareImg.addChild(qrcode);

        //截图到<img>
        let texture: egret.RenderTexture = new egret.RenderTexture();
        texture.drawToTexture(shareImg);
        let imgUrl = texture.toDataURL("image/jpeg", new egret.Rectangle(
            this.stage.width - this.stage.stageWidth,
            this.stage.height - this.stage.stageHeight,
            this.stage.stageWidth,
            this.stage.stageHeight >= 1200 ? this.stage.stageHeight : 1200
        ));

        let t = this.img.parent.localToGlobal(this.img.x, this.img.y);
        setShareImg(imgUrl, new egret.Rectangle(t.x, t.y, this.img.width * MUtils.fixAreaRatio, this.img.height * MUtils.fixAreaRatio), 0, false);
    }

    onDestroy() {
        clearShareImg();

        RES.destroyRes("share_qrcode_png");
        RES.destroyRes(this.shareImgUrl);
    }
}