VideoPlayBackViewController.m 33.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
//
//  VideoPlayBackViewController.m
//  SCIOLiveCN
//
//  Created by huayu on 16/6/29.
//  Copyright © 2016年 huayu. All rights reserved.
//
#import "JSONKit.h"
#import "VideoTableViewCell.h"
#import "ArticleTableViewCell.h"
#import "VideoPlayBackViewController.h"
//#import "OldVideoDetailViewController.h"

@interface VideoPlayBackViewController ()<CNLivePlayerControllerDelegate> {
    BOOL isPlay;
    UIButton *_shareButton;

}

@end

@implementation VideoPlayBackViewController
- (void)Pop:(id)sender{
    [self.videoController stop];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (id)initWithDictionary:(NSDictionary *)dictionary{
    if (self = [super init]) {
        _dictionary = [NSDictionary dictionaryWithDictionary:dictionary];
        if ([_dictionary[@"videoFlag"] isEqualToString:@"1"]) {
            if (![_dictionary[@"videoUrl"] isEqualToString:@""]) {
                isPlay = YES;
                url = _dictionary[@"videoUrl"];
                if (0 == [url length]) {
                    url = _dictionary[@"uploadVideoUrl"];
                }
                url = [url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                movieUrl = [NSURL URLWithString:url];
                videoHeight = MainScreenWidth * (9.0 / 16.0);

            } else {
                isPlay = NO;
                videoHeight = MainScreenWidth * (9.0 / 16.0);

            }
            
        } else {
            isPlay = NO;
            videoHeight = 0;
        }
        
        NSLog(@"movieUrl -> %@",movieUrl);
        videoHeight = MainScreenWidth * (9.0 / 16.0);

    }
    return self;
}

- (NSString *)setHTMLString {
//    NSString* htmlHeader = [[NSString alloc] initWithFormat:@"<html><p><font style=\"font-size:20px;\"><strong>%@</strong></font><br>%@</p><body>",[_dicArticle objectForKey:@"Tittle"],[_dicArticle objectForKey:@"PublishDateTime"]];
    NSString* htmlBody = [[NSString alloc] initWithFormat:@"<p><font style=\"font-size:%@px;\">%@</font></p>",fontArray[fontIndex],[_dicArticle objectForKey:@"Content"]];
    NSString* htmlFooter = @"</body></html>";
    NSString* strHtml = [[NSString alloc] initWithFormat:@"%@%@",htmlBody,htmlFooter];
    return strHtml;
}
- (void)loadData{
    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
        return;
    }
    [SVProgressHUD show];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:tuwen([_dictionary[@"gxbArticleId"] intValue]) parameters:nil headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              // 请求成功,解析数据
        NSString * jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//              NSLog(@"jsonString == %@",jsonString);
        NSArray *arr = [jsonString objectFromJSONString];
        self->_dicArticle = [arr objectAtIndex:0];
//              NSLog(@"%@", _dicArticle);
        [self->_webView loadHTMLString:[self setHTMLString] baseURL:nil];
        [SVProgressHUD dismiss];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        NSLog(@"%@", [error localizedDescription]);
        [SVProgressHUD dismiss];
        //[SVProgressHUD showErrorWithStatus:CustomStr(@"ServerBusy") duration:0.5];
            
    }];
}
- (void)loadShareView {
    UIImageView *lineImage = [[UIImageView alloc] init];
    if (iPhoneX) {
        lineImage.frame = CGRectMake(0, MainScreenHeight - 44 - 34, MainScreenWidth, 1);
    } else {
        lineImage.frame = CGRectMake(0, MainScreenHeight - 44, MainScreenWidth, 1);
    }
    lineImage.backgroundColor = Color_Line;
    [self.view addSubview:lineImage];
    
    UIButton *fontSizeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [fontSizeButton setImage:[UIImage imageNamed:@"cnlive_fontsize"] forState:UIControlStateNormal];
    if (iPhoneX) {
        [fontSizeButton setFrame:CGRectMake((MainScreenWidth/2 - 33)/2, MainScreenHeight - 44 + (44 - 22)/2 - 34, 33, 22)];
    } else {
        [fontSizeButton setFrame:CGRectMake((MainScreenWidth/2 - 33)/2, MainScreenHeight - 44 + (44 - 22)/2, 33, 22)];
    }
    [fontSizeButton addTarget:self action:@selector(shareButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:fontSizeButton];
    [fontSizeButton setTag:10000];
    
    UIButton *isFavoriteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    TableData *notice = [[TableData alloc] initWithJSONDictionary:_dictionary];
    BOOL isIn = [[DBAction sharedDBAction] isInTable:[User_Defaults objectForKey:Language_Local] notice:notice];
    if (isIn) {
        [isFavoriteButton setImage:[UIImage imageNamed:@"cnlive_isfavorited"] forState:UIControlStateNormal];
    } else {
        [isFavoriteButton setImage:[UIImage imageNamed:@"cnlive_isfavorite"] forState:UIControlStateNormal];
    }
    if (iPhoneX) {
        [isFavoriteButton setFrame:CGRectMake((MainScreenWidth - 23)/2, MainScreenHeight - 44 + (44 - 22)/2 - 34, 33, 22)];
    } else {
        [isFavoriteButton setFrame:CGRectMake((MainScreenWidth - 23)/2, MainScreenHeight - 44 + (44 - 22)/2, 33, 22)];
    }
    [isFavoriteButton addTarget:self action:@selector(shareButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:isFavoriteButton];
    [isFavoriteButton setTag:20000];
    
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setImage:[UIImage imageNamed:@"cnlive_share"] forState:UIControlStateNormal];
    if (iPhoneX) {
        [shareButton setFrame:CGRectMake((MainScreenWidth*3/2 - 22)/2, MainScreenHeight - 44 + (44 - 22)/2 - 34, 33, 22)];
    } else {
        [shareButton setFrame:CGRectMake((MainScreenWidth*3/2 - 22)/2, MainScreenHeight - 44 + (44 - 22)/2, 33, 22)];
    }
    [shareButton addTarget:self action:@selector(shareButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
    [shareButton setTag:30000];
    _shareButton = shareButton;
}
- (void)shareButtonTaped:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (10000 == btn.tag) {
        if ([fontArray count] - 1 == fontIndex) {
            fontIndex = 0;
        } else {
            fontIndex++;
        }
        [_webView loadHTMLString:[self setHTMLString] baseURL:nil];
    } else if (20000 == btn.tag) {
        TableData *notice = [[TableData alloc] initWithJSONDictionary:_dictionary];
        BOOL isIn = [[DBAction sharedDBAction] isInTable:[User_Defaults objectForKey:Language_Local] notice:notice];
        if (!isIn) {
            BOOL isInsert = [[DBAction sharedDBAction] insertTable:[User_Defaults objectForKey:Language_Local] notice:notice];
            if (isInsert) {
                [AlertViewTool showHUDViewText:CustomStr(@"CollectSuccess")];
                [btn setImage:[UIImage imageNamed:@"cnlive_isfavorited"] forState:UIControlStateNormal];
            }
        } else {
            BOOL isDelete = [[DBAction sharedDBAction] deleteTable:[User_Defaults objectForKey:Language_Local] notice:notice];
            if (isDelete) {
                [AlertViewTool showHUDViewText:CustomStr(@"CancelCollect")];
                [btn setImage:[UIImage imageNamed:@"cnlive_isfavorite"] forState:UIControlStateNormal];
            }
        }
    } else if (30000 == btn.tag) {
        NSString *img = [NSString stringWithFormat:@"%@",_dictionary[@"img"]];
        NSString *title = [NSString stringWithFormat:@"%@",_dictionary[@"title"]];
        NSString *text = [NSString stringWithFormat:@"%@",!_dictionary[@"desc"]||[_dictionary[@"desc"] isEqualToString:@""]?title:_dictionary[@"desc"]];
        NSString *url = [NSString stringWithFormat:@"%@",_dictionary[@"pageUrl"]];
        [[TemplateShareManager manager] shareImage:img title:title text:text url:url controller:self];
        return;
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.liveController stop];
    self.liveController = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[JGMusicManager shareMusicManager] playStop];
//    if ([_dictionary[@"videoFlag"] isEqualToString:@"0"]) {
//        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(Pop:) forControlEvents:UIControlEventTouchUpInside];
//        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:headerButton];
//        self.navigationItem.title = _dictionary[@"cmsColumnName"];
//        
//    }else{
//        [self.navigationController setNavigationBarHidden:YES];
//
//    }
    [self.navigationController setNavigationBarHidden:YES];
    
    NSError *error = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &error];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.liveController stopShow];
    [self.navigationController setNavigationBarHidden:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadShareView];
    self.view.backgroundColor = [UIColor whiteColor];
    if (iPhoneX) {
        backgroundView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, videoHeight + 44, MainScreenWidth, MainScreenHeight - videoHeight - 44 - 34 - 44)];
    } else {
        backgroundView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, videoHeight, MainScreenWidth, MainScreenHeight - videoHeight - 44)];
    }
    backgroundView.bounces = NO;
    [self.view addSubview:backgroundView];

     NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);";

     WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
     WKUserContentController *wkUController = [[WKUserContentController alloc] init];
     [wkUController addUserScript:wkUScript];

     WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
     config.userContentController = wkUController;
     relatedWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
