//
//  NewsListController.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2019/12/1.
//  Copyright © 2019 雷俊博. All rights reserved.
//

#import "NewsListController.h"
#import "NewsListTableViewCell.h"
#import "NewsList2Cell.h"
#import "NewsTextCell.h"
#import "NewsImagesCell.h"
#import "JHNewsModel.h"

#import "UIView+frameAdjust.h"

#import "CTToast.h"

#import <BUAdSDK/BUAdSDK.h>
#import "NewsWebViewController.h"


#import "TABAnimated.h"
#import <TABKit/TABKit.h>




#define NewPageSize 15

@interface NewsListController ()<UITableViewDelegate,UITableViewDataSource, BUNativeExpressAdViewDelegate,NewsWebViewControllerDelegate>
{
    NSString* startTimeStr;
    NSString* endTimeStr;
    NSString* currentPageUrl;

    int timeLength;
    
    BOOL firstLoadOk;
    
    NSInteger currentPage;
}

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSMutableArray *dataArray;

@property (nonatomic, strong)NSMutableArray *tempArray;

@property (nonatomic, strong)NSMutableArray *mixDataArray;

@property (nonatomic, strong) NSMutableDictionary *dispatchTable;

@property (nonatomic, strong) NSMutableArray *expressAdViews;

@property (nonatomic, strong) BUNativeExpressAdManager *adManager;

@property (strong, nonatomic) NSTimer *timer;

@property (nonatomic, strong)UIView *animationView;


@end

@implementation NewsListController
- (void)dealloc {
    _tableView.delegate = nil;
}
- (instancetype)initWithType:(NSString *)type
{
    self = [super init];
    if (self) {
        self.type = type;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //init
    currentPage = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    self.expressAdViews = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
    self.tempArray = [NSMutableArray array];
    self.mixDataArray = [NSMutableArray array];
    
    
    
    for (int i = 0; i < 10; i++) {
        JHNewsModel *model = [[JHNewsModel alloc]init];
        
        model.view_type = @"1";
        
        model.news_pic = @"http://images8.m.china.com.cn/oss/mchina/20210420/11/img_a3b31532f8617f9d9f96a40b4651ed5c_240_176.jpg";
        model.news_from = @"中国网财经";
        model.news_from = @"1小时前";
        
        [self.mixDataArray addObject:model];
    }
  
    
    //add
    [self.view addSubview:self.tableView];
       
   
    
    timeLength = 80;

    
//    // 支持视频广告的 PlacementId 会混出视频与图片广告
//    self.nativeExpressAd = [[GDTNativeExpressAd alloc] initWithPlacementId:@"2081471194429990" adSize:CGSizeMake(ScreenWidth, 340)];
//
//    self.nativeExpressAd.delegate = self;
//
//    // 配置视频播放属性
//
//
//    self.nativeExpressAd.videoAutoPlayOnWWAN = NO;
//
//    self.nativeExpressAd.videoMuted = YES;
    
    BUAdSlot *slot1 = [[BUAdSlot alloc] init];
    slot1.adSize = CGSizeMake(ScreenWidth, 0);
    slot1.ID = @"946265855";
    slot1.AdType = BUAdSlotAdTypeFeed;
    
    BUSize *imgSize = [BUSize sizeBy:BUProposalSize_Feed228_150];
    slot1.imgSize = imgSize;
    slot1.position = BUAdSlotPositionFeed;
    
    
    self.adManager = [[BUNativeExpressAdManager alloc] initWithSlot:slot1 adSize:CGSizeMake(ScreenWidth, 0)];
    self.adManager.delegate = self;
    //[self.adManager loadAd:(NSInteger)self.adCountSliderValue];
    
    
    

//
//
//    [BUAdSDKManager setAppID:@"5109638"];
//
//    NSString* version =  BUAdSDKManager.SDKVersion;
//    NSLog(@"穿山甲版本号:%@",version);
//#if DEBUG
//    // Whether to open log. default is none.
//    [BUAdSDKManager setLoglevel:BUAdSDKLogLevelDebug];
//#endif
//    [BUAdSDKManager setIsPaidApp:NO];
    
    
   
    
   
    
//    [self.tableView tab_startAnimationWithCompletion:^{
//        [self.tableView.mj_header beginRefreshing];
//    }];
    
    
    
    
    [self.tableView tab_startAnimation];
    [self.tableView.mj_header beginRefreshing];
    //新闻页面刷新
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NewsRefreshData) name:@"HeadNewsRefreshData" object:nil];
  }
  #pragma mark - 刷新新闻
  - (void)NewsRefreshData{
      [self refreshData];
  }
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick endLogPageView:@"看看新闻"];
    [JANALYTICSService stopLogPageView:@"看看新闻"];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
     [JANALYTICSService startLogPageView:@"看看新闻"];
    [MobClick beginLogPageView:@"看看新闻"];
    
//    [self.tableView tab_startAnimation];
    
}

