TopNoticeViewController.m 12.1 KB
//
//  TopNoticeViewController.m
//  SCIOLiveCN
//
//  Created by huayu on 16/5/31.
//  Copyright © 2016年 huayu. All rights reserved.
//
#import "JSONKit.h"
#import "TopNoticeViewController.h"
//#import <ShareSDKUI/ShareSDK+SSUI.h>
//#import <ShareSDK/ShareSDK.h>

@interface TopNoticeViewController ()<WKNavigationDelegate>
{
    NSDictionary *headerDic;
    NSDictionary *bodyDic;
}
@property (nonatomic, strong) NSArray *fontArray;
@property (nonatomic, assign) NSInteger fontIndex;

@end

@implementation TopNoticeViewController
#pragma mark - Data
-(void)loadHeaderData{
    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
        return;
    }
    [AlertViewTool showHUDView];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *josnParameters = [NSString stringWithFormat:@"{\"plat\":\"i\",\"version\":\"5.0\",\"appid\":\"gxb\",\"cmsContentId\":\"%@\"}",self.forecaseDic[@"programs"][0][@"cmsContentId"]];
    NSLog(@"%@",josnParameters);
    NSDictionary *parameters = @{@"params":josnParameters
                                };
    NSString *urlStr = REQUESTURL(@"gxb/api/programByContentId");
    [manager POST:urlStr parameters:parameters headers:nil  progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
        [AlertViewTool hideHUDView];
        // 请求成功,解析数据
        NSString * jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"jsonString == %@",jsonString);
        
        NSDictionary *dic = [jsonString objectFromJSONString];
        self -> headerDic = dic[@"program"];

        [self loadWebView];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        NSLog(@"%@", [error localizedDescription]);
        [AlertViewTool hideHUDView];
        [AlertViewTool showHUDViewText:CustomStr(@"ServerBusy")];
         
    }];
}
- (void)loadBodyData {
    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *josnParameters = [NSString stringWithFormat:@"{\"plat\":\"i\",\"version\":\"5.0\",\"appid\":\"gxb\",\"type\":\"program\",\"id\":\"%@\"}",self.forecaseDic[@"programs"][0][@"cmsContentId"]];
    NSLog(@"%@",josnParameters);
    NSDictionary *parameters = @{@"params":josnParameters
                                };
    NSString *urlStr = REQUESTURL(@"gxb/api/programDetail");
    [manager POST:urlStr parameters:parameters headers:nil  progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
        [AlertViewTool hideHUDView];
        // 请求成功,解析数据
        NSString * jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"jsonString == %@",jsonString);
        
        self->bodyDic = [jsonString objectFromJSONString];
        [self loadWebView];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        NSLog(@"%@", [error localizedDescription]);
        [AlertViewTool hideHUDView];
        [AlertViewTool showHUDViewText:CustomStr(@"ServerBusy")];
         
    }];
}
- (void)loadWebView
{
    if (headerDic && bodyDic) {
        NSString* htmlHeader = [[NSString alloc] initWithFormat:@"<html><p><font style=\"font-size:20px;\"><strong>%@</strong></font><br>%@</p><style type=\"text/css\">    img{width: 100%% !important;    height: auto !important;}</style><body>",[headerDic objectForKey:@"title"],[headerDic objectForKey:@"publishDate"]];

        NSString* htmlBody   = [bodyDic objectForKey:@"content"];
        NSString* htmlFooter = @"</body></html>";
        NSString* strHtml = [[NSString alloc] initWithFormat:@"%@%@%@",htmlHeader,htmlBody,htmlFooter];
        [self->_webView loadHTMLString:strHtml baseURL:nil];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    _fontArray = @[@"16",@"20",@"24"];
    _fontIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"FontSize"];
    
    [self setUpNavigationBar];
    [self loadHeaderData];
    [self loadBodyData];
    [self loadShareView];
    [self setUpUI];

}
#pragma mark - UI
- (void)setUpNavigationBar{
    self.navigationController.navigationBar.barTintColor = Color_Blue;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:18]};
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    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 = CustomStr(@"Announcements");
}
- (void)setUpUI{
    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;
    if (iPhoneX) {
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight - 88 - 44 - 34) configuration:config];
    } else {
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight - 64 - 44) configuration:config];
    }
    _webView.scrollView.backgroundColor = [UIColor whiteColor];
    _webView.backgroundColor = [UIColor whiteColor];
