
$.fn.dataStatistics = function(options){
		options = $.extend({
	        max  : 500,       //初始数值
	        min  : 0, //最大数字
	        time : 60000,  //时长
	        len:4, //数字是几位数
			price:0, //金额
			couponId:0, //订单id
			platform:'App',
			count:0,
	    },options || {});

	    var ths = this;//解决this指向问题

	    //初始化---------------------------------------start

  		var el = ths.find('.set_last');
			var html = '<div class="digit">' +
				'  <div class="digit_top">' +
				'    <span class="digit_wrap"></span>' +
				'  </div>' +
				'  <div class="shadow_top"></div>' +
				'  <div class="digit_bottom">' +
				'    <span class="digit_wrap"></span>' +
				'  </div>' +
				'  <div class="shadow_bottom"></div>' +
				'</div>'




  		//初始化值
	var nowNums=zfill(options.max, options.len).toString().split("");
  		//补0
  		function zfill(num, size) {
			    var s = "000" + num;
			    return s.substr(s.length-size);
			}

			 ths.find('.digit_set').each(function() {
          for(i=0; i<=9; i++) {
            $(this).append(html);
            currentDigit = $(this).find('.digit')[i];
            $(currentDigit).find('.digit_wrap').append(9-i);
          }
        });

      //初始化数值填入
      $.each(nowNums, function(index,val) {
      	 var set =ths.find('.digit_set').eq(index);
      	 var i =parseInt(val)
      	 set.find('.digit').eq(9-i).addClass('active');
      	 set.find('.digit').eq(9-i+1).addClass('previous');
      });

      //初始化---------------------------------------end

      //执行
	var difference = 0; //执行次数
	var nownumber = options.min; //优惠券数量
	var Activityendtime = ''; //活动结束时间
			function run(diff){
				if(diff){
					difference = diff
				}else {
					 difference =options.max-options.min;//要执行动画的次数

				}
				if(nownumber == 0){ //优惠券没有的时候处理
					clearInterval(timer2); //优惠券用完 清楚定时器



					$(".received_img").attr("src","");
					$('.img_bg_M').css("background-image","url(../images/MJ_200@3x.png)");
					$('.img_bg_M p').css("color","#CCCCCC");
					$('.img_btn p').css("color","#FFFFFF");
					$('.img_btn p').html('活动结束')
					$('.box_content_t').hide()
					$('.img_btn').css("background-color", "#CCCCCC");
					// layer.msg('优惠券被抢光了！')

				}

				//后一位数
	  		function increase() {
	  			//执行次数为0时,停止执行
	  			if (difference<1) {
					clearInterval(timer1);

					return false;

				}
	  			difference--;

	        //翻页动画
	        var current = el.find('.active'),
	            previous = el.find('.previous');
	        previous.removeClass('previous');
	        current.removeClass('active').addClass('previous');

	        if (current.next().length == 0) {
	          el.find('.digit:first-child').addClass('active');
	          var prev = el.prev();
	          prevNumber(prev);
	        } else {
	          current.next().addClass('active');
	        }
	      }

	  		var timer1 = setInterval(increase,1000);

			}
  		//当数字翻到9的时候，前一位数执行一次动画
  		function prevNumber(ths){
  			var current = ths.find('.active'),
            previous = ths.find('.previous');
        previous.removeClass('previous');
        current.removeClass('active').addClass('previous');

        if (current.next().length == 0) {
          ths.find('.digit:first-child').addClass('active');
          var prev = ths.prev();
          if (prev.length>0) {
          	prevNumber(prev);
          }
        } else {
          current.next().addClass('active');
        }
  		}
  		run();

		var timer2 = setInterval(()=>{
			$.ajax({
				type: "POST",
				url: `${getApiUrl().urlJava}api/appActivity/getUserPurchaseTime`,
				contentType: "application/json",
				data: getJavaData({}),
				async: false,
				success: function (res) {
					if (res.resultCode === 1) {
						if(nownumber > 0){
							let num = nownumber -  res.data.repertory ; // 算出动画执行的次数
							nownumber = res.data.repertory; // 算出现在的数字
							// let num = 475 ; // 算出动画执行的次数
							// nownumber = 0; // 算出现在的数字

							if(num>0){
								run(num)
							}
							if(nownumber == 0 ){
								Activityendtime = res.data.expirationDate.replace('T',' ').replace(/-/g,'/');
							}
							options.count = res.data.count;
							let activityStartDate = new Date(res.data.activityStartDate.replace('T',' ').replace(/-/g,'/')).getTime();
							let activityEndDate = new Date(res.data.activityEndDate.replace('T',' ').replace(/-/g,'/')).getTime();


							let nowDate = new Date(res.data.currentTime.replace('T',' ').replace(/-/g,'/')).getTime();  //服务器时间

							if(activityStartDate  >= nowDate){//活动还没开始
								clearInterval(timer2);
							}else if( nowDate >= activityEndDate){ //活动结束

								$(".received_img").attr("src","");
								$('.img_bg_p1').css("color","#CCCCCC");
								$('.img_bg_p2').css("color","#CCCCCC");
								$('.img_btn p').css("color","#FFFFFF");
								$('.img_btn').css("background-color", "#CCCCCC");

								$('.img_btn p').html('活动结束')
								$('.box_content_t').hide()
								clearInterval(timer2); //活动结束 清楚定时器
							} else {
								if(nownumber > 0){
									if(res.data.count != 0){
										$(".received_img").attr("src","");
										$('.img_btn p').html(res.data.redemptionPrice + '元抢购')

									}else {
										$(".received_img").attr("src","../images/received@3x.png");
										$('.img_btn p').html('去使用')


									}
								}else {
									$(".received_img").attr("src","");
									$('.img_bg_p1').css("color","#CCCCCC");
									$('.img_bg_p2').css("color","#CCCCCC");
									$('.img_btn p').css("color","#FFFFFF");
									$('.img_btn p').html('活动结束')
									$('.box_content_t').hide()
									$('.img_btn').css("background-color", "#CCCCCC");
								}


							}

						}else {
							clearInterval(timer2); //没有优惠券 清楚定时器
						}


					}else {
						clearInterval(timer2); //没有优惠券 清楚定时器
					}
				},
				error: function (res) {

				}
			});
		},(difference+5)*1000) //5s请求一次接口

	$('.img_btn').click(function () {

		if($('.img_btn p').css('color')=='rgb(224, 50, 52)'){  //判断按钮是否可以点击
			if( options.count !=0){  //判断是可以抢购
				if(options.platform == 'App'){
					window.postMessage(JSON.stringify({'action' : 'showHud', 'message' : '抢购中...'}));
				}
				$.ajax({
					type: "POST",
					url: `${getApiUrl().urlJava}api/appActivity/PanicBuyingCoupon`,
					contentType: "application/json",
					data: getJavaData({redemptionPrice:options.price,couponId:options.couponId}),
					async: false,
					success: function (res) {
						if(options.platform == 'App'){
							window.postMessage(JSON.stringify({'action' : 'dismissHud'}));
						}
						if (res.resultCode === 1) {
							if(options.platform == 'App'){
								window.postMessage(JSON.stringify({'action' : 'showToast', 'message' : res.message}));
							}else {
								layer.msg(res.message)
							}
							var  timer3 = setInterval(()=>{ //1,需要timer2的定时器走完了 才走timer3的定时器

								nownumber = nownumber -1;
								run(1)
								clearInterval(timer3) //2,执行动画之后清除timer3
							},difference*1000)

							let title ='200元' + $('.img_bg_p1').html();
							let data = {

								'action' : 'jump', // showToast->一个提示信息 showHud->一个黑色的loading
								'page' : 'payment',
								'pageData' : {
									'couponId' : res.data.couponId,
									'title':title,
									'price':res.data.preferPrice,
									'backKey':'reload',
									'data':res.data
								}
							}
							if(options.platform == 'App'){
								window.postMessage(JSON.stringify(data));
							}
							// 跳转到支付
							else if(options.platform == 'xcx'){
								let data={};
								data.sOrderNo=res.data.id;
								data.sProductName=title;
								data.productId=res.data.couponId;
								data.dTotalPrice=res.data.preferPrice;

								wx.miniProgram.getEnv(function (res) {
									window.wx.miniProgram.navigateTo({
										url: `/pages/Home/pay/pay?data=`+JSON.stringify(data),
									});
									});
							}
							else if(options.platform == 'H5'){
								let userInfo = getLocalStorage()
								let data={};
								data.sOrderNo=res.data.id;
								data.sProductName=title;
								data.productId=res.data.couponId;
								data.dTotalPrice=res.data.preferPrice;

								window.location.href = 'http://127.0.0.1:5500/html/pay.html?sOrderNo='+data.sOrderNo+'&sProductName='+data.sProductName+'&productId='+data.productId+'&dTotalPrice='+data.dTotalPrice+'&CustomerId='+userInfo.customerId;
							}

						}else {
							if(options.platform == 'App'){
								window.postMessage(JSON.stringify({'action' : 'showToast', 'message' : res.message}));
							}else {
								layer.msg(res.message)
							}
								window.location.reload()

						}
					},
					error: function (res) {
						console.log(options.platform)
						if(options.platform == 'App'){
							window.postMessage(JSON.stringify({'action' : 'dismissHud'}));
						}else {

						}

						layer.msg(res.message)
					}
				});
			}else {
				layer.msg('去使用优惠券')

			}
		}else {
			if($('.img_btn p').text() == '活动结束'){
				if(options.platform == 'App'){
					window.postMessage(JSON.stringify({'action' : 'showToast', 'message' : '活动已结束'}));
				}else {
					layer.msg('活动已结束')
				}
			}else {
				if(options.platform == 'App'){
					window.postMessage(JSON.stringify({'action' : 'showToast', 'message' : '活动还未开始'}));
				}else {

					layer.msg('活动还未开始')
				}
			}
		}

	})
	};