//- (void)loadADData {
//
//    if (self.expressAdViews.count >= 18) {
//        return;
//    }
//
//    BUAdSlot *slot1 = [[BUAdSlot alloc] init];
//    slot1.ID = @"945759461";
//    slot1.AdType = BUAdSlotAdTypeFeed; //required
//    slot1.supportRenderControl = YES;
//    BUSize *imgSize = [BUSize sizeBy:BUProposalSize_Feed228_150];
//    slot1.imgSize = imgSize;
//    slot1.position = BUAdSlotPositionFeed;
//
//    if (!self.nativeExpressAdManager) {
//        self.nativeExpressAdManager = [[BUNativeExpressAdManager alloc] initWithSlot:slot1 adSize:CGSizeMake(ScreenWidth, ScreenWidth / 1.78)];
//    }
//    self.nativeExpressAdManager.delegate = self;
//
//    [self.nativeExpressAdManager loadAdDataWithCount:3];
//
//}

#pragma mark - loadData
- (NSDictionary *)requestParams
{
    
    NSString* province = [UserDefault objectForKey:@"locationProvince"];
    
    NSString* provinceValue = [self getLocationAddressKeyWithProvinceName:province];
    
    NSDictionary *param = @{
        @"news_type":self.type,
        @"address":provinceValue,
//        @"start": @(0),
//        @"end":@(NewPageSize)
       // @"key":JUHEAPPKey
    };
    
    return param;
}

- (void)loadData
{
    
    
    [self.mixDataArray removeAllObjects];
    
    for (int i = 0; i < 10; i++) {
        JHNewsModel *model = [[JHNewsModel alloc]init];
        
        model.view_type = @"1";
        
        model.news_pic = @"http://images8.m.china.com.cn/oss/mchina/20210420/11/img_a3b31532f8617f9d9f96a40b4651ed5c_240_176.jpg";
        model.news_from = @"中国网财经";
        model.news_from = @"1小时前";
        
        [self.mixDataArray addObject:model];
    }
    
    NSString *urlString = JUHEUrlString;
    NSLog(@"新闻列表:url:%@",urlString);
    NSLog(@"params:%@",[self requestParams]);
    WeakSelf
    //[SVProgressHUD show];
    NSLog(@"请求前时间:%@",[NSDate date]);
    
    
    
    [NetworkRequest NewsPost:urlString Params:[self requestParams] Success:^(id _Nonnull objc) {
       // [SVProgressHUD dismiss];
        [self.tableView tab_startAnimation];
        
        
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *status = [NSString stringWithFormat:@"%@",objc[@"status"]];
            if ([status isEqualToString:@"0"]) {
                NSLog(@"新闻请求成功并渲染时间:%@",[NSDate date]);
                
                self->firstLoadOk = YES;
                
               
                
                [self.expressAdViews removeAllObjects];
                [self.dataArray removeAllObjects];
                weakSelf.dataArray = [NSMutableArray arrayWithArray:[JHNewsModel mj_objectArrayWithKeyValuesArray:objc[@"news_list"]]];
                //[weakSelf.tableView reloadData];
                //[weakSelf.nativeExpressAd loadAd:10];
                
                [self loadNewsData];
                
               
                return;
            }else{
                //if (!self->firstLoadOk) {
                    [self.expressAdViews removeAllObjects];
                    [self.dataArray removeAllObjects];
                    [self.mixDataArray removeAllObjects];
                    
                    [weakSelf.tableView reloadData];
                //}
            }
        }else{
            //if (!self->firstLoadOk) {
                [self.expressAdViews removeAllObjects];
                [self.dataArray removeAllObjects];
                [self.mixDataArray removeAllObjects];
                [weakSelf.tableView reloadData];
            //}
        }
        
        [weakSelf.tableView.mj_header endRefreshing];
//        [self.tableView tab_endAnimationEaseOut];
        
    } Failure:^(NSError* error) {
       // [SVProgressHUD dismiss];
        
        
        
//        [self.tableView tab_startAnimation];
        
        [weakSelf.tableView.mj_header endRefreshing];
        [self.tableView tab_endAnimationEaseOut];
        
        //if (!self->firstLoadOk) {
            [self.expressAdViews removeAllObjects];
            [self.dataArray removeAllObjects];
        [self.mixDataArray removeAllObjects];
            
            [weakSelf.tableView reloadData];
        //}
        
        NSLog(@"error:%@",error);
    }];
}

- (void)creatLoadSuccessView
{
    
    [self.tableView.mj_header endRefreshing];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    bgView.backgroundColor = [UIColor colorWithHex:0xe1f2ff];
    
    
    
    [self.view addSubview:bgView];
    
    UILabel *lb_title = [UILabel new];
    lb_title.text = @"数据刷新成功";
    lb_title.textColor = [UIColor colorWithHex:0xFF1986d4];
    lb_title.font = [UIFont systemFontOfSize:14];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:lb_title];
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(bgView);
    }];
    
    [self performSelector:@selector(dismissUI) withObject:nil afterDelay:1];
    
    self.animationView = bgView;
}

- (void)dismissUI
{
    [self.animationView removeFromSuperview];
    self.animationView = nil;
    
    
}


