ArticleDetailViewController.m 14.9 KB
//
//  ArticleDetailViewController.m
//  CNLiveScioLive
//
//  Created by CNLive-zxw on 2018/9/21.
//  Copyright © 2018年 CNLive. All rights reserved.
//

#import "ArticleDetailViewController.h"
#import "CNHomeModel.h"
#import "CNLiveNewsDetailModel.h"
#import <WebKit/WebKit.h>
#import "CNLiveNewsDetailsView.h"

@interface ArticleDetailViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
{
    UIProgressView *_progressView;
    NSString *_htmlString;
    NSString *_htmlUrl;
    BOOL _isHaveVideo;

}
//@property (nonatomic, strong) NSMutableArray *data;
//@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) CNLiveNewsDetailsView *detailsView;

@property (nonatomic, strong) NSArray *fontArray;
@property (nonatomic, assign) NSInteger fontIndex;

@end

@implementation ArticleDetailViewController
#pragma mark - Data
/*
- (void)loadData{
//    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
//        [SVProgressHUD showErrorWithStatus:CustomStr(@"NetworkiInterruption") duration:0.5];
//        return;
//    }
    NSString *strUrl = @"http://app.phonemovie.cnlive.com/gxb/api/programRelative";
    NSString *categoryId = [NSString stringWithFormat:@"{\"plat\":\"i\",\"version\":\"5.0\",\"appid\":\"gxb\",\"cmsContentId\":\"%@\"}",self.model.cmsContentId];
    NSDictionary *parameters = @{@"params":categoryId};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [XWHTTPTool POST:strUrl params:parameters success:^(id json) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        // 请求成功,解析数据
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:json];
        
        if ([dic[@"errorCode"] isEqualToString:@"0"]) {
            
            NSArray *programs = dic[@"programs"];
            
            if ([programs isKindOfClass:[NSArray class]]) {
                for (NSDictionary *dics in programs) {
                    [CNLiveNewsDetailModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
                        return @{ @"ID" : @"id" ,@"Description" : @"description" };
                    }];
                    
                    NSLog(@"%@",dics);
                    [self.data addObject:[CNLiveNewsDetailModel mj_objectWithKeyValues:dics]];
                }
                
            }
            
        } else {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [AlertViewTool showHUDAddedToView:self.view text:dic[@"errorMessage"]];
            
        }
        
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [AlertViewTool showHUDAddedToView:self.view text:CustomStr(@"ServerBusy")];
        
    }];
}
- (void)loadMoreData{
 
    
}
 */
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:_progressView];
    
    NSError *error = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: &error];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    //计数统计
    
    if ([self.model.cmsColumnId isEqualToString:@"spzl/srbd/"]) {
        //深入报道
        [CNLiveStat event:@"srbdsl"];
    }else if ([self.model.cmsColumnId  isEqualToString:@"spzl/zcjd/"]){
        //国新图说
        [CNLiveStat event:@"gxtssl"];
    }else if ([self.model.cmsColumnId  isEqualToString:@"spzl/gzdt/"]){
        //要闻
        [CNLiveStat event:@"ywsl"];
    }else if ([self.model.cmsColumnId isEqualToString:@"spzl/hyjj/"]){
        //焦点
        [CNLiveStat event:@"jdsl"];
    }else if ([self.model.cmsColumnId  isEqualToString:@"spzl/lingdaoyaowen/"]){
        //领导要闻
        [CNLiveStat event:@"ldywsl"];
    }else if ([self.model.cmsColumnId  isEqualToString:@"spzl/bw/"]){
        //部委
        [CNLiveStat event:@"bwsl"];
    }else if ([self.model.cmsColumnId  isEqualToString:@"spzl/dfdt/"]){
        //地方外宣
        [CNLiveStat event:@"dfwxsl"];
    }else if ([self.model.cmsColumnId isEqualToString:@"spzl/scio/"]){
        //scio news
        [CNLiveStat event:@"newssl"];
    }else if ([self.model.cmsColumnId  isEqualToString:@"spzl/wqtw/"]){
        //往期图文
        [CNLiveStat event:@"wqtwsl"];
    }else if ([self.model.cmsColumnId isEqualToString:@"spzl/fbhgg/"]){
        //发布会公告
        [CNLiveStat event:@"fbhggsl"];
    }else if ([self.model.cmsColumnId  isEqualToString:@"spzl/toutiao/"]){
        //头条
        [CNLiveStat event:@"ttsl"];
    }else if ([self.model.cmsColumnId  isEqualToString:@"spzl/yidaiyilu/"]){
        //一带一路
        [CNLiveStat event:@"ydylsl"];
    }else if ([self.model.cmsColumnId isEqualToString:@"spzl/zixun/"]){
        //资讯
        [CNLiveStat event:@"zxsl"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavigationBar];
    
    _fontIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"FontSize"];
    
    _htmlString = [NSString stringWithContentsOfURL:[NSURL URLWithString:self.model.pageUrl] encoding:NSUTF8StringEncoding error:nil];
    //替换掉html页面中的展示js
    NSString *replace = [_htmlString stringByReplacingOccurrencesOfString:@"previewImage.start(obj);" withString:@""];
    _htmlString = replace;
    _htmlUrl = self.model.pageUrl;
    if ([_htmlString containsString:@"<video"]) {
        _isHaveVideo = YES;
        [[JGMusicManager shareMusicManager] playStop];
    }
    [self createUI];


    // Do any additional setup after loading the view.
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_progressView removeFromSuperview];
}
- (NSString *)setHTMLString {
    NSString* htmlHeader = [[NSString alloc] initWithFormat:@"<p><font style=\"font-size:20px;\"><strong>%@</strong></font><p>%@</p><font color=\"#184085\">%@</font> </p>",self.model.title,self.model.createDate,@"来源 : 国新网"];
    NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@<font style=\"font-size:%@px;\">%@</font></div>",htmlHeader,_fontArray[_fontIndex],self.model.content];
    NSLog(@"htmlcontent = %@",htmlcontent);
    return htmlcontent;
}
#pragma mark - UI
- (void)setUpNavigationBar{
    self.navigationController.navigationBar.barTintColor = Color_Blue;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:18]};
    //左
    UIButton *headerButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
    headerButton.layer.cornerRadius = 2.0;
    headerButton.layer.masksToBounds = true;
    [headerButton setImage:[UIImage imageNamed:@"cnlive_white_back"] forState:UIControlStateNormal];
    [headerButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:headerButton];
    self.navigationItem.title = self.model.cmsColumnName;
    
}
- (void)createUI{
    [self.view addSubview:self.webView];
    [_webView loadHTMLString:_htmlString baseURL:[NSURL URLWithString:_htmlUrl]];
    self.detailsView.dic = [self.model toDictionary];

    self.detailsView.pics = @[@"cnlive_fontsize", @"cnlive_isfavorite" ,@"cnlive_share"];
    __weak typeof(self) weakSelf = self;

    self.detailsView.block = ^(NSInteger tag) {
        switch (tag) {
            case 1000://字体
            {
                if (weakSelf.fontArray.count - 1 == weakSelf.fontIndex) {
                    weakSelf.fontIndex = 0;
                } else {
                    weakSelf.fontIndex++;
                }
                if (0 == weakSelf.fontIndex) {
                    NSLog(@"0");
//                    [weakSelf.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'"];
                    [weakSelf.webView evaluateJavaScript:[NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust = '100%'"] completionHandler:nil];
                } else if (1 == weakSelf.fontIndex) {
                    NSLog(@"1");
//                    [weakSelf.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '120%'"];
                    [weakSelf.webView evaluateJavaScript:[NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust = '120%'"] completionHandler:nil];
                } else if (2 == weakSelf.fontIndex) {
                    NSLog(@"2");
//                    [weakSelf.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '140%'"];
                    [weakSelf.webView evaluateJavaScript:[NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust = '140%'"] completionHandler:nil];
                }
            }
                break;
            case 1001://收藏
            {
                NSDictionary *dic = [weakSelf.model toDictionary];
                TableData *notice = [[TableData alloc] initWithJSONDictionary:dic];
                BOOL isIn = [[DBAction sharedDBAction] isInTable:notice];
                if (!isIn) {
                    BOOL isInsert = [[DBAction sharedDBAction] insertTable:notice];
                    if (isInsert) {
                        [AlertViewTool showHUDAddedToView:weakSelf.view text:CustomStr(@"CollectSuccess")];
                        [weakSelf.detailsView.btn setImage:[UIImage imageNamed:@"cnlive_isfavorited"] forState:UIControlStateNormal];
                        
                    }
                    
                } else {
                    BOOL isDelete = [[DBAction sharedDBAction] deleteTable:notice];
                    if (isDelete) {
                        [AlertViewTool showHUDAddedToView:weakSelf.view text:CustomStr(@"CancelCollect")];
                        [weakSelf.detailsView.btn setImage:[UIImage imageNamed:@"cnlive_isfavorite"] forState:UIControlStateNormal];
                        
                    }
                }
                
                
            }
                break;
            case 1002://分享
            {
                [[TemplateShareManager manager] shareImage:self.model.img title:self.model.title text:self.model.desc?self.model.desc:self.model.title url:self.model.pageUrl controller:self];
                return;
            }
                break;
                
            default:
                break;
        }
        
    };
    [self.view addSubview:self.detailsView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
}

/*
#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.
}
*/
#pragma mark - Lazy Laoding
- (WKWebView *)webView {
    if (!_webView) {
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        config.preferences = [WKPreferences new];
        config.preferences.minimumFontSize = 10;
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.userContentController = [[WKUserContentController alloc]init];
        [config.userContentController addScriptMessageHandler:self name:@"goback"];
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight-NavBarHeight-TabBarHeight) configuration:config];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        _webView.scrollView.bounces = NO;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];

    }
    return _webView;
}
- (UIProgressView *)progressView{
    if(!_progressView){
        _progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 44, CGRectGetWidth(self.view.frame), 2)];
        _progressView.progressTintColor = Color_Blue;
        [self.view addSubview:self.progressView];
    }
    return  _progressView;
}
- (NSArray *)fontArray{
    if (!_fontArray) {
        _fontArray = [[NSArray alloc] initWithObjects:@"16", @"20", @"24", nil];
    }
    return _fontArray;
}

//- (UITableView *)tableView{
//    if(!_tableView){
//        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight-45-NavBarHeight-TabBarHeight) style:UITableViewStylePlain];
//        _tableView.delegate = self;
//        _tableView.dataSource = self;
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _tableView.backgroundColor = HEXCOLOR(0xebebeb);
//
//_tableView.estimatedRowHeight = 0;
//_tableView.estimatedSectionHeaderHeight = 0;
//_tableView.estimatedSectionFooterHeight = 0;
//        //  设置上拉加载
//        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//        _tableView.mj_footer = footer;
//
//    }
//    return _tableView;
//}
//- (NSMutableArray *)data{
//    if (!_data) {
//        _data = [[NSMutableArray alloc] init];
//    }
//    return _data;
//}
#pragma mark - 监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if (self.webView.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:YES];
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView setNavigationDelegate:nil];
    [self.webView setUIDelegate:nil];
}
- (CNLiveNewsDetailsView *)detailsView{
    if (!_detailsView) {
        _detailsView = [[CNLiveNewsDetailsView alloc] initWithFrame:CGRectMake(0, MainScreenHeight-TabBarHeight-NavBarHeight, MainScreenWidth, TabBarHeight)];
    }
    return _detailsView;
}
@end