$(function () {
    // var api = 'https://' + window.location.host;
    var api = 'https://mdev.zuihuibi.cn';
    var gitUrlParam = window.location.search;
    var shareCode = null;
    var activityEncryptData = null;
    var activityTaskInfoList = [];
    // 获取活动信息
    var activityInfo = null;
    const shareInfo = {
        shareCode: null,
        adultCount: 1,
        dayCount: 366,
        shareType: 1,
        customerId: null,
        planId: 424,
        os: checkOs(),
        channel: 0,
        url: window.location.href,
        isOrder: 0
    }
    const param = {
        phone: '',
        deviceType: '',
        verificationCodeValider: false,
        customerId: '',
        name: '',
    };
    const REG_CODE = /^(1)\d{10}$/;
    $("#phone,#name,#code").blur(function () {
        window.scrollTo(0, 0);
    })
    var deviceType = checkDeviceType();
    param.deviceType = deviceType;
    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 getQueryString(name) {
        const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        const r = decodeURIComponent(gitUrlParam).substr(1).match(reg);
        if (r != null) {
            return r[2];
        }
        return null;
    }

    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(type) {
        $("#loginCodeBtn").click(function () {
            if (!$("#loginPhone").val()) {
                layer.open({
                    content: '手机号不能为空',
                    skin: 'msg',
                    time: 3
                });
                return;
            }
            if (!REG_CODE.test($("#loginPhone").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: $("#loginPhone").val()
                }),
                headers: {
                    "X-Authorization": token
                },
                async: false,
                success: function (res) {
                    if (res.success) {
                        layer.open({
                            content: '发送成功',
                            skin: 'msg',
                            time: 3 //2秒后自动关闭
                        });
                        $('#loginCodeBtn').attr('disabled', true)
                        var timeCount = 60;
                        var codeBtnHtml = '获取验证码';
                        var timer = setInterval(function () {
                            timeCount--;
                            codeBtnHtml = '(' + timeCount + ')s';
                            if (timeCount <= 0) {
                                codeBtnHtml = '重新获取';
                                clearInterval(timer);
                                timeCount = 60;
                                $('#loginCodeBtn').removeAttr('disabled')
                            }
                            $("#loginCodeBtn").html(codeBtnHtml)
                        }, 1000)
                    } 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: `${api}/2019Double12/index.html`,
                    desc: '做任务100%得红包，最高888元~',
                    imgUrl: 'https://ajb-images.oss-cn-shanghai-finance-1-pub.aliyuncs.com/7/2019doubleeleven.jpg',
                    success: function () {

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

    // 自定义分享
    function wxShare() {
        var double12_customerInfo = localStorage.getItem('double12_customerInfo');
        var double12_customerInfo_id = JSON.parse(double12_customerInfo).customerId;
        shareInfo.customerId = double12_customerInfo_id;
        shareInfo.shareCode = Math.random().toString(36).substr(2, 15);
        shareInfo.url = `${api}/2019Double12/invitation.html?shareCode=${shareInfo.shareCode}`;
        // 默认的分享信息
        const shareData = {
            title: '银盾年终感恩回馈，现金红包抽不停',
            link: shareInfo.url,
            desc: '做任务100%得红包，最高888元~',
            imgUrl: 'https://ajb-images.oss-cn-shanghai-finance-1-pub.aliyuncs.com/7/2019doubleeleven.jpg',
            success: function () {
                $.ajax({
                    url: api + '/api/shareCallBack',
                    type: 'POST',
                    contentType: "application/json",
                    data: JSON.stringify(shareInfo),
                    headers: {
                        "X-Authorization": token
                    },
                    success: function (res) {
                        if (res['success']) {
                            $(".markbox").hide();
                            layer.open({
                                content: '分享成功',
                                skin: 'msg',
                                time: 3 //2秒后自动关闭
                            });

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

    // 登录 1.活动主页面登录分享 2.被分享者页面注册 3.抽奖
    function loginIn(type) {
        if (type === 2) {
            const NAME_REGEXP = /(^[\u4e00-\u9fa5]{1}[\u4e00-\u9fa5\.·()（）。]{0,48}[\u4e00-\u9fa5]{1}$)|(^[a-zA-Z]{1}[a-zA-Z\s]{0,48}[a-zA-Z]{1}$)/;
            if (!NAME_REGEXP.test($('#inviteeName').val()) || !$('#inviteeName').val()) {
                layer.open({
                    content: '请输入正确的姓名',
                    skin: 'msg',
                    time: 3 //2秒后自动关闭
                });
                return;
            }
        }
        if ($("#code").val().length == 4) {
            const verificationCodeRequest = {
                mobileNo: $("#loginPhone").val(),
                verificationCode: $("#code").val(),
            }
            if ($("#loginPhone").val() && $("#code").val()) {
                if (!REG_CODE.test($("#loginPhone").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: $("#loginPhone").val()
                            }),
                            success: function (res) {
                                param.customerId = res.data.customerId;
                                var double12_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: $("#loginPhone").val()
                                };
                                localStorage.setItem('double12_customerInfo', JSON.stringify(double12_customerInfo));
                                if (!res.success) {
                                    layer.open({
                                        content: res.message,
                                        skin: 'msg',
                                        time: 3
                                    })
                                } else {
                                    if (param.verificationCodeValider) {
                                        if (type === 1) {
                                            wxShare();
                                            $('.loginInBox').hide();
                                            $('.markbox').show();
                                            getActivityInfo();
                                        } else if (type === 2) {
                                            activityLogin($('#inviteeName').val(), $("#loginPhone").val(), {"hmsr": "double12"});
                                            $('#registerModal').show();
                                        } else if (type === 3) {
                                            $('.loginInBox').hide();
                                            getActivityInfo();
                                            window.scrollTo(0, document.body.scrollHeight)
                                        }
                                    }
                                }
                            }
                        })
                    }
                })
            } else {
                param.verificationCodeValider = false;
            }
        } else {
            layer.open({
                content: '请检查手机号和验证码是否正确',
                skin: 'msg',
                time: 3 //2秒后自动关闭
            });
            return;
        }
    }

    // 立即注册
    $('.registerBtn').bind("click", function () {
        loginIn(2)
    });
    // 登录分享
    $('.loginIn').bind("click", function () {
        loginIn(1)
    });


    function checkOs() {
        let os;
        const isWin = (navigator.platform === 'Win32') || (navigator.platform === 'Windows');
        const isMac = (navigator.platform === 'Mac68K') ||
            (navigator.platform === 'MacPPC') ||
            (navigator.platform === 'Macintosh') ||
            (navigator.platform === 'MacIntel');
        if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
            os = 1;
            return os; // 这是iOS平台下浏览器
        } else if (/android/i.test(navigator.userAgent)) {
            os = 2;
            return os; // 这是Android平台下浏览器
        } else if (isWin) {
            os = 3;
            return os; // 这是Window平台下浏览器
        } else if (isMac) {
            os = 4;
            return os; // 这是mac系统
        } else if (/Linux/i.test(navigator.userAgent)) {
            os = 5;
            return os; // 这是Linux平台下浏览器
        } else {
            os = 6;
            return os;
        }
    }

    hideMarkBox();
    function hideMarkBox() {
        $('.markbox').click(function () {
            $('.markbox').hide()
        });
    }

    // 显示或隐藏规则弹窗
    hideRuleBox();
    function hideRuleBox() {
        $('.closeIcon,.close').click(function () {
            $('#ruleModalBox').hide();
            $('#registerModal').hide();
            $('#luckDrawModal').hide();
        });
        $('#rules').click(function () {
            $('#ruleModalBox').show();
        });
    }

    // 注册成功去购买獴哥
    // UNDO:从后台获取一个加密字符串
    goBuy();
    function goBuy() {
        $('.goBuy').click(function () {
            if (getQueryString('shareCode')) {
                window.open(`${api}/consulting?shareCode=${getQueryString('shareCode')}&source=${activityEncryptData}`);
            } else {
                window.open(`${api}/consulting?source=${activityEncryptData}`);
            }

        })
    }

//    立即投保
    goInsure();
    function goInsure() {
        $('.goProduct').click(function () {
            if (getQueryString('shareCode')) {
                window.location.href = `${api}/pdetail/381?shareCode=${getQueryString('shareCode')}`;
            } else {
                window.location.href = `${api}/pdetail/381`;
            }

        })
    }

    // 立即邀请
    goInvitation();
    function goInvitation() {
        $('.invite').click(function () {
            if (param.deviceType !== '3') {
                layer.open({
                    content: '请用微信打开页面进行邀请好友',
                    skin: 'msg',
                    time: 5, //2秒后自动关闭，
                });
                return;
            } else {
                var double12_customerInfo = JSON.parse(localStorage.getItem('double12_customerInfo'));
                if (double12_customerInfo) {
                    wxShare();
                    $('.markbox').show();
                } else {
                    $('.loginInBox').show();
                }

            }

        })
    }

    // 关闭登录弹窗
    closeLoginInModal();
    function closeLoginInModal() {
        $('.closeBtn').click(function () {
            $('.loginInBox').hide();
        })
    }

//    查询用户的抽奖次数信息
    getActivityInfo();
    function getActivityInfo() {
        $.ajax({
            type: "POST",
            url: api + '/api/activity/getActivityInfo',
            contentType: "application/json",
            data: JSON.stringify({
                activityId: 12,
                customerId: param.customerId
            }),
            headers: {
                "X-Authorization": token
            },
            async: false,
            success: function (res) {
                if (res['success']) {
                    // 查询活动信息
                    activityInfo = res['data']['activityInfo'];
                    activityTaskInfoList = activityInfo['activityTaskInfoList'];
                    if (activityInfo.isActive !== 1) {
                        layer.open({
                            content: '活动已经结束',
                            skin: 'msg',
                            time: 5, //2秒后自动关闭，
                        });
                        return;
                    } else {
                        //    总共还剩多少红包
                        $('#giftSum').html(activityInfo.activityGiftInfo.giftSum);
                        var task01 = activityTaskInfoList.filter(item => item.taskCode === '12task1').pop() || [];
                        var task02 = activityTaskInfoList.filter(item => item.taskCode === '12task2').pop() || [];
                        var task03 = activityTaskInfoList.filter(item => item.taskCode === '12task3').pop() || [];
                        var task04 = activityTaskInfoList.filter(item => item.taskCode === '12task4').pop() || [];
                        if (task01.length > 0 || task02.length > 0 || task03.length > 0 || task04.length > 0) {
                            if (task01.activityOpportunityUsedInfo.leftTimes > 0) {
                                $('#task01 img').setAttribute('src', './images/red_pocket_active.png')
                            } else if (task01.activityOpportunityUsedInfo.drawTimes > 0) {
                                $('#task01 img').setAttribute('src', './images/red_pocket_finish.png')
                            } else {
                                $('#task01 img').setAttribute('src', './images/red_pocket_disabled.png')
                            }
                            if (task02.activityOpportunityUsedInfo.leftTimes > 0) {
                                $('#task02 img').setAttribute('src', './images/red_pocket_active.png')
                            } else if (task02.activityOpportunityUsedInfo.drawTimes > 0) {
                                $('#task02 img').setAttribute('src', './images/red_pocket_finish.png')
                            } else {
                                $('#task02 img').setAttribute('src', './images/red_pocket_disabled.png')
                            }
                            if (task03.activityOpportunityUsedInfo.leftTimes > 0) {
                                $('#task03 img').setAttribute('src', './images/red_pocket_active.png')
                                $('#task03 .remainRedPocketCount').html(task03.activityOpportunityUsedInfo.leftTimes);
                            } else {
                                $('#task03 .remainRedPocketCount').html(0);
                            }
                            if (task04.activityOpportunityUsedInfo.leftTimes > 0) {
                                $('#task04 img').setAttribute('src', './images/red_pocket_active.png');
                                $('#task04 .remainRedPocketCount').html(task04.activityOpportunityUsedInfo.leftTimes);
                            } else {
                                $('#task04 .remainRedPocketCount').html(0);
                            }
                        }
                    }
                }
            }
        })
    }

//    任务跳转
    $('#ai').click(function () {
        taskUrl(1)
    });
    $('#buyService').click(function () {
        taskUrl(2)
    });
    $('#goYDL').click(function () {
        taskUrl(4)
    });
    function taskUrl(type) {
        if (type === 1) {
            // 问卷
            window.open(`${api}/questionnaire/#/index?source=Double12`);
        } else if (type === 2) {
            // 购买獴哥服务
            window.open(`${api}/consulting/?source=Double12`);
        } else if (type === 4) {
            // 银盾保险在线
            window.open(`${api}/index/?source=Double12`);
        }
    }

    // 点击开红包
    $('#task01').click(function () {
        openRedPocket(0)
    });
    $('#task02').click(function () {
        openRedPocket(0)
    });
    $('#task03').click(function () {
        openRedPocket(1)
    });
    $('#task04').click(function () {
        openRedPocket(1)
    });
//    开启红包 1可开启 0 不可开启
    function openRedPocket(status) {
        if (localStorage.getItem('double12_customerInfo')) {
            //已经登录
        } else {
            // 未登录
            $('.loginInBox').show();

            return;
        }
        if (status === 1) {
            $('#luckDrawModal').show();
        } else if (status === 0) {
            layer.open({
                content: '红包次数不足，赶快完成任务获取吧',
                skin: 'msg',
                time: 5, //2秒后自动关闭，
            });
            return;
        }
    }

//    获取加密字符串
    function activityLogin(name, mobileNo, channelLaunchAD) {
        $.ajax({
            type: "POST",
            url: api + '/api/activity/activityLogin',
            contentType: "application/json",
            data: JSON.stringify({
                name: name,
                mobileNo: mobileNo,
                channelLaunchAD: channelLaunchAD,
            }),
            headers: {
                "X-Authorization": token
            },
            async: false,
            success: function (res) {
                if (res['success']) {
                    activityEncryptData = res['data']['encryptData']
                }
            }
        })
    }
});