import Panel from "../../Module/Panel";
import { _decorator, Button, easing, game, ImageAsset, Label, Node, RenderTexture, Sprite, SpriteFrame, Texture2D, tween, UITransform, v3 } from "cc";
import ShareCenter from "../ShareCenter";
import { WebNetName, getWebData } from "../Utils/WebNet/WebNet";
import { dateFormatter, getUrlParam, loadImg, randomNum } from "../Utils/Utils";
import { wxShareImg } from "../Utils/appFn";
import { showToast } from "../../Module/UIFast";
const { ccclass, property } = _decorator;

@ccclass('PosterPanel')
export default class PosterPanel extends Panel {

    static bundle: string = "";
    static skin = "PosterPanel";
    static group = "PosterPanel";

    @property(Node)
    close: Node = null;

    @property(Sprite)
    posterImgShowSection: Sprite = null; // 海报签文图(展示区域)

    @property(Label)
    titleShowSection: Label = null; // 日期(展示区域)

    @property(Sprite)
    codeShowSection: Sprite = null; // 二维码(展示区域)

    @property(Sprite)
    posterImgShotSection: Sprite = null; // 海报签文图(截图区域)

    @property(Label)
    titleShotSection: Label = null; // 日期(截图区域)

    @property(Sprite)
    codeShotSection: Sprite = null; // 二维码(截图区域)

    @property(RenderTexture)
    rt: RenderTexture = null;

    @property(Node)
    saveBtn: Node = null;

    randomImgData = { image: '', level: '' };
    posterBase64Data = null

    async start() {
        this.view["yaoBgSvga"].active = true
        this.view["yaoSvga"].active = true
        this.view["bgSvga"].active = false
        this.view["scaleAniBox"].active = false

        // 摇签动效播放完后 出现海报
        this.scheduleOnce(async () => {
            this.view["yaoBgSvga"].active = false
            this.view["yaoSvga"].active = false
            this.view["bgSvga"].active = true
            this.view["scaleAniBox"].active = true

            tween(this.view["scaleAniBox"])
                .set({ scale: v3(0, 0, 0) })
                .to(0.3, { scale: v3(1.1, 1.1, 1.1) }, { easing: easing.smooth })
                .to(0.4, { scale: v3(1, 1, 1) }, { easing: easing.smooth })
                .start();

            this.titleShowSection.string = dateFormatter(+new Date(), 'yyyy/MM/dd');
            this.titleShotSection.string = dateFormatter(+new Date(), 'yyyy/MM/dd');

            const { posterImgs } = getWebData(WebNetName.getFrontVariable).data || {}
            this.randomImgData = posterImgs[randomNum(0, posterImgs.length)] || {}
            const randomImg = this.randomImgData?.image
            if (randomImg) {
                const res = await loadImg(randomImg, this.posterImgShowSection.getComponent(UITransform).width);
                this.posterImgShowSection.spriteFrame = res?.spriteFrame
                this.posterImgShotSection.spriteFrame = res?.spriteFrame
            }

            this.createQRCode()

            setTimeout(() => {
                // 随机出结果后 就直接完成任务
                this.data?.sharedFun?.(this.randomImgData.level);
            }, 2000)
        }, 1)

        this.close.on(Button.EventType.CLICK, this.onClose, this);
        this.saveBtn.on(Button.EventType.CLICK, this.saveHandle, this)
        
    }

    /**
     * 分享海报到微信
     */
    saveHandle = () => {
        this.btnEnable(this.saveBtn, false);
        if (!!this.posterBase64Data) {
            // 去掉图片base64码前面部分data:image/png;base64
            const base64 = this.posterBase64Data.replace(/^data:image\/\w+;base64,/, "");
            wxShareImg(base64)
        } else {
            showToast("海报生成中, 请稍等")
        }
        this.btnEnable(this.saveBtn, true);
    }

    /**
     * 返回首页
     */
    onClose = () => {
        this.hidePanel();
        this.clearCapture();
    }

    // 获取二维码
    createQRCode = async () => {
        await ShareCenter.ins.getInviteCode();
        const { appKey, shareOrigin } = getWebData(WebNetName.getFrontVariable).data
        const QRcodeUrl = `${shareOrigin || location.origin}${ShareCenter.ins.shareUrl}&appKey=${appKey}&openBs=openbs&show=blank&inviteCode=${ShareCenter.ins.inviteCode}&channel=${getUrlParam("channel")}`
        console.info("QRcodeUrl====>", QRcodeUrl)
        window["QRCode"].toDataURL(QRcodeUrl, (err, url) => {
            if (err) {
                return;
            }
            let img = new Image();
            img.src = url;
            img.onload = () => {
                let img2c = new ImageAsset(img)
                const texture = new Texture2D();
                texture.image = img2c
                const newFrame = new SpriteFrame();
                newFrame.texture = texture
                this.codeShowSection.spriteFrame = newFrame;
                this.codeShotSection.spriteFrame = newFrame;

                // director.once(Director.EVENT_AFTER_DRAW, () => {
                //     const canvas = game.canvas;
                //     const base64 = canvas.toDataURL("image/png");
                //     console.info('截图',base64)
                //     
                // });
                //此处开始执行截屏
                this.screenshot()
            }
        });

    }

    private dom: HTMLDivElement
    _canvas: HTMLCanvasElement = null!;
    _buffer: ArrayBufferView = null!;

    screenshot() {
        this.scheduleOnce(() => {
            this.copyRenderTex();
        }, 0.5)
    }
    copyRenderTex() {

        const width = this.rt.width;
        const height = this.rt.height;
        this._buffer = this.rt.readPixels();

        if (!this._canvas) {
            this._canvas = document.createElement('canvas');
            this._canvas.width = width;
            this._canvas.height = height;
        } else {
            const ctx = this._canvas.getContext('2d');
            ctx.clearRect(0, 0, width, height);
        }

        const ctx = this._canvas.getContext('2d')!;
        const rowBytes = width * 4;
        for (let row = 0; row < height; row++) {
            const sRow = height - 1 - row;
            const imageData = ctx.createImageData(width, 1);
            const start = sRow * width * 4;
            for (let i = 0; i < rowBytes; i++) {
                imageData.data[i] = this._buffer[start + i];
            }
            ctx.putImageData(imageData, 0, row);
        }

        this.posterBase64Data = this._canvas.toDataURL()
        // console.log('this.posterBase64Data', this.posterBase64Data);

        // 本地预览海报结果时 可放开
        // const wRem = width / 100;
        // const hRem = height / 100;

        // const domHtml = `
        //     <div style="pointer-events: none; width: 100%; height: 100%; position: absolute; left: 0; top: 0; display: flex; align-items: center; justify-content: center">
        //         <img 
        //             src="${this._canvas.toDataURL()}" 
        //             style="width:${wRem}rem;height:${hRem}rem; pointer-events: auto"
        //         >
        //     </div>
        // `;

        // this.dom = document.createElement('div');
        // this.dom.innerHTML = domHtml;
        // game.container.appendChild(this.dom);
    }
    clearCapture() {
        if (this.dom) {
            game.container!.removeChild(this.dom)
        }
        this.dom = null;
    }
}
