$(function () {
    // var api = 'https://' + window.location.host;
    var api = 'https://mdev.zuihuibi.cn';
    var gitUrlParam = window.location.search;
    const param = {
        phone: '',
        deviceType: '',
        verificationCodeValider: false,
        customerId: '',
        name: '',
        babyGender: '',
        babyBirth: ''
    };
    var calendar = new LCalendar();
    calendar.init({
        'trigger': '#babyBirth', //标签id
        'type': 'date', //date 调出日期选择 datetime 调出日期时间选择 time 调出时间选择 ym 调出年月选择,
        'minDate': (new Date().getFullYear() - 19) + '-' + (new Date().getMonth() + 1) + '-' + (new Date().getDate() + 1), //最小日期
        'maxDate': (new Date().getFullYear()) + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() //最大日期
    });
    const REG_CODE = /^(1)\d{10}$/;
    const REG_NAME = /(^[\u4e00-\u9fa5]{1}[\u4e00-\u9fa5\.·。]{0,48}[\u4e00-\u9fa5]{1}$)|(^[a-zA-Z]{1}[a-zA-Z\s]{0,48}[a-zA-Z]{1}$)/;
    // $("#phone,#name,#code").blur(function () {
    //     window.scrollTo(0, 0);
    // })
    function getToken() {
        $.ajax({
            type: "POST",
            url: api + '/api/authorize/obtainToken',
            contentType: "application/json",
            data: JSON.stringify({
                ticket: 'job'
            }),
            async: false,
            success: function (res) {
                token = res.data.token
            }
        })
        return token;
    }

    var token = getToken();

    function checkDeviceType() {
        if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
            if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
                deviceType = '3';
            } else {
                deviceType = '2';
            }
        } else {
            deviceType = '1';
        }
        return deviceType;
    }

    var deviceType = checkDeviceType();
    param.deviceType = deviceType;

    sendPhone()
    //发送验证码
    function sendPhone() {
        $("#codeBtn").click(function () {
            if ($('#codeBtn').attr('disabled')) {
                layer.open({
                    content: '请勿重复发送！',
                    skin: 'msg',
                    time: 3
                });
                return;
            }
            if (!$("#phone").val()) {
                layer.open({
                    content: '手机号不能为空！',
                    skin: 'msg',
                    time: 3
                });
                return;
            }
            if (!REG_CODE.test($("#phone").val())) {
                layer.open({
                    content: '请输入正确的手机号码！',
                    skin: 'msg',
                    time: 3 //2秒后自动关闭
                });
                return;
            }
            $.ajax({
                type: "POST",
                url: api + '/api/verificationCode',
                contentType: "application/json",
                data: JSON.stringify({
                    type: 1,
                    mobileNo: $("#phone").val()
                }),
                headers: {
                    "X-Authorization": token
                },
                async: false,
                success: function (res) {
                    if (res.success) {
                        layer.open({
                            content: '发送成功',
                            skin: 'msg',
                            time: 3 //2秒后自动关闭
                        });
                        $('#codeBtn').attr('disabled', true);
                        var timeCount = 60;
                        var codeBtnHtml = '获取验证码';
                        var timer = setInterval(function () {
                            timeCount--;
                            codeBtnHtml = '(' + timeCount + ')s';
                            if (timeCount <= 0) {
                                codeBtnHtml = '重新获取';
                                clearInterval(timer);
                                timeCount = 60;
                                $('#codeBtn').removeAttr('disabled')
                            }
                            $("#codeBtn").html(codeBtnHtml)
                        }, 1000)
                    } else {
                        layer.open({
                            content: res.message,
                            skin: 'msg',
                            time: 3
                        })
                    }
                }
            })
        })
    }

    checkVerificationCode()
    //验证验证码
    function checkVerificationCode() {
        $("#code").keyup(function () {
            if ($("#code").val().length == 4) {
                const verificationCodeRequest = {
                    mobileNo: $("#phone").val(),
                    verificationCode: $("#code").val(),
                }
                if ($("#phone").val() && $("#code").val()) {
                    if (!REG_CODE.test($("#phone").val())) {
                        layer.open({
                            content: '请输入正确的手机号码！',
                            skin: 'msg',
                            time: 3 //2秒后自动关闭
                        });
                        return;
                    }
                    $.ajax({
                        url: api + '/api/checkVerificationCode',
                        type: 'POST',
                        contentType: "application/json",
                        data: JSON.stringify(verificationCodeRequest),
                        headers: {
                            "X-Authorization": token
                        },
                        success: function (res) {
                            param.verificationCodeValider = res.success;
                            if (!res.success) {
                                layer.open({
                                    content: res.message,
                                    skin: 'msg',
                                    time: 3
                                })
                            }
                            $.ajax({
                                url: api + '/api/login',
                                method: 'POST',
                                contentType: "application/json",
                                headers: {
                                    "X-Authorization": token
                                },
                                data: JSON.stringify({
                                    mobileNo: $("#phone").val()
                                }),
                                success: function (res) {
                                    param.customerId = res.data.customerId;
                                    var customerInfo = {
                                        customerId: res.data.customerId,
                                        customerName: res.data.customerName,
                                        customerNickName: res.data.customerNickName,
                                        headImgPath: res.data.headImgePath,
                                        cusLevel: res.data.cusLevel,
                                        cusLevelDesc: res.data.cusLevelDesc,
                                        referralLevel: res.data.referralLevel,
                                        referralLevelDesc: res.data.referralLevelDesc,
                                        totalFortune: res.data.totalFortune,
                                        mobileNo: $("#phone").val()
                                    };
                                    localStorage.setItem('customerInfo', JSON.stringify(customerInfo));
                                    if (!res.success) {
                                        layer.open({
                                            content: res.message,
                                            skin: 'msg',
                                            time: 3
                                        })
                                    }
                                }
                            })
                        }
                    })
                } else {
                    param.verificationCodeValider = false;
                }
            }

        })
    }

    // 宝宝性别
    babyGender();
    function babyGender() {
        $('.babyGender').click(function (event) {
            param.babyGender = event.currentTarget.dataset.attr;
            $(this).addClass("actived").siblings().removeClass("actived");
        })

    }

    // 设定宝宝出生日期的最大日期
    setMaxDate();
    function setMaxDate() {
        //得到当前时间
        var date_now = new Date();
        //得到当前年份
        var year = date_now.getFullYear();
        //得到当前月份
        //注：
        //  1：js中获取Date中的month时，会比当前月份少一个月，所以这里需要先加一
        //  2: 判断当前月份是否小于10，如果小于，那么就在月份的前面加一个 '0' ， 如果大于，就显示当前月份
        var month = date_now.getMonth() + 1 < 10 ? "0" + (date_now.getMonth() + 1) : (date_now.getMonth() + 1);
        //得到当前日子（多少号）
        var date = date_now.getDate() < 10 ? "0" + date_now.getDate() : date_now.getDate();
        //设置input标签的max属性
        $("#babyBirth").attr("max", year + "-" + month + "-" + date);
    }

    // 关闭弹窗
    closeDialog();
    function closeDialog() {
        $('#closeBtn').click(function () {
            $('.dialog').hide();
        })
    }

    goMeasurement();

    function goMeasurement() {
        $("#goMeasurement").click(function () {
            if (!REG_CODE.test($("#phone").val())) {
                layer.open({
                    content: '请输入正确的手机号码！',
                    skin: 'msg',
                    time: 3 //2秒后自动关闭
                });
                return;
            } else {
                param.phone = $("#phone").val()
            }
            if (!param.verificationCodeValider) {
                layer.open({
                    content: '请检查您的验证码是否正确',
                    skin: 'msg',
                    time: 3 //2秒后自动关闭
                });
                return;
            }
            if ($("#name").val() && !REG_NAME.test($("#name").val())) {
                layer.open({
                    content: '请检查您的姓名是否正确！',
                    skin: 'msg',
                    time: 3 //2秒后自动关闭
                });
                return;
            } else {
                param.name = $("#name").val()
            }
            $.ajax({
                url: api + '/api/login',
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify({
                    mobileNo: $("#phone").val()
                }),
                headers: {
                    "X-Authorization": token
                },
                success: function (res) {
                    if (res['success']) {
                        param.customerId = res.data.customerId;
                        var customerInfo = {
                            customerId: res.data.customerId,
                            customerName: res.data.customerName,
                            customerNickName: res.data.customerNickName,
                            headImgPath: res.data.headImgePath,
                            cusLevel: res.data.cusLevel,
                            cusLevelDesc: res.data.cusLevelDesc,
                            referralLevel: res.data.referralLevel,
                            referralLevelDesc: res.data.referralLevelDesc,
                            totalFortune: res.data.totalFortune,
                            mobileNo: $("#phone").val()
                        };
                        localStorage.setItem('customerInfo', JSON.stringify(customerInfo));
                        const data = {
                            mobileNo: param.phone,
                            name: param.name,
                            babyGender: param.babyGender,
                            babyBirth: $("#babyBirth").val(),
                            sourceChannel: '20203月妈咪宝贝线上推广',
                            mktCampaign: null,
                            mktTask: null,
                            sourcePlanName: null,
                            sourcePublishdate: null,
                            sourceArticle: null
                        }
                        $.ajax({
                            url: api + '/api/activity/momBabyPromotion',
                            type: 'POST',
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            headers: {
                                "X-Authorization": token
                            },
                            success: function (res) {
                                if (res['success']) {
                                    $('.dialog').show();
                                } else {
                                    layer.open({
                                        content: res.message,
                                        skin: 'msg',
                                        time: 3
                                    })
                                }
                            }
                        })
                    } else {
                        layer.open({
                            content: res.message,
                            skin: 'msg',
                            time: 3
                        })
                    }
                }
            })
        })
    }

    getWxConfig();
    //    获取微信分享配置
    function getWxConfig() {
        var url = location.href.split('#')[0];
        $.ajax({
            type: "POST",
            url: api + '/api/wxConfig',
            contentType: "application/json",
            data: JSON.stringify({
                url: url
            }),
            headers: {
                "X-Authorization": token
            },
            async: false,
            success: function (res) {
                wx.config({
                    debug: false,
                    appId: res.data.appId,
                    timestamp: res.data.timestamp,
                    nonceStr: res.data.nonceStr,
                    signature: res.data.signature,
                    jsApiList: res.data.jsApiList,
                    beta: true
                });
                // 默认的分享信息
                const shareData = {
                    title: '给孩子一份全面保障需要多少钱？',
                    link: window.location.href,
                    desc: '全能少儿险保费预测，速来测测看~',
                    imgUrl: 'https://ajb-images.oss-cn-shanghai-finance-1-pub.aliyuncs.com/images/menggo_head.png',
                    success: function () {

                    }
                };
                wx.ready(function () {
                    wx.onMenuShareAppMessage(shareData); // 分享微信
                    wx.onMenuShareTimeline(shareData); // 分享到朋友圈
                    wx.onMenuShareQQ(shareData); // 分享到QQ
                });
            }
        })
    }

});