- (void)loadNewsData
{
    [self.mixDataArray removeAllObjects];
    currentPage = 1;
    [self.tempArray removeAllObjects];
    
    BOOL success = [UserDefault boolForKey:@"quickLookNews"];
    
    NSInteger maxCount = success ? 21 : 12;
    
    
    if (self.dataArray.count > maxCount) {
        
        for (int i = 0; i < maxCount; i++) {
            [self.tempArray addObject:self.dataArray[i]];
        }
        
        [self.adManager loadAdDataWithCount:3];
        _tableView.mj_footer.hidden  =  NO;
    }else{
        self.tempArray = self.dataArray;
        [self.adManager loadAdDataWithCount:3];
        
        _tableView.mj_footer.hidden  =  YES;
    }
    
//    self.tableView.tableFooterView = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        [self loadMoreNewsData];
//    }];
    
    //currentPage++;
    
}

- (void)loadMoreNewsData
{
    [self.tempArray removeAllObjects];
    
    BOOL success = [UserDefault boolForKey:@"quickLookNews"];
    
    NSInteger maxCount = success ? 21 : 12;
    
    if (self.dataArray.count >= currentPage * maxCount) {
        
        NSLog(@"currentPage:%ld",currentPage);
        
        for (int i = 0; i < maxCount; i++) {
            [self.tempArray addObject:self.dataArray[(currentPage - 1) * maxCount + i]];
        }
        
        [self.adManager loadAdDataWithCount:3];
    }else{
        NSLog(@"currentPage:%ld",currentPage);
        
        for (int i = 0; i < (self.dataArray.count - (currentPage - 1) * maxCount); i++) {
            [self.tempArray addObject:self.dataArray[(currentPage - 1) * maxCount + i]];
        }
        
        [self.adManager loadAdDataWithCount:3];
        
        _tableView.mj_footer.hidden  =  YES;
        
    }
    
    
}




#pragma mark - 看新闻得金币
- (NSDictionary *)readNewsGetCoinsRequestPara {
    NSDictionary* params = @{
        @"uid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
        @"telphone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
        @"watchstarttime":startTimeStr ? startTimeStr :@"",
        @"watchendtime":endTimeStr ? endTimeStr : @"",
        @"currentpagetotalheight":@(0),
        @"currentNewsHeight":@(0),
        @"currentPageUrl":currentPageUrl ,
        @"frommodel":[NSNumber numberWithInt:2],
        @"eventtype":[NSNumber numberWithInt:1001],
        
        @"slidingdistance":@(0),
        @"slidingTime":@(0)
    };
    
    return params;
}
- (void)readNewsGetCoinsRequest {
    NSString *url = [NSString stringWithFormat:@"%@news/readnews",CoinsBaseUrl];//外网
    
    [NetworkRequest Get:url Params:[self readNewsGetCoinsRequestPara] Success:^(id _Nonnull objc) {
        
        NSLog(@"objc:%@",objc);
        
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString* code = [NSString stringWithFormat:@"%@",objc[@"code"]];
            if ([code isEqualToString:@"0"]) {
                if ([objc[@"result"] isKindOfClass:[NSDictionary class]]) {
                    NSString*score = [NSString stringWithFormat:@"+%@",objc[@"result"][@"score"]];
                    [CTToast showWithMessage:score image:@"readNews-coins-toastBackView" duration:1];
                }
            }
        }
        
    } Failure:^(NSError* error) {
        NSLog(@"error");
    }];
    
}



#pragma mark - NewsWebViewControllerDelegate
//第一次加载完成返回总高度和当前时间戳(精确到秒)
- (void)kkNewsDetailViewControllerDidFirstFinishLoad:(NewsWebViewController *)vc withTime:(NSString *)timeStr {
    
    startTimeStr = timeStr;
}

