$(function () {
    // var api = 'https://' + window.location.host;
    var api = 'https://m.zuihuibi.cn';
    var gitUrlParam = window.location.search;
    var shareCode = null;
    var lotteryGiftId = null;
    var leftTimes = null;
    const shareInfo = {
        shareCode: null,
        adultCount: 1,
        dayCount: 366,
        shareType: 1,
        customerId: null,
        planId: 381,
        os: checkOs(),
        channel: 0,
        url: window.location.href,
        isOrder: 0
    }
    const param = {
        phone: '',
        deviceType: '',
        verificationCodeValider: false,
        customerId: '',
        name: '',
    };
    var click = false;
    var gift = [
        {id: 0, name: '戴森吸尘器'},
        {id: 1, name: '100元红包'},
        {id: 2, name: '30元红包'},
        {id: 3, name: '轻奢旅行10件套（十份）'},
        {id: 4, name: '50元红包'},
        {id: 5, name: '水墨牛卡洗漱5件套（十份）'},
        {id: 6, name: '10元红包'},
        {id: 7, name: 'kalahari花季系列洗沐护润四件套（十份）'}
    ]
    var lottery = {
        index: -1,    //当前转动到哪个位置，起点位置
        count: 0,    //总共有多少个位置
        timer: 0,    //setTimeout的ID，用clearTimeout清除
        speed: 20,    //初始转动速度
        times: 0,    //转动次数
        cycle: 20,    //转动基本次数：即至少需要转动多少次再进入抽奖环节
        prize: -1,    //中奖位置
        init: function (id) {
            if ($("#" + id).find(".lottery-unit").length > 0) {
                $lottery = $("#" + id);
                $units = $lottery.find(".lottery-unit");
                this.obj = $lottery;
                this.count = $units.length;
                $lottery.find(".lottery-unit-" + this.index).addClass("active");
            }
            ;
        },
        roll: function () {
            var index = this.index;
            var count = this.count;
            var lottery = this.obj;
            $(lottery).find(".lottery-unit-" + index).removeClass("active");
            index += 1;
            if (index > count - 1) {
                index = 0;
            }
            ;
            $(lottery).find(".lottery-unit-" + index).addClass("active");
            this.index = index;
            return false;
        },
        stop: function (index) {
            this.prize = index;
            return false;
        }
    };
    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}/2019Double11/index.html`,
                    desc: '银盾保险双十一狂欢节，千元大礼等你来抽！',
                    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 customerInfo = localStorage.getItem('customerInfo');
        customerInfo = JSON.parse(customerInfo).customerId;
        shareInfo.customerId = customerInfo;
        shareInfo.shareCode = Math.random().toString(36).substr(2, 15);
        shareInfo.url = `${api}/2019Double11/invitation.html?shareCode=${shareInfo.shareCode}`;
        // 默认的分享信息
        const shareData = {
            title: '送你一份民宿保障计划',
            link: shareInfo.url,
            desc: '银盾保险双十一狂欢节，千元大礼等你来抽！',
            imgUrl: 'https://ajb-images.oss-cn-shanghai-finance-1-pub.aliyuncs.com/1/381-383/381-383.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 ($("#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 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('customerInfo', JSON.stringify(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();
                                            getLotteryOpportunityInfo();
                                        } else if (type === 2) {
                                            $('#registerModal').show();
                                        } else if (type === 3) {
                                            $('.loginInBox').hide();
                                            getLotteryOpportunityInfo();
                                            window.scrollTo(0, document.body.scrollHeight)
                                        }
                                    }
                                }
                            }
                        })
                    }
                })
            } else {
                param.verificationCodeValider = false;
            }
        }
    }

    // 立即注册
    $('.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').click(function () {
            $('#ruleModalBox').hide();
            $('#registerModal').hide();
            $('#luckDrawModal').hide();
        });
        $('#rules').click(function () {
            $('#ruleModalBox').show();
        });
    }

    // 注册成功去投保
    goBuy();
    function goBuy() {
        $('.goBuy').click(function () {
            if (getQueryString('shareCode')) {
                window.location.href = `${api}/2019Double11/index.html?shareCode=${getQueryString('shareCode')}`
            } else {
                window.location.href = `${api}/2019Double11/index.html`
            }

        })
    }

//    立即投保
    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 customerInfo = JSON.parse(localStorage.getItem('customerInfo'));
                if (customerInfo) {
                    wxShare();
                    $('.markbox').show();
                    $('#luckDrawModal').hide();
                } else {
                    $('.loginInBox').show();
                }

            }

        })
    }

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

//    九宫格抽奖
    luckDraw();
    lottery.init('lottery');
    function luckDraw() {
        $("#lottery a").click(function () {
            var customerInfo = JSON.parse(localStorage.getItem('customerInfo'));
            if (!customerInfo) {
                $('.loginInBox').show();
                $('#loginBtn').html("<button class='commonBtn' id='goLuckDraw'>去抽奖</button>")
                $('#goLuckDraw').bind("click", function () {
                    loginIn(3)
                });
                window.scrollTo(0, document.body.scrollHeight)
            } else if (!leftTimes || leftTimes < 1) {
                layer.open({
                    content: '抽奖次数不足,马上邀请好友获得抽奖机会吧',
                    skin: 'msg',
                    time: 3, //2秒后自动关闭，
                })
                return false;
            } else {
                if (click) {//click控制一次抽奖过程中不能重复点击抽奖按钮，后面的点击不响应
                    $("#lottery a").css({'background-color': '#ccc'})
                    return false;
                } else {
                    lottery.speed = 100;
                    roll();    //转圈过程不响应click事件，会将click置为false
                    click = true; //一次抽奖完成后，设置click为true，可继续抽奖
                    return false;
                }
            }

        });
    }

    function roll() {
        lottery.times += 1;
        lottery.roll();//转动过程调用的是lottery的roll方法，这里是第一次调用初始化
        if (lottery.times > lottery.cycle + 10 && lottery.prize == lottery.index) {
            var selcGift = gift.filter(item => item.id === lottery.prize).pop();
            if (selcGift.name) {
                $('#luckDrawModal').show();
                $("#lottery a").css({'background-color': '#e8b971'})
                $('#gift').html(`恭喜你获得${selcGift.name}`);
            }
            // 更新抽奖机会
            getLotteryOpportunityInfo();
            clearTimeout(lottery.timer);
            lottery.prize = -1;
            lottery.times = 0;
            click = false;


        } else {
            if (lottery.times < lottery.cycle) {
                lottery.speed -= 10;
            } else if (lottery.times == lottery.cycle) {
                // var index = Math.random()*(lottery.count)|0;//中奖物品通过一个随机数生成
                var customerInfo = JSON.parse(localStorage.getItem('customerInfo'));
                var customerId = null;
                if (customerInfo) {
                    customerId = customerInfo.customerId;
                    $.ajax({
                        type: "POST",
                        url: api + '/api/activity/lottery',
                        contentType: "application/json",
                        data: JSON.stringify({
                            customerId: customerId
                        }),
                        headers: {
                            "X-Authorization": token
                        },
                        async: false,
                        success: function (res) {
                            if (res['success']) {
                                lotteryGiftId = res['data']['lotteryGiftId'];
                                var index = parseInt(lotteryGiftId) - 1;
                                lottery.prize = index;
                            } else {
                                layer.open({
                                    content: res['message'],
                                    skin: 'msg',
                                    time: 5, //2秒后自动关闭，
                                });
                                return false;
                            }
                        }
                    })
                }
            } else {
                if (lottery.times > lottery.cycle + 10 && ((lottery.prize == 0 && lottery.index == 7) || lottery.prize == lottery.index + 1)) {
                    lottery.speed += 110;
                } else {
                    lottery.speed += 20;
                }
            }
            if (lottery.speed < 40) {
                lottery.speed = 40;
            }
            ;
            // console.log(lottery.times + '^^^^^^' + lottery.speed + '^^^^^^^' + lottery.prize);
            lottery.timer = setTimeout(roll, lottery.speed);//循环调用
        }
        return false;
    }

//    查询用户的抽奖次数信息
    getLotteryOpportunityInfo();
    function getLotteryOpportunityInfo() {
        $('#leftTimes').html('0')
        var customerInfo = JSON.parse(localStorage.getItem('customerInfo'));
        var customerId = null;
        if (customerInfo) {
            customerId = customerInfo.customerId;
        } else if (getQueryString('customerId')) {
            customerId = getQueryString('customerId');
        }
        if (customerId) {
            $.ajax({
                type: "POST",
                url: api + '/api/getLotteryOpportunityInfo',
                contentType: "application/json",
                data: JSON.stringify({
                    customerId: customerId
                }),
                headers: {
                    "X-Authorization": token
                },
                async: false,
                success: function (res) {
                    if (res['success']) {
                        leftTimes = res['data']['leftTimes'];
                        $('#leftTimes').html(res['data']['leftTimes'])
                    }
                }
            })
        }
    }
});