SelectedViewController.m 13.4 KB
//
//  SelectedViewController.m
//  SCIOLiveCN
//
//  Created by dly on 2018/6/7.
//  Copyright © 2018年 dly. All rights reserved.
//

#import "SelectedViewController.h"

@interface SelectedViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSInteger _curMediaIndex;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *mediaHeaderView;
@property (nonatomic ,strong) UISegmentedControl *segmentedControl;

@property (nonatomic, strong) UITextField *textfield;

@property (nonatomic, strong) NSArray *showArray;

@end

@implementation SelectedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self layout];
    [self setNaviation];
    [self getList];
}

- (void)setNaviation{
    
    NSString *title = @"";
    switch (self.type) {
        case 1:
            title = @"部门";
            break;
        case 2:
            title = @"发言人";
            break;
            case 3:
            title = @"主要媒体";
            break;
        default:
            break;
    }
    self.title = title;
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBarTintColor:HEXCOLOR(0x195ac9)];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:20],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"cnlive_white_back"] forState:UIControlStateNormal];
    [leftButton setFrame:CGRectMake(0, 0, 20, 20)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton addTarget:self action:@selector(clearUp) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitle:@"清空选择" forState:UIControlStateNormal];
    [rightButton setFrame:CGRectMake(0, 0, 44, 44)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

- (void)getList {
    
    NSString *strUrl = [NSString stringWithFormat:@"%@/%@",REQUESTURL(@"gxb/api"),self.url];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:@"i" forKey:@"plat"];
    [param setObject:@"5.0" forKey:@"version"];
    [param setObject:CNLiveAppId forKey:@"appid"];
    
    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strUrl
       parameters:@{@"params" : [self convertToJsonData:param]} headers:nil
         progress:^(NSProgress * _Nonnull uploadProgress) {}
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              NSDictionary *dic = [NSDictionary dictionaryWithDictionary:responseObject];
              
              self.dataArray = [NSArray arrayWithArray:dic[@"settings"]];
              self.showArray = [NSArray arrayWithArray:dic[@"settings"]];
              [self.tableView reloadData];
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              // 请求失败
              [AlertViewTool showHUDAddedToView:self.view text:CustomStr(@"ServerBusy")];
          }];
}


- (void)searchKey {
    
    
    [self.selectedDelegate selected:self.textfield.text type:self.type];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)clearUp {
    
    [self.selectedDelegate selected:@"" type:self.type];
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)layout {

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight - NavBarHeight)];
    self.tableView.backgroundColor = HEXCOLOR(0xF7F6F6);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (self.type == 3 || self.type == 2 || self.type == 1) {
        
        return 60;
    }
    
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (self.type == 2 || self.type == 1) {
        
        return self.headerView;
    }
    if (self.type == 3) {
        return self.mediaHeaderView;
    }
    
    return nil;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellID = @"SearcIdentifier";
    UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
   NSString *tilte = self.showArray[indexPath.row];
    cell.backgroundColor = HEXCOLOR(0xF7F6F6);
    cell.textLabel.text = tilte;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.textColor = HEXCOLOR(0xA0A1A1);
    [[cell viewWithTag:1000] removeFromSuperview];
    
    if ([tilte isEqualToString:self.selectedText]) {
        
        UIImage *img = [UIImage imageNamed:@"cnlive_pitch"];
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(MainScreenWidth - 40, 22 - img.size.width / 2 , img.size.width, img.size.height)];
        image.tag = 1000;
        image.image = img;
        [cell addSubview:image];
    }
 
    return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = @"";
    if (self.showArray.count > 0) {
        text = self.showArray[indexPath.row];
    }else
    {
        text = self.dataArray[indexPath.row];
    }
    
    self.selectedText = text;
    [self.selectedDelegate selected:text type:self.type];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)textFieldDidChange:(UITextField *)textField {
    


    NSString *key = textField.text;
    if (key.length == 0) {
        
        self.showArray = [NSArray arrayWithArray:self.dataArray];
        [self.tableView reloadData];
        return;
    }
    NSMutableArray *result = [NSMutableArray array];
    for (NSString *title in self.dataArray) {
        
        if ([title containsString:key]) {
            [result addObject:title];
        }
    }
    
    self.showArray = [NSArray arrayWithArray:result];
    [self.tableView reloadData];
}

