//
//  SmartInterrogationViewController.m
//  Open
//
//  Created by 雷俊博 on 2020/2/28.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "SmartInterrogationViewController.h"
#import "Constants.h"
#import "AiDaAlertView.h"
#import "SmartInterrogationTableViewCell.h"
#import "GTCountSDK.h"

#import "UIView+frameAdjust.h"
#import "UINavigationBar+handle.h"
#import "YDAuthenticationHelper.h"
#import "LoginVC.h"

#import "HeathMedicalBtnTableViewCell.h"
#import "HMMoreSpecialZoneTableCell.h"
#import "HMNewsHeaderView.h"

//新闻
#import "JHNewsModel.h"
#import "NewsViewController.h"
#import "HeadLineViewController.h"
#import "NewsListTableViewCell.h"
#import "NewsList2Cell.h"
#import "NewsTextCell.h"
#import "NewsImagesCell.h"
#import "NewsWebViewController.h"
#import "YDTempUrlInstance.h"


@interface SmartInterrogationViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,HeathMedicalBtnTableViewCellDelegate,HMMoreSpecialZoneTableCellDelegate,HMNewsHeaderViewDelegate>
@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)UIImageView* topImg;

@property (nonatomic, strong)AiDaAlertView* aiDaView;

@property (nonatomic, strong)NSArray *newsArray;



@end

@implementation SmartInterrogationViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //禁止手势返回
//    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
//    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
//    [self.view addGestureRecognizer:pan];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    UIWindow *curWindow = [[UIApplication sharedApplication].delegate window];
    if (self.aiDaView) {
        [curWindow  bringSubviewToFront:self.aiDaView.maskView];
         [curWindow bringSubviewToFront:self.aiDaView];
        
    }
    
    [GTCountSDK trackCountEvent:@"kanbingmaiyao_functionList_show" withArgs:@{}];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    UIWindow *curWindow = [[UIApplication sharedApplication].delegate window];
    if (self.aiDaView) {
         [curWindow  sendSubviewToBack:self.aiDaView];
         [curWindow  sendSubviewToBack:self.aiDaView.maskView];
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
   
    
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0x1986d4] image:nil isOpaque:YES];//颜色
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
    
     //[self.view addSubview:self.scrollView];
    [self.view addSubview:self.tableView];
    
    [self creatNav];
    
    [self loadNewsData];
}

- (void)creatNav
{
    
    
    UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = [UIColor colorWithHex:0x1986d4];
    [self.view addSubview:nav];
    
    UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(cl_kNavBarHeight);
    }];
    
    UILabel*titleLabel = [[UILabel alloc]init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = self.title;
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [nav addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(cl_kNavBarHeight);
    }];
    
    
    
}

#pragma mark - 获取新闻数据

- (NSDictionary *)requestParams
{
    
    NSString* province = [UserDefault objectForKey:@"locationProvince"];
    
    NSString* provinceValue = [self getLocationAddressKeyWithProvinceName:province];
    
    NSDictionary *param = @{
        @"news_type":@"china",
        @"address":provinceValue,
        @"start":@(0),
        @"end":@(10)
    };
    
    return param;
}

- (void)loadNewsData
{
    NSString *urlString = JUHEUrlString;
    NSLog(@"新闻列表:url:%@",urlString);
    NSLog(@"params:%@",[self requestParams]);
    WeakSelf
    
    NSLog(@"请求前时间:%@",[NSDate date]);
    [NetworkRequest NewsPost:urlString Params:[self requestParams] Success:^(id _Nonnull objc) {
       
        
        
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *status = [NSString stringWithFormat:@"%@",objc[@"status"]];
            if ([status isEqualToString:@"0"]) {
                NSLog(@"新闻请求成功并渲染时间:%@",[NSDate date]);
                
               
                weakSelf.newsArray = [NSMutableArray arrayWithArray:[JHNewsModel mj_objectArrayWithKeyValuesArray:objc[@"news_list"]]];
                [weakSelf.tableView reloadData];
            }
        }
        
        
        
    } Failure:^(NSError* error) {
        
        NSLog(@"error:%@",error);
    }];
}


