$(function () {
    var api = 'https://' + window.location.host;
    // var api = 'https://mdev.zuihuibi.cn';
    var gitUrlParam = window.location.search;
    var shareCode, customerId = null;
    var customerEncryptResult = null;
    var activityTaskInfoList = [];
    // 获取活动信息
    var activityInfo = null;
    // 各项任务详情信息
    var task01, task02, task03, task04 = 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: '',
    };
    var double12_customerInfo = localStorage.getItem('double12_customerInfo');
    if (getQueryString('customerId')) {
        customerId = getQueryString('customerId');
    } else if (double12_customerInfo) {
        customerId = JSON.parse(double12_customerInfo).customerId;
    }
    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/double12_banner.jpg',
                    success: function () {

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

    // 自定义分享
    function wxShare() {
        shareInfo.customerId = customerId;
        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: '送你1对1家庭风险管理定制服务，速来领取~',
            imgUrl: 'https://ajb-images.oss-cn-shanghai-finance-1-pub.aliyuncs.com/images/menggo_head.png',
            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) {
        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) {
                                customerId = param.customerId = res.data.customerId;
                                var double12_customerInfo = {
                                    customerId: res.data.customerId,
                                    customerName: $('#inviteeName').val(),
                                    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) {
                                            desEncrypt(JSON.stringify({
                                                customerId: res.data.customerId,
                                                mobileNo: $("#loginPhone").val(),
                                                name: $('#inviteeName').val(),
                                                campaignInfo: {'campaignCode': 'double12'}
                                            }))
                                            $('#registerModal').show();
                                        } else if (type === 3) {
                                            $('.loginInBox').hide();
                                            getActivityInfo();
                                        }
                                    }
                                }
                            }
                        })
                    }
                })
            } 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')}&campaign=${customerEncryptResult}&task=12task3`);
            } else {
                window.open(`${api}/consulting?campaign=${customerEncryptResult}&task=12task3`);
            }

        })
    }

//    立即投保
    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 {
                if (customerId) {
                    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: customerId || null
            }),
            headers: {
                "X-Authorization": token
            },
            async: false,
            success: function (res) {
                if (res['success']) {
                    if (res['data']['customerId']) {
                        desEncrypt(JSON.stringify({customerId: res['data']['customerId']}));
                    }
                    // 查询活动信息
                    activityInfo = res['data']['activityInfo'];
                    activityTaskInfoList = activityInfo['activityTaskInfoList'];
                    if (activityInfo.isActive !== 1) {
                        layer.open({
                            content: '活动已经结束',
                            skin: 'msg',
                            time: 5, //2秒后自动关闭，
                        });
                        localStorage.removeItem('double12_customerInfo');
                        return;
                    } else {
                        //    总共还剩多少红包
                        $('#giftSum').html(activityInfo.activityGiftInfo.giftSum);
                        if(Number(activityInfo.activityGiftInfo.giftSum) < 0){$('#giftSum').html(0);}
                        task01 = activityTaskInfoList.filter(item => item.taskCode === '12task1').pop() || [];
                        task02 = activityTaskInfoList.filter(item => item.taskCode === '12task2').pop() || [];
                        task03 = activityTaskInfoList.filter(item => item.taskCode === '12task3').pop() || [];
                        task04 = activityTaskInfoList.filter(item => item.taskCode === '12task4').pop() || [];
                        if(task01.length < 1){ $('.risk1 .disabledMask').show();}
                        if(task02.length < 1){ $('.risk2 .disabledMask').show();}
                        if(task03.length < 1){ $('.risk3 .disabledMask').show();}
                        if(task04.length < 1){ $('.risk4 .disabledMask').show();}
                        if (task01 && task01.activityOpportunityUsedInfo) {
                            if (task01.activityOpportunityUsedInfo.leftTimes > 0) {
                                $('#task01 img').attr('src', './images/red_pocket_active.png')
                            } else if (task01.activityOpportunityUsedInfo.drawTimes > 0) {
                                $('#task01 img').attr('src', './images/red_pocket_finish.png');
                                $('.login').hide();
                            } else {
                                $('#task01 img').attr('src', './images/red_pocket_disabled.png')
                            }
                            if (task01.activityOpportunityUsedInfo.totalTimes > 0) {
                                $('#ai').html('查看方案');
                                $('.completeIcon1').show();
                            }
                        } else {
                            if (customerId) {
                                $('#task01 img').attr('src', './images/red_pocket_disabled.png')
                            }
                        }
                        if (task02 && task02.activityOpportunityUsedInfo) {
                            if (task02.activityOpportunityUsedInfo.leftTimes > 0) {
                                $('#task02 img').attr('src', './images/red_pocket_active.png')
                            } else if (task02.activityOpportunityUsedInfo.drawTimes > 0) {
                                $('#task02 img').attr('src', './images/red_pocket_finish.png');
                                $('.login').hide();
                            } else {
                                $('#task02 img').attr('src', './images/red_pocket_disabled.png')
                            }
                            if (task02.activityOpportunityUsedInfo.totalTimes > 0) {
                                $('#buyService').html('查看方案');
                                $('.completeIcon2').show();
                            }
                        } else {
                            if (customerId) {
                                $('#task02 img').attr('src', './images/red_pocket_disabled.png')
                            }
                        }
                        if (task03 && task03.activityOpportunityUsedInfo) {
                            if (task03.activityOpportunityUsedInfo.leftTimes > 0) {
                                $('#task03 img').attr('src', './images/red_pocket_active.png');
                                $('#task03 .remainRedPocketCount').html(task03.activityOpportunityUsedInfo.leftTimes);
                            } else {
                                $('#task03 .remainRedPocketCount').html(0);
                            }
                        }
                        if (task04 && task04.activityOpportunityUsedInfo) {
                            if (task04.activityOpportunityUsedInfo.leftTimes > 0) {
                                $('#task04 img').attr('src', './images/red_pocket_active.png');
                                $('#task04 .remainRedPocketCount').html(task04.activityOpportunityUsedInfo.leftTimes);
                            } else {
                                $('#task04 .remainRedPocketCount').html(0);
                            }
                        }
                    }
                }
            }
        })
    }