//    _webView.scalesPageToFit = YES;
    _webView.opaque = NO;
    _webView.navigationDelegate = self;
    [self.view addSubview:_webView];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadShareView {
    UIImageView *lineImage = [[UIImageView alloc] init];
    if (iPhoneX) {
        lineImage.frame = CGRectMake(0, MainScreenHeight - 44 - 34 - 88, MainScreenWidth, 1);
    } else {
        lineImage.frame = CGRectMake(0, MainScreenHeight - 64 - 44, MainScreenWidth, 1);
    }
    lineImage.backgroundColor = Color_Line;
    [self.view addSubview:lineImage];
    //字体按钮
    UIButton *fontSizeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    fontSizeButton.tag = 10000;
    [fontSizeButton setImage:[UIImage imageNamed:@"cnlive_fontsize"] forState:UIControlStateNormal];
    if (iPhoneX) {
        [fontSizeButton setFrame:CGRectMake((MainScreenWidth/2 - 33)/2, MainScreenHeight - 44 + (44 - 22)/2 - 34 - 88, 33, 22)];
    } else {
        [fontSizeButton setFrame:CGRectMake((MainScreenWidth/2 - 33)/2, MainScreenHeight - 44  - 64 + (44 - 22)/2, 33, 22)];
    }
    [fontSizeButton addTarget:self action:@selector(shareButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:fontSizeButton];
    
    //收藏按钮
    UIButton *isFavoriteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    isFavoriteButton.tag = 20000;
    TableData *notice = [[TableData alloc] initWithJSONDictionary:_forecaseDic[@"programs"][0]];
    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 - 88, 33, 22)];
    } else {
        [isFavoriteButton setFrame:CGRectMake((MainScreenWidth - 23)/2, MainScreenHeight - 44  - 64 + (44 - 22)/2, 33, 22)];
    }
    [isFavoriteButton addTarget:self action:@selector(shareButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:isFavoriteButton];
    
    //分享按钮
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareButton.tag = 30000;
    [shareButton setImage:[UIImage imageNamed:@"cnlive_share"] forState:UIControlStateNormal];
    if (iPhoneX) {
        [shareButton setFrame:CGRectMake((MainScreenWidth*3/2 - 22)/2, MainScreenHeight - 44 + (44 - 22)/2 - 34 - 88, 33, 22)];
    } else {
        [shareButton setFrame:CGRectMake((MainScreenWidth*3/2 - 22)/2, MainScreenHeight - 44 - 64 + (44 - 22)/2, 33, 22)];
    }
    [shareButton addTarget:self action:@selector(shareButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
}

- (void)shareButtonTaped:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (10000 == btn.tag) {
        if ([_fontArray count] - 1 == _fontIndex) {
            _fontIndex = 0;
        } else {
            _fontIndex++;
        }
        if (0 == _fontIndex) {
            [_webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'" completionHandler:nil];
        } else if (1 == _fontIndex) {
            [_webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '120%'" completionHandler:nil];
        } else if (2 == _fontIndex) {
            [_webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '140%'" completionHandler:nil];
        }
    } else if (20000 == btn.tag) {
        TableData *notice = [[TableData alloc] initWithJSONDictionary:_forecaseDic[@"programs"][0]];
        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:@"%@",_forecaseDic[@"programs"][0][@"img"]];
        NSString *title = [NSString stringWithFormat:@"%@",_forecaseDic[@"programs"][0][@"title"]];
        NSString *text = [NSString stringWithFormat:@"%@",!_forecaseDic[@"programs"][0][@"desc"]||[_forecaseDic[@"programs"][0][@"desc"] isEqualToString:@""]?title:_forecaseDic[@"programs"][0][@"desc"]];
        NSString *url = [NSString stringWithFormat:@"%@",_forecaseDic[@"programs"][0][@"pageUrl"]];
        [[TemplateShareManager manager] shareImage:img title:title text:text url:url controller:self];
        return;

    }
}


@end