$(function () {

    var C = CanvasKit;
    var searchObject=getURLParams(window.location.href);
    var needGeneral=0;
    var appKey=searchObject.appKey;
    var userId=searchObject.userId||"";
    if(searchObject.hasOwnProperty("ID")&&searchObject.hasOwnProperty("name")&&searchObject.hasOwnProperty("phone")){
        needGeneral=1;
    }

    function rewiteUrl(cid) {
        var url=window.location.href
        if(url.match(/&cid=\d+/)){
            url=url.replace(/&cid=\d+/,'&cid='+cid);
        }else{
            url+='&cid='+cid;
        }
        history.replaceState("","",url);
    }



    // console.enabled_server_log = constant.debug;

    function TimingAnimate(opt) {
        C.Animate.call(this, opt);
        this.shifting = 0;
        this.fn = opt.fn;
        this.initial_velocity = +(opt.velocity || opt.v || 0);
        this.max_velocity = +(opt.max_velocity || opt.max_v || 0);
        this.acceleration = +(opt.acceleration || opt.a || 0);
        this.velocity = this.initial_velocity;
    }

    C.extendClass(TimingAnimate, C.Animate, {
        _start: function () {
            this.shifting = 0;
            this.velocity = this.initial_velocity;
        },
        _update: function (interval, elapsedTime) {
            var t = elapsedTime / 1000, //总时间
                a = this.acceleration, //加速度
                t0 = (this.max_velocity - this.initial_velocity) / a,//达到最大速度时间点
                t1 = t < t0 ? t : t0,//匀加速时间
                t2 = t > t0 ? t - t0 : 0, //匀速时间
                v0 = this.initial_velocity, //初速度
                mv = this.max_velocity; //最大速度

            this.shifting = v0 * t1 + .5 * a * t1 * t1 + mv * t2;
            this.velocity = v0 + a * t1;
            for (var key in this.fn) {
                if ((key === 'position' || key === 'alpha' || key === 'color') && typeof this.fn[key] === 'function') {
                    this.node[key] = this.fn[key].call(this, this.shifting);
                }
            }
        }
    })

    function Ball(radial_radius, radius, position, color) {
        C.Circle.call(this, radius, position, color);
        this.turning_velocity = 4;
        this.shadow.alpha = 1;
        this.status = 'none';
        this.center = this.position;
        this.radial_radius = radial_radius;
        this.tube = radius * 2;
        this.radius = radius * 1.4;

        var scale = .85;

        this.points = {
            a: [this.center[0] - this.radial_radius * .40 * scale, this.center[1] - this.radial_radius * .10 * scale],
            b: [this.center[0] - this.radial_radius * .12 * scale, this.center[1] + this.radial_radius * .30 * scale],
            c: [this.center[0] + this.radial_radius * .57 * scale, this.center[1] - this.radial_radius * .31 * scale]
        }

        this.turning_angle = (function (points, o, r) {
            //ax + by + c = 0;
            var a = points.b[1] - points.a[1],
                b = points.a[0] - points.b[0],
                c = points.b[0] * points.a[1] - points.a[0] * points.b[1],
                d = Math.abs((a * o[0] + b * o[1] + c) / Math.sqrt(a * a + b * b));
            return Math.PI * 2 - Math.acos(d / r) - Math.atan(-a / b);
        })(this.points, this.center, this.radial_radius);
    }

    C.extendClass(Ball, C.Circle, {
        _draw: function (ctx) {
            switch (this.status) {
                case 'none':
                    this._draw_none(ctx);
                    break;
                case 'timer':
                case 'timer+':
                    this._draw_run_timer(ctx);
                    break;
                case '-loader':
                    this._draw_will_loader(ctx);
                    break;
                case 'loader':
                    this._draw_run_loader(ctx);
                    break;
                case 'loaded':
                    this._draw_will_do(ctx);
                    break;
                case 'doing':
                    this._draw_run_doing(ctx);
                    break;
                case 'done':
                    this._draw_run_done(ctx);
                    break;
                default:

            }
        },
        _get_stretch_rate: function () {
            return Math.max(0, (this.animate.velocity - this.turning_velocity) / (this.animate.max_velocity - this.turning_velocity));
        },
        _get_I: function () {
            return Math.max(0, Math.PI * 2 * .05 * this._get_stretch_rate());
        },
        _get_point_angle: function (angle) {
            return this.animate.fn.position.call(this.animate, angle);
        },
        _play: function () {
            var fn = function (s) {
                return [this.node.center[0] + this.node.radial_radius * Math.sin(s),
                    this.node.center[1] + this.node.radial_radius * Math.cos(s)];
            }
            this.animate = new TimingAnimate({
                node: this,
                v: 2,
                max_v: 10,
                a: .1,
                fn: {
                    position: fn
                }
            });
            this.position = fn.bind(this.animate)(0);
            this.animate.play();
            this.status = 'loader';
        },
        _draw_none: function (ctx) {

        },
        _draw_run_timer: function (ctx) {
            var elapsedTime = this.timer.elapsedTime,
                finishedTime = Math.round(this.time) * 1000,
                startAngle = -Math.PI / 2,
                angle = Math.PI * 2;
            if (finishedTime > elapsedTime) {
                var elapsedSec = Math.floor(elapsedTime / 1000) * 1000,
                    elapsedMs = elapsedTime - elapsedSec,
                    beatMs = 800;
                angle *= elapsedSec / finishedTime;
                if (elapsedMs > 1000 - beatMs) {
                    angle += Math.PI * 2000 * C.Easing.Quadratic.InOut(C.mix(0, 1, (elapsedMs - (1000 - beatMs)) / beatMs)) / finishedTime;
                }
            } else {
                this.timer.stop();
                this.status = 'timer+';
            }

            ctx.save();
            ctx.lineWidth = this.tube;
            ctx.strokeStyle = C.convertColor(this.color, this.alpha);
            ctx.beginPath();
            ctx.arc(this.center[0], this.center[1], this.radial_radius, startAngle, startAngle + angle, false);
            ctx.stroke();
            ctx.restore();
        },
        _draw_will_loader: function (ctx) {
            var elapsedTime = this.timer.elapsedTime,
                finishedTime = 400,
                startAngle = -Math.PI / 2,
                endAngle = startAngle + Math.PI * 2;
            if (finishedTime > elapsedTime) {
                var a = C.Easing.Quadratic.InOut(finishedTime > elapsedTime ? elapsedTime / finishedTime : 1);
                var b = Math.PI * a;
                startAngle += b;
                endAngle -= b;

                if (endAngle <= startAngle) {
                    endAngle = startAngle;
                }

                ctx.save();
                ctx.lineCap = "round";
                ctx.lineWidth = C.mix(this.tube, this.radius * 2, a);
                ctx.strokeStyle = C.convertColor(this.color, this.alpha);
                ctx.beginPath();
                ctx.arc(this.center[0], this.center[1], this.radial_radius, startAngle, endAngle, false);
                ctx.stroke();
                ctx.restore();
            } else {
                this._play();
            }
        },
        _draw_run_loader: function (ctx) {
            var v = this.animate.velocity,
                stretch_rate = this._get_stretch_rate(),
                s = this.animate.shifting || 0;
            if (v > this.turning_velocity) {
                this.shadow.enabled = true;
                this.shadow.blur = Math.round(6 * stretch_rate);
                this.alpha = .4 + .6 * (1 - stretch_rate);
            } else {
                this.shadow.enabled = false;
                this.shadow.blur = 0;
                this.alpha = 1;
            }

            // C.Circle.prototype._draw.call(this,ctx);
            ctx.save();
            if (v <= this.turning_velocity) {
                ctx.fillStyle = C.convertColor(this.color, this.alpha);

                ctx.beginPath();
                ctx.arc(this.position[0], this.position[1], this.radius, 0, Math.PI * 2, true);
                ctx.closePath();
                ctx.fill();
            } else {
                var points = [],
                    dI = this.radius / this.radial_radius / 3,
                    I = this._get_I();
                this._draw_ring(ctx, s, this._get_I(), 0);

            }
            ctx.restore();
        },
        _draw_ring: function (ctx, start_angle, I, is_gradient) {
            var points = [],
                dI = this.radius / this.radial_radius / 3;

            for (var i = 0; i * dI <= I; i++) {
                points.push(this._get_point_angle(start_angle - i * dI));
            }
            is_gradient = !!is_gradient;

            var alpha = is_gradient ? 1 : this.alpha;

            ctx.strokeStyle = C.convertColor(this.color, alpha);
            ctx.fillStyle = ctx.strokeStyle;
            ctx.shadowOffsetX = this.shadow.offset.x;
            ctx.shadowOffsetY = this.shadow.offset.y;
            ctx.shadowBlur = this.shadow.blur;
            ctx.shadowColor = C.convertColor(this.color, 1); // 颜色

            var circle_start_angle = -start_angle + Math.PI * .5;
            ctx.beginPath();
            ctx.arc(points[0][0], points[0][1], this.radius, circle_start_angle, circle_start_angle + Math.PI, true);
            ctx.closePath();
            ctx.fill();

            var length = points.length, point = points.shift(), i = 0;

            if (points.length) {
                ctx.beginPath();
                ctx.moveTo(point[0], point[1]);
                while (points.length) {
                    if (is_gradient) {
                        alpha = C.mix(1, this.alpha, C.Easing.Cubic.Out(i / length));
                        ctx.strokeStyle = C.convertColor(this.color, alpha);
                        ctx.fillStyle = ctx.strokeStyle;
                    }

                    ctx.lineWidth = this.radius * 2;
                    point = points.shift();
                    ctx.lineTo(point[0], point[1]);
                    ctx.closePath();
                    ctx.stroke();
                    ctx.beginPath();
                    ctx.moveTo(point[0], point[1]);
                    i++;
                }
            }


            ctx.beginPath();
            circle_start_angle = -(start_angle - (length - 1) * dI) - Math.PI * .5;
            ctx.arc(point[0], point[1], this.radius, circle_start_angle, circle_start_angle + Math.PI, true);
            ctx.closePath();
            ctx.fill();
        },
        _draw_will_do: function (ctx) {
            this._draw_run_loader(ctx);
            if ((this.animate.shifting || 0) >= this.turning_angle) {
                this.status = 'doing';
                this.end_timer.start();
            }
        },
        _draw_run_done: function (ctx) {
            var points = [];
            points.push(this.points.a);
            points.push(this.points.b);
            points.push(this.points.c);
            for (var i = 0; i < points.length - 1; i++) {
                this._draw_lines(ctx, points[i], points[i + 1]);
            }
        },
        _draw_run_doing: function (ctx) {
            var elapsedTime = this.end_timer.elapsedTime;
            var points = [];
            if (elapsedTime > this.duration) {
                this.status = 'done';
                this._draw_run_done(ctx);
                typeof this._fn == 'function' && this._fn();
                delete this._fn;
                return;
            } else {
                var f = C.Easing.Back.Out(Math.min(elapsedTime / this.duration, 1));

                if (f < this.a_rate) {
                    if (f < this.b_rate) {
                        var I = this._get_I() - this.animate.velocity * elapsedTime / 1000;
                        if (I > 0) {
                            ctx.save();
                            this._draw_ring(ctx, this.turning_angle, I, 1);
                            ctx.restore();
                        }
                        points.push(this.turning_point);
                    } else {
                        points.push(C.mix(this.turning_point, this.points.a, (f - this.b_rate) / (1 - this.b_rate)));
                    }
                    points.push(C.mix(this.turning_point, this.points.b, f / this.a_rate));
                } else {
                    points.push(C.mix(this.turning_point, this.points.a, (f - this.b_rate) / (1 - this.b_rate)));
                    points.push(this.points.b);
                    points.push(C.mix(this.points.b, this.points.c, (f - this.a_rate) / (1 - this.a_rate)));
                }
            }
            for (var i = 0; i < points.length - 1; i++) {
                this._draw_lines(ctx, points[i], points[i + 1]);
            }
        },
        _draw_lines: function (ctx, a, b) {
            ctx.save();
            ctx.beginPath();
            ctx.lineWidth = this.radius * 2;
            ctx.lineCap = "round";
            ctx.strokeStyle = C.convertColor(this.color, 1);
            ctx.moveTo(a[0], a[1]);
            ctx.lineTo(b[0], b[1]);
            ctx.stroke();
            ctx.restore();
        },
        _draw_circle: function (ctx, point) {
            ctx.save();
            ctx.fillStyle = C.convertColor(this.color, this.alpha);
            ctx.beginPath();
            ctx.arc(point[0], point[1], this.radius, 0, Math.PI * 2, true);
            ctx.closePath();
            ctx.fill();
            ctx.restore();
        },
        play: function () {
            if (this.timer) {
                this.timer.stop();
            }
            if (this.animate) {
                this.animate.pause();
            }
            if (this.status == 'timer+' || this.status == 'timer') {
                this.status = '-loader';
                this.timer = (new C.Timer()).start();
            } else {
                this._play();
            }
        },
        timing: function (time, fn) {
            if (this.timer) {
                this.timer.stop();
            }
            if (this.animate) {
                this.animate.pause();
            }
            this.status = 'timer';
            this.alpha = 1;
            this.time = time;
            $('.canvas-dashboard .loader .sec').html(time);
            this.timer = (new C.Timer()).start().repeat(1000, function () {
                var second = time - Math.round(this.elapsedTime / 1000);
                fn(second);
            });

        },
        end: function (fn) {
            this.status == 'loader' && (this.status = 'loaded') && (function () {
                this.turning_angle = Math.ceil(((this.animate.shifting || 0) - this.turning_angle) / (Math.PI * 2)) * Math.PI * 2 + this.turning_angle;
                this.turning_point = this._get_point_angle(this.turning_angle);
                this.a_rate = 1 / (1 + C.distance(this.points.c, this.points.b) / C.distance(this.turning_point, this.points.b));
                this.b_rate = 1 / (1 + C.distance(this.turning_point, this.points.a) / (this._get_I() * this.radial_radius));
                this.end_timer = new C.Timer();
                this.duration = Math.round((C.distance(this.turning_point, this.points.b) + C.distance(this.points.b, this.points.c)) * (1.70158 + 3) * 1000 / (this.radial_radius * this.animate.velocity));
                this._fn = fn;
            }.bind(this))();
        }
    });


    function CanvasLoader() {
        this.loader = $('.canvas-dashboard');
        this.dashboard = $('.user-fields-dashboard');
        this._init = function () {
            var stage = new C.Stage(),
                width = stage.getWidth(),
                height = stage.getHeight(),
                radius = Math.min(width, height) / 2 * .9,
                tube = 3 * radius / 40,
                cirque = new C.Cirque(radius, tube, [width / 2, height / 2], Math.PI * 2);

            this.circle = new Ball(cirque.radius, tube * .5, cirque.position),
                this.renderer = new C.Renderer(stage);


            cirque.color = 0xf6f6f6;
            this.circle.shadow.enabled = true;
            this.circle.shadow.blur = 12;
            this.circle.color = 0x439df8;
            stage.add(cirque).add(this.circle);

            this.renderer.on('update', function (event, interval, elapsedTime) {
            })
        }

        this.init = function () {
            if (!this.renderer) {
                if (!$("canvas").is(":visible")) {
                    this.dashboard.addClass("loader");
                    this._init();
                    this.dashboard.removeClass("loader");
                }
            }
        }

        this.play = function () {
            this.init();
            this.dashboard.addClass("loader");
            this.loader.removeClass("pause");
            this.renderer.run();
            if (this.circle.status == 'loader') {
                return;
            }
            this.circle.play();
        }

        this.pause = function () {
            if (this.circle && this.circle.status == 'loader') {
                this.circle.status = 'none';
            }
            this.loader.addClass("pause");
        }

        this.setTag = function (tag) {
            if (this.circle && this.circle.status == 'timer' || this.circle.status == 'timer+') {
                return;
            }
            this.loader.find(".label").html(function () {
                switch (tag) {
                    case 'query':
                        return '任务提交成功';
                    case 'logined':
                        return '登录完成，等待授权';
                    case 'data':
                        return '正在查询中...';
                    case 'success':
                        return '认证完成';
                }
                return '';
            });
            this.loader.find(".loader>*").not("canvas").detach();
            if (this.text_timeout_timer) {
                clearTimeout(this.text_timeout_timer);
                delete this.text_timeout_timer;
            }
            if (this.text_interval_timer) {
                clearTimeout(this.text_interval_timer);
                delete this.text_interval_timer;
            }
            if (tag == 'query') {
                this.loader.find(".loader").append($("<div>", {'class': 'content'})
                    .append($("<div>", {'class': 'message'}).html('此时退出不影响查询结果')));
                this.text_timeout_timer = setTimeout(function () {
                    if (this.circle.status == 'loader') {
                        this.loader.find(".loader .message").html("当前查询较慢，可能还需要几秒")
                    }
                    delete this.text_timeout_timer;
                }.bind(this), 30 * 1000);
            } else if (tag == 'data') {
                var texts = ['认证时间较长，请耐心等待', '您可能需要等待几分钟'], i = 0;
                this.loader.find(".loader").append($("<div>", {'class': 'content'})
                    .append($("<div>", {'class': 'message'}).html(texts[0])));
                this.text_interval_timer = setInterval(function () {
                    if (this.circle.status == 'loader') {
                        this.loader.find(".loader .message").html(texts[(++i) % texts.length]);
                    }
                    delete this.text_interval_timer;
                }.bind(this), 10 * 1000);
            }
        }

        this.setText = function (text) {
            this.loader.find(".label").html(text);
        }

        this.timing = function (duration, fn) {
            this.init();
            this.dashboard.addClass("loader");
            this.loader.removeClass("pause");
            var self = this;
            this.renderer.run();
            this.loader.find(".loader >*").not("canvas").detach();
            this.loader.find(".loader").append($("<div>", {'class': 'content'})
                .append($("<div>", {'class': 'message'}).html('您可能需等待'))
                .append($("<div>", {'class': 'sec'})));
            this.circle.timing(duration, function (second) {
                if (second == 0) {
                    fn && fn.call(self);
                } else {
                    if (second == 1) {
                        setTimeout(function () {
                            self.loader.find('.content').addClass('in');
                        }, 800);
                    }
                    self.loader.find('.sec').html(second);
                }
            });
        }
        this.end = function (fn) {
            this.circle.end(function () {
                this.renderer.pause();
                fn && fn();
            }.bind(this));
            this.loader.find('.content').addClass('in');
        }
        this.stop = function () {
            this.renderer.pause();
            this.circle.status = 'none';
            this.dashboard.removeClass("loader");
        }
    }

    function CSSLoader() {
        this.dashboard = $('.user-fields-dashboard');
        this.init=function () {
            this.dashboard.addClass("loader");
            $('.canvas-dashboard').hide()
            $('.css-loader-dash').show();
            $('.css-shadow').show()

        }
        this.play=function(){
            this.init()
        }
        this.pause=function(){
            this.dashboard.removeClass("loader");
            $('.css-loader-dash').hide();
            $('.css-shadow').hide()
        }
        this.setTag=function(){
            // this.dashboard.removeClass("loader");
            // $('.css-loader-dash').hide();
            // $('.css-shadow').show()
        };
        this.setText=function(){
            // this.dashboard.removeClass("loader");
            // $('.css-loader-dash').hide();
            // $('.css-shadow').show()
        }
        this.end=function (fn) {
            $("#load").html("认证完成，即将为您跳转")
            fn && fn();
        }
        this.stop=function(){
            this.dashboard.removeClass("loader");
            $('.css-loader-dash').hide();
            $('.css-shadow').hide()
        }
        this.timing=function(duration,fn){
            var self = this;
            fn && fn.call(self)
        }
    }

    var taskId = $('#form').attr('data-taskId')||"";
    var nextStepFlag = 0;
    var queryStatus='init';
    var orderSn=$('#form').attr('data-ordersn');
    var redirectUrl=$('#form').attr('data-redirectUrl');
    var cityName=$('.gjj-center-pannel h1').text();
    var orderStatus=$('#form').attr('data-status')

    function listen_ws_job(params, success, failed) {
        var url
        if (window.location.protocol == 'http:'){
            url= 'ws://' + window.location.host + window.location.pathname + 'ws?taskId=' + taskId+'&orderSn='+orderSn+'&cityName='+$('.gjj-center-pannel h1').text()+'&needGeneral='+needGeneral;

        }else{
            url= 'wss://' + window.location.host + window.location.pathname + 'ws?taskId=' + taskId+'&orderSn='+orderSn+'&cityName='+$('.gjj-center-pannel h1').text()+'&needGeneral='+needGeneral;
        }

        var ws = new WebSocket(url);

        var timer=setTimeout(function () {
            failed({msg:"任务超时"})
        },1000*60*10)

        ws.onmessage = function (msg) {
            if (msg.data == "ok") {
                // console.log("等待查询结果ws连接成功");
                if(needGeneral){
                    var generalParams={
                        ID:searchObject.ID,
                        name:searchObject.name,
                        phone:searchObject.phone,
                        taskId:taskId
                    }
                    ws.send(JSON.stringify(generalParams))
                }
            } else {
                clearTimeout(timer)
                msg = JSON.parse(msg.data);
                if (msg.errcode == 0) {
                    if(msg.data.code!=1){
                        ws.close()
                    }
                    success(msg.data)
                } else {
                    ws.close()
                    failed(msg.data)
                }
            }
        }


    }

    function listen_loop_job(params, success, failed) {
        params={taskId:taskId,orderSn:orderSn,cityName:$('.gjj-center-pannel h1').text()}
        return (new Scheduler({timeout: 10 * 60 * 1000})).begin(function () {
                var self = this;
                $.ajax({
                    type: "POST",
                    url: window.location.pathname + 'ws/getJob',
                    data: params,
                    success: function (data) {
                        // console.log(data)
                        msg = JSON.parse(data);
                        if (msg.errcode == 0) {
                            if (msg.data.code == 2) {
                                self.update();
                            } else {
                                self.end(msg)
                            }
                        } else {
                            self.end(msg)
                        }
                    },
                    error: function (xhr, type) {
                        self.update()
                    }
                })
            }, function (msg) {
                if (msg.errcode == 0) {
                    success(msg.data)
                } else {
                    failed(msg.data)
                }
            }, function (error) {
                var data = {msg: '任务超时'}
                failed(data)
            }
        )
    }

    function gjjJobV2() {
        var self = this, loader = new CanvasLoader();
        var userAgent = navigator.userAgent;
        var index = userAgent.indexOf("Android")
        if(index >= 0){
            var androidVersion = parseFloat(userAgent.slice(index+8));
            if(androidVersion<4.4){
                loader = new CSSLoader();
            }
        }
        this.config = $("#carrier-config").data();
        window.loader = loader;
        this.loader = loader;
        this.expiration_time = 0;
    }

    $.fn.bindPhoneActionEvent = $.fn.bindPhoneActionEvent || function (){
        return this.find(".tab-control .tab-nav label").off('click').on("click", function () {
            var $ul = $('#tab-content ul');
            var self = $(this);
            if (self.hasClass("active") || self.closest(".tab-nav").hasClass('disabled')) {
                return
            }
            var index = self.index();
            var o = self.closest(".tab-nav").find(".active").removeClass("active");
            self.addClass("active");
            $ul.css('display', 'none').removeClass("active");
            $ul.eq(index).css('display', 'block').addClass('active');
            $('#submit').submitFields($('.active .input-option,.checkbox .input-option')).off('click').on('click', function () {
                if ($('#main-tpl').hasClass('loading')) {
                    $('#main-tpl').removeClass('loading');
                    $(document).trigger('mutation')
                } else {
                    var params = $(".active input,select").valMap();
                    if(checkLoginParams(params)){
                        queryStatus='query';
                        query.commitJob(params)
                    }
                }
            });

        });
    }



    gjjJobV2.prototype = {
        commitJob: function (params) {
            var self = this;
            loader.play();
            loader.setTag('data')
            // params = {params: JSON.stringify(params)}
            doJsonAjax(
                window.location.pathname + 'ajax/commitParams',
                params,
                function (data) {
                    taskId = data.data.taskId;if (!!window.WebSocket && window.WebSocket.prototype.send) {
                        listen_ws_job({}, function (data) {
                            if (data.code == 1) {
                                switch (data.type) {
                                    case 'radio':
                                        self.getNextSel(data)
                                        break;
                                    case 'text':
                                        nextStepFlag = 1
                                        self.getNextInput(data)
                                        break;
                                    case '110':
                                        loader.setTag("query");
                                        break;
                                }
                            } else {
                                self.success()
                            }
                        }, function (data) {
                            $.prompt(data.msg);
                            self.failed();
                        })}else{
                        listen_loop_job({}, function (data) {
                            if (data.code == 1) {
                                switch (data.type) {
                                    case 'radio':
                                        self.getNextSel(data)
                                        break;
                                    case 'text':
                                        nextStepFlag = 1
                                        self.getNextInput(data)
                                        break;
                                }
                            } else {
                                self.success()
                            }
                        }, function (data) {
                            $.prompt(data.msg);
                            self.failed();
                        })
                    }

                },
                function (code) {
                    $.prompt("提交任务出错");
                }
                )
        },
        success: function () {
            // console.log("最终认证成功")
            loader.end(function () {
                var redirectParams=(redirectUrl.indexOf('?')>-1?'&':'?')+'status=success&orderSn='+orderSn+'&timestamp='+new Date().getTime();
                window.location.href=redirectUrl+redirectParams;
            })
        },
        failed: function () {
            // console.log("查询出错");
            loader.stop();
            // $('#main-tpl').removeClass('loading');
            if ($('.selectMenu').length > 0) {
                $('.selectMenu').remove()
            }
            $('#tab-content  input[name="code"]').val('');
            $('#tab-content  input[name="phoneCode"]').val('');
            if (nextStepFlag) {
                var url = window.location.pathname + '/getCity';
                var params = {cid: $('#form').attr('data-cid')}
                doAjax("GET", url, params)
            } else {
                $(document).trigger("setup_task");
            }
        },
        getNextSel: function (data) {
            var self = this
            loader.pause()
            if ($('.selectMenu').length > 0) {
                $('.selectMenu').remove()
            }
            // $('#main-tpl').removeClass('loading')
            $('#main-tpl').append(data.html);
            $('.selectMenu .selItem ').off('click').on('click', function (event) {
                var self = $(this);
                if (self.find(".checked").length > 0) {
                    return
                }
                var index = self.index();
                $('.selectMenu .selItem ').find(".checkbox").removeClass("checked");
                $('.selectMenu .selItem ').eq(index).find(".checkbox").addClass('checked');
            })
            $('.selectMenu .btn ').off('click').on('click', function (event) {
                // if ($('.selectMenu ').hasClass('loading')) {
                //     return
                // }
                // $('.selectMenu ').addClass('loading');
                $('.selectMenu .selItem ').off('click')
                var params = {
                    args: {menu: $('.selectMenu .selItem ').find(".checked").attr('data-key')},
                    taskId: taskId
                };
                self.commitJob(params)
                $('.selectMenu ').remove();
                $('.note-field').remove()
            })
        },
        getNextInput: function (data) {
            loader.stop();
            $('#form').html(data.html);
            $('#submit').attr('disabled', 'disabled')
            $('.phoneCodeBtn').lock($('.phoneCodeBtn').data('cd'))
            $('.phoneCodeBtn').off('click').on('click',function (event) {
                var self=$(this)
                self.lock(self.data('cd'));
                var params = {taskId: taskId, type: 'phone_code'}
                $.ajax({
                    type: "POST",
                    url: window.location.pathname + 'ajax/getCode',
                    data: params,
                    success: function (data) {
                        if(data.code=="0"){
                            $.prompt("验证码发送成功，请注意查收")
                        }else{
                            $.prompt("验证码发送失败，请一分钟后再试")
                        }
                        // self.unlock()
                    },
                    error: function (xhr, type) {
                        if (xhr == 500) {
                            $.prompt("程序员哥哥写错代码了！");
                        } else if (xhr == 404) {
                            $.prompt("接口文件不见了！");
                        } else if (xhr == 0) {
                            $.prompt("请确认设备已连接到网络！");
                        } else {
                            $.prompt("服务器好像挂了！");
                        }
                    }
                })
            })

            // $('#tab-content .active input').off('input change').on('input change', function () {
            //     checkParams() ? $('#submit').removeAttr('disabled') : $('#submit').attr('disabled', 'disabled')
            // });

        }

    }


    $(document).on('setup_task', function () {
        nextStepFlag = 0;
        queryStatus='init';
        var url = window.location.pathname + 'ajax/createGjjTask';
        var params = {cid: $('#form').attr('data-cid'),orderSn:orderSn,appKey:appKey,userId:userId};
        $.ajax({
            type: "POST",
            url: url,
            data: params,
            success: function (data) {
                taskId = data.data.taskId;
                var c = $("input[name]").filter(function () {
                    return $(this).attr("name") == 'args[code]'
                })
                if(c.length>0){
                    getCode()
                }
                $('.captcha-wrapper').off('click').on('click', function () {
                    if($('.captcha-wrapper').hasClass('loading')){
                        return
                    }
                    $('.captcha-wrapper').removeClass('failed').addClass('loading');

                    getCode()
                })
            },
            error: function (xhr, type) {
                if (xhr == 500) {
                    $.prompt("程序员哥哥写错代码了！");
                } else if (xhr == 404) {
                    $.prompt("接口文件不见了！");
                } else if (xhr == 0) {
                    $.prompt("请确认设备已连接到网络！");
                } else {
                    $.prompt("服务器好像挂了！");
                }
            }
        })
    }).on('mutation', function (event) {

        var query = new gjjJobV2();
        window.query = query;
        switch (orderStatus){
            case "query":
                loader.play();
                loader.setTag('query')
                if (!!window.WebSocket && window.WebSocket.prototype.send) {
                    listen_ws_job({}, function (data) {
                        query.success()
                    }, function (data) {
                        $.prompt(data.msg);
                        query.failed();
                    })}else{
                    listen_loop_job({}, function (data) {

                        query.success()

                    }, function (data) {
                        $.prompt(data.msg);
                        query.failed();
                    })
                }
                break;
            case "success":
                loader.play();
                loader.setTag('data');
                query.success()
                break;
            default:
                if($("#tab-content").length>0){
                    $(document).trigger('setup_task');
                }
                break;
        }

        $(document).bindPhoneActionEvent();
        $('#submit').submitFields($('.active .input-option,.checkbox .input-option ')).off('click').on('click', function () {
            if ($('#main-tpl').hasClass('loading')) {
                $('#main-tpl').removeClass('loading');
                $(document).trigger('mutation')
            } else {
                var params = $(".active input,select").valMap();
                if(checkLoginParams(params)){
                    queryStatus='query';
                    query.commitJob(params)
                }
            }
        });

        $('.gjj-center-pannel').off('click').on('click', function (event) {
            if(queryStatus=='query'){
                return
            }
            if ($(' #switcher-tpl').length > 0) {
                $(' #main-tpl').hide();
                $('.gjj-list-pannel').show();
                $('.gjj-filter-list-pannel').hide();
                $(' #switcher-tpl').show();
                searchEvent()
            } else {
                $("section.gjj-center-pannel h1").addClass("loading")
                $.ajax({
                    type: 'GET',
                    url: window.location.pathname + 'cityList',
                    success: function (data) {
                        $("section.gjj-center-pannel h1").removeClass("loading")
                        $('body .container').append(data);
                        $(' #main-tpl').hide();
                        searchEvent();

                    },
                    error: function (xhr, type) {
                        if (xhr == 500) {
                            $.prompt("程序员哥哥写错代码了！");
                        } else if (xhr == 404) {
                            $.prompt("接口文件不见了！");
                        } else if (xhr == 0) {
                            $.prompt("请确认设备已连接到网络！");
                        } else {
                            $.prompt("服务器好像挂了！");
                        }
                    }
                })
            }


        });


        $('.header-notice').off('click').on('click', function () {
            $(' .dark-panel').addClass('show out')
        });
        $('.dark-panel').off('click').on('click', function () {
            $(this).removeClass('show out')
        });
        $('.left-link').off('click').on('click', function () {
            try {
                eval.call(window,$('script[type="text/jbscript"]').text());
            } catch(e) {
                console.log(e);
            }

        });



    }).trigger('mutation');
    function checkLoginParams(params){
        for(var item in params.args){
            if (item==='ID') {
                if(!/^\d{14}(\d{3})?[\dXx]$/.test(params.args[item])){
                    $.prompt('身份证格式不对');
                    return false
                }
            }
            if (item==='phone') {
                if(!/^1\d{10}$/.test(params.args[item])){
                    $.prompt('手机格式不正确');
                    return false
                }
            }
            if (item==="Email"||item==="email") {
                if (!/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(params.args[item])) {
                    $.prompt('邮箱格式不正确');
                    return false
                }
            }
        }
        return true

    }
    function searchEvent() {
        $('.gjj-list-pannel h5 ').off('click').on('click', function () {
            var self = $(this);
            if (self.hasClass('open')) {
                self.removeClass('open')
            } else {
                self.addClass("open");
            }
        });
        $('.gjj-list-pannel ul li ul li').off('click').on('click', function (e) {
            var url = window.location.pathname + '/getCity';
            var params = {cid: $(this).attr('data-id')}
            doAjax("GET", url, params)
        })
        $('.search-bar input').off('input change').on('input change', function (e) {


            var searchWord = $('.search-bar input').val().replace(/'|\s/, "");
            if(searchWord==""){
                $('.gjj-filter-list-pannel').hide()
                $('.gjj-list-pannel').show();
                return
            }
            var list = $('.gjj-list-pannel ul li ul li');
            $('.gjj-list-pannel').hide();
            var backHtml = ''
            for (var i = 0; i < list.length; i++) {
                var item = list[i].innerText;
                if (item.indexOf(searchWord) > -1 || pinyin.getFullChars(item).toLowerCase().indexOf(searchWord) > -1 || pinyin.getCamelChars(item).toLowerCase().indexOf(searchWord) > -1) {
                    backHtml += list[i].outerHTML
                }
            }
            $('.gjj-filter-list-pannel ul').html(backHtml);
            $('.gjj-filter-list-pannel').show();
            $('.gjj-filter-list-pannel ul li').off('click').on('click', function () {
                var url = window.location.pathname + '/getCity';
                var params = {cid: $(this).attr('data-id')}
                doAjax("GET", url, params)

            })
        })
    }

    function checkParams() {
        var checkItem = $('#tab-content .active input');
        if(!$('#check')[0].checked||checkItem.length==0){
            return false
        };

        for (var i = 0; i < checkItem.length; i++) {
            if (checkItem[i].value.length == 0) {
                return false
            }
        }
        return true
    }


    function getCode() {
        getImgJsonAjax(
            window.location.pathname + 'ajax/getCode',
            {taskId: taskId, type: 'code'},
            function (data) {
                if(data.code==0){
                    addImg(data)
                }else{
                    $('.captcha-wrapper').removeClass("loading").addClass('failed')
                }
            },function (code) {
                $('.captcha-wrapper').removeClass("loading").addClass('failed')
            }
        )
    }


    function addImg(data) {
        $('.captcha-wrapper').removeClass('loading')
        var item = $('.code img');
        for (var i = 0; i < item.length; i++) {
            item[i].src = 'data:image/png;base64,' + data.data.img;
            $('.captcha-wrapper').removeClass('failed')
        }
    }


    function doAjax(method, url, params) {
        $.ajax({
            type: method,
            url: url,
            data: params,
            success: function (data) {
                rewiteUrl(data.cid)
                $('#form').html(data.html);
                $('#form').attr('data-cid', data.cid)
                $('.gjj-center-pannel h1').html(data.cityName);
                $('#switcher-tpl').hide()
                $('#main-tpl').show();
                if(data.dark){
                    $('.dark-panel').remove()
                    $('#main-tpl').append(data.dark)
                }
                if(data.tip){
                    $('.forgot-pwd .left-link').html(data.tip)
                }else{
                    $('.forgot-pwd .left-link').html("")
                }
                if(data.func){
                    $('#diaFunc').html(data.func)
                }
                $('#submit').attr('disabled', 'disabled')
                // console.log('test')
                if (data.code == 0) {
                    $(document).trigger('mutation');
                }


            },
            error: function (xhr, type) {
                if (xhr == 500) {
                    $.prompt("程序员哥哥写错代码了！");
                } else if (xhr == 404) {
                    $.prompt("接口文件不见了！");
                } else if (xhr == 0) {
                    $.prompt("请确认设备已连接到网络！");
                } else {
                    $.prompt("服务器好像挂了！");
                }
            }
        })
    }



});
