TopNoticeViewController.m 13.7 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 ()<UIWebViewDelegate>
@property (nonatomic, strong) NSArray *fontArray;
@property (nonatomic, assign) NSInteger fontIndex;

@end

@implementation TopNoticeViewController
#pragma mark - Data
- (void)loadTrailerData {
    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
        return;
    }
    [AlertViewTool showHUDView];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:yugao parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        [AlertViewTool hideHUDView];
        // 请求成功,解析数据
        NSString * jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"jsonString == %@",jsonString);
        NSArray *arr = [jsonString objectFromJSONString];
        NSDictionary *dic = [arr objectAtIndex:0];
        
//        NSString* htmlHeader = [[NSString alloc] initWithFormat:@"<html><p><font style=\"font-size:20px;\"><strong>%@</strong></font><br>%@</p><body>",[dic objectForKey:@"Tittle"],[dic objectForKey:@"PublishDateTime"]];
        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>",[dic objectForKey:@"Tittle"],[dic objectForKey:@"PublishDateTime"]];
        
        NSString* htmlBody   = [dic objectForKey:@"Content"];
        NSString* htmlFooter = @"</body></html>";
        NSString* strHtml = [[NSString alloc] initWithFormat:@"%@%@%@",htmlHeader,htmlBody,htmlFooter];
        [self->_webView loadHTMLString:strHtml baseURL:nil];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        NSLog(@"%@", [error localizedDescription]);
        [AlertViewTool hideHUDView];
        [AlertViewTool showHUDViewText:CustomStr(@"ServerBusy")];
         
    }];
}

- (void)loadData {
        NSString *strUrl = @"http://app.phonemovie.cnlive.com/gxb/api/cataloglatest";
        //NSLog(@"%@",strUrl);
        NSString *categoryId = [NSString stringWithFormat:@"{\"plat\":\"i\",\"version\":\"5.0\",\"appid\":\"gxb\",\"categoryId\":\"wz/fbhgg/\",\"page\":\"1\",\"pageSize\":\"1\"}"];
        //NSLog(@"%@",categoryId);
        if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
            [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
            return;
        }
        NSDictionary *parameters = @{@"params":categoryId};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:strUrl parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
            // 请求成功,解析数据
            self->_dictionary = [NSDictionary dictionaryWithDictionary:responseObject];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self loadShareView];
            });
            
        }
         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             // 请求失败
             [AlertViewTool showHUDViewText:CustomStr(@"ServerBusy")];
             
         }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    _fontArray = @[@"16",@"20",@"24"];
    _fontIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"FontSize"];
    
    [self setUpNavigationBar];
    [self loadTrailerData];
    [self loadData];
    [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{
    if (iPhoneX) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight - 88 - 44 - 34)];
    } else {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight - 64 - 44)];
    }
    _webView.scrollView.backgroundColor = [UIColor whiteColor];
    _webView.backgroundColor = [UIColor whiteColor];
//    _webView.scalesPageToFit = YES;
    _webView.opaque = NO;
    _webView.delegate = self;
    [self.view addSubview:_webView];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
}

- (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:_dictionary[@"programs"][0]];
    BOOL isIn = [[DBAction sharedDBAction] isInTable: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 stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'"];
        } else if (1 == _fontIndex) {
            [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '120%'"];
        } else if (2 == _fontIndex) {
            [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '140%'"];
        }
    } else if (20000 == btn.tag) {
        TableData *notice = [[TableData alloc] initWithJSONDictionary:_dictionary[@"programs"][0]];
        BOOL isIn = [[DBAction sharedDBAction] isInTable:notice];
        if (!isIn) {
            BOOL isInsert = [[DBAction sharedDBAction] insertTable:notice];
            if (isInsert) {
                [AlertViewTool showHUDViewText:CustomStr(@"CollectSuccess")];
                [btn setImage:[UIImage imageNamed:@"cnlive_isfavorited"] forState:UIControlStateNormal];
            }
        } else {
            BOOL isDelete = [[DBAction sharedDBAction] deleteTable:notice];
            if (isDelete) {
                [AlertViewTool showHUDViewText:CustomStr(@"CancelCollect")];
                [btn setImage:[UIImage imageNamed:@"cnlive_isfavorite"] forState:UIControlStateNormal];
            }
        }
    } else if (30000 == btn.tag) {
        __weak typeof(self) weakSelf = self;
        NSString *img = [NSString stringWithFormat:@"%@",_dictionary[@"programs"][0][@"img"]];
        NSArray* imageArray = nil;
        if (!_dictionary[@"programs"][0][@"img"]||[img isEqualToString:@""]) {
            imageArray = @[[UIImage imageNamed:@"cnlive_zhouxin_icon"]];
        } else {
            imageArray = @[img];
        }
        if (imageArray) {
            NSString *text = [NSString stringWithFormat:@"%@",_dictionary[@"programs"][0][@"subTitle"]];
            if (!_dictionary[@"programs"][0][@"subTitle"]||[text isEqualToString:@""]) {
                text = _dictionary[@"programs"][0][@"title"];
            }
            NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
            [shareParams SSDKSetupShareParamsByText:text
                                             images:imageArray
                                                url:[NSURL URLWithString:_dictionary[@"programs"][0][@"pageUrl"]]
                                              title:_dictionary[@"programs"][0][@"title"]
                                               type:SSDKContentTypeAuto];
            [ShareSDK showShareActionSheet:nil
                                     items:nil
                               shareParams:shareParams
                       onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                           NSLog(@"%lu",(unsigned long)state);
                           switch (state) {
                               case SSDKResponseStateSuccess:
                               {
                                   UIAlertController *alert = [UIAlertController alertControllerWithTitle:CustomStr(@"ShareSuccess") message:nil preferredStyle:UIAlertControllerStyleAlert];
                                   UIAlertAction *action1 = [UIAlertAction actionWithTitle:CustomStr(@"Sure") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                       NSLog(@"点击了确定,进入确定的事件");
                                       
                                   }];
                                   [alert addAction:action1];
                                   [weakSelf presentViewController:alert animated:YES completion:nil];
                                   break;
                               }
                               case SSDKResponseStateFail:
                               {
                                   UIAlertController *alert = [UIAlertController alertControllerWithTitle:CustomStr(@"ShareFailure") message:nil preferredStyle:UIAlertControllerStyleAlert];
                                   UIAlertAction *action1 = [UIAlertAction actionWithTitle:CustomStr(@"Sure") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                       NSLog(@"点击了确定,进入确定的事件");
                                       
                                   }];
                                   [alert addAction:action1];
                                   [weakSelf presentViewController:alert animated:YES completion:nil];
                                   break;
                               }
                               default:
                                   break;
                           }
                       }
             ];
            
        }
        return;
    }
}


@end