//    relatedWebView = [[WKWebView alloc] initWithFrame:CGRectZero];
    relatedWebView.scrollView.backgroundColor = [UIColor whiteColor];
//    relatedWebView.dataDetectorTypes = UIDataDetectorTypeNone;
    relatedWebView.backgroundColor = [UIColor whiteColor];
    relatedWebView.scrollView.bounces = NO;
    relatedWebView.navigationDelegate = self;
    relatedWebView.UIDelegate = self;
    relatedWebView.opaque = NO;
    relatedWebView.tag = 1000;
    [backgroundView addSubview:relatedWebView];
    
    NSString* htmlHeader = [[NSString alloc] initWithFormat:@"<html><font style=\"font-size:20px;\"><strong>%@</strong></font><br><p>%@</p><p>%@:%@</p><body>",[_dictionary objectForKey:@"title"],[_dictionary objectForKey:@"createDate"], CustomStr(@"Source"), [_dictionary objectForKey:@"author"]?[_dictionary objectForKey:@"author"]:@"国新客户端"];
    NSString* htmlFooter = [[NSString alloc] initWithFormat:@"<div class=\"logo\" style=\"text-indent:2em\">%@</div></body></html>",[_dictionary objectForKey:@"desc"]];

    NSString* strHtml = [[NSString alloc] initWithFormat:@"%@%@",htmlHeader,htmlFooter];
    [relatedWebView loadHTMLString:strHtml baseURL:nil];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundView = nil;
    self.tableView.scrollEnabled = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [backgroundView addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    self.errorLabe = [[UILabel alloc] initWithFrame:CGRectZero];
    self.errorLabe.backgroundColor = [UIColor clearColor];
    self.errorLabe.textColor = HEXCOLOR(0x333333);
    self.errorLabe.font = [UIFont systemFontOfSize:15];
    [backgroundView addSubview:self.errorLabe];
    self.errorLabe.text = @"没有数据";
    self.errorLabe.hidden = YES;
    
    if (!isPlay) {
        [self loadMovieView];
    } else {
        [self addCNLivePlayerWithURL:movieUrl];
//        [self addVideoPlayerWithURL:movieUrl];
    }
    
    fontIndex = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"FontSize"];
    heightArr = [NSMutableArray arrayWithArray:@[@"0",@"0",@"0"]];
    fontArray = @[@"16",@"20",@"24"];
    isShow = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pausePlayer) name:@"PausePlayerNotification" object:nil];
}


