//
//  HeadLineViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/7/31.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "HeadLineViewController.h"
#import "KKStatusLabel.h"
#import "NewsViewController.h"
#import "HeadTVViewController.h"
#import "HeadNewsViewController.h"
#import "NewsViewController.h"

#import "GovWeatherModel.h"
#import "KKBubbleView.h"
#import "WETianqiController.h"
#import "KKSelectNewsTypeAlertView.h"

#import "KKLisenViewController.h"
#import "NewsSearchListController.h"
@interface HeadLineViewController ()

@property (nonatomic, strong)KKStatusLabel *selectLabel;

//@property (nonatomic, strong)HeadNewsViewController *newsVC;

@property (nonatomic, strong)NewsViewController *newsVC;

@property (nonatomic, strong)HeadTVViewController *tvVC;

//@property (nonatomic, strong)GovWeatherModel *weatherModel;
@property (nonatomic, strong)NSDictionary *weatherDic;

@property (nonatomic, strong)UILabel *lb_weather;

@property (nonatomic,strong)KKBubbleView *bubbleView;

@property (nonatomic, strong)KKStatusLabel *tvLabel;

@property (nonatomic, strong)UILabel *countdownLab;
@property (nonatomic) dispatch_source_t timer;
@end

@implementation HeadLineViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];

    if (![self.from isEqualToString:@"home"]) {
        [self showGuideView];
        
//        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"showSuspension"]) {
//           //悬浮按钮
//           [[clickEvent instance] SuspensionBtnRooterVC:self];
//        }
    }

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //[self addChildViewController:self.newsVC];
    [self addChildViewController:self.tvVC];
    //[self.view addSubview:self.newsVC.view];
    [self.view addSubview:self.tvVC.view];
    
    
    CGFloat topY = [self.from isEqualToString:@"home"] ? cl_kNavigationBarHeight  : cl_kNavigationBarHeight + 10;
    CGFloat bottomD = [self.from isEqualToString:@"home"] ? 0 : -cl_kTabBarHeight;
    
//    [self.newsVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.offset(0);
//        make.top.offset(topY);
//        make.bottom.offset(bottomD);
//    }];
    [self.tvVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(0);
        make.bottom.offset(bottomD);
    }];
    
    //[self navConfig];
    
    //[self requestWeatherData];
    
    if ([self.from isEqualToString:@"home"]) {
        [self.view bringSubviewToFront:self.newsVC.view];
    }
    //悬浮倒计时闹钟
    if (self.TaskModel.clickeventFlag == 601  && self.TaskModel.taskStatus == 305) {
        [self SuspensionCountdown];
    }
}
#pragma mark - 悬浮倒计时闹钟
- (void)SuspensionCountdown{
    UIView *SuspensionView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 80, ScreenHeight -  200, 60, 80)];
    [self.view addSubview:SuspensionView];
    [self.view bringSubviewToFront:SuspensionView];
    UIPanGestureRecognizer   *panTouch    =   [[UIPanGestureRecognizer  alloc]initWithTarget:self action:@selector(handlePan:)];
    [SuspensionView addGestureRecognizer:panTouch];
    
    UIImageView *alarmImgView = [[UIImageView alloc]initWithFrame:CGRectMake(9.5, 0, 41, 46)];
    alarmImgView.image = [UIImage imageNamed:@"alarm"];
    [SuspensionView addSubview:alarmImgView];
    
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 35, 60, 30)];
    baseView.backgroundColor = [UIColor colorWithHex:0xff9126];
    baseView.layer.masksToBounds = YES;
    baseView.layer.cornerRadius = 15;
    [SuspensionView addSubview:baseView];
    
    UILabel *countdownLab = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 50, 30)];
    countdownLab.textAlignment = NSTextAlignmentCenter;
    countdownLab.text = @"浏览10秒领取奖励";
    countdownLab.textColor = [UIColor whiteColor];
    countdownLab.font = [UIFont boldSystemFontOfSize:10];
    countdownLab.numberOfLines = 0;
    [baseView addSubview:countdownLab];
    self.countdownLab = countdownLab;
    
    [self updateCountdownUI];
}
/**
 *  处理拖动手势
 *
 *  @param recognizer 拖动手势识别器对象实例
 */
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    //视图前置操作
    [recognizer.view.superview bringSubviewToFront:recognizer.view];
    
    CGPoint center = recognizer.view.center;
    CGFloat cornerRadius = recognizer.view.frame.size.width / 2;
    CGPoint translation = [recognizer translationInView:self.view];
    //NSLog(@"%@", NSStringFromCGPoint(translation));
    recognizer.view.center = CGPointMake(center.x + translation.x, center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self.view];
    
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        //计算速度向量的长度，当他小于200时，滑行会很短
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        CGFloat slideMult = magnitude / 200;
        //NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult); //e.g. 397.973175, slideMult: 1.989866
        
        //基于速度和速度因素计算一个终点
        float slideFactor = 0.1 * slideMult;
        CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),
                                         center.y + (velocity.y * slideFactor));
        //限制最小［cornerRadius］和最大边界值［self.view.bounds.size.width - cornerRadius］，以免拖动出屏幕界限
        finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius),
                           self.view.bounds.size.width - cornerRadius);
        finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius),
                           self.view.bounds.size.height - cornerRadius);
        
        //使用 UIView 动画使 view 滑行到终点
        [UIView animateWithDuration:slideFactor*2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             recognizer.view.center = finalPoint;
                         }
                         completion:nil];
    }
}
- (void)updateCountdownUI{
    typeof(self) wSelf = self;
    // 倒计时时间
    __block int timeout         = self.TaskModel.clickTime;
    dispatch_queue_t queue      = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer  = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

    // 每秒执行
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{

        if (timeout <= 0)
        {
            //取消
            dispatch_source_cancel(wSelf.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                // 设置界面的按钮显示，根据自己需求设置
                wSelf.countdownLab.text = @"奖励已发放";
            });
        }
        else
        {
            
            NSString *strTime = [NSString stringWithFormat:@"浏览%i秒领取奖励", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                wSelf.countdownLab.text = strTime;
            });
            timeout--;
        }
    });
    //恢复
    dispatch_resume(_timer);
}
- (void)dealloc
{
    //移除定时器
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil; // OK
    }
}

- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:navView];
  
    //返回按钮
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"blackBack"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(10, cl_kStatusBarHeight, 60, 44);
    backBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    
    //新闻
   
    
    //视频
    KKStatusLabel *tvLabel = [KKStatusLabel new];
    tvLabel.backgroundColor = [UIColor clearColor];
    tvLabel.text = @"视频";
    self.tvLabel = tvLabel;
    
    CGFloat tvTop = 0.0;
    CGFloat tvHeight = 0.0;
    if ([self.from isEqualToString:@"home"]) {
        
        tvTop = cl_kStatusBarHeight;
        tvHeight = 44;
        
    }else{
        
        tvTop = cl_kStatusBarHeight + 6;
        tvHeight = 38;
    }
    
    tvLabel.frame = CGRectMake(10, tvTop, 55, tvHeight);
    tvLabel.labelSelected = YES;
    tvLabel.tag = 200;
    tvLabel.userInteractionEnabled = YES;
    [navView addSubview:tvLabel];
    
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]init];
    [tap2 addTarget:self action:@selector(labelTapAction:)];
    [tvLabel addGestureRecognizer:tap2];
    
    KKStatusLabel *newsLabel = [KKStatusLabel new];
    newsLabel.text = @"";
    newsLabel.frame = CGRectMake(CGRectGetMaxX(tvLabel.frame) + 10, tvTop, 0, 0);
    newsLabel.labelSelected = NO;
    newsLabel.tag = 201;
    newsLabel.userInteractionEnabled = YES;
    [navView addSubview:newsLabel];    
    self.selectLabel = tvLabel;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    [tap addTarget:self action:@selector(labelTapAction:)];
    [newsLabel addGestureRecognizer:tap];
    
    
    //注释掉新闻搜索