//控制器关闭返回当前时间戳
- (void)kkNewsDetailViewControllerDidClose:(NewsWebViewController *)vc withTime:(NSString *)timeStr {
//    endTimeStr = timeStr;
//
//
//    NSInteger number = endTimeStr.integerValue - startTimeStr.integerValue;
//
//    NSLog(@">>>>%ld",number);
//
//    if (number >= 13000) {
//        [self readNewsGetCoinsRequest];
//    }
    
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.mixDataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id model = self.mixDataArray[indexPath.section];
    
    if ([model isKindOfClass:[JHNewsModel class]]) {
        JHNewsModel* newsModel = (JHNewsModel *)model;
        
        if ([newsModel.view_type isEqualToString:@"2"]) {
            NewsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsListTableViewCell"];
            
            cell.selectionStyle =  UITableViewCellSelectionStyleNone;
            
            
            [cell refreshUIWithModel:newsModel];
            
            
            return cell;
        }else if ([newsModel.view_type isEqualToString:@"0"]){
            NewsTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsTextCell"];
            
            cell.selectionStyle =  UITableViewCellSelectionStyleNone;
            
            
            [cell refreshUIWithModel:newsModel];
            
            
            return cell;
        } else if ([newsModel.view_type isEqualToString:@"1"]) {
            NewsList2Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsList2Cell"];
            
            cell.selectionStyle =  UITableViewCellSelectionStyleNone;
            
            
            [cell refreshUIWithModel:newsModel];
            
            
            return cell;
        }else if ([newsModel.view_type isEqualToString:@"3"]) {
            NewsImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsImagesCell"];
            
            cell.selectionStyle =  UITableViewCellSelectionStyleNone;
            
            
            [cell refreshUIWithModel:newsModel];
            
            
            return cell;
        }else{
            NewsTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsTextCell"];
            
            cell.selectionStyle =  UITableViewCellSelectionStyleNone;
            
            
            [cell refreshUIWithModel:newsModel];
            
            
            return cell;
        }
        
    }else if ([model isKindOfClass:[BUNativeExpressAdView class]]){
        BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)model;
        UITableViewCell *cell = nil;
        cell = [tableView dequeueReusableCellWithIdentifier:@"BUDNativeExpressCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //[self addAccessibilityIdentifier:model];
        // 重用BUNativeExpressAdView，先把之前的广告试图取下来，再添加上当前视图
       
        
        for (UIView* view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
        UIView* line = [UIView new];
        line.backgroundColor = [UIColor colorWithHex:0xcccccc];
        line.tag = 100;
        
        UIView *view = model;
        view.tag = indexPath.section;
        //[self addAccessibilityIdentifier:(GDTNativeExpressProAdView *)view];
        [cell.contentView addSubview:view];
        [cell.contentView addSubview:line];
        
        
        [expressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.offset(0);
        }];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(0);
            make.left.offset(15);
            make.right.offset(-15);
            make.height.offset(0.5);
        }];
        return cell;
    } else{
        
        BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)model;
        
        UIView* line = [UIView new];
        line.backgroundColor = [UIColor colorWithHex:0xcccccc];
        line.tag = 100;
        
        expressView.tag = 1000;
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nativeexpresscell" forIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        for (UIView* view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
                
        [cell.contentView addSubview:expressView];
        [cell.contentView addSubview:line];
        
        
        [expressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.offset(0);
        }];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(0);
            make.left.offset(15);
            make.right.offset(-15);
            make.height.offset(0.5);
        }];
        
        return cell;
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    id model = self.mixDataArray[indexPath.section];
    if ([model isKindOfClass:[JHNewsModel class]]) {
        return UITableViewAutomaticDimension;
    }else{
        UIView* view = (UIView *)model;
        
        CGFloat height = view.bounds.size.height + 0.5;
    
        return height;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id model = self.mixDataArray[indexPath.section];
    if ([model isKindOfClass:[JHNewsModel class]]) {
        JHNewsModel*newsModel = (JHNewsModel *)model;
        
        NewsWebViewController *vc = [[NewsWebViewController alloc]init];
        
        vc.title = @"新闻资讯";
        
        
        NSString* usr_id  = nil;
        
        if ([UserDefault boolForKey:@"firstlog"]) {
            usr_id = [NSString stringWithFormat:@"%@",@([getPeopleID PeopleID])];
        }
        
        if ([Tools isBlankString:usr_id]) {
            vc.url = [newsModel.news_url stringByAppendingFormat:@"&usr_id=%@",[Tools getDeviceUUID]];;
        }else{
            vc.url = [newsModel.news_url stringByAppendingFormat:@"&usr_id=%@",usr_id];
        }
        
        vc.model = newsModel;
       
        vc.delegate = self;
        
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
        currentPageUrl = newsModel.news_url;
    }

}

//#pragma mark - AccessibilityIdentifier
//- (void)addAccessibilityIdentifier:(GDTNativeExpressProAdView *)adView {
//    adView.accessibilityIdentifier = @"express_draw_view";
//}
//
//- (void)removeAccessibilityIdentifier:(GDTNativeExpressProAdView *)adView {
//    adView.accessibilityIdentifier = nil;
//}