- (void)pausePlayer {
    [self.liveController pause];
}

- (void)loadMovieView {
    [[NSUserDefaults standardUserDefaults] setObject:@0 forKey:@"GraphicLive_DidLockScreen"];
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, iPhoneX ? 44 : 0, MainScreenWidth, videoHeight)];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [imageView sd_setImageWithURL:[NSURL URLWithString:_dictionary[@"img"]] placeholderImage:[UIImage imageNamed:@"cnlive_placeholder"]];
    [self.view addSubview:imageView];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton addTarget:self action:@selector(Pop:) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:[UIImage imageNamed:@"cnlive_white_back"] forState:UIControlStateNormal];
    [backButton setFrame:CGRectMake(0, StatusBarHeight, 44, 44)];
    [self.view addSubview:backButton];
}

- (void)addVideoPlayerWithURL:(NSURL *)videoUrl{
    if (!self.videoController) {
        CGRect frame = CGRectMake(0, iPhoneX ? 44 : 0, MainScreenWidth, videoHeight);
        self.videoController = [[ZXVideoPlayerController alloc] initWithFrame:frame];
        __weak typeof(self) weakSelf = self;
        self.videoController.videoPlayerShare = ^{
            __strong typeof(self) strongSelf = weakSelf;
            [strongSelf shareButtonTaped:strongSelf->_shareButton];
        };
        self.videoController.videoPlayerGoBackBlock = ^{
            __strong typeof(self) strongSelf = weakSelf;
            [[NSUserDefaults standardUserDefaults] setObject:@0 forKey:@"ZXVideoPlayer_DidLockScreen"];
            strongSelf.videoController = nil;
            [strongSelf Pop:nil];
        };
        self.liveController.delegate = self;
        [self.videoController showInView:self.view];
    }
    ZXVideo *video = [[ZXVideo alloc] init];
    video.playUrl = url;
    video.title = _dictionary[@"title"];
    self.videoController.video = video;
}

