//
//  NewsViewController.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2019/11/18.
//  Copyright © 2019 雷俊博. All rights reserved.
//

#import "NewsViewController.h"
#import "UIView+frameAdjust.h"




#import "MFPageTitleView.h"
#import "MFPageContentView.h"

#import "NewsListController.h"

//天气
#import "LMJScrollTextView.h"
#import "WETianqiController.h"

#import <Reachability.h>
#import <sys/utsname.h>

//小满
#import <BXMediaSDK/BXMediaMaterialManager.h>
#import "KKActivityViewController.h"
#import "HeadTVViewController.h"
#import "HeadNewsTVViewController.h"

#import "KKSelectNewsTypeAlertView.h"

@interface NewsViewController ()<MFPageTitleViewDelegate,MFPageContentViewDelegate>

@property (nonatomic, strong)MFPageTitleView *pageTitleView;

@property (nonatomic, strong)MFPageContentView *pageContentView;

@property (nonatomic, strong)BXMMaterialModel *materialModel;

@property (nonatomic, strong)NewsListController *firstVC;

@end

@implementation NewsViewController
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
     [JANALYTICSService startLogPageView:@"看看新闻"];
    [MobClick beginLogPageView:@"看看新闻"];
    
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [MobClick endLogPageView:@"看看新闻"];
    [JANALYTICSService stopLogPageView:@"看看新闻"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [GTCountSDK trackCountEvent:@"news_mainpage_show" withArgs:@{}];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"新闻头条";
    self.tabBarItem.title = @"头条";
    
    [self.view addSubview:self.pageTitleView];
    [self.view addSubview:self.pageContentView];
    
    //[self configNavBarItems];
    
    [self loadData];
    
    [TABAnimated sharedAnimated].openAnimationTag = YES;
    
    
     
   // [self hiddenrequest];
     
    NSLog(@">>>>>>>>>>>>>>%ld",self.currentIndex);
//
//    [self.pageTitleView setPageTitleView:0 originalIndex:3 targetIndex:4];
//    [self.pageContentView setPageContentViewCurrentIndex:4];
    
}

- (void)configNavBarItems
{
    LMJScrollTextView *cityView = [[LMJScrollTextView alloc]initWithFrame:CGRectMake(0, 0, 100, 40) textScrollModel:LMJTextScrollContinuous direction:LMJTextScrollMoveLeft];
    
    UILabel *lb_weather = [[UILabel alloc]init];
    
    
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:cityView];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithCustomView:lb_weather];
    
    
    
    NSString *city = nil;
    NSString *weather = nil;
    NSDictionary *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"TQData"];
    if (![NSString blankString:data[@"cityname"]]) {
        
        
        city = [NSString stringWithFormat:@"%@",data[@"cityname"]];
       
        weather = [NSString stringWithFormat:@"%@  %@℃~%@℃",data[@"weather"],data[@"ltemp"],data[@"htemp"]];
        
    }else {
        city = @"上海市";
        
        weather =@"晴 22℃";
    }
    
    CGFloat width  = [city sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil]].width;
    if (width >= 100) {
        cityView.frame = CGRectMake(0, 0, 100, 40);
        [cityView startScrollWithText:city textColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:16]];
    }else {
        cityView.frame = CGRectMake(0, 0, width, 40);
        [cityView startShowWithText:city textColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:16]];
    }
    
    
    
    CGFloat width2  = [weather sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil]].width;
    
    lb_weather.frame = CGRectMake(0, 0, width2, 40);
    lb_weather.textColor = [UIColor whiteColor];
    lb_weather.font = [UIFont systemFontOfSize:16];
    
    lb_weather.text = weather;
    
    self.navigationItem.rightBarButtonItems = @[item2,item];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGesture:)];
    [cityView addGestureRecognizer:singleTap];
    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGesture:)];
    lb_weather.userInteractionEnabled = YES;
    
    [lb_weather addGestureRecognizer:singleTap1];
    
}



#pragma mark - loadData
- (NSDictionary *)requestParams
{
    
    
    NSDictionary *param = @{
        @"os":@"IOS",
        @"osv":[[UIDevice currentDevice] systemVersion],
        //@"mac":[IPTool getMacAddress],
        @"networktype":[self internetStatus],
        @"brand":@"Apple",
        @"model":[IPTool getCurrentDeviceModel],
        @"devicetype":[IPTool getCurrentDeviceType],
        @"remoteip":[IPTool getIPAddress2],
        @"idfa":[IPTool getIDFA],
        @"width":@([IPTool getCurrentWidthResolution]),
        @"height":@([IPTool getCurrentHeightResolution]),
        @"orientation":@"1",
        @"appid":@"com.weface.kksocialsecurity",
        @"appname":@"看看生活",
//        @"start": @(0),
//        @"end":@(NewPageSize)
       // @"key":JUHEAPPKey
    };
    
    return param;
}