//    抽红包
    function lottery(campaignTaskCode) {
        $.ajax({
            type: "POST",
            url: api + '/api/activity/lottery',
            contentType: "application/json",
            data: JSON.stringify({
                campaignCode: "double12",
                customerId: customerId || null,
                campaignTaskCode: campaignTaskCode
            }),
            headers: {
                "X-Authorization": token
            },
            async: false,
            success: function (res) {
                if (res['success']) {
                    $('#gift').html(`恭喜你，获得${res['data']['lotteryGiftName']}`);
                    getActivityInfo();
                } else {
                    layer.open({
                        content: res['message'],
                        skin: 'msg',
                        time: 5, //2秒后自动关闭，
                    });
                    return;
                }

            }
        })
    }

//    任务跳转
    $('#ai').click(function () {
        taskUrl(1)
    });
    $('#buyService').click(function () {
        taskUrl(2)
    });
    $('#goYDL').click(function () {
        taskUrl(4)
    });
    function taskUrl(type) {
        if (type === 1) {
            // 问卷
            if (task01 && task01.activityOpportunityUsedInfo && task01.activityOpportunityUsedInfo.totalTimes > 0) {
                window.open(task01.activityOpportunityUsedInfo.finishedDirectUrl)
            } else {
                window.open(`${api}/questionnaire/#/index?campaign=double12&task=12task1`);
            }
        } else if (type === 2) {
            // 购买獴哥服务
            if (task02 && task02.activityOpportunityUsedInfo && task02.activityOpportunityUsedInfo.totalTimes > 0) {
                window.open(`${api}/member?customerIdEncrypt=${customerEncryptResult}`)
            } else {
                window.open(`${api}/consulting/?campaign=double12&task=12task2`);
            }
        } else if (type === 4) {
            // 银盾保险在线
            window.open(`${api}/index`);
        }
    }

    // 点击开红包
    $('#task01').click(function () {
        openRedPocket(task01.activityOpportunityUsedInfo && task01.activityOpportunityUsedInfo.leftTimes > 0, task01.activityOpportunityUsedInfo && task01.activityOpportunityUsedInfo.drawTimes > 0, '12task1')
    });
    $('#task02').click(function () {
        openRedPocket(task02.activityOpportunityUsedInfo && task02.activityOpportunityUsedInfo.leftTimes > 0, task02.activityOpportunityUsedInfo && task02.activityOpportunityUsedInfo.drawTimes > 0, '12task2')
    });
    $('#task03').click(function () {
        openRedPocket(task03.activityOpportunityUsedInfo && task03.activityOpportunityUsedInfo.leftTimes > 0, false, '12task3')
    });
    $('#task04').click(function () {
        openRedPocket(task04.activityOpportunityUsedInfo && task04.activityOpportunityUsedInfo.leftTimes > 0, false, '12task4')
    });
//    开启红包 1可开启 0 不可开启
//    drawTimes 是否已经开启
    function openRedPocket(status, drawTimes, campaignTaskCode) {
        if (Number(activityInfo.activityGiftInfo.giftSum) < 0) {
            layer.open({
                content: '本次红包已领完，下次早点来哦',
                skin: 'msg',
                time: 5, //2秒后自动关闭，
            });
            return;
        }
        if (customerId) {
            //已经登录
        } else {
            // 未登录
            $('.loginInBox').show();
            $('#loginBtn').html("<button class='commonBtn redPocketLoginIn'>登录去开红包</button>");
            // 开启红包登录
            $('.redPocketLoginIn').bind("click", function () {
                loginIn(3)
            });
            return;
        }
        if (status) {
            $('#luckDrawModal').show();
            lottery(campaignTaskCode);
        } else if (!status && !drawTimes) {
            layer.open({
                content: '红包次数不足，赶快完成任务获取吧',
                skin: 'msg',
                time: 5, //2秒后自动关闭，
            });
            return;
        } else if (!status && drawTimes) {
            layer.open({
                content: '该任务只能领取一次红包',
                skin: 'msg',
                time: 5, //2秒后自动关闭，
            });
            return;
        }
    }

//  加密
    function desEncrypt(encryptString) {
        $.ajax({
            type: "POST",
            url: api + '/api/data/security/desEncrypt',
            contentType: "application/json",
            data: JSON.stringify({
                encryptString: encryptString,
                type: 'encrypt'
            }),
            headers: {
                "X-Authorization": token
            },
            async: false,
            success: function (res) {
                if (res['success']) {
                    customerEncryptResult = res['data']['encryptResult']
                }
            }
        })
    }
});