// CNLivePlayer
- (void)addCNLivePlayerWithURL:(NSURL *)videoUrl {
    if (!self.liveController) {
        CGRect frame = CGRectMake(0, iPhoneX ? 44 : 0, MainScreenWidth, videoHeight);
        // Url
        self.liveController = [[CNLivePlayerController alloc] initWithContentURL:[NSURL URLWithString:url]];
        [self.liveController configPlayerWithFrame:frame isLiving:NO];
        [self.liveController showInView:self.view];

//        self.liveController = [[CNLivePlayerController alloc] initVodPlayWithVId:@"1ca25e58c388476b8037e8eb0ef5e8b3" authSuccess:^{
//            [self.liveController configPlayerWithFrame:frame isLiving:NO];
//            [self.liveController showInView:self.view];
//        } authFailed:^(NSDictionary *errorInfo) {
//            NSLog(@"初始化点播播放器失败%@", errorInfo);
//        }];
        
        [[NSUserDefaults standardUserDefaults] setObject:@0 forKey:@"ZXVideoPlayer_DidLockScreen"];
        __weak typeof(self) weakSelf = self;
        self.liveController.videoPlayerGoBackBlock = ^{
            __strong typeof(self) strongSelf = weakSelf;
            [[NSUserDefaults standardUserDefaults] setObject:@0 forKey:@"ZXVideoPlayer_DidLockScreen"];
            [strongSelf.liveController destroyPlayer];
//            strongSelf.liveController = nil;
            [strongSelf Pop:nil];
        };
        self.liveController.delegate = self;

    }
    ZXVideo *video = [[ZXVideo alloc] init];
    video.title = _dictionary[@"title"];
    self.liveController.video = video;
}