- (void)loadData
{
    NSString *urlString = JUHEUrlString;
    NSLog(@"新闻提交用户信息url:%@",urlString);
    //NSLog(@"params:%@",[self requestParams]);
    [NetworkRequest NewsPost:urlString Params:nil Success:^(id _Nonnull objc) {
       // [SVProgressHUD dismiss];
       
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *status = [NSString stringWithFormat:@"%@",objc[@"status"]];
            NSString *usr_id = [NSString stringWithFormat:@"%@",objc[@"usr_id"]];
            if ([status isEqualToString:@"0"]) {
                [UserDefault setObject:usr_id forKey:@"usr_info_usr_id"];
                [UserDefault synchronize];
            }
        }
        
        
        
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
}


#pragma mark - 隐藏
- (void)hiddenrequest
{
    
    
     NSString * url =[NSString stringWithFormat:@"%@%@",[NetworkConfig ipSwitchConfig],SwitchRequest];
    
    NSString*version = nil;
           NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
           NSArray*vArr = [v componentsSeparatedByString:@"."];
           
           for (int i = 0; i < vArr.count; i++) {
               if (version == nil) {
                   version = [NSString stringWithFormat:@"kklife%@",vArr[i]];
               }else{
                   version = [version stringByAppendingFormat:@"%@",vArr[i]];
               }
           }
           
           NSDictionary*params = @{
               @"version":version
           };
              
      [NetworkRequest Get:url Params:params Success:^(id _Nonnull responseObject) {
          
          NSString* state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
          if ([state isEqualToString:@"200"]) {
              NSString* result = responseObject[@"result"];
              if ([result isEqualToString:@"0"]) {
                  
                  [self addRedPackage];
              }
          }
          
          
      } Failure:^(NSError* error) {
         
    }];
}

- (void)addRedPackage
{
    //素材使用代码
   //素材曝光,一般在素材加载完成的时候调用.如果不知道素材加载好的时机,可以在素材所在页面加载完成的时候调用
//  __block NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
   
   
   //加载素材
   //__weak typeof(self) weakSelf = self;
   [BXMediaMaterialManager getEntranceMaterialsWithAppkey:@"kksh-IOS-hdgj_xsekjn" placId:@"6667" thirdUserId:@"" success:^(BXMMaterialModel *model) {
       //weakSelf.model = model;
       if (model) {
           
           self.materialModel = model;
           [BXMediaMaterialManager entranceShowEventTrackingWithPlaceId:@"6667" userId:@"" materialModel:model];
           
           UIImageView *redPackageView = [[UIImageView alloc]init];
  
           redPackageView.frame = CGRectMake(ScreenWidth - 100, ScreenHeight - TAB_BAR_HEIGHT - 120, 60, 60);
           
           
           [redPackageView sd_setImageWithURL:[NSURL URLWithString:model.materialPath]];
           
           redPackageView.userInteractionEnabled = YES;
           
           [self.view addSubview:redPackageView];
           
           UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(redPackClick:)];
           
           [redPackageView addGestureRecognizer:ges];
           
           
           
       }
   } fail:^(NSString *error) {
       
   }];
}

#pragma mark - MFPageTitleViewDelegate
- (void)selectedIndexInPageTitleView:(MFPageTitleView *)pageTitleView selectedIndex:(NSInteger)selectedIndex
{
    [self.pageContentView setPageContentViewCurrentIndex:selectedIndex];
}
#pragma mark - MFPageContentViewDelegate
- (void)pageContentViewScroll:(CGFloat)progress originalIndex:(NSInteger)originalIndex targetIndex:(NSInteger)targetIndex
{
    [self.pageTitleView setPageTitleView:progress originalIndex:originalIndex targetIndex:targetIndex];
}

#pragma mark - public methods
- (void)refreshFirstNewsVCData
{
    [self.firstVC refreshData];
}


#pragma mark - event response
- (void)singleTapGesture:(UITapGestureRecognizer *)ges
{
    NSDictionary *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"TQData"];
    
    if (![NSString blankString: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];
    }
}