#pragma mark - 获取定位省份的key
- (NSString *)getLocationAddressKeyWithProvinceName:(NSString *)province
{
    NSString* str = @"bj";
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"newProvince" ofType:@"plist"];
    //其次通过这个文件路径获得字典文件(因为Info.plist内容本身就是个字典集)
    NSArray *provinceArr = [NSArray arrayWithContentsOfFile:filePath];
    
    for (NSDictionary* dic in provinceArr) {
        if ([dic[@"provinceName"] isEqualToString:province]) {
            str = dic[@"provinceValue"];
            break;
        }
    }
    
    
    return str;
}




#pragma mark - 爱达api请求
- (NSDictionary *)aiDaTokenRequestPara
{
    NSDictionary* params = @{
        @"loginId":[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue,
        @"telephone":[getPeopleID PeopleIphoneNmber]
    };
    return params;
}

- (void)aiDaTokenRequest:(void (^)(bool success, NSString*token))response
{
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaConfig],AiDaTokenRequest];
    NSLog(@"爱达token的url:%@",url);
    
    NSLog(@"params:%@",[self aiDaTokenRequestPara]);
    
    [NetworkRequest Get3:url Params:[self aiDaTokenRequestPara] Success:^(id _Nonnull responseObject) {
        
        NSLog(@"responseObject:%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*token = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                
                
                response(YES,token);
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}

- (NSDictionary *)aidaUrlRequestPara
{
    NSDictionary* params = @{
        @"deviceid":[[[[UIDevice currentDevice] identifierForVendor] UUIDString]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]],
        @"mobile":[[getPeopleID PeopleIphoneNmber] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]],
        @"uid":[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue
    };
    return params;
}

- (void)aidaUrlRequestWithToken:(NSString *)token
{
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaUrlConfig],AiDaUrlRequest];
    NSLog(@"爱达url的url:%@",url);
    
    NSLog(@"params:%@",[self aidaUrlRequestPara]);
    
    [NetworkRequest Get2:url Params:[self aidaUrlRequestPara] Token:token Success:^(id  _Nonnull responseObject) {
        
         NSLog(@"responseObject:%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*url = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
               // NSString*url = @"https://stg-web-embed.adachina.com/?mobile=xCCGm0DRJiot9hZPsZYewg==&source=kksb_app&deviceId=d908ad05-761d-4472-b151-a223e8e01ced&uid=12145123121";
                 
//                NSMutableCharacterSet *lastSet = [[NSMutableCharacterSet alloc] init];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"-_.!~*;/?:@&=$,#"]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
//
//                url = [url stringByAddingPercentEncodingWithAllowedCharacters:lastSet];
                
                if ([self.navigationController.visibleViewController isKindOfClass:[SmartInterrogationViewController class]]) {
                    Web2ViewController * vc = [Web2ViewController new];
                    vc.title= @"智能问诊";
                    vc.skipUrl = [NSURL URLWithString:url];
                   // vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
              
                
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
    } Failure:^(NSError * _Nonnull error) {
        
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
        
    }];
}

#pragma mark - 医疗服务
- (void)getHaoDaifuUrlRequest {
    
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstlog"]) {
        [self unLoginTap];
        return;
    }
    
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaUrlConfig],HaoDaiFuUrlRequest];
    
    NSDictionary* params = @{
        @"userId":@([getPeopleID PeopleID]),
        @"telphone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
    };
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post:url Params:params Success:^(id _Nonnull responseObject) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*url = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                
//                NSMutableCharacterSet *lastSet = [[NSMutableCharacterSet alloc] init];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"-_.!~*;/?:@&=$,#"]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
//
//                url = [url stringByAddingPercentEncodingWithAllowedCharacters:lastSet];
                
                if ([self.navigationController.visibleViewController isKindOfClass:[SmartInterrogationViewController class]]) {
                    Web2ViewController * vc = [Web2ViewController new];
                    vc.title= @"医疗服务";
                    vc.skipUrl = [NSURL URLWithString:url];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
              
                
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        
    }];
    
}
#pragma mark - 第二行跳转
- (void)getUrlRequestpageType:(int)pageType withTitle:(NSString *)title{

    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstlog"]) {
        [self unLoginTap];
        return;
    }
    
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipSwitchConfig],KbUrlRequest];
    NSDictionary* params = @{
        @"name":[getPeopleID Peopletitle],
        @"phone":[getPeopleID PeopleIphoneNmber],
        @"openId":@([getPeopleID PeopleID]),
        @"pageType": @(pageType)
    };
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post:url Params:params Success:^(id _Nonnull responseObject) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*url = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                NSString *encodedString = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
                if ([self.navigationController.visibleViewController isKindOfClass:[SmartInterrogationViewController class]]) {
                    Web2ViewController * vc = [Web2ViewController new];
                    vc.title= title;
                    vc.skipUrl = [NSURL URLWithString:encodedString];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        
    }];
    
}