//隐藏navigation tabbar 电池栏
- (void)toolbarHidden:(BOOL)Bool{
    [[UIApplication sharedApplication] setStatusBarHidden:Bool withAnimation:UIStatusBarAnimationFade];
    [self.navigationController setNavigationBarHidden:Bool];    
}
- (void)moviePlay:(NSURL *)_movieUrl{
    playBtn.hidden = YES;
    imageView.hidden = YES;
    [[NSUserDefaults standardUserDefaults] setObject:@1 forKey:@"ZXVideoPlayer_DidPlayBack"];
    [self.videoController showInView:self.view];
    [self.videoController videoPlay];
}
- (void)PlayMovie:(UIButton *)sender{
    if (0 == [url length]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒"
                                                        message:@"视频链接不存在!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [self moviePlay:movieUrl];
}
- (void)showGraphicLive:(id)sender {
    isShow = !isShow;
    if (isShow) {
        upDownImage.image = [UIImage imageNamed:@"cnlive_button_up"];
        [backgroundView setContentSize:CGSizeMake(MainScreenWidth, 40 + descriptionHeight + [heightArr[fontIndex] floatValue] + self.tableView.frame.size.height)];
        [_webView setFrame:CGRectMake(0, 40 + descriptionHeight, MainScreenWidth, [heightArr[fontIndex] floatValue])];
        CGRect frame = self.tableView.frame;
        frame.origin.y = 40 + descriptionHeight + graphicLiveHeight;
        [self.tableView setFrame:frame];
        _webView.hidden = NO;
    } else {
        upDownImage.image = [UIImage imageNamed:@"cnlive_button_down"];
        [backgroundView setContentSize:CGSizeMake(MainScreenWidth, 40 + descriptionHeight + self.tableView.frame.size.height)];
        [_webView setFrame:CGRectZero];
        CGRect frame = self.tableView.frame;
        frame.origin.y = 40 + descriptionHeight;
        [self.tableView setFrame:frame];
        _webView.hidden = YES;
    }
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *requestURL = navigationAction.request.URL;
    NSString *scheme = navigationAction.request.URL.scheme;
    if (([scheme isEqualToString: @"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString: @"mailto" ]) && (navigationAction.navigationType == WKNavigationTypeLinkActivated )) {
        [[UIApplication sharedApplication] openURL:requestURL];
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    if (1000 == webView.tag) {
        CGRect frame = relatedWebView.frame;
        frame.size.width = MainScreenWidth;
        frame.size.height = 1;
        relatedWebView.frame = frame;
//        descriptionHeight = relatedWebView.scrollView.contentSize.height;
        
        [webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result,NSError * _Nullable error){
            NSLog(@"scrollHeight高度:%.2f",[result floatValue]);
            descriptionHeight = [result floatValue];
            [relatedWebView setFrame:CGRectMake(0, 0, MainScreenWidth, descriptionHeight)];
            lineImage1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, descriptionHeight, MainScreenWidth, 1)];
            lineImage1.backgroundColor = Color_Line;
            [backgroundView addSubview:lineImage1];
            
            upDownButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [upDownButton addTarget:self action:@selector(showGraphicLive:) forControlEvents:UIControlEventTouchUpInside];
            [upDownButton setFrame:CGRectMake(0, descriptionHeight, MainScreenWidth, 40)];
            [backgroundView addSubview:upDownButton];
            
            UILabel *graphicLive = [[UILabel alloc] initWithFrame:CGRectMake(20, descriptionHeight, MainScreenWidth/2, 40)];
            graphicLive.font = [UIFont systemFontOfSize:13];
            graphicLive.backgroundColor = [UIColor clearColor];
            graphicLive.textColor = HEXCOLOR(0x184085);
            [backgroundView addSubview:graphicLive];
            graphicLive.text = @"发布会图文播报";
            
            upDownImage = [[UIImageView alloc] initWithFrame:CGRectMake(MainScreenWidth - 31, descriptionHeight + 16, 13, 7)];
            upDownImage.image = [UIImage imageNamed:@"cnlive_button_down"];
            [backgroundView addSubview:upDownImage];
            
            lineImage2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40 + descriptionHeight, MainScreenWidth, 1)];
            lineImage2.backgroundColor = Color_Line;
            [backgroundView addSubview:lineImage2];
            
            [backgroundView setContentSize:CGSizeMake(MainScreenWidth, 40 + descriptionHeight)];
            
            NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);";

            WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
            WKUserContentController *wkUController = [[WKUserContentController alloc] init];
            [wkUController addUserScript:wkUScript];

            WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
            config.userContentController = wkUController;
            
            _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    //        _webView = [[WKWebView alloc] initWithFrame:CGRectZero];
            _webView.scrollView.backgroundColor = [UIColor clearColor];
    //        _webView.dataDetectorTypes = UIDataDetectorTypeNone;
            _webView.backgroundColor = [UIColor clearColor];
            _webView.scrollView.bounces = NO;
            _webView.UIDelegate = self;
            _webView.navigationDelegate = self;
            
            _webView.opaque = NO;
            _webView.tag = 2000;
            
            [backgroundView addSubview:_webView];

        }];
        [self loadRelatedInformation];
        [self loadData];
        
    } else if (2000 == webView.tag) {
        CGFloat width = MainScreenWidth - 20;
        NSString *string = [NSString stringWithFormat:
                            @"var script = document.createElement('script');"
                            "script.type = 'text/javascript';"
                            "script.text = \"function ResizeImages() { "
                            "var myimg,oldwidth;"
                            "var maxwidth=%f;" //缩放系数
                            "for(i=0;i <document.images.length;i++){"
                            "myimg = document.images[i];"
                            "if(myimg.width > maxwidth){"
                            "oldwidth = myimg.width;"
                            "myimg.width = maxwidth;"
                            "myimg.height = myimg.height * (maxwidth/oldwidth);"
                            "}"
                            "}"
                            "}\";"
                            "document.getElementsByTagName('head')[0].appendChild(script);",width];
//            [webView stringByEvaluatingJavaScriptFromString:string];
//            [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
        [webView evaluateJavaScript:string completionHandler:nil];
        [webView evaluateJavaScript:@"ResizeImages();" completionHandler:nil];
        
        CGRect frame = _webView.frame;
        frame.size.width = MainScreenWidth;
        frame.size.height = 1;
        _webView.frame = frame;
//        graphicLiveHeight = _webView.scrollView.contentSize.height;
        
        CGFloat contentHeight = webView.scrollView.contentSize.height;
        [webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result,NSError * _Nullable error){
            NSLog(@"scrollHeight高度:%.2f",[result floatValue]);
            graphicLiveHeight = [result floatValue];
            NSLog(@"%@",NSStringFromCGRect(_webView.frame));
            NSLog(@"%@",NSStringFromCGSize(_webView.scrollView.contentSize));
            if (0 == [heightArr[fontIndex] floatValue]) {
                [heightArr replaceObjectAtIndex:fontIndex withObject:[NSString stringWithFormat:@"%f",graphicLiveHeight]];
            }
            
            if (isShow) {
                NSLog(@"fontIndex = %d",fontIndex);
                [backgroundView setContentSize:CGSizeMake(MainScreenWidth, 40 + descriptionHeight + [heightArr[fontIndex] floatValue] + 285)];
                [_webView setFrame:CGRectMake(0, 40 + descriptionHeight, MainScreenWidth, [heightArr[fontIndex] floatValue])];
                CGRect frame = self.tableView.frame;
                frame.origin.y = 40 + descriptionHeight + graphicLiveHeight;
                [self.tableView setFrame:frame];
                _webView.hidden = NO;
            }
        }];
    
    }
}

