import { INetData } from "../../libs/tc/interface/INetData";
import { DataManager } from "../../libs/tw/manager/DataManager";
import { NetManager } from "../../libs/tw/manager/NetManager";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import Panel from "../views/Panel";
export default class PhotoPanel extends Panel {
    constructor(scene) {
        super()
        this.show()
        this.scene = scene;

        egret.Ticker.getInstance().register(this.onEnterFrame, this);
    }

    private scene: any;
    private isVideo: boolean = true;
    private buffer: any;
    private oCapture: any;
    private photoCanvas: any;
    private photoContext: any;
    private basePic: any;

    public photoModel: eui.Image;
    public picBtn: eui.Button;
    public closeModelBtn: eui.Button;
    public warningTxt: eui.Label;
    public comfirmBtn: eui.Button;
    public rePicBtn: eui.Button;

    private show() {

        this.oCapture = document.getElementById("photoVideo");
        this.photoCanvas = document.getElementById("photoCanvas");
        this.photoContext = this.photoCanvas.getContext('2d');
        document.getElementById("image").onchange = this.previewFile.bind(this);
    }

    private onEnterFrame() {

    }

    initEvents() {
        this.closeModelBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_closeModelBtn, this);
        this.comfirmBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_comfirmBtn, this);
    }

    removeEvents() {
        this.closeModelBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_closeModelBtn, this);
        this.comfirmBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_comfirmBtn, this);
    }

    // 关闭拍照
    private onClick_closeModelBtn(e: egret.TouchEvent) {
        PanelCtrl.instance.closeCurrent();
        this.isVideo = false;
        this.scene.playSceneVisibleHandler(true);
    }

    // 确认
    private onClick_comfirmBtn(e: egret.TouchEvent) {
        // canvas 转 base64 图片
        let dataURL = window["$"]("canvas").eq(0)[0].toDataURL('image/jpeg');
        this.getMixedPic(dataURL, (success) => {
            if (success) {
                // 融合成功
                let img = DataManager.ins.getData('getMixedPic').data.image;
                PanelCtrl.instance.closeCurrent();
                this.scene.playSceneVisibleHandler(true);
                PanelCtrl.instance.show(ModuleTypes.RESULT_PANEL, img)
            } else {
                // 融合失败
                let data = { type: 'err', msg: '融合失败，请重试' }
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
            }
        })

    }

    //获取集卡卡片信息
    private getMixedPic(base64, callback) {
        let data: any = {
            base64: base64,
        }
        window['debug'] && (data = {});
        const net: INetData = {
            name: 'getMixedPic',
            uri: '/customActivity/face/qq',
            type: 'post',
            dataType: 'json',
            param: data,
            callback: callback,
        };
        NetManager.ins.send(net)
    }

    private previewFile() {
        let scope = this;
        let img = document.getElementById("preBasePic");
        // 仅限上传单张图片
        let file = document.getElementById("image")['files'][0];
        let reader = new FileReader();
        reader.addEventListener("load", () => {
            img['src'] = reader.result;  // 存储在本地的图片的base64编码

            scope.drawPhoto(img, 0, 0, 750, 1206)
        }, false);

        if (file) {
            reader.readAsDataURL(file);
        }
    }

    // 将照片画在画布上
    public drawPhoto(photo, x, y, w, h) {
        let canvas = window['$']("#photoCanvas")[0];
        if (canvas.getContext) {
            let ctx = canvas.getContext("2d");
            let img = new Image();
            img.onload = () => {
                let orient;
                //获取照片的拍摄方向
                window['EXIF'].getData(photo, function () {
                    orient = window['EXIF'].getTag(this, 'Orientation');
                    let imgWidth = canvas.width = this.width;
                    let imgHeight = canvas.height = this.height;

                    let canvas_w = Number(ctx.canvas.width);
                    let canvas_h = Number(ctx.canvas.height);
                    if (orient && orient != 1) {
                        switch (orient) {
                            case 6:     // 旋转90度
                                ctx.save();//保存状态
                                ctx.translate(canvas_w / 2, canvas_h / 2);//设置画布上的(0,0)位置，也就是旋转的中心点
                                ctx.rotate(90 * Math.PI / 180);//把画布旋转90度
                                // 执行Canvas的drawImage语句
                                ctx.drawImage(img, Number(y) - canvas_h / 2, Number(x) - canvas_w / 2, h, w);//把图片绘制在画布translate之前的中心点，
                                ctx.restore();//恢复状态
                                break;
                            case 3:     // 旋转180度
                                ctx.rotate(Math.PI);
                                ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
                                break;
                            case 8:     // 旋转-90度
                                canvas.width = imgHeight;
                                canvas.height = imgWidth;
                                ctx.rotate(3 * Math.PI / 2);
                                ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
                                break;
                        }
                    } else {
                        ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
                    }
                });
            }
            img.src = photo.src; // 设置图片源地址
        }
    }

    protected get skinKey() { return 'Photo' }
}