//#pragma mark - BUNativeExpressAdViewDelegate
//- (void)nativeExpressAdSuccessToLoad:(BUNativeExpressAdManager *)nativeExpressAd views:(NSArray<__kindof BUNativeExpressAdView *> *)views {
//    [self.tableView.mj_header endRefreshing];
//    [self.tableView.mj_footer endRefreshing];
//    //【重要】不能保存太多view，需要在合适的时机手动释放不用的，否则内存会过大
//    if (views.count) {
//
//        [self.expressAdViews addObjectsFromArray:views];
////        [self.expressAdViews addObject:views.firstObject];
//        [views enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)obj;
//            expressView.rootViewController = self;
//            // important: 此处会进行WKWebview的渲染，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
//            [expressView render];
//            if (!(((currentPage - 2)*NewPageSize + (idx + 1) * 6 -1) >= self.dataArray.count)) {
//                [self.dataArray insertObject:expressView atIndex:((currentPage - 2)*NewPageSize + (idx + 1) * 6 -1)];
//            }
////            *stop = YES;
//        }];
//    }
//    [self.tableView reloadData];
//    [self pbud_logWithSEL:_cmd msg:@""];
//}
//
//- (void)nativeExpressAdFailToLoad:(BUNativeExpressAdManager *)nativeExpressAd error:(NSError *)error {
//    [self pbud_logWithSEL:_cmd msg:[NSString stringWithFormat:@"error:%@", error]];
//    [self.tableView.mj_header endRefreshing];
//    [self.tableView.mj_footer endRefreshing];
//}
//
//- (void)nativeExpressAdViewRenderSuccess:(BUNativeExpressAdView *)nativeExpressAdView {
//    [self.tableView reloadData];
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateCurrentPlayedTime) userInfo:nil repeats:YES];
//        [self.timer fire];
//    });
//    [self pbud_logWithSEL:_cmd msg:[NSString stringWithFormat:@"nativeExpressAdView.videoDuration:%ld", (long)nativeExpressAdView.videoDuration]];
//}
//
//- (void)updateCurrentPlayedTime {
//    for (BUNativeExpressAdView *nativeExpressAdView in self.expressAdViews) {
//        [self pbud_logWithSEL:_cmd msg:[NSString stringWithFormat:@"nativeExpressAdView.currentPlayedTime:%.4f", nativeExpressAdView.currentPlayedTime]];
//    }
//}
//
//- (void)nativeExpressAdView:(BUNativeExpressAdView *)nativeExpressAdView stateDidChanged:(BUPlayerPlayState)playerState {
//    [self pbud_logWithSEL:_cmd msg:[NSString stringWithFormat:@"playerState:%ld", (long)playerState]];
//}
//
//- (void)nativeExpressAdViewRenderFail:(BUNativeExpressAdView *)nativeExpressAdView error:(NSError *)error {
//    [self pbud_logWithSEL:_cmd msg:[NSString stringWithFormat:@"error:%@", error]];
//}
//
//- (void)nativeExpressAdViewWillShow:(BUNativeExpressAdView *)nativeExpressAdView {
//    [self pbud_logWithSEL:_cmd msg:@""];
//}
//
//- (void)nativeExpressAdViewDidClick:(BUNativeExpressAdView *)nativeExpressAdView {
//    [self pbud_logWithSEL:_cmd msg:@""];
//}
//
//- (void)nativeExpressAdViewPlayerDidPlayFinish:(BUNativeExpressAdView *)nativeExpressAdView error:(NSError *)error {
//    [self pbud_logWithSEL:_cmd msg:@""];
//}
//
//- (void)nativeExpressAdView:(BUNativeExpressAdView *)nativeExpressAdView dislikeWithReason:(NSArray<BUDislikeWords *> *)filterWords {//【重要】需要在点击叉以后 在这个回调中移除视图，否则，会出现用户点击叉无效的情况
//    [self.expressAdViews removeObject:nativeExpressAdView];
//    [self.dataArray removeObject:nativeExpressAdView];
//
//    NSUInteger index = [self.dataArray indexOfObject:nativeExpressAdView];
//    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:index inSection:0];
//    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//    [self pbud_logWithSEL:_cmd msg:@""];
//}
//
//- (void)nativeExpressAdViewDidClosed:(BUNativeExpressAdView *)nativeExpressAdView {
//    [self pbud_logWithSEL:_cmd msg:@""];
//}
//
//- (void)nativeExpressAdViewWillPresentScreen:(BUNativeExpressAdView *)nativeExpressAdView {
//    [self pbud_logWithSEL:_cmd msg:@""];
//}
//
//- (void)nativeExpressAdViewDidCloseOtherController:(BUNativeExpressAdView *)nativeExpressAdView interactionType:(BUInteractionType)interactionType {
//    NSString *str;
//    if (interactionType == BUInteractionTypePage) {
//        str = @"ladingpage";
//    } else if (interactionType == BUInteractionTypeVideoAdDetail) {
//        str = @"videoDetail";
//    } else {
//        str = @"appstoreInApp";
//    }
//    [self pbud_logWithSEL:_cmd msg:str];
//}
//
//
//- (void)pbud_logWithSEL:(SEL)sel msg:(NSString *)msg {
//    //BUD_Log(@"SDKDemoDelegate BUNativeExpressFeedAdView In VC (%@) extraMsg:%@", NSStringFromSelector(sel), msg);
//}


#pragma mark - GDTNativeExpressProAdManagerDelegete
/**
 * 拉取广告成功的回调
 */
