$(function () {
    // var api = 'https://' + window.location.host;
    var api = 'https://mdev.zuihuibi.cn';
    var gitUrlParam = window.location.search;
    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}$/;
    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);
    })
    $(".right").click(function () {
        if (getQueryString('source')) {
            $('.modalBox').hide();
            goTopay()
        } else {
            $("#phone").val('')
            $("#code").val('')
            $("#name").val('')
            $('.modalBox').show();
        }

    })
    $('.closeModal').click(function () {
        $('.modalBox').hide();
    })
    if (getQueryString('hmsr') || getQueryString('hmpl') || getQueryString('hmkw') || getQueryString('hmci')) {
        window.localStorage.setItem('hmsr', getQueryString('hmsr'))
        window.localStorage.setItem('hmpl', getQueryString('hmpl'))
        window.localStorage.setItem('hmkw', getQueryString('hmkw'))
        window.localStorage.setItem('hmci', getQueryString('hmci'))
    }
    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();
    //解密来源
    getChannel()
    function getChannel() {
        if (getQueryString('source')) {
            $.ajax({
                type: "POST",
                url: api + '/api/activity/getActivityOrderInfo',
                contentType: "application/json",
                data: JSON.stringify({ encryptData: getQueryString('source') }),
                async: false,
                headers: { "X-Authorization": token },
                success: function (res) {
                    if (res['success']) {
                        res = res['data'];
                        window.localStorage.setItem('hmsr', res['channelLaunchAD']['hmsr'])
                        window.localStorage.setItem('hmpl', res['channelLaunchAD']['hmpl'])
                        window.localStorage.setItem('hmkw', res['channelLaunchAD']['hmkw'])
                        window.localStorage.setItem('hmci', res['channelLaunchAD']['hmci'])
                        param.name = res['name'];
                        param.phone = res['mobileNo'];
                        param.customerId = res['customerId'];
                    }
                }
            })
        }

    }
    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;
    //获取产品价格
    var nowPrice = getGoodsPrice()
    function getGoodsPrice() {
        $.ajax({
            type: "POST",
            url: api + '/api/voucherInfoQuery',
            contentType: "application/json",
            data: JSON.stringify({ planId: 424 }),
            async: false,
            headers: { "X-Authorization": token },
            success: function (res) {
                if (res['data']) {
                    $(".nowPrice").html(res['data']['voucherSalePrice'])
                    $(".primeCost").html(res['data']['voucherValue'])
                    nowPrice = res['data']['voucherSalePrice']
                }
            }
        })
        return nowPrice
    }
    function getQueryString(name) {
        const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        const r = decodeURIComponent(gitUrlParam).substr(1).match(reg);
        if (r != null) {
            return r[2];
        }
        return null;
    }
    sendPhone()
    //发送验证码
    function sendPhone(type) {
        $("#codeBtn").click(function () {
            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
                        })
                    }
                }
            })
        })
    }

    // 登陆发送验证码
    sendLoginPhone()
    // //发送验证码
    function sendLoginPhone() {
        $("#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
                        })
                    }
                }
            })
        })
    }

    checkLoginVerificationCode()
    //验证登录验证码
    function checkLoginVerificationCode() {
        $("#loginCode").keyup(function () {
            if ($("#loginCode").val().length == 4) {
                const verificationCodeRequest = {
                    mobileNo: $("#loginPhone").val(),
                    verificationCode: $("#loginCode").val(),
                }
                if ($("#loginPhone").val() && $("#loginCode").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
                                })
                            }
                        }
                    })
                } else {
                    param.verificationCodeValider = false;
                }
            }

        })
    }

    getPay();

    function getPay() {
        $("#pay").click(function () {
            goTopay()
        })
    }

    function goTopay() {
        if (getQueryString('source')) {
            param.verificationCodeValider = true;
        } else {
            param.name = $("#name").val();
            param.phone = $("#phone").val();
        }
        if (!REG_CODE.test(param.phone)) {
            layer.open({
                content: '请输入正确的手机号码！',
                skin: 'msg',
                time: 3 //2秒后自动关闭
            });
            return;
        }

        if (!param.verificationCodeValider) {
            layer.open({
                content: '请检查您的验证码是否正确',
                skin: 'msg',
                time: 3 //2秒后自动关闭
            });
            return;
        }
        if (!REG_NAME.test(param.name)) {
            layer.open({
                content: '请检查您的姓名是否正确！',
                skin: 'msg',
                time: 3 //2秒后自动关闭
            });
            return;
        }
        const startDate = new Date();
        const endDate = new Date(new Date(startDate).setFullYear(new Date(startDate).getFullYear() + 1));
        endDate.setDate(endDate.getDate() - 1);
        const data = {
            customerId: param.customerId,
            planId: '424',
            startDate: startDate.getFullYear() + '-' + dateFormat((Number(startDate.getMonth()) + 1)) + '-' + dateFormat((Number(startDate.getDate()))),
            endDate: endDate.getFullYear() + '-' + dateFormat((Number(endDate.getMonth()) + 1)) + '-' + dateFormat((Number(endDate.getDate()))),
            price: nowPrice,
            holder: {
                name: param.name,
                mobileNo: param.phone
            },
            channelLaunchAD: {
                hmsr: window.localStorage.getItem('hmsr'),
                hmpl: window.localStorage.getItem('hmpl'),
                hmkw: window.localStorage.getItem('hmkw'),
                hmci: window.localStorage.getItem('hmci')
            },
            deviceType: param.deviceType,
            paymentMethod: '1',
            shareCode: getQueryString('shareCode')
        }
        if (isWeiXin()) {
            data.paymentMethod = '1';
        } else {
            data.paymentMethod = '2';
        }
        $.ajax({
            url: api + '/api/voucherBuy',
            type: 'POST',
            contentType: "application/json",
            data: JSON.stringify(data),
            headers: {
                "X-Authorization": token
            },
            success: function (res) {
                if (res['commonResult']) {
                    if (res['content']) {
                        const action = res['content']['action'];
                        const params = res['content']['param'];
                        const actionType = res['content']['actionType'];
                        const charset = res['content']['charset'];
                        getOrPost(action, params, charset, actionType);
                    }
                } else {
                    layer.open({
                        content: res.message,
                        skin: 'msg',
                        time: 3
                    })
                }
            }
        })
    }
    function dateFormat(e) {
        if (Number(e) < 10) {
            return '0' + e;
        } else {
            return e;
        }
    }

    // 判断是get请求还是post请求进行支付请求
    function getOrPost(action, params, charset, actionType) {
        let url = '';
        let paramHTML = '';
        let hiddenContent = '';
        const d = document.getElementById('d');
        if (actionType.toLowerCase() === 'get') {
            url = action;
            if (params) {
                for (let i = 0; i < params.length; i++) {
                    url += '&' + params[i].name + '=' + params[i].value;
                }
            }
            window.location.href = url;
        } else if (actionType.toLowerCase() === 'post') {
            if (params) {
                for (let i = 0; i < params.length; i++) {
                    paramHTML += '<input type="text" value="' + params[i].value + '" name="' + params[i].name + '" hidden>'
                }
            }
            hiddenContent +=
                '<form action="' + action + '"method="post" accept-charset="' + charset + '" onsubmit="document.charset=\'' + charset + '\';">' +
                paramHTML +
                '<button type="submit" id="submit" hidden></button>' +
                '</form>';
            d.innerHTML = hiddenContent;
            document.getElementById('submit').click()
        }
    }

    isWeiXin();

    function isWeiXin() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/_SQ_/i) == '_sq_') {
            $('.share').show();
            return true;
        } else {
            $(".share").hide();
            return false;
        }
    }

    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: '1对1家庭风险管理服务',
                    link: window.location.href,
                    desc: '产品太多、条款复杂、买哪个好，理不理赔? 獴哥保险诊所来帮您解决，提供1对1风险分析和保险方案定制。',
                    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
                });
            }
        })
    }

    // 自定义分享
    wxShare();

    function wxShare() {
        $('.share').click(function () {
            if (!localStorage.getItem('customerInfo')) {
                $('.loginInBox').show();
            } else {
                $('.markbox').show()
                var customerInfo = localStorage.getItem('customerInfo')
                customerInfo = JSON.parse(customerInfo).customerId;
                shareInfo.customerId = customerInfo;
                shareInfo.shareCode = Math.random().toString(36).substr(2, 15)
                shareInfo.url = window.location.href + '&shareCode=' + shareInfo.shareCode
                // 默认的分享信息
                const shareData = {
                    title: '1对1家庭风险管理服务',
                    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)
            }
        })
    }
    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;
                }
            }

        })
    }

    loginIn();
    // 登录
    function loginIn() {
        $('#loginIn').click(function () {
            if (!REG_CODE.test($("#loginPhone").val())) {
                layer.open({
                    content: '请输入正确的手机号码！',
                    skin: 'msg',
                    time: 3 //2秒后自动关闭
                });
                return;
            } else {
                param.phone = $("#loginPhone").val()
            }
            if (!param.verificationCodeValider) {
                layer.open({
                    content: '请检查您的验证码是否正确',
                    skin: 'msg',
                    time: 3 //2秒后自动关闭
                });
                return;
            }
            $.ajax({
                url: api + '/api/login',
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify({
                    mobileNo: $("#loginPhone").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: $("#loginPhone").val()
                        };
                        localStorage.setItem('customerInfo', JSON.stringify(customerInfo));
                        $('.loginInBox').hide();
                    } else {
                        layer.open({
                            content: res.message,
                            skin: 'msg',
                            time: 3
                        })
                    }
                }
            })
        })
    }

    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; // 这是Android平台下浏览器
        } 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;
        }
    }

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