- (void)shareButtonCNLivePlayerController:(CNLivePlayerController *)view{
    [self shareButtonTaped:_shareButton];
        
}

- (void)loadRelatedInformation {
    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
        return;
    }
    NSString *strUrl = REQUESTURL(@"gxb/api/programRelative");
    NSLog(@"%@",strUrl);
    NSString *categoryId = [NSString stringWithFormat:@"{\"plat\":\"i\",\"version\":\"5.0\",\"appid\":\"gxb\",\"cmsContentId\":\"%@\"}",_dictionary[@"cmsContentId"]];
    NSLog(@"%@",categoryId);
    NSDictionary *parameters = @{@"params":categoryId};
    [AlertViewTool showHUDView];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strUrl
       parameters:parameters headers:nil 
         progress:^(NSProgress * _Nonnull uploadProgress) {}
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              // 请求成功,解析数据
              NSDictionary *_dic = [NSDictionary dictionaryWithDictionary:responseObject];
              NSLog(@"%@",_dic);
              if ([_dic[@"errorCode"] isEqualToString:@"0"]) {
                  NSArray *array = _dic[@"programs"];
                  if (array.count != 0) {
                      _newsArray = [NSArray arrayWithArray:array];
                      [self.tableView setFrame:CGRectMake( 0, 40 + relatedWebView.scrollView.contentSize.height, MainScreenWidth, 36 + 86*_newsArray.count)];
                  }
                  [backgroundView setContentSize:CGSizeMake(MainScreenWidth,40 + descriptionHeight + [heightArr[fontIndex] floatValue] + self.tableView.frame.size.height)];
                  [self.tableView reloadData];
              } else {
                  [AlertViewTool showHUDViewText:_dic[@"errorMessage"]];
              }
              [AlertViewTool hideHUDView];