#pragma mark - 未登录跳转

- (void)unLoginTap {
    [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
}



#pragma mark - 比财

- (NSDictionary *)getBCRequestParam
{
    NSDictionary *params = @{
        @"phone":[[getPeopleID PeopleIphoneNmber] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]],
        @"id":[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue
    };
    return params;
}

- (void)getBCRequest:(NSString *)token
{
   NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaUrlConfig],BCUrlRequest];
    NSLog(@"比财url的url:%@",url);
    
    NSLog(@"params:%@",[self getBCRequestParam]);
    
    [NetworkRequest Get2:url Params:[self getBCRequestParam] Token:token Success:^(id  _Nonnull responseObject) {
        
         NSLog(@"responseObject:%@",responseObject);
                
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*url = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                
//                NSMutableCharacterSet *lastSet = [[NSMutableCharacterSet alloc] init];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"-_.!~*;/?:@&=$,#"]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
//
//                url = [url stringByAddingPercentEncodingWithAllowedCharacters:lastSet];
                
                if ([self.navigationController.visibleViewController isKindOfClass:[SmartInterrogationViewController class]]) {
                    Web2ViewController * vc = [Web2ViewController new];
                    vc.title= @"比财";
                    vc.skipUrl = [NSURL URLWithString:url];
                   // vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
              
                
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
        
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}


#pragma mark - HeathMedicalBtnTableViewCellDelegate
- (void)HeathMedicalBtnClickWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            [self jumpToHTML5:@"https://m.haodf.com/nopen/yzexpertlist?partnerkey=9b6a9ed2bbf5910c" andJAnalytics:@"专家义诊"];
        }
            break;
        case 1:
        {
            [self getHaoDaifuUrlRequest];//医疗服务
        }
            break;
        case 2:
        {
            [self goToYaoDouVCWithLoginUrl:@"https://k.yaodouwang.com/"];
        }
            break;
        case 3:
        {
//            NSString * strA = @"https://www.shuidichou.com/tf/ads/business/register?channel=BD_cooperation_index_kankanshebao";
//            [self jumpToHTML5:strA andJAnalytics:@"大病筹款"];
            //[self goToSmartVC];//智能问诊
            [[clickEvent instance] clickEventRooterVC:self Content:@"lifeJSYZ" menuName:@""];
        }
            break;
        case 4:
        {
            //今日特价
            [self getUrlRequestpageType:1 withTitle:@"今日特价"];
        }
            break;
        case 5:
        {
            //居家必备
            [self getUrlRequestpageType:2 withTitle:@"居家必备"];
        }
            break;
        case 6:
        {
            //儿童专区
            [self getUrlRequestpageType:3 withTitle:@"儿童专区"];
        }
            break;
        case 7:
        {
            //医疗器械
            [self getUrlRequestpageType:4 withTitle:@"医疗器械"];
        }
            break;
        default:
            break;
    }
}