//- (void)gdt_nativeExpressProAdSuccessToLoad:(GDTNativeExpressProAdManager *)adManager views:(NSArray<__kindof GDTNativeExpressProAdView *> *)views
//{
//    NSLog(@"%s",__FUNCTION__);
//    self.expressAdViews = [NSMutableArray arrayWithArray:views];
//    if (self.expressAdViews.count) {
//        [self.expressAdViews enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            GDTNativeExpressProAdView *adView = (GDTNativeExpressProAdView *)obj;
//            adView.controller = self;
//            adView.delegate = self;
//            [adView render];
//            NSLog(@"eCPM:%ld eCPMLevel:%@", [adView eCPM], [adView eCPMLevel]);
////            if (!(((idx + 1) * 6 -1) >= self.dataArray.count)) {
////                if (idx == 0) {
////                    [self.dataArray insertObject:adView atIndex:3];
////                }else{
////                    [self.dataArray insertObject:adView atIndex:4+ ((idx - 1 + 1) * 6 -1)];
////                }
////
////            }
//            NSInteger index = 2 + idx * 6;
//            if (index >= self.tempArray.count) {
//                NSInteger k = index - self.tempArray.count;
//                if (k < 1) {
//                    [self.tempArray addObject:adView];
//                }
//                //[self.tempArray addObject:adView];
//            }else{
//                [self.tempArray insertObject:adView atIndex:index];
//            }
//
//
//
//
//
//
//        }];
//
//        [self.mixDataArray addObjectsFromArray:self.tempArray];
//
//
//
//
//    }
//
//
//
//
//    [self.tableView reloadData];
//
//    if (currentPage == 1) {
//        [self.tableView tab_endAnimationEaseOut];
//        [self creatLoadSuccessView];
//    }
//    currentPage++;
//
//    [self.tableView.mj_header endRefreshing];
//    [self.tableView.mj_footer endRefreshing];
//
//    NSLog(@"广告请求成功时间:%@",[NSDate date]);
//}

/**
 * 拉取广告失败的回调
 */
//- (void)gdt_nativeExpressProAdFailToLoad:(GDTNativeExpressProAdManager *)adManager error:(NSError *)error
//{
//    NSLog(@"%s",__FUNCTION__);
//    NSLog(@"Express Ad Load Fail : %@",error);
//    [self.mixDataArray addObjectsFromArray:self.tempArray];
//    [self.tableView reloadData];
//    if (currentPage == 1) {
//        [self.tableView tab_endAnimationEaseOut];
//        [self creatLoadSuccessView];
//    }
//    currentPage++;
//
//
//    [self.tableView.mj_header endRefreshing];
//    [self.tableView.mj_footer endRefreshing];
//}
//
//
//#pragma mark - GDTNativeExpressProAdViewDelegate;
//- (void)gdt_NativeExpressProAdViewRenderSuccess:(GDTNativeExpressProAdView *)nativeExpressAdView
//{
//    NSLog(@"%s",__FUNCTION__);
//    [self.tableView reloadData];
//
//}
//
//- (void)gdt_NativeExpressProAdViewRenderFail:(GDTNativeExpressProAdView *)nativeExpressProAdView
//{
//    UIView *superView = nativeExpressProAdView.superview;
//
//    UITableViewCell* cell = (UITableViewCell *)superView.superview;
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//
//
//
//
//
//    [self.dataArray removeObjectAtIndex:indexPath.section];
//    //[nativeExpressAdView removeFromSuperview];
//    [self.tableView reloadData];
//}
//
//- (void)gdt_NativeExpressProAdViewClicked:(GDTNativeExpressProAdView *)nativeExpressAdView
//{
//    NSLog(@"%s",__FUNCTION__);
//}
//
//- (void)gdt_NativeExpressProAdViewClosed:(GDTNativeExpressProAdView *)nativeExpressAdView
//{
//    NSLog(@"%s",__FUNCTION__);
//
//    UIView *superView = nativeExpressAdView.superview;
//
//    UITableViewCell* cell = (UITableViewCell *)superView.superview;
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//
//
//
//
//
//    [self.dataArray removeObjectAtIndex:indexPath.section];
//    //[nativeExpressAdView removeFromSuperview];
//    [self.tableView reloadData];
//
//}
//
//- (void)gdt_NativeExpressProAdViewExposure:(GDTNativeExpressProAdView *)nativeExpressAdView
//{
//    NSLog(@"%s",__FUNCTION__);
//}
//
//- (void)gdt_NativeExpressProAdViewWillPresentScreen:(GDTNativeExpressProAdView *)nativeExpressAdView
//{
//    NSLog(@"%s",__FUNCTION__);
//}
//
//- (void)gdt_NativeExpressProAdViewDidPresentScreen:(GDTNativeExpressProAdView *)nativeExpressAdView
//{
//    NSLog(@"%s",__FUNCTION__);
//}
//
//- (void)gdt_NativeExpressProAdViewWillDissmissScreen:(GDTNativeExpressProAdView *)nativeExpressAdView
//{
//    NSLog(@"%s",__FUNCTION__);
//}
//
//- (void)gdt_NativeExpressProAdViewDidDissmissScreen:(GDTNativeExpressProAdView *)nativeExpressAdView
//{
//    NSLog(@"%s",__FUNCTION__);
//}
//
//- (void)gdt_NativeExpressProAdView:(GDTNativeExpressProAdView *)nativeExpressProAdView playerStatusChanged:(GDTMediaPlayerStatus)status
//{
//    NSLog(@"%s",__FUNCTION__);
//}

#pragma mark - BUNativeExpressAdViewDelegate
/**
 * Sent when views successfully load ad
 */