- (void)redPackClick:(UIGestureRecognizer *)ges
{
//    NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    [BXMediaMaterialManager entranceClickEventTrackingWithPlaceId:@"6667" userId:@"" materialModel:self.materialModel];
    
    KKActivityViewController *vc = [KKActivityViewController new];
    vc.title = @"天天赚钱";
    vc.placeId = @"6667";
    vc.buId = @"946405763";
    vc.gdtAdId = @"9002117197798706";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 获取网络状态
-(NSString *)internetStatus {
    
    Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    NSString *net = @"WIFI";
    switch (internetStatus) {
        case ReachableViaWiFi:
            net = @"1";
            break;
            
        case ReachableViaWWAN:
            //net = @"蜂窝数据";
            net = [self getNetType];   //判断具体类型
            break;
            
        case NotReachable:
            net = @"0";
            
        default:
            net = @"0";
            break;
    }
    
    return net;
}

//针对蜂窝网络判断是3G或者4G
- (NSString *)getNetType
{
    NSString *netconnType = @"2";
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    NSString *currentStatus = info.currentRadioAccessTechnology;
    if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
        netconnType = @"2";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
        netconnType = @"2";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
        netconnType = @"4";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){
        netconnType = @"2";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){
        netconnType = @"2";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
        netconnType = @"3";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
        netconnType = @"4";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
        netconnType = @"4";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
        netconnType = @"4";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){
        netconnType = @"2";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
        netconnType = @"5";
    }
    return netconnType;
}



#pragma mark - getters and setters
- (MFPageTitleView *)pageTitleView
{
    if (!_pageTitleView) {
        MFPageTitleViewConfig *config = [[MFPageTitleViewConfig alloc]init];
        config.titleColor = K_RGB(43, 43, 43);
        config.titleSelectedColor = K_MainColor;
        config.titleFont = [UIFont systemFontOfSize:18 weight:UIFontWeightRegular];
        config.indicatorColor = K_MainColor;
        config.selectedIndex = self.currentIndex;
        
        
        _pageTitleView = [[MFPageTitleView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 41) titles:@[@"热点",@"三农",@"养老",@"国内",@"本地",@"国际",@"社会",@"娱乐",@"科学",@"教育",@"健康",@"财经",@"军事",@"体育"] config:config];
//        _pageTitleView = [[MFPageTitleView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 41) titles:@[@"热点",@"听新闻",@"养老",@"国内",@"本地",@"国际"] config:config];
        _pageTitleView.delegate = self;
    }
    return _pageTitleView;
}

- (MFPageContentView *)pageContentView
{
    if (!_pageContentView) {
        NSMutableArray <UIViewController *> *childControllers = [[NSMutableArray alloc]init];
        
        
        //NSArray*types=@[@"hot",@"radio_hot",@"care",@"china",@"local",@"world"];
        NSArray*types=@[@"hot",@"farmer",@"care",@"china",@"local",@"world",@"society",@"play",@"science",@"parent",@"healthy",@"economics",@"military",@"sport"];
        for (int i =0 ; i < types.count; i++) {
//            if (i == 3) {
//                HeadNewsTVViewController *tvVC = [HeadNewsTVViewController new];
//                CGFloat red = (CGFloat)(arc4random() %256);
//                CGFloat green = (CGFloat)(arc4random() %256);
//                CGFloat blue = (CGFloat)(arc4random() %256);
//
//                tvVC.view.backgroundColor = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];
//                [childControllers addObject:tvVC];
//            }else{
            NewsListController *vc = [[NewsListController alloc]initWithType:types[i]];
            vc.from = self.from;
//            CGFloat red = (CGFloat)(arc4random() %256);
//            CGFloat green = (CGFloat)(arc4random() %256);
//            CGFloat blue = (CGFloat)(arc4random() %256);
//
//            vc.view.backgroundColor = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];
            [childControllers addObject:vc];
            if (i == 0) {
                self.firstVC = vc;
            }
//            }
           
        }
        CGFloat pageContentViewY = self.pageTitleView.maxY;
        if ([self.from isEqualToString:@"home"]) {
            _pageContentView = [[MFPageContentView alloc]initWithFrame:CGRectMake(0, pageContentViewY, ScreenWidth, ScreenHeight - self.pageTitleView.height) parentVC:self childVCs:childControllers];
        }else{
            _pageContentView = [[MFPageContentView alloc]initWithFrame:CGRectMake(0, pageContentViewY, ScreenWidth, ScreenHeight - self.pageTitleView.height - Height_TapBar) parentVC:self childVCs:childControllers];
        }
        
        
        
        _pageContentView.delegate = self;
    }
    return _pageContentView;
}

/*
#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