//{"plat":"i","version":"5.0","appid":"gxb","cmsContentId":"944501"}
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              // 请求失败
              NSLog(@"%@", [error localizedDescription]);
              [AlertViewTool hideHUDView];
//              [AlertViewTool showHUDViewText:CustomStr(@"ServerBusy")];

          }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_newsArray count];
}
-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    return 86.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30.0;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, 1)];
    lineImage.backgroundColor = Color_Line;
    [view addSubview:lineImage];
    
    UILabel *relatedInformation = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, MainScreenWidth - 24, 30)];
    relatedInformation.backgroundColor = [UIColor clearColor];
    relatedInformation.textColor = HEXCOLOR(0x333333);
    relatedInformation.font = [UIFont systemFontOfSize:15];
    [view addSubview:relatedInformation];
    relatedInformation.text = CustomStr(@"RelevantInformation");
    return view;
}
-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section {
    return 6.0;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, 6)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *_dic = _newsArray[indexPath.row];
    if ([@"program" isEqualToString:_dic[@"type"]]) {
        static NSString *identifier = @"videoCell";
        VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[VideoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        [cell.backImage sd_setImageWithURL:[NSURL URLWithString:_dic[@"img"]] placeholderImage:[UIImage imageNamed:@"backDefault"]];
        cell.playImage.image = [UIImage imageNamed:@"playButton"];
        cell.titleLabel.text = _dic[@"title"];
        cell.timeLabel.text  = _dic[@"createDate"];
        return cell;
    } else if ([@"article" isEqualToString:_dic[@"type"]]) {
        static NSString *identifier = @"articleCell";
        ArticleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[ArticleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        [cell.backImage sd_setImageWithURL:[NSURL URLWithString:_dic[@"img"]] placeholderImage:[UIImage imageNamed:@"backDefault"]];
        cell.titleLabel.text = _dic[@"title"];
        cell.timeLabel.text  = _dic[@"createDate"];
        return cell;
    }
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%@",_newsArray[indexPath.row]);
    NSDictionary *_dic = _newsArray[indexPath.row];
    [self pushViewTo:_dic];
}
- (void)pushViewTo:(NSDictionary *)_dic {
    if ([@"program" isEqualToString:_dic[@"type"]]) {
        OldVideoDetailViewController *vc = [[OldVideoDetailViewController alloc] initWithDictionary:_dic];
        vc.title = _dic[@"cmsColumnName"];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([@"article" isEqualToString:_dic[@"type"]]) {
        OldArticleDetailViewController *vc = [[OldArticleDetailViewController alloc] initWithDictionary:_dic];
        vc.title = _dic[@"cmsColumnName"];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)viewDidLayoutSubviews{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
        [cell setSeparatorInset:UIEdgeInsetsZero];
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
        [cell setLayoutMargins:UIEdgeInsetsZero];
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}
- (BOOL)shouldAutorotate {
    return isPlay;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return iPhoneX ? UIStatusBarStyleDefault : UIStatusBarStyleLightContent;
}

@end