#pragma mark - HMMoreSpecialZoneTableCellDelegate
- (void)HMMoreSpecialZoneBtnClickWithIndex:(NSInteger)index
{
    switch (index) {
        case 200:
        {
            [self goToYaoDouVCWithLoginUrl:@"https://k.yaodouwang.com/exercise?id=251"];//保健养生
        }
            break;
        case 201:
        {
            [self goToYaoDouVCWithLoginUrl:@"https://k.yaodouwang.com/exercise?id=249"];//女性专区
        }
            break;
        case 202:
        {
            [self goToYaoDouVCWithLoginUrl:@"https://k.yaodouwang.com/exercise?id=250"];//男性专区
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - HMNewsHeaderViewDelegate
- (void)HMNewsHeaderViewBtnClickWithIndex:(NSInteger)index
{
    
    HeadLineViewController*newsVC = [HeadLineViewController new];
    newsVC.title = @"新闻";
    newsVC.from = @"home";
    newsVC.currentIndex = 11;
    newsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:newsVC animated:YES];
    
//    NewsViewController*newsVC = [NewsViewController new];
//    newsVC.title = @"新闻";
//    newsVC.from = @"home";
//    newsVC.currentIndex = 11;
//    newsVC.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:newsVC animated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"y:%lf",scrollView.contentOffset.y);
    if (scrollView.contentOffset.y <= 0) {
        scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0);
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return 1;
    }
    return self.newsArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        HeathMedicalBtnTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HeathMedicalBtnTableViewCell"];
        
        cell.delegate = self;
        
        [cell reloadData];
        
        return cell;
    }else if (indexPath.section == 1){
        
        HMMoreSpecialZoneTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HMMoreSpecialZoneTableCell"];
        
        cell.delegate = self;
        
        
        return cell;
    }
    
    JHNewsModel* newsModel = self.newsArray[indexPath.row];
    
    if ([newsModel.view_type isEqualToString:@"2"]) {
        NewsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsListTableViewCell"];
        
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        
        
        [cell refreshUIWithModel:newsModel];
        
        
        return cell;
    }else if ([newsModel.view_type isEqualToString:@"0"]){
        NewsTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsTextCell"];
        
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        
        
        [cell refreshUIWithModel:newsModel];
        
        
        return cell;
    } else if ([newsModel.view_type isEqualToString:@"1"]) {
        NewsList2Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsList2Cell"];
        
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        
        
        [cell refreshUIWithModel:newsModel];
        
        
        return cell;
    }else if ([newsModel.view_type isEqualToString:@"3"]) {
        NewsImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsImagesCell"];
        
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        
        
        [cell refreshUIWithModel:newsModel];
        
        
        return cell;
    }else{
        NewsTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsTextCell"];
        
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        
        
        [cell refreshUIWithModel:newsModel];
        
        
        return cell;
    }
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        HMNewsHeaderView * headerView = [[HMNewsHeaderView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 46 * WIDTHRADIU)];
        headerView.delegate = self;
        
        return headerView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 46 * WIDTHRADIU;
    }
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return 10 * WIDTHRADIU;
    }
    
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 108 * WIDTHRADIU;
    }else if (indexPath.section == 1){
        return 199 * WIDTHRADIU;
    }
    return UITableViewAutomaticDimension;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2) {
        
        
        JHNewsModel* newsModel = self.newsArray[indexPath.row];
        
        NewsWebViewController *vc = [[NewsWebViewController alloc]init];
        
        vc.title = @"新闻资讯";
        
        
        NSString* usr_id  = nil;
        
        if ([UserDefault boolForKey:@"firstlog"]) {
            usr_id = [NSString stringWithFormat:@"%@",@([getPeopleID PeopleID])];
        }
        
        if ([Tools isBlankString:usr_id]) {
            vc.url = newsModel.news_url;
        }else{
            vc.url = [newsModel.news_url stringByAppendingFormat:@"&usr_id=%@",usr_id];
        }
        
        vc.model = newsModel;
       
        
        [self.navigationController pushViewController:vc animated:YES];
        
    }
   
    
    
}




