//
//  HLNativeTableViewController.m
//  HLAdSDKDemo
//
//  Created by Liubin on 2024/3/11.
//

#import "HLNativeTableViewController.h"
#import "HLTestNativeTableViewCell.h"
#import <ULinkAd/HMAdsSDKExtension.h>

@interface HLNativeTableViewController ()<UITableViewDelegate, UITableViewDataSource, HMAdsFeedAdDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *closeBtn;
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *nativeAdArray;

@property (nonatomic, assign) NSInteger maxCount;
@property (nonatomic, assign) NSInteger adIndex;

@end

@implementation HLNativeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    for (NSInteger i = 0; i<20; i++) {
        [self.dataArray addObject:@(i)];
    }
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.tableView.frame = CGRectMake(0, 64,  [UIScreen mainScreen].bounds.size.width,  [UIScreen mainScreen].bounds.size.height-64);
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
        
    self.maxCount = 3;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (NSInteger i = 0; i < self.maxCount; i++) {
            [self loadNativeAd];
        }
    });
    
    self.closeBtn.frame = CGRectMake(16, 64, 40, 40);
    self.titleLabel.frame = CGRectMake(0, 64, self.view.frame.size.width, 40);
    self.titleLabel.center = CGPointMake(self.view.center.x, self.closeBtn.center.y);
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.closeBtn];
    
}

- (void)loadNativeAd {
    HMAdsFeedAd *feedAd = [[HMAdsFeedAd alloc] initHMAdsFeedAdWithPlacementId:@"8004302" adSize:CGSizeMake(self.view.frame.size.width, 0)];
    feedAd.rootViewController = self;
    feedAd.delegate = self;
//    [feedAd loadFeedImgaeStyle:HLAdsFeedImageStyleTop edge:0];
    [feedAd loadAdData];
    [self.nativeAdArray addObject:feedAd];
}


- (void)clickClose {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - Feed Delegate
/**
 * feed广告开始请求
 */
- (void)feedAdHMAdsDidStartAd:(HMAdsFeedAd *)feedAd {
    NSLog(@"信息流开始请求:%@", feedAd);
}

/**
 * feed广告加载成功
 */
- (void)feedAdHMAds:(HMAdsFeedAd *)feedAd didReceiveAd:(UIView *)feedView {
    NSLog(@"信息流加载成功：%@ view: %@ 单价：%.f", feedAd, feedView, [feedAd adEcpm]);
    NSUInteger index = arc4random() % (self.dataArray.count - 3) + 2;
    if (feedView) {
        [self.dataArray insertObject:feedView atIndex:index];
    }
#warning 如果同时加载多条广告，请自行判断reloadData时机
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void)feedAdHMAds:(HMAdsFeedAd *)feedAd didRenderSuccessAd:(UIView *)feedView {
    NSLog(@"信息流渲染成功：%@，广告View：%@", feedAd, feedView);
}

/**
 * feed广告展示成功
 */
- (void)feedAdHMAdsDidShowAd:(HMAdsFeedAd *)feedAd view:(UIView *)view {
    NSLog(@"信息流展示：%@，广告View：%@", feedAd, view);

}

/**
   feed广告接收失败回调
 */
- (void)feedAdHMAds:(HMAdsFeedAd *)feedAd didFailWithError:(NSError *)error {
    NSLog(@"信息流失败:%@",error);
}

/**
 * feed点击广告回调
 */
- (void)feedAdHMAdsClickAd:(HMAdsFeedAd *)feedAd view:(UIView *)view {
    NSLog(@"信息流点击：%@，广告View：%@", feedAd, view);
}

///  feed点击跳转app
- (void)feedAdHMAdDidEnterBackground:(nonnull HMAdsFeedAd *)feedAd {
    NSLog(@"信息流点击跳转app：%@", feedAd);
}

/**
 * feed关闭广告回调
 */
- (void)feedAdHMAdsClosedAd:(HMAdsFeedAd *)feedAd view:(UIView *)view {
    NSLog(@"信息流关闭:%@",view);
    [self.nativeAdArray removeObject:feedAd];
    [self.dataArray removeObject:view];
    [self.tableView reloadData];
}

- (void)feedAdHMAdDidClosedWebBrower:(HMAdsFeedAd *)feedAd {
    NSLog(@"信息流落地页关闭:%@", feedAd);
}


- (void)showAlertWithTitle:(NSString *)title Handler:(void (^ __nullable)(UIAlertAction *action))handler {
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:nil message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        handler(action);
    }];
    [alter addAction:sure];
    [self presentViewController:alter animated:YES completion:nil];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    id object = [self.dataArray objectAtIndex:indexPath.row];
    if ([object isKindOfClass:UIView.class]) {
        // 加载广告传入的adSize高度为0时，可获取广告view的高度
        UIView *nativeView  = (UIView *)object;
        return nativeView.frame.size.height;
    } else {
        return 80;
    }
}


#pragma mark - UITableViewDataSource

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    id object = [self.dataArray objectAtIndex:indexPath.row];
    if ([object isKindOfClass:UIView.class]) {
        NSInteger tag = indexPath.row + 1000;
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HLTestNativeTableViewCell" forIndexPath:indexPath];
        UIView *subView = [cell.contentView viewWithTag:tag];
        if ([subView superview]) {
            [subView removeFromSuperview];
        }
        UIView *nativeView  = (UIView *)object;
        nativeView.tag = tag;
        [cell.contentView addSubview:nativeView];
        return cell;
    }
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        cell.textLabel.text = [NSString stringWithFormat:@"测试：%ld", indexPath.row];
        cell.contentView.backgroundColor = UIColor.grayColor;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *title = [NSString stringWithFormat:@"点击测试：%ld", indexPath.row];
    [self showAlertWithTitle:title Handler:^(UIAlertAction *action) {
        
    }];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = self.view.backgroundColor;
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
        [_tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"UITableViewCell"];
        [_tableView registerClass:HLTestNativeTableViewCell.class forCellReuseIdentifier:@"HLTestNativeTableViewCell"];

        if (@available(iOS 15.0,*)) {
            // 设置组头默认22高度
            _tableView.sectionHeaderTopPadding = YES;
        }
    }
    return _tableView;
}

- (UIButton *)closeBtn {
    if (!_closeBtn) {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [_closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
        [_closeBtn setTitleColor:UIColor.blueColor forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(clickClose) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.backgroundColor = UIColor.whiteColor;
        _titleLabel.textColor = UIColor.blackColor;
        _titleLabel.font = [UIFont systemFontOfSize:16];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.text = @"模板原生列表Demo";
    }
    return _titleLabel;;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArray;
}

- (NSMutableArray *)nativeAdArray {
    if (!_nativeAdArray) {
        _nativeAdArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _nativeAdArray;
}

@end