- (void)nativeExpressAdSuccessToLoad:(BUNativeExpressAdManager *)nativeExpressAdManager views:(NSArray<__kindof BUNativeExpressAdView *> *)views
{
    NSLog(@"%s",__FUNCTION__);
    self.expressAdViews = [NSMutableArray arrayWithArray:views];
    if (self.expressAdViews.count) {
        [self.expressAdViews enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            BUNativeExpressAdView *adView = (BUNativeExpressAdView *)obj;
            adView.rootViewController = self;
            [adView render];
//            if (!(((idx + 1) * 6 -1) >= self.dataArray.count)) {
//                if (idx == 0) {
//                    [self.dataArray insertObject:adView atIndex:3];
//                }else{
//                    [self.dataArray insertObject:adView atIndex:4+ ((idx - 1 + 1) * 6 -1)];
//                }
//
//            }
            
            BOOL success = [UserDefault boolForKey:@"quickLookNews"];
            
            NSInteger index = success ? (5 + idx * 9) : (2 + idx * 6);
            if (index >= self.tempArray.count) {
                NSInteger k = index - self.tempArray.count;
                if (k < 1) {
                    [self.tempArray addObject:adView];
                }
                //[self.tempArray addObject:adView];
            }else{
                [self.tempArray insertObject:adView atIndex:index];
            }
            
            
           
            
            

        }];
        
        [self.mixDataArray addObjectsFromArray:self.tempArray];
        
    
        

    }

    


    [self.tableView reloadData];
    
    if (currentPage == 1) {
        [self.tableView tab_endAnimationEaseOut];
        [self creatLoadSuccessView];
    }
    currentPage++;
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];

    NSLog(@"广告请求成功时间:%@",[NSDate date]);
}

/**
 * Sent when views fail to load ad
 */
- (void)nativeExpressAdFailToLoad:(BUNativeExpressAdManager *)nativeExpressAdManager error:(NSError *_Nullable)error
{
    NSLog(@"%s",__FUNCTION__);
    NSLog(@"Express Ad Load Fail : %@",error);
    [self.mixDataArray addObjectsFromArray:self.tempArray];
    [self.tableView reloadData];
    if (currentPage == 1) {
        [self.tableView tab_endAnimationEaseOut];
        [self creatLoadSuccessView];
    }
    currentPage++;
   
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

/**
 * This method is called when rendering a nativeExpressAdView successed, and nativeExpressAdView.size.height has been updated
 */
- (void)nativeExpressAdViewRenderSuccess:(BUNativeExpressAdView *)nativeExpressAdView
{
    NSLog(@"%s",__FUNCTION__);
    [self.tableView reloadData];
}

/**
 * This method is called when a nativeExpressAdView failed to render
 */
- (void)nativeExpressAdViewRenderFail:(BUNativeExpressAdView *)nativeExpressAdView error:(NSError *_Nullable)error
{
    UIView *superView = nativeExpressAdView.superview;
    
    UITableViewCell* cell = (UITableViewCell *)superView.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    
    
    
    
    [self.mixDataArray removeObjectAtIndex:indexPath.section];
    //[nativeExpressAdView removeFromSuperview];
    [self.tableView reloadData];
}

/**
 * Sent when an ad view is about to present modal content
 */
- (void)nativeExpressAdViewWillShow:(BUNativeExpressAdView *)nativeExpressAdView
{
    
}

/**
 * Sent when an ad view is clicked
 */
- (void)nativeExpressAdViewDidClick:(BUNativeExpressAdView *)nativeExpressAdView
{
    NSLog(@"%s",__FUNCTION__);
}

/**
Sent when a playerw playback status changed.
@param playerState : player state after changed
*/
- (void)nativeExpressAdView:(BUNativeExpressAdView *)nativeExpressAdView stateDidChanged:(BUPlayerPlayState)playerState
{
    NSLog(@"%s",__FUNCTION__);
}

/**
 * Sent when a player finished
 * @param error : error of player
 */
- (void)nativeExpressAdViewPlayerDidPlayFinish:(BUNativeExpressAdView *)nativeExpressAdView error:(NSError *)error
{
    NSLog(@"%s",__FUNCTION__);
}

/**
 * Sent when a user clicked dislike reasons.
 * @param filterWords : the array of reasons why the user dislikes the ad
 */
- (void)nativeExpressAdView:(BUNativeExpressAdView *)nativeExpressAdView dislikeWithReason:(NSArray<BUDislikeWords *> *)filterWords
{
    NSLog(@"%s",__FUNCTION__);
    
    UIView *superView = nativeExpressAdView.superview;
    
    UITableViewCell* cell = (UITableViewCell *)superView.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    
    
    
    
    [self.mixDataArray removeObjectAtIndex:indexPath.section];
    //[nativeExpressAdView removeFromSuperview];
    [self.tableView reloadData];
}

/**
 * Sent after an ad view is clicked, a ad landscape view will present modal content
 */
- (void)nativeExpressAdViewWillPresentScreen:(BUNativeExpressAdView *)nativeExpressAdView
{
    
}

/**
 This method is called when another controller has been closed.
 @param interactionType : open appstore in app or open the webpage or view video ad details page.
 */
- (void)nativeExpressAdViewDidCloseOtherController:(BUNativeExpressAdView *)nativeExpressAdView interactionType:(BUInteractionType)interactionType
{
    
}


/**
 This method is called when the Ad view container is forced to be removed.
 @param nativeExpressAdView : Ad view container
 */
- (void)nativeExpressAdViewDidRemoved:(BUNativeExpressAdView *)nativeExpressAdView
{
    NSLog(@"%s",__FUNCTION__);
    
    UIView *superView = nativeExpressAdView.superview;
    
    UITableViewCell* cell = (UITableViewCell *)superView.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    
    
    
    
    [self.mixDataArray removeObjectAtIndex:indexPath.section];
    //[nativeExpressAdView removeFromSuperview];
    [self.tableView reloadData];
}


#pragma mark - 获取定位省份的key
- (NSString *)getLocationAddressKeyWithProvinceName:(NSString *)province
{
    NSString* str = @"bj";
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"newProvince" ofType:@"plist"];
    //其次通过这个文件路径获得字典文件(因为Info.plist内容本身就是个字典集)
    NSArray *provinceArr = [NSArray arrayWithContentsOfFile:filePath];
    
    for (NSDictionary* dic in provinceArr) {
        if ([dic[@"provinceName"] isEqualToString:province]) {
            str = dic[@"provinceValue"];
            break;
        }
    }
    
    
    return str;
}