#pragma mark - event response
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)goToNextVCClick:(UITapGestureRecognizer *)tap
{
    WeakSelf
    
        if (tap.view.tag == 201) {
            if (![[NSUserDefaults standardUserDefaults]boolForKey:@"aida_allow"]) {
                
                self.aiDaView = [AiDaAlertView showAlertViewWithTitle:nil imageName:nil ViewController:self type:AiDaAlertViewTypeAD block:^(BOOL success) {
                    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"aida_allow"];
                    [[NSUserDefaults standardUserDefaults]synchronize];
                   [self aiDaTokenRequest:^(bool success, NSString *token) {
                     if (success) {
                         [weakSelf aidaUrlRequestWithToken:token];
                     }
                   }];
                }];
                
                return;
               
            }
            
           
            
            [self aiDaTokenRequest:^(bool success, NSString *token) {
                if (success) {
                    [weakSelf aidaUrlRequestWithToken:token];
                }
            }];
        }else if (tap.view.tag == 200){
             [self jumpToHTML5:@"https://m.haodf.com/nopen/yzexpertlist?partnerkey=9b6a9ed2bbf5910c" andJAnalytics:@"在线义诊"];
        }else if (tap.view.tag == 202){
            //[self jumpToHTML5:@"https://kksb.wy.guahao.com/booking" andJAnalytics:@"医疗服务"];
            
            [self getHaoDaifuUrlRequest];
        }else if (tap.view.tag == 203){
            //NSString * strA = @"https://www.shuidihuzhu.com/toufang/throwIn?typeFrom=external&channel=sdhzkksb";
                                  
                                  
             // [self jumpToHTML5:strA andJAnalytics:@"水滴互助"];
             if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
                 [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
                 return;
             }
                                  
          tap.view.userInteractionEnabled = NO;
          
          NSDictionary * params = @{@"appId":@"201912161758",
                                       @"phone":[getPeopleID PeopleIphoneNmber]};
             __weak typeof(self) weakSelf = self;
             [YDAuthenticationHelper authentication:@"https://kankan.yaodouwang.com/user/login/open" body:params success:^(id  _Nonnull response) {
                 
                 if ([response isKindOfClass:[NSDictionary class]]) {
                     NSDictionary * data = response[@"data"];
                     NSURL * skipUrl = [YDAuthenticationHelper jointUrlWithBody:data andUrl:@"https://k.yaodouwang.com/"];
                     Web2ViewController * vc = [Web2ViewController new];
                     vc.title= @"平价药房";
                     vc.skipUrl = skipUrl;
                     [weakSelf.navigationController pushViewController:vc animated:YES];
                     [GTCountSDK trackCountEvent:@"H5_PingMingYaoFang" withArgs:nil];
                     
                 }else{
                     NSLog(@"数据格式不正确 ===> %@",response);
                 }
                 tap.view.userInteractionEnabled = YES;
             } fail:^(id  _Nonnull error) {
                 tap.view.userInteractionEnabled = YES;
                 NSLog(@"请求失败，请登录 ===> %@",error);
                 [weakSelf alertShow:@"网络异常,请稍后重试"];
             }];
        }
    
    
}

#pragma mark - 智能问诊
- (void)goToSmartVC
{
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
       
        [self unLoginTap];
        return;
    }
    
    WeakSelf
         if (![[NSUserDefaults standardUserDefaults]boolForKey:@"aida_allow"]) {
                      
             self.aiDaView = [AiDaAlertView showAlertViewWithTitle:nil imageName:nil ViewController:self type:AiDaAlertViewTypeAD block:^(BOOL success) {
                 [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"aida_allow"];
                 [[NSUserDefaults standardUserDefaults]synchronize];
                 [self aiDaTokenRequest:^(bool success, NSString *token) {
                   if (success) {
                       [weakSelf aidaUrlRequestWithToken:token];
                   }
                 }];
             }];
          
          return;
                     
      }
                  
                 
                  
      [self aiDaTokenRequest:^(bool success, NSString *token) {
          if (success) {
              [weakSelf aidaUrlRequestWithToken:token];
          }
      }];
    
    return;
}


