//进入openid处理流程
$.authAjax({
    url: api+"marketing/weixin/openidProcess"
    // success: function () {
    //     $.showLoading('数据加载中');
    // }
});

//获取活动标题
$.authAjax({
    url: api+"marketing/weixin/getActivityTitle",
    success: function (res) {
        document.title = res;
    }
});

//页面结构加载完成后执行
$(function() {
    //判断活动是否过期
    if (!activityIsExpired()) {
        return false;
    }

    //获取并显示码对应的奖励，如果return false，就不继续向下执行
    if (!showReward()) {
        return false;
    }

    //绑定单击事件
    $("#receiveReward").on("click",function () {
        var img = $('#receiveReward').children("img");
        if (img.attr("src") == "images/gray_btn.png"){
            receiveReward();
        }
    });

    $(".b-close").on("click",function () {
        $.closePopup();
    });

    $("#explain_popup").on("click",function () {
        $('#explain').popup();
    });

    $("#register_button").on("click",function () {
        register();
    });

    //获取js-sdk签名
    createJsapiSignature(currentUrl);

    //config信息验证成功后会执行ready方法
    wx.ready(function() {
        getLocation(
            function (latitude,longitude) {
                scanRecord(latitude,longitude);
                localStorage.setItem('agreeLocation','true');
            },
            function () {
                scanRecord('0.0','0.0');
                localStorage.setItem('agreeLocation','false');
            }
        );
    });

    //config信息验证失败后会执行error方法
    wx.error(function(res){
        console.log(res);
        $.toast("获取凭据失败", "cancel");
    });

    $("#birthDate").datetimePicker({
        times: function () {
            return [];
        }
    });
});

//判断活动是否过期
function activityIsExpired(){
    var flag = true;
    $.authAjax({
        url: api+"marketing/weixin/activityIsExpired",
        async: false,
        success: function (res) {
            //活动未开始或已结束
            if (res.code != 0) {
                $('#prompt').text(res.msg);
                // $.hideLoading();
                flag = false;
            }
        }
    })
    return flag;
}

//获取并显示码对应的奖励
function showReward() {
    var flag = true;
    $.authAjax({
        url: api+"marketing/weixin/calculateReward",
        async: false,
        success: function (res) {
            $('#prompt').text(res.msg);
            $("#reward").text(res.data);
            //二维码失效
            if (res.code != 0) {
                $('#rewardBtn').attr("src","images/gray_btn.png");
                flag = false;
            } else {
                $('#unit').show();
                if (res.data == 0) {
                    $('#rewardBtn').attr("src","images/gray_btn.png");
                } else {
                    $('#rewardBtn').attr("src","images/btn.png");
                }
            }
            // $.hideLoading();
        }
    })
    return flag;
}


//记录活动（扫码）事件
function scanRecord(latitude,longitude) {
    // alert("记录扫码事件");
    $.authAjax({
        url: api+"marketing/weixin/scanRecord",
        type: "POST",
        data: {
            latitude: latitude,
            longitude:longitude,
        }
    })
}

//领取奖励，如果return false，就不继续向下执行
function receiveReward() {
    if (!userIsSubscribeApp()) {
        $("#mpQrcode").popup();
        return false;
    }

    if (!userIsAgreeLocation()) {
        $.alert("未能获取到位置信息，无法领取！请重新扫码参与活动");
        return false;
    }

    if (!userIsRegister()) {
        $("#register").popup();
        return false;
    }
    awardProcess();
}

//用户是否关注公众号
function userIsSubscribeApp() {
    var userIsSubscribeApp;
    $.authAjax({
        url : api+"marketing/weixin/userIsSubscribeApp",
        async: false,
        success: function (res) {
            userIsSubscribeApp = res.data;
            if (!userIsSubscribeApp) {
                //读取公众号二维码
                $('#mpQrcodeImg').attr("src",res.msg);
            }
        }
    })
    return userIsSubscribeApp;
}

//用户是否同意地理位置授权
function userIsAgreeLocation() {
    var agreeLocation = localStorage.getItem('agreeLocation');
    return agreeLocation == "true";
}

//用户是否注册（即含地理位置信息）
function userIsRegister() {
    var userIsRegister;

    $.authAjax({
        url : api+"marketing/weixin/userIsRegister",
        async: false,
        success: function (data) {
            userIsRegister = data;
        }
    })

    if (!userIsRegister) {
        //填入昵称和性别数据
        $.authAjax({
            url: api+"marketing/weixin/getWxUserInfo",
            success: function (res) {
                $('input[name="nickName"]').val(res.nickname);
                $('input[name="sex"][value="'+res.sex+'"]').prop('checked',true);
            }
        });
    }
    return userIsRegister;
}

//奖励处理流程
function awardProcess() {
    $.showLoading('奖励发放中');

    getLocation(
        function (latitude,longitude) {
            $.authAjax({
                url : api+"marketing/weixin/awardProcess",
                async: false,
                data: {
                    latitude: latitude,
                    longitude: longitude
                },
                success: function (res) {
                    $.hideLoading();
                    if (res.code == 0) {
                        $.toast(res.msg);
                        $('#rewardBtn').attr("src","images/gray_btn.png");
                        $("#receiveReward").unbind("click");
                    } else {
                        $.toast(res.msg, "cancel");
                    }
                },
                error: function (res) {
                    $.hideLoading();
                    $.toast("请求失败", "cancel");
                }
            })
        }
    );
}

//注册
function register() {
    var phone = $('input[name="phone"]').val();
    var birthDate = $('input[name="birthDate"]').val();
    var nickName = $('input[name="nickName"]').val();
    var sex = $('input[name="sex"]').val();

    if (phone == "") {
        $.toptip("手机号不能为空");
        return false;
    } else {
        var TEL_REGEXP = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/;
        if (!TEL_REGEXP.test(phone)) {
            $.toptip("手机号格式不正确");
            return false;
        }
    }

    if (birthDate == "") {
        $.toptip("生日不能为空");
        return false;
    }

    if (nickName == "") {
        $.toptip("昵称不能为空");
        return false;
    }

    if (sex == "") {
        $.toptip("性别不能为空");
        return false;
    }

    $.showLoading('数据提交中');

    getLocation(
        function (latitude,longitude) {
            var arr = $("#registerForm").serializeArray();
            arr.push({name:"latitude",value:latitude},{name:"longitude",value:longitude});
            var json = {};
            $.each(arr, function () {
                json[this.name] = this.value;
            });

            $.authAjax({
                url: api+"marketing/weixin/terminalUser",
                type: "PUT",
                data: {
                    json:JSON.stringify(json)
                },
                success: function (data) {
                    $.hideLoading();
                    if (data.code == 0) {
                        $.toast(data.msg);
                        $.closePopup();
                    }
                },
                error: function (data) {
                    $.hideLoading();
                    $.toast("请求失败", "cancel");
                }
            });

        }
    );
}
