Vue.config.devtools = true;
function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}
var v = new Vue({
    el: ".container",
    data: {
        canvasNode: null,
        previewImage: '',
        num:'',
        dayNum :'',
        list: {
        },
        ossClient: null, // oss
        clientJs: null,
        fileUrl: ''
    },
    created:function (){
        if($.cookie("memToken")){
            this.memToken = $.cookie("memToken");
            this.isLogin=1;
        }
        if($.cookie("memHeadImg")){
            this.memHeadImg = $.cookie("memHeadImg");
        }
        if (!checkLogin()) {
            // goLogin();
            return false;
        }
        this.id = getQueryVariable("id");
        this.getIndexData();
        this.client();
        this.getFileNameUUID();
        this.day();
    },
    mounted: function (){
        setTimeout(() => {
            $(".loading-item").fadeOut(200);
        },500)
        this.initalHandle()
        window.addEventListener('resize', this.initalHandle, false)
    },
    methods: {
        getIndexData() {
            var that = this;
            $.ajax({
                type: 'post',
                url: serverHttp + "/signatrue/checkSign",
                data: {
                    memToken: that.memToken,
                    conferenceId: that.id
                },
                success: function (data) {
                    if(data.code == 200 && data.data){
                        that.list = data.data;
                        that.list.memCard = that.memToken;
                    }
                }
            });
        },
        client() {
            var that = this;
            that.clientJs = new OSS.Wrapper({
                // region: 'oss-cn-beijing.aliyuncs.com',
                region: 'oss-cn-beijing',
                accessKeyId: 'LTAI5tHTG5eNAC7pmoqUDghi',
                accessKeySecret: 'K8aZK7RWhqw4LdkP9MtwiC7Rq0avwt',
                bucket: 'qkj-web',
                secure: true
            })
        },
        // 生成随机文件名称  规则八位随机字符，加下划线连接时间戳
        getFileNameUUID(){
            function rx() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
            }
            this.num = `${+new Date()}_${rx()}${rx()}`
        },
        day() {
            var nowDate = new Date()
            var date = {
                year: nowDate.getFullYear(),
                month: nowDate.getMonth() + 1,
                day: nowDate.getDate()
            }
            this.dayNum = date.year + (date.month >= 10 ? date.month : '0' + date.month) + (date.day >= 10 ? date.day : '0' + date.day)
        },
        initalHandle () {
            const _canvasBox = this.$refs.canvasRef
            const _canvas = this.$refs.canvasMapRef
            if (!_canvasBox || !_canvas) {
                return false
            }

            _canvas.width = _canvasBox.clientWidth
            _canvas.height = _canvasBox.clientHeight

            this.clearCanvasHandle()
            this.canvasNode = new SignaturePad(_canvas, {
                minWidth: 4,
                maxWidth: 4,
                penColor: 'rgb(0, 0, 0)'
            })

            // var hei = $(window).height() + 'px';
            // $(".btn-box").css("width",hei)
        },

        clearCanvasHandle () {
            if (this.canvasNode) {
                this.canvasNode.clear()
                this.previewImage = null
            }
        },

        makeCanvasHandle () {
            const canvasNode = this.canvasNode
            // 重新初始化画布
            if (!canvasNode) {
                this.initalHandle()
            }

            // 是否签字
            if (canvasNode.isEmpty()) {
                alert('您还没有签名')
                return false
            }

            // 图像旋转二次处理
            const _boxWidth = window.innerWidth
            const _boxHeight = window.innerHeight
            const _signImg = canvasNode.toDataURL('image/png', 0.6)
            if (_boxWidth < _boxHeight) {
                this.rotateBase64Img(_signImg, -90, (imgUrlRes) => {
                    this.previewImage = imgUrlRes
                    this.uploadFile();
                })
            } else {
                this.previewImage = _signImg
                this.uploadFile();
            }
        },
        fileType (dataurl, filename) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename, {type: mime});
        },
        uploadFile(){
            this.fileType(this.previewImage,'签名.png')
            this.Upload(this.fileType(this.previewImage,'签名.png'))
        },
        submit(){
            var that = this;
            $.ajax({
                type: 'post',
                url: serverHttp + "/signatrue/addSign",
                data: that.list,
                success: function (data) {
                    if(data.code == 200){
                        window.location.href=document.referrer;
                        // window.location.href = serverHttp + '/signatrue/info?from=H5&id=' + that.list.conferenceId + '&m=' + that.list.m
                     }
                }
            });
        },
        Upload(file) {
            console.log(file)
            const that = this
            async function multipartUpload() {
                const temporary = file.name.lastIndexOf('.')
                const fileNameLength = file.name.length
                const fileFormat = file.name.substring(
                    temporary + 1,
                    fileNameLength
                )
                const fileName = that.num + '.' + fileFormat
                const day = that.dayNum
                that.ossClient = that.clientJs.multipartUpload(`sign/${day}/${fileName}`, file).then(res => {
                    // 上传成功返回值
                    that.fileUrl = res.url
                    that.list.signImg = res.url
                    that.submit();
                })
            }
            multipartUpload()
        },
        rotateBase64Img(src, edg, callback){
            try {
                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d')

                let imgW = 0 // 图片宽度
                let imgH = 0 // 图片高度
                let size = 0 // canvas初始大小

                if (edg % 90 !== 0) {
                    throw new Error('旋转角度必须是90的倍数!')
                }

                (edg < 0) && (edg = (edg % 360) + 360)
                const quadrant = (edg / 90) % 4 // 旋转象限
                const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 } // 裁剪坐标

                const image = new Image()
                image.src = src
                image.crossOrigin = 'anonymous'

                image.onload = function () {
                    imgW = image.width
                    imgH = image.height
                    size = imgW > imgH ? imgW : imgH

                    canvas.width = size * 2
                    canvas.height = size * 2
                    switch (quadrant) {
                        case 0:
                            cutCoor.sx = size
                            cutCoor.sy = size
                            cutCoor.ex = size + imgW
                            cutCoor.ey = size + imgH
                            break
                        case 1:
                            cutCoor.sx = size - imgH
                            cutCoor.sy = size
                            cutCoor.ex = size
                            cutCoor.ey = size + imgW
                            break
                        case 2:
                            cutCoor.sx = size - imgW
                            cutCoor.sy = size - imgH
                            cutCoor.ex = size
                            cutCoor.ey = size
                            break
                        case 3:
                            cutCoor.sx = size
                            cutCoor.sy = size - imgW
                            cutCoor.ex = size + imgH
                            cutCoor.ey = size + imgW
                            break
                    }

                    ctx.translate(size, size)
                    ctx.rotate(edg * Math.PI / 180)
                    ctx.drawImage(image, 0, 0)

                    const imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey)
                    if (quadrant % 2 === 0) {
                        canvas.width = imgW
                        canvas.height = imgH
                    } else {
                        canvas.width = imgH
                        canvas.height = imgW
                    }
                    ctx.putImageData(imgData, 0, 0)

                    if (typeof callback === 'function') {
                        callback(canvas.toDataURL('image/png', 0.7))
                    }
                }
            } catch (e) {
                console.log(e)
            }
        }
    },
    beforeDestroy () {
        window.removeEventListener('resize', this.initalHandle, false)
    }
})
