<template>
  <div id="captcha_div"></div>
</template>

<script>
import '@/assets/css/captcha.css'
var captcha = {};
export default {
    name: 'Captcha',
    methods: {
        initCaptcha(param, success, failure){
            param.path="/"
            if(param.type == 3){
                var that = this;
                param.widthInt =  parseInt(param.width);
                param.zoomRate = 315/param.widthInt;
                param.heightInt = parseInt(196/param.zoomRate);
                param.height = param.heightInt + "px";
                param.fragWidth = parseInt(33/param.zoomRate) + "px";
                param.bgSize = parseInt((315+33)/param.zoomRate) + "px";
                console.log("width:"+param.widthInt+"|zoomRate:"+param.zoomRate+"|heightInt:"+param.heightInt);
                captcha = {
                    conf : param, // json
                    data:null,
                    loaded : false,
                    captchaSlider : {
                        e : null,
                        x : 0,
                        y : 0,
                        width:0,
                        onMove : false,
                        init : function() {
                            var s = this;
                            captcha.captchaSlider.width = parseInt(captcha.conf.width);
                            s.e = $("#captcha_slider")[0];
                            s.e.addEventListener('mousedown', function(){
                                s.onMouseDown(event, s);
                            }, false);
                            s.e.addEventListener('touchstart', function(){
                                s.onMouseDown(event.touches[0], s);
                            }, false);
                            s.e.addEventListener('touchmove', function(){
                                // console.log(event.touches[0].clientX)
                                s.onMouseMove(event.touches[0], s);
                            }, false);
                            s.e.addEventListener('touchend', function(){
                                s.onMouseUp(event.touches[0], s);
                            }, false);
                        },
                        onMouseUp : function(e,t) {
                            if(t.onMove){
                                t.onMove = false;
                                if(t.e.offsetLeft != 0){
                                    captcha.onVerify(100*t.e.offsetLeft / captcha.captchaSlider.width);
                                    t.e.style.left=0;
                                    $('#captcha_fragment')[0].style.left = t.e.style.left;
                                }
                            }
                        },
                        onMouseDown : function(e,t) {
                            if(captcha.loaded){
                                $("#captcha_panel")[0].style.display='block';
                                $("#captcha_bg")[0].style.display='block';
                                $("#captcha_fragment")[0].style.display='block';
                            }
                            t.onMove = true;
                            t.x = e.clientX;
                            t.y = e.clientY;

                        },
                        onMouseMove : function(e,t) {
                            // console.log(t.width);
                            if(t.onMove){
                                if(e.clientX - t.x <=0){
                                    t.e.style.left = 0;
                                }else if(e.clientX - t.x > t.width - t.e.clientWidth){
                                    t.e.style.left  = (t.width - t.e.clientWidth) + "px";
                                }else{
                                    t.e.style.left = (e.clientX - t.x) + "px";
                                }
                                $('#captcha_fragment')[0].style.left = t.e.style.left;
                            }
                        }
                    },
                    init : function(success, failure) {
                        var elementDiv = $(this.conf.element);
                        var type = this.conf.type;
                        var captchaTemplateHtml = null;
                        var captchaTemplateHtmlUpdateTime = null;
                        if (window.localStorage) {
                            captchaTemplateHtmlUpdateTime = window.localStorage.getItem(type + "captcha.html.time");
                            if (Date.parse(new Date()) - captchaTemplateHtmlUpdateTime < 1)
                                captchaTemplateHtml = window.localStorage.getItem(type + "captcha.html" + that.getLanguage());
                        }
                        if (captchaTemplateHtml == null) {
                            var templateName="slide";
                            if(that.getLanguage()=="en_US"){
                                templateName+="_"+that.getLanguage();
                            }
                            templateName += '.html';
                            var htmlTemplate= $.ajax({
                                beforeSend: function(request) {
                                    request.setRequestHeader("Access-Control-Allow-Origin", "*");
                                },
                                url : captcha.conf.path + "captcha/" + templateName,
                                async : false,
                                cache : true
                            });
                            if (htmlTemplate.status = !200) {
                                instance.log("captcha template loading error");
                                failure("template html(captcha.html) can't be loaded");
                                return;
                            }
                            if (window.localStorage) {
                                window.localStorage.setItem(type + "captcha.html.time", Date.parse(new Date()));
                                window.localStorage.setItem(type + "captcha.html" + that.getLanguage(), htmlTemplate.responseText);
                                captchaTemplateHtml = htmlTemplate.responseText
                            }
                        }

                        elementDiv.html(captchaTemplateHtml);
                        var bg =document.getElementById('captcha_bg');
                        bg.style.backgroundImage = "url('" +captcha.conf.path + "captcha/blank.png')";
                        bg.style.backgroundSize = captcha.conf.bgSize + " 100%";
                        bg.style.width = captcha.conf.width;
                        //bg.style.height = captcha.conf.height;
                        bg.style.height = "100%";
                        var frag = document.getElementById('captcha_fragment');
                        frag.style.backgroundImage = "url('" +captcha.conf.path + "captcha/blank.png')";
                        frag.style.backgroundSize = captcha.conf.bgSize + " 100%";
                        //frag.style.height = captcha.conf.height;
                        frag.style.width = captcha.conf.fragWidth;
                        frag.style.backgroundPosition = "-" + captcha.conf.width +" 0px";

                        document.getElementById('captcha_main').style.width = captcha.conf.width;
                        $("#captcha_refresh")[0].addEventListener('click', this.onRefresh, false);
                        var slider = captcha.captchaSlider;
                        window.addEventListener('mousemove', function(){slider.onMouseMove(event,slider)}, false);
                        window.addEventListener('mouseup', function(){slider.onMouseUp(event,slider)}, false);
                        this.captchaSlider.init();
                        this.onRefresh();
                        success(this);
                    },
                    refresh:function(){
                        captcha.onRefresh();
                    },
                    onRefresh: function() {
                        $.ajax({
                            beforeSend: function(request) {
                                request.setRequestHeader("Access-Control-Allow-Origin", "*");
                            },
                            url : captcha.conf.path + "captchas/get?type="+ captcha.conf.type+"&t="
                                + Math.random() +"&width=" + captcha.conf.widthInt+"&height=" + captcha.conf.heightInt,
                            success:function(resp){
                                $("#captcha_bg").attr('src',"/captcha/blank.png");
                                document.getElementById('captcha_bg').style.backgroundImage = "url('" +resp.data.backGround + "')";
                                document.getElementById('captcha_fragment').style.backgroundImage = "url('" +resp.data.backGround + "')";
                                captcha.data=resp.data;
                                captcha.loaded = true;
                                captcha.verified = false;
                                that.$emit('getCaptchaToken', resp.data.token);
                                $('.verification-result-slip').show();
                                $('.slip-failed').hide();
                                $('.slip-success').hide();
                                $('.captcha_tips').show();
                            },
                            error:function(resp){
                                captcha.log(resp.status);
                            }
                        });
                    },
                    onVerify : function(value){
                        if(captcha.verified){
                            return;
                        }
                        $("#captcha_panel")[0].style.display='none';
                        $.ajax({
                            beforeSend: function(request) {
                                request.setRequestHeader("Access-Control-Allow-Origin", "*");
                            },
                            url : captcha.conf.path +"captchas/check?token="+captcha.data.token+"&data="+value,
                            async : false,
                            success:function(resp){
                                that.$emit('getValidate', resp.validate)
                                captcha.verified = resp.result;
                                if(captcha.verified){
                                    $('.verification-result-slip').show();
                                    $('.slip-failed').hide();
                                    $('.captcha_tips').hide();
                                    $('.slip-success').show();
                                    $('#captcha_slider').hide();
                                }else{
                                    $('.verification-result-slip').show();
                                    $('.slip-success').hide();
                                    $('.captcha_tips').hide();
                                    $('.slip-failed').show();
                                    // TODO 定时调用刷新
                                }
                                captcha.conf.onVerify(resp, captcha);
                            },
                            error:function(resp){
                                captcha.log(resp.message);
                            }
                        });
                    },
                    debug : function(message) {
                        // logLevel error[1],warning[2],log[3],debug[4],all[5]
                        if (this.conf.logLevel >= 4) {
                            console.log("captcha debug:" + message);
                        }
                    },
                    log : function(message) {
                        // logLevel error[1],warning[2],log[3],debug[4],all[5]
                        if (this.conf.logLevel >= 3) {
                            console.log("captcha log:" + message);
                        }
                    },
                    warning : function(message) {
                        // logLevel error[1],warning[2],log[3],debug[4],all[5]
                        if (this.conf.logLevel >= 2) {
                            console.log("captcha warning:" + message);
                        }
                    },
                    error : function(message) {
                        if (this.conf.logLevel >= 1) {
                            console.log("captcha error:" + message);
                        }
                    }
                };
                captcha.init(success, failure);
            }
        },
        captchaInit(){
            let that = this
            that.initCaptcha(
                {
                element : '#captcha_div',// requred by type [3/4/5]
                logLevel : 5, // logLevel error[1],warning[2],log[3],debug[4],all[5]
                type : '3', // TEXT("字符验证码", 1), ARITHMETIC("数字计算验证码", 2), DRAG("滑动验证码", 3), CHOOSE("选择结果验证码", 4), POSITION("位置选择验证码", 5);
                width : "310px",
                onVerify : function(message, instance) {
                    // console.log("check captcha:"+message.result);
                    if (message.result) {
                        $('.slip-success')[0].style.display = "inline-block";
                        that.$emit('getResult', true)
                    } else {
                        $('.slip-failed')[0].style.display = "inline-block";
                        instance.refresh();
                    }
                }
            }, function(instance) {
                if (instance.conf.type >= 3) {
                    // $('#tr_validation_code')[0].style.display = '';
                } else {
                    // $('#tr_validation_code_input')[0].style.display = '';
                }
                instance.log("captcha instance initialization success, waiting for image loading");
                var capthcaInstance = instance;
            }, function(err) {alert(err);});
        },
        getCookie:function(name){
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        },
        getLanguage:function(){
            if(this.getCookie("Language")){
                return this.getCookie("Language");
            }else{
                var lang =(navigator.language || navigator.browserLanguage).toLowerCase();
                if(lang.indexOf('en')>=0 ){
                    return "en_US";
                }
                return "";
            }
        }
    }
}
</script>

<style>

</style>