$(function () {

    function searchToObject() {
        var pairs = window.location.search.substring(1).split("&"),
            obj = {},
            pair,
            i;
        for (i in pairs) {
            if (pairs[i] === "") continue;
            pair = pairs[i].split("=");
            obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
        }
        return obj;
    }

    var searchObject = searchToObject();
    var needGeneral = 0;
    var appKey = searchObject.appKey;
    var userId = searchObject.userId || "";
    var selectCity = searchObject.selectCity || 0;
    if (searchObject.hasOwnProperty("ID") && searchObject.hasOwnProperty("name") && searchObject.hasOwnProperty("phone")) {
        needGeneral = 1;
    }

    edit()

    function edit() {
        if (!($(".tab-nav").length)) {
            var textcontent = $("#tab-content label").text();
            $("#form").prepend('<div class="tab-control"><label>请以' + textcontent  + '登录社保账户</label></div>');
        }

        if ($(".header-notice").length) {
            $(".tab-helppage").css('display', 'block');
            new Dialog({
                title: "不知道怎么查?",
                html: '<div class="content"><div class="content">' + $('.helpcontent')[0].innerHTML + '</div></div>',
            }).model({alert: false});
        }

        $(".ui-overlay").off('click').on("click", function () {
            $(".dialog").removeClass('out');
            $(".ui-overlay").removeClass('out');
        })

        $(".tab-helppage").on("click", function () {
            $(".dialog").addClass('out');
            $(".ui-overlay").addClass('out');
        })
    }


    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);
    }


    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 = $("#form").attr("city-name");
    var orderStatus = $("#form").attr("data-status");
    var cityId = $("#tab-content .active").data('cid')

    function loading() {
        $("#form").css('display','none');
        $(".canvas-dashboard").css('display','block');
        $(".canvas-dashboard .loader img")[0].src="/gjj/css/img/zqq1.gif";
        $("button").addClass('loading');
        $(".footer").css('display', 'none');
    }

    function refroze() {
        $("#form").css('display','block');
        $(".canvas-dashboard").css('display','none');
        $(".canvas-dashboard .loader img")[0].src='';
        $("button").removeClass('loading');
        $(".footer").css('display', 'block');
    }


    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=" + cityname + "&needGeneral=" + needGeneral + "&appKey=" + appKey;
        } else {
            url = "wss://" + window.location.host + window.location.pathname + "ws?taskId=" + taskId + "&orderSn=" + orderSn + "&cityName=" + cityname + "&needGeneral=" + needGeneral + "&appKey=" + appKey;
        }

        var ws = new WebSocket(url);
        var timer = setTimeout(function () {
            failed({msg: "任务超时"});
        }, 1000 * 60 * 10);
        ws.onmessage = function (msg) {
            if (msg.data == "ok") {
                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: cityname, appKey: appKey};
        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) {
                        var 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() {
    }

    gjjJobV2.prototype = {
        commitJob: function (params) {
            var self = this;
            loading();
            // params = {params: JSON.stringify(params),cid: cityId,orderSn:orderSn,appKey:appKey,userId:userId,taskId:taskId};
            params = {params: JSON.stringify(params),cid: $("#form").attr("data-cid"),orderSn:orderSn,appKey:appKey,userId:userId,taskId:taskId};

            var url = window.location.pathname + "ajax/commitParams";
            $.ajax({
                type: "POST",
                url: url,
                data: params,
                success: function (data) {
                    if (data.code != 0) {
                        $.prompt(data.msg);
                        self.failed();
                        return;
                    }
                    taskId = data.data.taskId;
                    if (!!window.WebSocket && window.WebSocket.prototype.send) {
                        listen_ws_job({}, function (data) {
                            if (data.code == 1) {
                                switch (data.type) {
                                    case "text":
                                        nextStepFlag = 1;
                                        self.getNextInput(data);
                                        break;
                                    case "110":
                                        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 "text":
                                        nextStepFlag = 1;
                                        self.getNextInput(data);
                                        break;
                                    case "110":
                                        loader.setTag("query");
                                        break;
                                }
                            } else {
                                self.success();
                            }
                        }, function (data) {
                            $.prompt(data.msg);
                            self.failed();
                        });
                    }
                },
                error: function (xhr, type) {
                    if (xhr == 500) {
                        $.prompt("程序员哥哥写错代码了！");
                    } else if (xhr == 404) {
                        $.prompt("接口文件不见了！");
                    } else if (xhr == 0) {
                        $.prompt("请确认设备已连接到网络！");
                    } else {
                        $.prompt("服务器好像挂了！");
                    }

                }
            });
        },
        success: function () {
            if (redirectUrl.length > 11 && redirectUrl.substr(0, 11) == "javascript:") {
                $.ajax({
                    type: "POST",
                    url: window.location.pathname + "ajax/redirect",
                    data: {callback: redirectUrl},
                    success: function (data) {
                        window.location.href = redirectUrl;
                    },
                    error: function (xhr, type) {
                        window.location.href = redirectUrl;
                    }
                });
            } else {
                $("#form").attr("data-status", "success")
                var redirectParams = (redirectUrl.indexOf("?") > -1 ? "&" : "?") + "status=success&orderSn=" + orderSn + "&timestamp=" + new Date().getTime();
                if (userId.length > 0) {
                    redirectParams += "&userId=" + userId
                }
                $.ajax({
                    type: "POST",
                    url: window.location.pathname + "ajax/redirect",
                    data: {callback: redirectUrl + redirectParams},
                    success: function (data) {
                        window.location.href = redirectUrl + redirectParams;
                    },
                    error: function (xhr, type) {
                        window.location.href = redirectUrl + redirectParams;
                    }
                });
            }
        },
        failed: function () {
            refroze();
            $("#tab-content  input[name=\"code\"]").val("");
            $("#tab-content  input[name=\"phoneCode\"]").val("");
            $("#submit").submitFields(".active .input-option,.checkbox .input-option");
            if (nextStepFlag) {
                var url = window.location.pathname + "/getCity";
                var params = {cid: cityId, appKey: appKey};
                doAjax("GET", url, params);
            } else {
                $(document).trigger("setup_task");
            }
        },
        getNextInput: function (data) {
            refroze();
            $("#form").html(data.html);
            $("#submit").attr("disabled", "disabled");
            $(".phoneCodeBtn").lock($(".phoneCodeBtn").data("cd"));
            $(".phoneCodeBtn").parent('.input-wrapper').css('margin-top', '100px').css('margin-bottom', '50px');
            $(".phoneCodeBtn").parent('.input-wrapper').find('label').css('display', 'none')
            $(".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("服务器好像挂了！");
                        }
                    }
                });
            });
            if (checkImgCode()) {
                getCode("code");
            }
            $(".captcha-wrapper").off("click").on("click", function () {
                getCode("code");
            });
            $("#tab-content .active input").off("input change").on("input change", function () {
                checkParams() ? $("#submit").removeAttr("disabled") : $("#submit").attr("disabled", "disabled");
            });

        },
        refreshJob: function (params) {
            var self = this;
            queryStatus = "query";
            var url = window.location.pathname + "ajax/refresh";
            $.ajax({
                type: "POST",
                url: url,
                data: params,
                success: function (data) {
                    if (data.code != 0) {
                        $.prompt(data.msg);
                        self.refreshEnd("failed", "refresh");
                        return;
                    }
                    taskId = data.data.taskId;
                    if (!!window.WebSocket && window.WebSocket.prototype.send) {
                        listen_ws_job({}, function (data) {
                            if (data.code == 1) {
                                if (data.type == "110") {
                                    loader.setTag("query");
                                } else {
                                    $.prompt("任务刷新失败");
                                    self.refreshEnd("failed", "refresh");
                                }
                            } else {
                                self.refreshEnd("success", "refresh");
                            }
                        }, function (data) {
                            $.prompt(data.msg);
                            self.refreshEnd("failed", "refresh");
                        });
                    } else {
                        listen_loop_job({}, function (data) {
                            if (data.code == 1) {
                                self.refreshEnd("failed", "refresh");
                            } else {
                                self.refreshEnd("success", "refresh");
                            }
                        }, function (data) {
                            $.prompt(data.msg);
                            self.refreshEnd("failed", "refresh");
                        });
                    }
                },
                error: function (xhr, type) {
                    if (xhr == 500) {
                        $.prompt("程序员哥哥写错代码了！");
                    } else if (xhr == 404) {
                        $.prompt("接口文件不见了！");
                    } else if (xhr == 0) {
                        $.prompt("请确认设备已连接到网络！");
                    } else {
                        $.prompt("服务器好像挂了！");
                    }

                }
            });
        },
        refreshEnd: function (status, type, msg) {
            var redirectParams = (redirectUrl.indexOf("?") > -1 ? "&" : "?") + "status=" + status + "&orderSn=" + orderSn + "&timestamp=" + new Date().getTime();
            if (userId.length > 0) {
                redirectParams += "&userId=" + userId
            }
            if (type == "refresh") {
                redirectParams += "&type=refresh";
            }
            $.ajax({
                type: "POST",
                url: window.location.pathname + "ajax/redirect",
                data: {callback: redirectUrl + redirectParams},
                success: function (data) {
                    window.location.href = redirectUrl + redirectParams;
                },
                error: function (xhr, type) {
                    window.location.href = redirectUrl + redirectParams;
                }
            });

        }
    };


    $(document).on("setup_task", function () {
        nextStepFlag = 0;
        queryStatus = "init";
        var url = window.location.pathname + "ajax/createTask";
        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;
                if (checkImgCode()) {

                    if (orderStatus === "refresh") {
                        new Dialog({
                            title: "验证码",
                            html: "<div class=\"content\"><div class=\"refresh-code loading\"><img src=\"\"></div><label>看不清？点击图片更换验证码</label><div class=\"input\"><input name=\"code\" placeholder=\"请输入图示验证码\"  data-label=\"验证码\" id=\"inputRefresh\"></div></div>\n",
                            buttons: [{
                                title: "立即刷新",
                                className: "btnRefresh",
                                tap: function () {
                                    if ($("#inputRefresh").val() == "") {
                                        $.prompt("请输入验证码");
                                        return true;
                                    } else {
                                        var params = {
                                            code: $("#inputRefresh").val(),
                                            taskId: taskId,
                                            hasCode: true,
                                            orderSn: orderSn
                                        };
                                        query.refreshJob(params);
                                    }
                                }
                            }]
                        }).model({alert: true});
                        getCode("code", "refresh");
                        $(".refresh-code").off("click").on("click", function () {
                            if ($(".refresh-code").hasClass("loading")) {
                                return;
                            }
                            $(".refresh-code").removeClass("failed").addClass("loading");
                            getCode("code", "refresh");
                        });
                    } else {
                        getCode("code", "normal");
                        $(".captcha-wrapper").off("click").on("click", function () {
                            if ($(".captcha-wrapper").hasClass("loading")) {
                                return;
                            }
                            $(".captcha-wrapper").removeClass("failed").addClass("loading");
                            getCode("code", "normal");
                        });
                    }
                }

            },
            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":
                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":
                queryStatus = "query";
                query.success();
                break;
            case "refresh":
                queryStatus = "query";
                if (checkImgCode()) {
                    if ($("#tab-content").length > 0) {
                        $(document).trigger("setup_task");
                    }
                } else {
                    var params = {
                        hasCode: false,
                        orderSn: orderSn,
                        cid: cityId
                    };
                    query.refreshJob(params);
                }
                break;
            default:
                if ($("#tab-content").length > 0) {
                    $(document).trigger("setup_task");
                }
                break;
        }

        var $ul = $("#tab-content ul");
        $(".tab-control .tab-nav label").off("click").on("click", function () {
            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");
            if ($("#tab-content .active").data('cid') != cityId) {
                $("#tab-content .active .captcha-wrapper").removeClass('failed').addClass('loading')
                $(document).trigger("setup_task");

            }
        });

        $("#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 = $("ul.active input,ul.active select").valMap();
                if (checkLoginParams(params)) {
                    queryStatus = "query";
                    query.commitJob(params);
                }
            }
        });
        $(".header-notice").off("click").on("click", function () {
            $("#main-tpl").addClass("out");
            $(".helpPage").addClass("out");
        });
        $("#back").off("click").on("click", function () {
            $(".helpPage").removeClass("out");
            $("#main-tpl").removeClass("out");
        });


    }).trigger("mutation");

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

    }

    function checkParams() {
        var checkItem = $("#tab-content .active input");
        for (var i = 0; i < checkItem.length; i++) {
            if (checkItem[i].value.length == 0) {
                return false;
            }
        }
        return true;
    }


    function checkImgCode() {
        var paramsItem = $("#tab-content .active input");
        for (var i = 0; i < paramsItem.length; i++) {
            if (paramsItem[i].name == "code") {
                return true;
            }
        }
        return false;
    }

    function getCode(type, status) {
        var params = {taskId: taskId, type: type};
        $.ajax({
            type: "POST",
            url: window.location.pathname + "ajax/getCode",
            data: params,
            timeout: 1000 * 10,
            success: function (data) {
                if (status == "normal") {
                    if (data.code == 0) {
                        addImg(data);
                    } else {
                        $(".captcha-wrapper").removeClass("loading").addClass("failed");
                    }
                } else {
                    if (data.code == 0) {
                        $(".refresh-code img")[0].src = "data:image/png;base64," + data.data.img;
                        $(".refresh-code").removeClass("loading");
                    } else {
                        $(".refresh-code").removeClass("loading").addClass("failed");
                    }
                }


            },
            error: function (xhr, type) {
                if (status == "normal") {
                    $(".captcha-wrapper").removeClass("loading").addClass("failed");
                } else {
                    $(".refresh-code").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);
                $("#form").attr("city-name",data.cityName);
                $("#switcher-tpl").removeClass("out");
                $("#main-tpl").removeClass("out");
                if (data.dark) {
                    $(".helpPage .content").html(data.dark);
                }
                edit()
                $("#submit").attr("disabled", "disabled");
                if (data.code == 500) {
                    createTask(data.cid)
                }

                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("服务器好像挂了！");
                }
            }
        });
    }

    function createTask(cid) {

        var url = window.location.pathname + "ajax/createTask";
        var params = {cid: cid, orderSn: orderSn, appKey: appKey, userId: userId};
        $.ajax({
            type: "POST",
            url: url,
            data: params,
            success: function (data) {
                // console.log("createTask")

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

    }
});

function registersearchToObject() {
    var pairs = window.location.search.substring(1).split("&"),
        obj = {},
        pair,
        i;
    for ( i in pairs ) {
        if ( pairs[i] === "" ) continue;
        pair = pairs[i].split("=");
        obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
    }
    return obj;
}
var registersearchObject=registersearchToObject();
var registerappKey=registersearchObject.appKey||$("#form").attr("data-appKey")||"";
var registeruserId=registersearchObject.userId||"";
function sbregister() {
    var url = window.location.pathname + "ajax/sbregister";
    var params = {cid: $("#form").data('cid'),appKey:registerappKey,userId:registeruserId};
    $.ajax({
        type: "POST",
        url: url,
        data: params,
        success: function (data) {
            if (data.code != 0){
                $.prompt('访问失败,请稍后重试');
            }else{
                window.location.href = data.href;
            }
        },
        error: function (xhr, type) {
            if (xhr == 500) {
                $.prompt("程序员哥哥写错代码了！");
            } else if (xhr == 404) {
                $.prompt("接口文件不见了！");
            } else if (xhr == 0) {
                $.prompt("请确认设备已连接到网络！");
            } else {
                $.prompt("服务器好像挂了！");
            }
        }
    });
}
