window.foton = window.foton || {};
(function(){
    function pk(){
        this.baseUrl = window.location.origin;
        this.init();
    }

    p = pk.prototype;

    p.init = function(){
        this.bindEvent();
        this.listenTopBar();
        this.qjzs();
        this.jctj();
        this.yysj();

        // 模块动画
		var wow = new WOW({
			boxClass: 'wow',
			animateClass: 'animated',
			offset: 100,
			mobile: false,
			live: true
		});
		wow.init();
    }

    p.bindEvent = function(){
        const _this = this;
        // 预约试驾
        $(".submit").click(e=>{
            var flag = true;
            var msg = "";
            if(!$("#name").val()) {
                msg = "姓名不能为空!";
                flag = false;
                alertMsg(msg);
                return false;
            }
            p.checkPhoneNum($("#realPhone")).then( result => {
                if(!result){

                }else{
                    $(".yysj select").each(function() {
                        var select = $(this).find("option:selected");
                        if(select.val() == -1) {
                            flag = false;
                            msg = "请选择" + select.html();
                            return false;
                        }
                    });
                    if(!flag) {
                        alertMsg(msg);
                        return false;
                    }
        
        
        
                    if (flag) {
                        var params = {
                            BrandId: $("#brand").val(),
                            SeriesId: $("#carSeries").val(),
                            ProvinceId: $("#province").val(),
                            CityId: $("#city").val(),
                            DealerId: $("#Dealer").val(),
                            Name: $("#name").val(),
                            Phone: $("#realPhone").val(),
                            Remark: $("#Remark").val()
                    
                        };
                        _this.getData('post', _this.baseUrl+"/tunland/clue/PostLeads", params).then(resp => {
                            if(resp.status == 0){
                                alertMsg("提交成功");
                            }
                        })
                        p.LzInfo();
                    } else {
                        alertMsg(msg);
                    }
                }
            })
        })

        //关闭弹窗按钮
        $(".modalfooter button").on("click", function() {
            $(".alertbox").hide()
        });
    }

    // 导航栏吸附
    p.listenTopBar = function(){
        const _this = this;
        // 监听页面滚动,联动导航栏
        _this.listenScroll = true;

        $(document).scroll(e=>{
            let bannerH = $("#banner").height() - 71;
            let top = $(document).scrollTop();
            if(top >= bannerH){
                $("#navContainer").addClass("fixed");
            }else{
                $("#navContainer").removeClass("fixed");
            }
        })

        // 锚点
        let ary = ["cpld", "qjzs", "jctj", "cspz"];
        $("#navContainer .nav .n").click(e=>{
            let index = $(e.currentTarget).index();
            let section = $(`.${ary[index]}`);
            let top = section.offset().top - 80 - 75;
            
            window.scrollTo({
                top: top,
                behavior: "smooth"
            })

            _this.listenScroll = false;
            setTimeout(e=>{
                _this.listenScroll = true;
            },1500)

            $("#navContainer .nav .n").removeClass("active");
            $(e.currentTarget).addClass("active");
            $("#navContainer .nav .line").css("left", 106*index)
        })


        // 锚点控制导航
        let cpld = $(".cpld").offset().top;
        let qjzs = $(".qjzs").offset().top;
        let jctj = $(".jctj").offset().top;
        let cspz = $(".cspz").offset().top;
        window.onscroll = function(){
            if(_this.listenScroll === false){ return}

            let top = window.scrollY + 1000;

            let index = 0;
            if(top <= qjzs){
                index = 0;
            }else if(top <= jctj){
                index = 1;
            }else if(top <= cspz){
                index = 2;
            }else{
                index = 3;
            }
            $("#navContainer .nav .n").removeClass("active");
            $("#navContainer .nav .n").eq(index).addClass("active");
            $("#navContainer .nav .line").css("left", 106*index);

        }
    }

    // 全景展示滚动
    p.qjzs = function(){
      new Swiper(".qjzs .swiper-container", {
        prevButton:'.qjzs .wg',
        nextButton:'.qjzs .ns',
        onSlideChangeStart: function(swiper){
            // alert(swiper.activeIndex);
            $("#container .qjzs .nav .line").toggleClass("right");
        }
      });
    
    }

    // 精彩图集
    p.jctj = function(){

    
        var galleryTop = new Swiper('.swiper1', {
            spaceBetween: 10,
            onSlideChangeStart: function(swiper){
                let index = swiper.activeIndex;
                let len = $(".swiper1 img").length;
                
                if(index == 0){
                    galleryThumbs.slideTo(0);
                }else if(index == len-1){
                    galleryThumbs.slideTo(3);
                }
            }
        });
        var galleryThumbs = new Swiper('.swiper2', {
            spaceBetween: 24,
            slidesPerView: 'auto',
            touchRatio: 0.2,
            freeMode: true,
            watchSlidesProgress: false,
            onClick: function(swiper){
                let index = swiper.clickedIndex;
                galleryTop.slideTo(index);
            }
        });
    
    }


    // 预约试驾
    p.yysj = function(){
        const _this = this;
        setProvince();
        setBrand();



        function setProvince(){
            _this.getData('get', _this.baseUrl+ "/tunland/clue/getProvince").then(resp => {
                if(resp.status == 1 ){
                    return;
                }

                $("#province").empty();
                resp.data.unshift({ID:-1, FNAME:"省份"});
                $.each(resp.data, function(i, val) {
                    var $option = $('<option data-fcode="' + val.FCODE + '" value="' + val.ID + '">' + val.FNAME + '</option>');
                    $("#province").append($option);
                });
            })

            $("#province").bind("change", function() {
                var provinceid = $("#province option:selected").attr("value");
                setCity(provinceid);
            });
            
        }
        function setCity(provinceid){
            _this.getData('get', _this.baseUrl+ "/tunland/clue/getCityOfPronvince", {pId: provinceid}).then(resp => {
                if(resp.status == 1 ){
                    return;
                }

                $("#city").empty();
                resp.data.unshift({dmpCityId:-1, cityName:"市"});

                $.each(resp.data, function(i, val) {
                    var $option = $('<option value="' + val.dmpCityId + '">' + val.cityName + '</option>');
                    $("#city").append($option);
                });
            })

            $("#city").unbind("change");
            $("#city").bind("change", function() {
                _this.getData('get', _this.baseUrl+"/tunland/clue/getDealer", {cityId:$("#city").val()})
            });
        }
        function setBrand(){
            _this.getData('get', _this.baseUrl+ "/tunland/clue/getBrand").then(resp => {
                if(resp.status == 1 ){
                    return;
                }

                $("#brand").empty();
                
                resp.data.unshift({ID:-1, NAME:"品牌"});

                $.each(resp.data, function(i, val) {
                    if (val.ID == '504f7428-439a-4f87-9540-1ad1f334962e' || val.ID == -1) {
                        var $option = $('<option value="' + val.ID + '">' + val.NAME + '</option>');
                        $("#brand").append($option);
                    }
                });
            })

            $("#brand").bind("change", function() {
                setCarSeries($("#brand").val());
            });
        }
        function setCarSeries(brandId){
            $("#carSeries").empty();

            _this.getData('get', _this.baseUrl+ "/tunland/clue/getSeries", {brandId}).then( resp => {
                if(resp.status == 1 ){
                    return;
                }
                
                resp.data.unshift({ID:-1, NAME:"选择车型"});

                $.each(resp.data, function(i, val) {
                    var $option = $('<option value="' + val.ID + '">' + val.NAME + '</option>');
                    $("#carSeries").append($option);
                });
                // if(!isNaN(isbind)) {
                //     $("#carSeries").val(isbind);
                // }
            })
        }
    }

    p.checkPhoneNum = function(vInput, enable) {
        //手机号
        var reg = /^1(3|4|5|6|8|7)\d{9}$/;
        var flag = false;
    
        var phoneVal = vInput.val();
        if(phoneVal == "" || phoneVal == "手机号码") {
            alertMsg("手机号不能为空");
        } else if(!reg.test(phoneVal)) {
            alertMsg("请输入正确的手机号");
        } else {
            //验证手机号码是否已经注册过
            if(enable) {
                var urlJson = {
                    a: "Verifymtel",
                    tel: phoneVal
                }
                return new Promise(resolve => {
                    this.getData('get', _this.baseUrl+ "/tunland/clue/getProvince", urlJson).then(resp => {
                        if(resp.statcode == 0) {
                            resolve(true);
                        }else{
                            resolve(false);
                        }
                    })
                })
            } else {
                return Promise.resolve(true);
            }
        }
        return Promise.resolve(flag);
    }

    p.LzInfo = function () {
        const _this = this;
        $.ajax({
            type: "POST",
            async: false,
            url: _this.baseUrl+"/tunland/dmp/dmpLzInfo",
            data: {
                brandId: $("#brand").val(),
                seriesId: $("#carSeries").val(),
                provinceId: $("#province").val(),
                cityId: $("#city").val(),
                name: $("#name").val(),
                tel: $("#realPhone").val()
            },
            dataType: "json"
        });
    }

    p.getData = function(method="GET", url, data={}){
        return new Promise(resolve=>{
            $.ajax({
                url:url,
                method: method,
                data: method.toUpperCase()=="GET" ? data : JSON.stringify(data),
                dataType:'json',
                contentType:"application/json;charset=utf-8",
                success:e=>{
					resolve(e)
				}
            })
        })
    }

    function alertMsg(content) {
        $('.alertbox').show();
        $('.alertbox').css("z-index", "999");
        $(".modalbody").html(content);
    
    };

    window.foton.pk = pk;
})()