//    UIButton *searchBtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(newsLabel.frame) + 20, 0, 30, 30)];
//    searchBtn.centerY = tvLabel.centerY;
//    [searchBtn setImage:[UIImage imageNamed:@"searchIcon"] forState:UIControlStateNormal];
//    [searchBtn addTarget:self action:@selector(searchBtn) forControlEvents:UIControlEventTouchUpInside];
//    [navView addSubview:searchBtn];
//    
    
    
    UILabel *lb_weather = [UILabel new];
    CGFloat width = ScreenWidth - CGRectGetMaxX(newsLabel.frame) - 30;
    lb_weather.text = @"";
    lb_weather.textAlignment = NSTextAlignmentRight;
    lb_weather.textColor = [UIColor colorWithHex:0x808080];
    lb_weather.font = [UIFont systemFontOfSize:13 * WIDTHRADIU];
    [navView addSubview:lb_weather];
    self.lb_weather = lb_weather;
    [lb_weather mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-10 * WIDTHRADIU);
        make.centerY.equalTo(tvLabel);
        make.width.offset(width);
    }];

    BOOL show = [UserDefault boolForKey:@"KKBubbleView"];

    if ([self.from isEqualToString:@"home"]) {
        backBtn.hidden = NO;
        newsLabel.hidden = YES;
        tvLabel.hidden = YES;
    }else{
        backBtn.hidden = YES;
        newsLabel.hidden = NO;
        tvLabel.hidden = NO;
        
        
        if (!show) {
//            UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
//            CGRect rect=[newsLabel convertRect: newsLabel.bounds toView:window];
//            
//            KKBubbleView *bubbleView = [[KKBubbleView alloc]initWithFrame:CGRectMake(rect.origin.x - 25 + CGRectGetWidth(rect)/2.0, CGRectGetMaxY(rect) - 8, 150, 44)];
//            [self.view addSubview:bubbleView];
//            
//            
//            self.bubbleView = bubbleView;
//            
//            [UserDefault setBool:YES forKey:@"KKBubbleView"];
//            [UserDefault synchronize];
        }
    }
  
}
#pragma mark - 新闻搜索
- (void)searchBtn{
    NewsSearchListController *vc = [[NewsSearchListController alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)showGuideView
{
    BOOL alert = [[[NSUserDefaults standardUserDefaults] objectForKey:@"alertNews"] boolValue];
    if (alert) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"alertNews"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        return;
    }else{
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"alertNews"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    
    NSInteger x = (arc4random() % 2) + 1;

    switch (x) {
        case 1:
        {
            //[self showGuideMovieAlertView];
        }
            break;
        case 2:
        {
            //[self showGuideTingTingAlertView];
        }
            break;
        default:
            break;
    }
}
#pragma mark - 电影票弹框
- (void)showGuideMovieAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"GuideMovie"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }

    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"GuideMovie"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [NetworkRequest statisticsWithEventName:@"show_news_movie"];
    [GuideAlertView showInWindowWithImageName:@"find_mt" Block:^(BOOL success) {
        [NetworkRequest statisticsWithEventName:@"dialog_news_movie"];
        [weakSelf goToHeyshadow];
    }];
}
#pragma mark - 听听弹框
- (void)showGuideTingTingAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"GuideTingTing"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"showSuspension"]) {
        //yincang
        return;
    }

    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"GuideTingTing"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [NetworkRequest statisticsWithEventName:@"show_news_tingting"];
    [GuideAlertView showInWindowWithImageName:@"News_ts" Block:^(BOOL success) {
        [NetworkRequest statisticsWithEventName:@"dialog_news_tingting"];
        KKLisenViewController*vc = [KKLisenViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        vc.fromHome = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    }];
}
#pragma mark - 返利网
- (void)goToHeyshadow{
     UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
     __block KKNavViewController *nav1 = (KKNavViewController *)keywindow.rootViewController;
     
     if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstlog"]){
         
         NSInteger loginState = [UserDefault integerForKey:@"appleLoginState"];
         
         if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"] && loginState == 1031) {
             NSString* uid = [UserDefault objectForKey:@"appleId"];
             NSString* userId = [NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]];
             NSString* cus_name = [getPeopleID Peopletitle];
             NSString* photoUrl = [getPeopleID PeoplePhoto].absoluteString;

             BPViewController *bpVC = [[BPViewController alloc]init];
             bpVC.UID = uid;
             bpVC.Id = userId;
             bpVC.wxName = [NSString blankString:cus_name] ? @"" :cus_name;
             bpVC.wxPhotoUrl = photoUrl;
             bpVC.title = @"绑定手机号";
             bpVC.from = @"other";
             WeakSelf
             bpVC.block = ^(BOOL show) {
                 [weakSelf GetHeyshadowUrl];
             };
             UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:bpVC];
             [nav1 presentViewController:nav animated:YES completion:nil];
             return;
         }
         
         LoginVC *loginVC = [[LoginVC alloc]init];
         WeakSelf
         loginVC.block = ^(BOOL show) {
             [weakSelf GetHeyshadowUrl];
         };
         
         UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
         [nav1 presentViewController:nav animated:YES completion:nil];

         return;
     }else{
         [self GetHeyshadowUrl];
     }
}
#pragma mark - 电影券
- (void)GetHeyshadowUrl
{
    NSString *url = [NSString stringWithFormat:@"http://h5.weface.com.cn/20200228/haiying/login?tel=%@&id=%@",[getPeopleID PeopleIphoneNmber],@([getPeopleID PeopleID])];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
    NSDictionary *params = [NSDictionary dictionary];
    [KKLoadingAnimationView show];
    [NetworkRequest Get:url Params:params Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            NSString *url = [NSString stringWithFormat:@"%@",objc[@"result"]];
            
            url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
           
            [self jumpToHTML5:url andJAnalytics:@"电影券"];

        }else{
            [self alertShow:describe];
        }
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShow:@"网络异常"];
    }];
}
- (void)alertShow:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}
#pragma mark - h5页面跳转
-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{
    Web2ViewController*tc = [Web2ViewController new];
    tc.skipUrl =[NSURL URLWithString:url];
    tc.hidesBottomBarWhenPushed =YES;
    tc.title = janalytics;
    [self.navigationController pushViewController:tc animated:YES];
    
}
#pragma mark - 未登录跳转