- (void)getMediaList
{
    NSString *strUrl = REQUESTURL(@"gxb/api/mediaList");
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:@"i" forKey:@"plat"];
    [param setObject:@"5.0" forKey:@"version"];
    [param setObject:CNLiveAppId forKey:@"appid"];
    if (_curMediaIndex <= 1) {
        [param setObject:[NSString stringWithFormat:@"%ld",(long)_curMediaIndex] forKey:@"mediaArea"];
    }else if (_curMediaIndex == 2){
        [param setObject:[NSString stringWithFormat:@"%d",3] forKey:@"mediaArea"];
    }else if (_curMediaIndex == 3){
        [param setObject:[NSString stringWithFormat:@"%d",2] forKey:@"mediaArea"];
    }

    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDAddedToView:self.view text:CustomStr(@"NetworkiInterruption")];
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strUrl
       parameters:@{@"params" : [self convertToJsonData:param]} headers:nil 
         progress:^(NSProgress * _Nonnull uploadProgress) {}
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              // 请求成功,解析数据
              NSDictionary *dic = [NSDictionary dictionaryWithDictionary:responseObject];
              self.dataArray = [NSArray arrayWithArray:dic[@"settings"]];
              self.showArray = [NSArray arrayWithArray:dic[@"settings"]];
              [self.tableView reloadData];
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              // 请求失败
              [AlertViewTool showHUDAddedToView:self.view text:CustomStr(@"ServerBusy")];
          }];
}

- (void)changes:(UISegmentedControl *)seg{
    NSInteger index = seg.selectedSegmentIndex;

    _curMediaIndex = index+1;
    [self getMediaList];
}

- (UIView *)mediaHeaderView
{
    if (!_mediaHeaderView)
    {
        _mediaHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, 60)];
        _mediaHeaderView.backgroundColor = [UIColor whiteColor];
        
        NSArray* segmentArray = [NSArray arrayWithObjects:@"国内媒体",@"港澳台媒体",@"国外媒体",nil];
        UISegmentedControl * segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentArray];
        segmentedControl.frame = CGRectMake(10, 15, MainScreenWidth-20, 30);
        segmentedControl.tintColor = [UIColor colorWithRed:0.00 green:0.39 blue:1.00 alpha:1.00];
        segmentedControl.backgroundColor = [UIColor whiteColor];
        NSDictionary *selected = @{NSFontAttributeName:[UIFont systemFontOfSize:16],
                                   NSForegroundColorAttributeName:[UIColor whiteColor]};
        //定义未选中状态下的样式normal,类型为字典
        NSDictionary *normal = @{NSFontAttributeName:[UIFont systemFontOfSize:16],
                                 NSForegroundColorAttributeName:[UIColor blueColor]};
        
        [segmentedControl setTitleTextAttributes:normal forState:UIControlStateNormal];
        [segmentedControl setTitleTextAttributes:selected forState:UIControlStateSelected];
        
        segmentedControl.selectedSegmentIndex = 3;
        [segmentedControl addTarget:self action:@selector(changes:) forControlEvents:UIControlEventValueChanged];
        
        _segmentedControl = segmentedControl;
        _segmentedControl.selectedSegmentIndex = 0;
        [_mediaHeaderView addSubview:_segmentedControl];
    }
    return _mediaHeaderView;
}

- (UIView *)headerView {
   
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, 60)];
        _headerView.backgroundColor = [UIColor whiteColor];
        _textfield = [[UITextField alloc] initWithFrame:CGRectMake(20, 10, MainScreenWidth - 120, 40)];
        [_textfield addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        _textfield.layer.borderColor = HEXCOLOR(0xC4C5C8).CGColor;
        _textfield.layer.masksToBounds = YES;
        _textfield.layer.cornerRadius = 5;
        _textfield.layer.borderWidth = 1;
        // 增加输入框文字左边距
        CGRect f=CGRectMake(20, 10, 15, 40);
        _textfield.leftViewMode=UITextFieldViewModeAlways;
        UIView *leftview=[[UIView alloc] initWithFrame:f];
        _textfield.leftView=leftview;
        [_headerView addSubview:_textfield];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(searchKey) forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = HEXCOLOR(0x2A5AC2);
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 5;
        [button setTitle:@"确定" forState:UIControlStateNormal];
        button.frame =CGRectMake(MainScreenWidth - 80, 10, 60, 40);
        [_headerView addSubview:button];
        
    }
    
    return  _headerView;
}

- (NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
    
}

@end