#pragma mark - 药兜网
- (void)goToYaoDouVCWithLoginUrl:(NSString *)url
{
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
       
        [self unLoginTap];
        return;
    }
    if ([YDTempUrlInstance shareInstance].data && ![self compareWithLastDate:[YDTempUrlInstance shareInstance].lastDate]) {
        NSURL * skipUrl = [YDAuthenticationHelper jointUrlWithBody:[YDTempUrlInstance shareInstance].data andUrl:url];
        
        Web2ViewController * vc = [Web2ViewController new];
        vc.title= @"平价药房";
        vc.skipUrl = skipUrl;
        [self.navigationController pushViewController:vc animated:YES];
        [GTCountSDK trackCountEvent:@"H5_PingMingYaoFang" withArgs:nil];
        return;
    }
    
    
    NSDictionary * params = @{@"appId":@"201912161758",
                                 @"phone":[getPeopleID PeopleIphoneNmber]};
       __weak typeof(self) weakSelf = self;
    __block NSString* tempUrl = url;
       [YDAuthenticationHelper authentication:@"https://kankan.yaodouwang.com/user/login/open" body:params success:^(id  _Nonnull response) {
           
           if ([response isKindOfClass:[NSDictionary class]]) {
               NSDictionary * data = response[@"data"];
               NSURL * skipUrl = [YDAuthenticationHelper jointUrlWithBody:data andUrl:tempUrl];
               [YDTempUrlInstance shareInstance].data = data;
               [YDTempUrlInstance shareInstance].lastDate = [NSDate date];
               
               Web2ViewController * vc = [Web2ViewController new];
               vc.title= @"平价药房";
               vc.skipUrl = skipUrl;
               [weakSelf.navigationController pushViewController:vc animated:YES];
               [GTCountSDK trackCountEvent:@"H5_PingMingYaoFang" withArgs:nil];
               
           }else{
               NSLog(@"数据格式不正确 ===> %@",response);
           }
          
       } fail:^(id  _Nonnull error) {
           
           NSLog(@"请求失败，请登录 ===> %@",error);
           [weakSelf alertShow:@"网络异常,请稍后重试"];
       }];
}



#pragma mark - 跳转到H5页面
-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{
    
    Web2ViewController * vc = [Web2ViewController new];
    vc.title= janalytics;
    vc.skipUrl = [NSURL URLWithString:url];
    [self.navigationController pushViewController:vc animated:YES];
    

}

#pragma mark - 判断时间是否超过1.5分钟
- (BOOL)compareWithLastDate:(NSDate *)lastDate
{
    NSTimeInterval distanceBetweenDates = [[NSDate date] timeIntervalSinceDate:lastDate];
    distanceBetweenDates = fabs(distanceBetweenDates);
    CGFloat hoursBetweenDates = distanceBetweenDates / 60.0;

    if (hoursBetweenDates >= 1.5) {
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - 提示

- (void)alertShow:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}



#pragma mark - getters and setters
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        
        _tableView.estimatedSectionFooterHeight = 10;
        _tableView.estimatedSectionHeaderHeight = 10;
        _tableView.estimatedRowHeight = 50;
        
        [_tableView registerClass:[HeathMedicalBtnTableViewCell class] forCellReuseIdentifier:@"HeathMedicalBtnTableViewCell"];
        [_tableView registerClass:[HMMoreSpecialZoneTableCell class] forCellReuseIdentifier:@"HMMoreSpecialZoneTableCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsListTableViewCell" bundle:nil] forCellReuseIdentifier:@"NewsListTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsList2Cell" bundle:nil] forCellReuseIdentifier:@"NewsList2Cell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsTextCell" bundle:nil] forCellReuseIdentifier:@"NewsTextCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsImagesCell" bundle:nil] forCellReuseIdentifier:@"NewsImagesCell"];
        _tableView.tableHeaderView = self.topImg;
    }
    
    return _tableView;
}


- (UIImageView *)topImg
{
    if (!_topImg) {
        _topImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 110*WIDTHRADIU) ];
        _topImg.image = [UIImage imageNamed:@"hm_banner"];
        _topImg.userInteractionEnabled = YES;
        UITapGestureRecognizer*tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(topImgtap)];
        [_topImg addGestureRecognizer:tap];
        //_topImg.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _topImg;
}

#pragma mark - 头部图片点击
- (void)topImgtap{
    [self goToYaoDouVCWithLoginUrl:@"https://k.yaodouwang.com/"];
}

/*
#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.
}
*/

@end