- (void)unLoginTap {
    [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
}
#pragma mark - 获取天气
- (void)requestWeatherData
{
    WeakSelf
    NSString *url = WeatherUrl;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [NetworkRequest Get4:url Params:param Success:^(id _Nonnull responseObject) {

        NSLog(@"responseObject:%@",responseObject);
        NSDictionary *dic = responseObject;
        if (dic.count > 0) {
            weakSelf.weatherDic  = dic;
            
            NSString *low_temp = weakSelf.weatherDic[@"today"][@"low_temp"];
            NSString *high_temp = weakSelf.weatherDic[@"today"][@"high_temp"];
            if (low_temp.length > 3 && high_temp.length > 3) {
                self.lb_weather.text = [NSString stringWithFormat:@"%@  %@ %@~%@",weakSelf.weatherDic[@"city"],weakSelf.weatherDic[@"today"][@"weather"],[low_temp substringFromIndex:2],[high_temp substringFromIndex:2]];
            }
            
            self.lb_weather.userInteractionEnabled = YES;

            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(weatherTapClick:)];
            [self.lb_weather addGestureRecognizer:tap];
        }

    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);

    }];
}

#pragma mark - event response
- (void)labelTapAction:(UITapGestureRecognizer *)tap
{
//    WeakSelf
    if (self.bubbleView && self.bubbleView.superview) {
        [self.bubbleView removeFromSuperview];
    }
    KKStatusLabel *label = (KKStatusLabel *)tap.view;
    if (label.tag == self.selectLabel.tag) {
        return;
    }
    label.labelSelected = YES;
    self.selectLabel.labelSelected = NO;
    
    self.selectLabel = label;
    
    if (label.tag == 200) {
        
        [self.view bringSubviewToFront:self.tvVC.view];
    }else if (label.tag == 201){
        
        [self.view bringSubviewToFront:self.newsVC.view];
        
//        NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"KKSelectNewsTypeAlertView"];
//
//        if (oldTime && ([self intervalFromLastDate:oldTime toTheDate:[NSDate date]] < 6)) {
//            return;
//        }
//
//        NSDate *oldDate = [NSDate date];
//        [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"KKSelectNewsTypeAlertView"];
//        [[NSUserDefaults standardUserDefaults]synchronize];
//
//        [KKSelectNewsTypeAlertView showWithBlock:^(BOOL success) {
//
//            [UserDefault setBool:!success forKey:@"quickLookNews"];
//            [UserDefault synchronize];
//
//            [self.newsVC refreshFirstNewsVCData];
//        }];

    }
    
//    if (![self.from isEqualToString:@"home"]) {
//        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"showSuspension"]) {
//           //悬浮按钮
//           [[clickEvent instance] SuspensionBtnRooterVC:self];
//        }
//    }
    
}

