<template>
    <div class="nus_scanqrcode">
        <nu-aspect :aspect="1">
            <canvas class="nu_qrcodeCanvas" ref="canvas"></canvas>
        </nu-aspect>
         <!-- <nu-aspect :aspect="1">
            <video style="width: 100%" id="video" src="" controls muted="true"></video>
        </nu-aspect> -->
    </div>
</template>

<script>
import NuAspect from '../../widget/aspect';
import vModel from '../../../Mixins/vModel';
import jsQR from 'jsqr';

export default {
    mixins: [vModel({
        value: ''
    })],
    components: {
        NuAspect
    },
    data() {
        return {
            // myValue: '扫码中'
        };
    },
    beforeDestroy() {
        this._destroy = true;
    },
    mounted() {
        this.scanQrCode();
    },
    methods: {
        async scanQrCode() {
            let _that = this;
            // 设置参数LocalMediaStream
            // const canvasEl = document.createElement('canvas');
            // const canvasEl = document.getElementById('canvas');
            const canvasEl = _that.$refs.canvas;
            if (canvasEl) {
                const el = canvasEl.parentNode;
                canvasEl.width = el.offsetWidth * 2;
                canvasEl.height = el.offsetHeight * 2;
            }
            const ctx = canvasEl.getContext('2d');

            const videoEl = document.createElement('video');
            // const videoEl = document.getElementById('video');
            const videoAttr = {
                'x-webkit-airplay': true,
                'x5-playsinline': '',
                'playsinline': '',
                'webkit-playsinline': '',
                'x5-video-player-type': '',
                'x5-video-player-fullscreen': true,
                'autoplay': true,
                'muted': true,
                'style': 'width: 1px;height: 1px;opacity: 0;position: absolute;'
            };
            videoEl.muted = true;
            for (const key in videoAttr) {
                if (videoAttr.hasOwnProperty(key)) {
                    const val = videoAttr[key];
                    videoEl.setAttribute(key, val);
                }
            }
            document.body.appendChild(videoEl);
            if (navigator.mediaDevices === undefined) {
                navigator.mediaDevices = {};
            }
            if (navigator.mediaDevices.getUserMedia === undefined) {
                navigator.mediaDevices.getUserMedia = function (_constraints) {
                    const getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
                        navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
                    if (!getUserMedia) {
                        return Promise.reject(new Error('getUserMedia is not implemented in this  br owser'));
                    }
                    return new Promise(function (resolve, reject) {
                        getUserMedia.call(navigator, _constraints, resolve, reject);
                    });
                };
            }
            // const devices = await navigator.mediaDevices.enumerateDevices();
            // console.log(devices);
            navigator.mediaDevices.getUserMedia({
                video: {
                    width: canvasEl.width,
                    height: canvasEl.height,
                    facingMode: 'environment' // { exact: 'environment' }
                }
            }).then(function (stream) {
                console.info(stream);
                try {
                    window.stream = stream;
                    videoEl.srcObject = stream;
                } catch (error) {
                    videoEl.src = window.URL.createObjectURL(stream);
                }
                console.log('dsafsadf');
                genImg(canvasEl, ctx, videoEl);
                toText(canvasEl, ctx, videoEl);
                return navigator.mediaDevices.enumerateDevices();
            }).catch((err) => {
                console.error(err);
            });

            /**
            * 生成图片
            * @param {HTMLCanvasElement} _canvasEl canvas元素
            * @param {*} _ctx ctx
            * @param {*} _videoEl 视频元素
            */
            function toText(_canvasEl, _ctx, _videoEl) {
                if (!_that._destroy) {
                    // 识别二维码
                    const imageData = ctx.getImageData(0, 0, canvasEl.width, canvasEl.height);
                    const code = jsQR(imageData.data, imageData.width, imageData.height);
                    if (code && code.data) {
                        _that.myValue = code && code.data;
                    }
                    setTimeout(() => {
                        toText(_canvasEl, _ctx, _videoEl);
                    }, 500);
                }
            }
            /**
            * 生成图片
            * @param {HTMLCanvasElement} _canvasEl canvas元素
            * @param {*} _ctx ctx
            * @param {*} _videoEl 视频元素
            */
            function genImg(_canvasEl, _ctx, _videoEl) {
                window.requestAnimationFrame(() => {
                    if (!_that._destroy) {
                        _ctx.clearRect(0, 0, _canvasEl.width, _canvasEl.height);
                        _ctx.drawImage(_videoEl, 0, 0, _canvasEl.width, _canvasEl.height);
                        genImg(_canvasEl, _ctx, _videoEl);
                    }
                });
            }
        }
    }
};
</script>

<style lang="scss">
.nus_scanqrcode{
    width: 100%;
    .nu_qrcodeCanvas{
        width: 100%;
    }
}
</style>
