$(function () {
    var api = 'https://' + window.location.host;
    var gitUrlParam = window.location.search;
    var param = {
        sex: "1",
        money: '1',
        name: '',
        phone: '',
        hmsr: getQueryString('hmsr'),
        hmpl: getQueryString('hmpl'),
        hmkw: getQueryString('hmkw'),
        hmci: getQueryString('hmci'),
        deviceType: ''
    }

    init();
    function init() {
        //点击跳转到首屏
        orderBtn();
        checkMoney();
        //同意条款
        checkAgree();
        //提交测算
        submitBtn();
        //电话咨询
        phoneConsult();
        //选男
        choseMale();
        //选女
        choseFemale();
    }

    var deviceType = checkDeviceType();

    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;
                // 获取预约人数
                getCount();
            }
        });
        return token;
    }

    var token = getToken();

    function choseMale() {
        $(".male").click(function () {
            if ($(".item .male").hasClass('on')) {
                $(".item .male").removeClass('on')
                $(".item .male").html("&#xe664;")
                // console.log('男未选中')
                param.sex = ''
            } else {
                $(".item .male").addClass('on')
                $(".item .male").html("&#xe684;")
                $(".item .female").removeClass('on')
                $(".item .female").html("&#xe664;")
                param.sex = '1'
                // console.log('男选中')
            }
        })
    }

    function choseFemale() {
        $(".female").click(function () {
            if ($(".item .female").hasClass('on')) {
                $(".item .female").removeClass('on')
                $(".item .female").html("&#xe664;")
                // console.log('女未选中')
                param.sex = ''
            } else {
                $(".item .female").addClass('on')
                $(".item .female").html("&#xe684;")
                $(".item .male").removeClass('on')
                $(".item .male").html("&#xe664;")
                param.sex = '2'
                // console.log('女选中')
            }
        })
    }

    function orderBtn() {
        $("#orderBtn,#btn3,.jump").click(function () {
            $('html,body').animate({scrollTop: 0}, 'slow');
        })
    }

    function checkMoney() {
        $("#choseMoney").change(function () {
            $("#choseMoney").attr("value", this.value);
            param.money = $("#choseMoney").attr("value");
        })
    }

    function submitBtn() {
        $(".testBtn").click(function () {
            //判断性别选没选
            if (!param.sex) {
                $(".sexTips").html('性别不能为空');
                setTimeout(function () {
                    $(".sexTips").html('');
                }, 3000)
                return false;
            }
            var namereg = /(^[\u4e00-\u9fa5]{1}[\u4e00-\u9fa5\.·。]{0,48}[\u4e00-\u9fa5]{1}$)|(^[a-zA-Z]{1}[a-zA-Z\s]{0,48}[a-zA-Z]{1}$)/
            var phonereg = /^(1)\d{10}$/;
            //判断姓名
            if ($(".username").val()) {
                if (!namereg.test($(".username").val())) {
                    $(".nameTips").html('请输入正确的姓名');
                    $(".username").val('');
                    setTimeout(function () {
                        $(".nameTips").html('');
                    }, 3000)
                    return false;
                } else {
                    param.name = $(".username").val();
                }
            } else {
                $(".nameTips").html('姓名不能为空')
                setTimeout(function () {
                    $(".nameTips").html('');
                }, 3000);
                return false;
            }
            //判断电话号码
            if ($(".userphone").val()) {
                if (!phonereg.test($(".userphone").val())) {
                    $(".phoneTips").html('请输入正确的手机号码');
                    $(".userphone").val('');
                    setTimeout(function () {
                        $(".phoneTips").html('');
                    }, 3000)
                    return;
                } else {
                    param.phone = $(".userphone").val();
                }
            } else {
                $(".phoneTips").html('手机号码不能为空')
                setTimeout(function () {
                    $(".phoneTips").html('');
                }, 3000)
                return false;
                ;
            }
            //判断是否同意
            if (!$(".agree .iconfont").hasClass('on')) {
                $(".agreeTips").html("请同意最惠比用户条款")
                setTimeout(function () {
                    $(".agreeTips").html('');
                }, 3000)
                return false;
            }
            param.campaignId = '9';
            $.ajax({
                type: "POST",
                url: api + '/api/promotion/marketingSave',
                contentType: "application/json",
                data: JSON.stringify(param),
                headers: {"X-Authorization": token},
                success: function (res) {

                    if (res['success']) {
                        // //提示
                        layer.open({
                            content: '<div class="service_item"><p class="service">您的信息已提交成功,</p><p class="service">保险顾问将在1个工作日内为您提供服务</p></div>'
                            , btn: '我知道了'
                        });
                    } else {
                        layer.open({
                            content: `<div class="service_item"><p class="service">${res['message']}</p></div>`
                            , btn: '我知道了'
                        });
                    }
                }
            })
        })
    }

    function getCount() {
        $.ajax({
            type: "GET",
            url: api + '/api/promotion/counter',
            contentType: "application/json",
            headers: {"X-Authorization": token},
            success: function (res) {
                if (res['success']) {
                    $('.reservation').html('今天已有' + res['data'].count + '人预约');
                } else {
                    $('.reservation').html('今天已有200人预约');
                }
            }
        })
    }

    //底部tab切换
    $(".tab li").click(function () {
        $(this).addClass("selected").siblings().removeClass("selected");
    })
    function checkAgree() {
        $(".agree").click(function () {
            if ($(".agree .iconfont").hasClass('on')) {
                $(".agree .iconfont").removeClass('on')
                $(".agree .iconfont").html("&#xe612;")
            } else {
                $(".agree .iconfont").addClass('on')
                $(".agree .iconfont").html("&#xe504;")
            }
        })
    }

    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 phoneConsult() {
        $("#askBtn").click(function () {
            layer.open({
                title: [
                    '400-921-9290',
                    'background-color: #299bf3; color:#fff;margin:0;font-size:24px;'
                ]
                ,
                content: '<div class="totast_content"><a class="iconfont" href="tel:400-921-9290">&#xe6bb;</a><a class="callBtn" href="tel:400-921-9290">拨打电话</a></div>'
            });
        })
    }

    function checkDeviceType() {
        if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
            if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
                deviceType = '3';
            } else {
                deviceType = '2';
            }
            $('#compaignCS').show();
            loadStyle('./css/mstyle.css');
            loadCS('qd2852152378db2071ba910d37f416cc80a75cbad904', 'https://wp.qiye.qq.com/qidian/2852152378/db2071ba910d37f416cc80a75cbad904');
        } else {
            deviceType = '1';
            changeImg('1');
            $('#compaignCS').hide();
            loadStyle('./css/style.css');
            loadCS('qd28521523787345b6267b3523eb19ee27f8d383d595', 'https://wp.qiye.qq.com/qidian/2852152378/7345b6267b3523eb19ee27f8d383d595')
        }
        return deviceType;
    }

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

    //加载不同样式
    function loadStyle(url) {
        var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = url;
        var head = document.getElementsByTagName('head')[0];
        head.appendChild(link);
    }

    // 加载客服组件
    function loadCS(id, src) {
        if (document.getElementById(id)) {
            document.getElementById(id).parentNode.removeChild(document.getElementById(id));
        }
        var script = document.createElement('script');
        script.id = id;
        script.src = src;
        script.charset = 'utf-8';
        script.async = 'true';
        script.defer = 'true';
        var head = document.getElementsByTagName('head')[0];
        head.appendChild(script);
    }

    function changeImg(type) {
        if (type == '1') {
            $(".pbanner").attr('src', './images/pbanner.jpg')
            $(".btn1").attr('src', './images/pcbtn1.png')
            $(".testBtn").attr('src', './images/pcbtn3.png')
            $(".bg").attr('src', './images/pcbg_1.jpg')
            $(".bottom").hide();
            $("#orderBtn,#btn3").attr('src', './images/pcbtn2.png')
        }
    }

//    监听scroll
    var count_index = 0;
    $(window).scroll(
        function (e) {
            if (count_index == 0) {
                var timeIntervalFunction = setInterval(function () {
                    count_index--;
                    if (count_index <= 0) {
                        clearInterval(timeIntervalFunction);
                        count_index = 0;
                        $('#compaignCS div').removeClass('csBox-init-actived').addClass('csBox-init');
                    }
                }, 50);
            } else {
                $('#compaignCS div').removeClass('csBox-init').addClass('csBox-init-actived');
            }
            count_index++;
        }
    );
});