- (void)selectTV2VCWithLabel:(KKStatusLabel *)label
{
    if (label.tag == self.selectLabel.tag) {
        return;
    }
    label.labelSelected = YES;
    self.selectLabel.labelSelected = NO;
    
    self.selectLabel = label;
    
    if (label.tag == 200) {
        
        [self.view bringSubviewToFront:self.tvVC.view];
    }else if (label.tag == 201){
        
        [self.view bringSubviewToFront:self.newsVC.view];
        
        NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"KKSelectNewsTypeAlertView"];

        if (oldTime && ([self intervalFromLastDate:oldTime toTheDate:[NSDate date]] < 7)) {
            return;
        }
        
        NSDate *oldDate = [NSDate date];
        [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"KKSelectNewsTypeAlertView"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
        [KKSelectNewsTypeAlertView showWithBlock:^(BOOL success) {
            
            [UserDefault setBool:!success forKey:@"quickLookNews"];
            [UserDefault synchronize];
            
            [self.newsVC refreshFirstNewsVCData];
        }];
  
        
    }
}
//头条天气
- (void)weatherTapClick:(UITapGestureRecognizer *)tap
{
//    NSDictionary *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"TQData"];
//
//   if (![Tools isBlankString:data[@"cityname"]]) {
//       NSString *lat = [NSString stringWithFormat:@"%@",data[@"lat"]];
//       NSString *lng = [NSString stringWithFormat:@"%@",data[@"lng"]];
//       WETianqiController *controlltr = [[WETianqiController alloc] init];
//       [controlltr fetchWeatherDataLocationLat:[lat doubleValue] LocationLng:[lng doubleValue]];
//       [self presentViewController:controlltr animated:YES completion:NULL];
//   }else{
//       WETianqiController *controlltr = [[WETianqiController alloc] init];
//       [controlltr fetchWeatherDataLocationLat:31.22 LocationLng:121.48];
//       [self presentViewController:controlltr animated:YES completion:NULL];
//   }
    //WebVC *webvc = [[WebVC alloc]init];
    //webvc.url=@"https://m.tianqi.com/docking.html";
    //webvc.url=@"http://172.16.10.126:8848/myweb/index.html";
    //webvc.title=@"天气";

    //[self.navigationController pushViewController:webvc animated:YES];
}

- (void)backClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 判断是否是同一天
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}

#pragma mark - 判断两个日期相差几天
- (NSInteger)intervalFromLastDate: (NSDate *) date1 toTheDate:(NSDate *) date2
{
    NSTimeInterval late1 = [date1 timeIntervalSince1970];
    
    NSTimeInterval late2 = [date2 timeIntervalSince1970];
    
    NSTimeInterval cha = late2-late1;
    
    NSInteger day = cha / (3600 * 24);
    
    return day;
}


#pragma mark - getters and setters
- (void)setCurrentIndex2:(NSInteger)currentIndex2
{
    self.tvVC.selectIndex = currentIndex2;
    
    [self selectTV2VCWithLabel:self.tvLabel];
}
//- (HeadNewsViewController *)newsVC
//{
//    if (!_newsVC) {
//        _newsVC = [HeadNewsViewController new];
//    }
//    return _newsVC;
//}

- (NewsViewController *)newsVC
{
    if (!_newsVC) {
        _newsVC = [NewsViewController new];
        _newsVC.title = @"新闻";
        _newsVC.from = self.from;
        _newsVC.currentIndex = self.currentIndex;
        _newsVC.hidesBottomBarWhenPushed = YES;
    }
    return _newsVC;
}

- (HeadTVViewController *)tvVC
{
    if (!_tvVC) {
        _tvVC = [HeadTVViewController new];
    }
    return _tvVC;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