#pragma mark - public methods
- (void)refreshData
{
    [self.tableView tab_startAnimation];
    [self.tableView.mj_header beginRefreshing];
}


#pragma mark - getters and setters
- (UITableView *)tableView
{
    if (!_tableView) {
        
        if ([self.from isEqualToString:@"home"]) {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight  - 41) style:UITableViewStyleGrouped];
        }else{
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - 41) style:UITableViewStyleGrouped];
        }
        
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
        _tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        
        _tableView.estimatedSectionFooterHeight = 10;
        _tableView.estimatedSectionHeaderHeight = 10;
        _tableView.estimatedRowHeight = 50;
        
        [_tableView registerNib:[UINib nibWithNibName:@"NewsListTableViewCell" bundle:nil] forCellReuseIdentifier:@"NewsListTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsList2Cell" bundle:nil] forCellReuseIdentifier:@"NewsList2Cell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsTextCell" bundle:nil] forCellReuseIdentifier:@"NewsTextCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsImagesCell" bundle:nil] forCellReuseIdentifier:@"NewsImagesCell"];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"nativeexpresscell"];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"BUDNativeExpressCell"];
        
        
        
        
        
        //_tableView.tableFooterView = [UIView new];
       
    
        // 注意！！！
        // xib 动画数组的顺序是组件关联xib文件的顺序。
        // v2.0.9以后，增加openAnimationTag属性，方便快速定位动画元素。
//        _tableView.tabAnimated = [TABTableAnimated animatedWithCellClass:[NewsListTableViewCell class] cellHeight:228];
//
//        _tableView.tabAnimated = [TABTableAnimated animatedWithCellClass:[NewsTextCell class] cellHeight:81];
//        _tableView.tabAnimated.cancelGlobalCornerRadius = YES;
//        _tableView.tabAnimated.animatedHeight = 12.f;
        
        
        _tableView.tabAnimated = [TABTableAnimated animatedWithCellClass:[NewsList2Cell class] cellHeight:111];
        _tableView.tabAnimated.cancelGlobalCornerRadius = YES;
        _tableView.tabAnimated.animatedHeight = 12.f;
        _tableView.tabAnimated.dropAnimationDuration = 3;
        _tableView.tabAnimated.animatedSectionCount = 3;
        _tableView.tabAnimated.superAnimationType = TABViewSuperAnimationTypeShimmer;
        _tableView.tabAnimated.canLoadAgain = YES;
        
        _tableView.tabAnimated.adjustBlock = ^(TABComponentManager * _Nonnull manager) {
            manager.animation(0).height(0.02);
            manager.animation(5).height(0.02);
        };
        

        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self.tableView tab_startAnimation];
            [self loadData];
              
        }];
        
        [header setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
            
        // 往下拉的时候文字
            
        [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
            
        // 松手时候的文字
            
        [header setTitle:@"松开刷新" forState:MJRefreshStatePulling];
            
        // 隐藏时间
            
        header.lastUpdatedTimeLabel.hidden = YES;
      
        
        _tableView.mj_header = header;
    
        [_tableView tab_startAnimation];
        
        
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            if (self->currentPage == 1) {
                [SVProgressHUD showErrorWithStatus:@"暂无法点击"];
            }else{
                [self loadMoreNewsData];
            }
            
        } ];
        
        
        
    }
    return _tableView;
}

- (NSMutableDictionary *)dispatchTable
{
    if (_dispatchTable == nil) {
        _dispatchTable = [[NSMutableDictionary alloc]init];
    }
    return _dispatchTable;
}
/*
#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
