//
//  AuthB40ViewController.m
//  Open
//
//  Created by weface on 2023/9/4.
//  Copyright © 2023 QXY. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AuthB40ViewController.h"
#import "SuccessItemCell.h"
#import "SuccessItem2Cell.h"
#import "SuccessItem.h"
//微信订阅号推送
#import "WXApi.h"
#import "WXApiManager.h"
#import "PayAttentionToWXAlertView.h"
#import "PayAttention2ToWXAlertView.h"


#import "CTAPIBaseManager.h"

//红包弹框
#import "RedPackageView.h"

#import "PackageCoinsView.h"
#import "Package2CoinsView.h"

#import <ZJAnimationPopView.h>

#import "CoinsCenterViewController.h"
#import "Log2ViewController.h"
#import "KKUserIdentifyViewController.h"
#import "WeiJianQueryViewController.h"
#import "SmartInterrogationViewController.h"

#import "KKLisenViewController.h"

#import "AiDaAlertView.h"
//#import "SuccessItem.h"
#import "KKRedPackageClickEventModel.h"
#import "UIImageView+WebCache.h"
#import "SuccessItem.h"
#import "UIView+frameAdjust.h"

//极光小视频
#import "KKTabBarViewController.h"
#import "KKTVViewController.h"
#import "LittleVideoViewController.h"
#import "KKVideoViewController.h"
#import "KKSVideoViewController.h"

#import "InsuredInfoViewController.h"
#import "quickInsuredInfoViewController.h"

#import <YYText.h>
#import "SuccessItem3Cell.h"
#import "AuthB1ViewController.h"
#import "AuthSuccessEss.h"
#import <esscsdk/esscsdk.h>
#import "JsonUtils.h"
#import "GiveChanceDialog.h"
@interface AuthB40ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIApplicationDelegate,UIAlertViewDelegate,WXApiDelegate,WXApiManagerDelegate,UITableViewDelegate,UITableViewDataSource,EESBCallbackDelegate>
{
    BOOL isChange;
}

@property (nonatomic, strong)UIScrollView* scrollView;

@property (nonatomic, strong) NSArray *defaultArr;

@property (nonatomic, strong) NSMutableArray* dataArray;

//@property (nonatomic, strong)NSArray* titleArray;

@property (strong, nonatomic) UIImageView *imageView_1;
@property (strong, nonatomic) UIImageView *imageView_2;

@property (strong, nonatomic) UILabel *provinceTitle;

@property (strong, nonatomic) UILabel *lb_time;

@property (strong, nonatomic) UILabel *lb_address;

@property (nonatomic, strong)PackageCoinsView *coinsView;

@property (nonatomic, strong)AiDaAlertView* aiDaView;

//@property (nonatomic, strong)UICollectionView* collectionView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong)UIImageView *qrImg;

@property (nonatomic, copy)NSString *qrUrlString;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, assign) BOOL Ispush;
@end

@implementation AuthB40ViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.translucent = NO;
//    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:35/255.0 green:168/255.0 blue:222/255.0 alpha:1.0]];
//    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    //禁止手势返回
//    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
//    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
//    [self.view addGestureRecognizer:pan];
    
    //隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    UIWindow *curWindow = [[UIApplication sharedApplication].delegate window];
    if (self.aiDaView) {
        [curWindow  bringSubviewToFront:self.aiDaView.maskView];
         [curWindow bringSubviewToFront:self.aiDaView];
        
    }
    
    [GTCountSDK trackCountEvent:@"home_SBAuth_successPage" 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 colorWithHex:0xf4f4f4];
    
    [self.view addSubview:self.scrollView];
    
    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    };
    
    self.Ispush = NO;
    
    [self imageLoca];
    
    [self showView];
    

    [self getAllItemsRequest];

    [WXApiManager sharedManager].delegate = self;
    
    //如果认证成功,就把信息存储到本地
    
    [self insertUserInfo];

   // [self creatADBanner];
    
    BOOL authQunShow = [UserDefault boolForKey:@"authQunShow"];
        
    [self loadData];
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"good_comment_dialog"];
    [self showSuccessEss];//领取电子社保卡
}
-(void) showSuccessEss{

    //身份证号码去空格
    NSString *idNum = [self.idNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *url=@"https://web.kanface.com:444/electronic/social/issuance/isBind";
    NSDictionary *params = @{
                             @"idCard":[GMSm4Utils ecbEncryptText:idNum key:SMKey].lowercaseString
                             };
    [NetworkRequest PostNo:url Params:params Success:^(id _Nonnull obj) {
        NSString* state = [NSString stringWithFormat:@"%@",obj[@"state"]];
        if ([state isEqualToString:@"200"]) {
            NSNumber * boolNum = obj[@"result"];
            BOOL result = [boolNum boolValue];
            if(!result){
                [AuthSuccessEss showWithTitle:self :@"" btnYes:^{
                } btnNo:^{
                    [self getSSCardSign];
                } ];
            }else{
                [self showGiveChance];
            }
        }else{
            [self showGiveChance];
        }
        
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
        }];
}

-(void)showGiveChance{
    
//    NSString *url= [NSString stringWithFormat:@"http://score.weface.com.cn:8075/scoreService/drawservice/drawStatus?uid=%ld&eventype=10011",(long)[getPeopleID PeopleID]];
//    [NetworkRequest Post:url Params:params Success:^(id _Nonnull objc) {
//        NSString* state = [NSString stringWithFormat:@"%@",objc[@"code"]];
//        if([state isEqual:@"1026"]){
//
//        }
//    } Failure:^(NSError* error) {
//        NSLog(@"error:%@",error);
//    }];
    NSDictionary *params = @{};
    NSDate *date =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    NSString *time=[NSString stringWithFormat:@"%ld%ld%ld",currentYear,currentMonth,currentDay];
    NSString *give_chance_dialog=[[NSUserDefaults standardUserDefaults] objectForKey:@"give_chance_dialog"];
    if(give_chance_dialog!=nil&&[give_chance_dialog isEqualToString:time]){
        return;
    }
    NSString *send= [NSString stringWithFormat:@"http://score.weface.com.cn:8075/scoreService/drawservice/plusdraw?uid=%ld&eventype=10011&telphone=%@&frommodel=2",(long)[getPeopleID PeopleID],[getPeopleID PeopleUnPhoneNmber]];
    [NetworkRequest Post:send Params:params Success:^(id _Nonnull obj) {
        NSString* code = [NSString stringWithFormat:@"%@",obj[@"code"]];
        if([code isEqual:@"1006"]){
            [GiveChanceDialog showWithTitle:self.navigationController :@"" btnYes:^{
                NSLog(@"objc:%@",@"yes");
                [[clickEvent instance] clickEventRooterVC:self Content:@"mineLucky" menuName:@"mineLucky"];
            } btnNo:^{
                NSLog(@"objc:%@",@"no");
                [[clickEvent instance] clickEventRooterVC:self Content:@"mineLucky" menuName:@"mineLucky"];
            }];
            
            [[NSUserDefaults standardUserDefaults]setObject:time forKey:@"give_chance_dialog"];
        }
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)getSSCardSign{
    //姓名和身份证号码去空格
    self.name = [self.name stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.idNumber = [self.idNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *url = [[NSString stringWithFormat:@"%@/electronic/social/issuance/jbxSign",CSL_url]  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      
    NSString *name=[GMSm4Utils ecbEncryptText:self.name key:SMKey].lowercaseString;
    NSString *idNum=[GMSm4Utils ecbEncryptText:self.idNumber key:SMKey].lowercaseString;
    NSString *phone=[GMSm4Utils ecbEncryptText:[getPeopleID PeopleIphoneNmber] key:SMKey].lowercaseString;
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"name":name,
                             @"idCard":idNum,
                             @"phone":phone
                             };
    [[NSUserDefaults standardUserDefaults]setObject:name forKey:@"essCardName"];//保存name
    [[NSUserDefaults standardUserDefaults]setObject:idNum forKey:@"essCardIdNum"];//保存id
    [SVProgressHUD show];
    [NetworkRequest PostNomal:url Params:params Success:^(id _Nonnull objc) {
        [SVProgressHUD dismiss];
        NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        if ([state isEqualToString:@"200"]) {
            NSDictionary *result=objc[@"result"];
            NSString* token = [NSString stringWithFormat:@"%@",result[@"token"]];//获取token
            [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"essCardToken"];//保存token
            NSDictionary *data=result[@"data"];
            NSString* bindStatus = [NSString stringWithFormat:@"%@",data[@"bindStatus"]];//状态
            if([bindStatus isEqualToString:@"UNBIND"]||[bindStatus isEqualToString:@"BIND"]){//可申领
                NSString* returnUrl = [NSString stringWithFormat:@"%@",data[@"returnUrl"]];//社保卡url
                NSString *ess_token=[GMSm4Utils ecbDecryptText:returnUrl key:SMKey];
                NSString *url = [[SSCPublicHeader sharedSSCTool] webUrlWith:SSCServiceType_Main
                signStr:ess_token];
                [[SSCPublicHeader sharedSSCTool] presentWebVCFrom:self esscUrl:url
                esscDelegate:self];
            }else{//不可申领
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipays://"]]) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"alipays://platformapi/startapp?appId=2021001123625885&page=pages%2findex%2findex%3fprovideId%3d2088331168368991%26chInfo%3dXSbduanfanyong"] options:nil completionHandler:nil];
                    return;
                }
                if (![WXApi isWXAppInstalled]){
                    [Tools showMessage:@"请安装支付宝APP后重试"];
                    return;
                }
                WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                launchMiniProgramReq.userName = @"gh_45334679e384";  //拉起的小程序的username
                launchMiniProgramReq.path = @"pages/nhsa-code/index/index?channel=AAEKTLpkFoE88Zic8BqWR87_&cityCode=440300";    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                }];
            }
        }
    
    } Failure:^(NSError* error) {
        [SVProgressHUD dismiss];
        NSLog(@"error:%@",error);
    }];
}

- (void)backResponseResult:(NSString *)responseResult{
    NSLog(@"%@",responseResult);
    NSDictionary *dic = [NSDictionary dictionaryWithJsonString:responseResult];
    NSString *actionType = dic[@"actionType"];
    NSString *signNo=[GMSm4Utils ecbEncryptText:dic[@"signNo"] key:SMKey].lowercaseString;
    NSString *busiSeq=[GMSm4Utils ecbEncryptText:dic[@"busiSeq"] key:SMKey].lowercaseString;
    if ([actionType isEqualToString:@"001"]||[actionType isEqualToString:@"002"]) {//申领 和 当前渠道签发状态更新
        [self essUpdateStatus:@"BIND" signNo:signNo busiSeq:busiSeq type:@"3"];
    }else if([actionType isEqualToString:@"003"]){//解绑
        [self essUpdateStatus:@"UNBIND" signNo:signNo busiSeq:busiSeq type:@"3"];
    }else if([actionType isEqualToString:@"014"]){//待遇认证
        [self essAuthResult];
    }
}
-(void) essAuthResult {
    NSString *url = [[NSString stringWithFormat:@"%@/electronic/social/certification/saveCertification",CSL_url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * phone=[GMSm4Utils ecbEncryptText:[getPeopleID PeopleIphoneNmber] key:SMKey].lowercaseString;
    NSString *name=[[NSUserDefaults standardUserDefaults]stringForKey:@"essCardName"];//name
    NSString *idNum=[[NSUserDefaults standardUserDefaults]stringForKey:@"essCardIdNum"];//id
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"name":name,
                             @"idCard":idNum,
                             @"phone":phone
                             };
    [NetworkRequest PostEssResult:url Params:params Success:^(id _Nonnull objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                NSLog(@"%@",@"电子认证状态:更新成功!");
            }else if ([state isEqualToString:@"50009"]){//token过期
                NSString *refreshToken = [[NSString stringWithFormat:@"%@/electronic/social/issuance/refreshToken",CSL_url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [NetworkRequest PostEssResult:refreshToken Params:params Success:^(id _Nonnull obj){
                    if ([obj isKindOfClass:[NSDictionary class]]) {
                        NSString *tokenstate = [NSString stringWithFormat:@"%@",obj[@"state"]];
                        if ([tokenstate isEqualToString:@"200"]) {
                            NSString *newToken=obj[@"result"];
                            [[NSUserDefaults standardUserDefaults]setObject:newToken forKey:@"essCardToken"];//保存token
                            [self essAuthResult];
                        }
                    }
                } Failure:^(NSError *error) {
                    NSLog(@"error:%@",error);
                }];
            }
            
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

-(void) essUpdateStatus:(NSString *)status signNo:(NSString *)signNo  busiSeq:(NSString *)busiSeq type:(NSString *)type {
    NSString *url = [[NSString stringWithFormat:@"%@/electronic/social/issuance/updateSign",CSL_url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * phone=[GMSm4Utils ecbEncryptText:[getPeopleID PeopleIphoneNmber] key:SMKey].lowercaseString;
    NSString *name=[[NSUserDefaults standardUserDefaults]stringForKey:@"essCardName"];//name
    NSString *idNum=[[NSUserDefaults standardUserDefaults]stringForKey:@"essCardIdNum"];//id
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"name":name,
                             @"idCard":idNum,
                             @"phone":phone,
                             @"status":status,
                             @"signNo":signNo,
                             @"busiSeq":busiSeq,
                             @"type": type
                             };
    [NetworkRequest PostEssResult:url Params:params Success:^(id _Nonnull objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                NSLog(@"%@",@"签发状态:更新成功!");
            }else if ([state isEqualToString:@"50009"]){//token过期
                NSString *refreshToken = [[NSString stringWithFormat:@"%@/electronic/social/issuance/refreshToken",CSL_url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [NetworkRequest PostEssResult:refreshToken Params:params Success:^(id _Nonnull obj){
                    if ([obj isKindOfClass:[NSDictionary class]]) {
                        NSString *tokenstate = [NSString stringWithFormat:@"%@",obj[@"state"]];
                        if ([tokenstate isEqualToString:@"200"]) {
                            NSString *newToken=obj[@"result"];
                            [[NSUserDefaults standardUserDefaults]setObject:newToken forKey:@"essCardToken"];//保存token
                            [self essUpdateStatus:status signNo:signNo busiSeq:busiSeq type:type];
                        }
                    }
                } Failure:^(NSError *error) {
                    NSLog(@"error:%@",error);
                }];
            }
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    NSMutableArray *naviVCsArr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    for (UIViewController *vc in naviVCsArr) {
        if ([vc isKindOfClass:[InsuredInfoViewController class]]) {
            [naviVCsArr removeObject:vc];
            break;
        }else if ([vc isKindOfClass:[quickInsuredInfoViewController class]]){
            [naviVCsArr removeObject:vc];
            break;
        }else if ([vc isKindOfClass:[KKUserIdentifyViewController class]]){
            KKUserIdentifyViewController *fromVC = (KKUserIdentifyViewController *)vc;
            [fromVC clearText];
        }
    }
    self.navigationController.viewControllers = naviVCsArr;
}


-(void)imageLoca{
    
    
    //self.imageView_1.image = [self imageByScalingAndCroppingForSize:CGSizeMake(150*WIDTHRADIU, 150*WIDTHRADIU) and:self.imageView1];
    self.imageView_1.image=[self js_imageWithOriginalImage:[self imageByScalingAndCroppingForSize:CGSizeMake(160*WIDTHRADIU, 160*WIDTHRADIU) and:self.imageView1]];
}


-(void)showView{
    //获取省份和市区

}
- (void)extracted:(NSMutableDictionary *)params url:(NSString *)url {
    WeakSelf
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            if (code.integerValue == 1006) {
                //@1缩放s动画
                
                NSDate *oldDate = [NSDate date];
                [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"coinsauthenticationLastTime"];
                [[NSUserDefaults standardUserDefaults]synchronize];
                
                if ([responseObject[@"result"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary* result = responseObject[@"result"];
                    NSString* rewardType = [NSString stringWithFormat:@"%@",result[@"rewardType"]];
                    
                    if ([rewardType isEqualToString:@"3001"]) {
                        
                        NSNumber*rewardMoney = result[@"rewardMoney"];
                        NSString*money = [NSString stringWithFormat:@"%0.2f",rewardMoney.doubleValue];
                        [RedPackageView showMoneyWithVC:self money:money type:KKRedPackageTypeMoney from:RedPackageFromRenZheng  block:^(BOOL success) {
                            if (success) {
                                
                            }
                        }];
                    }else if ([rewardType isEqualToString:@"3002"]){
                         NSString*rewardCoins = [NSString stringWithFormat:@"%@",result[@"score"]];
                        [RedPackageView showMoneyWithVC:self money:rewardCoins type:KKRedPackageTypeCoins from:RedPackageFromRenZheng block:^(BOOL success) {
                            if (success) {
                               [weakSelf onClickImage];
                            }
                        }];
                    }
                }
                
                [weakSelf refreshCoins];
                
            }
        }
    }];
}

//雷俊博,认证成功获取金币
- (void)loadData{
    
//    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"coinsauthenticationLastTime"];
//
//    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
//        return;
//    }
    
    
   
     NSString *url = [NSString stringWithFormat:@"%@score/increateScore",CoinsBaseUrl];
    NSDictionary *dic = @{
                          @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"scoreType":@"1003",
                          @"reqTimesTamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2"
                          };
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&Kanwf574",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    
    

    
    
    [self extracted:params url:url];
    
}


- (void)refreshCoins
{
//    WeakSelf
    if ([getPeopleID PeopleID] && [getPeopleID PeopleIphoneNmber])
    {
        NSDictionary *params = @{
                                 @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                                 @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
                                 };
        NSString *url =[NSString stringWithFormat:@"%@score/getpersonintegrals",CoinsBaseUrl];
        [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
            
            if (responseObj) {
                NSString *code = [responseObj[@"code"] stringValue];
                if ([code isEqualToString:@"0"]) {
                    [getPeopleID getTotalCoins:responseObj[@"result"]];
                   
                    //[weakSelf showPopAnimationWithAnimationStyle:1];
//                                   [Package2CoinsView alertWithButtonClickedBlock:^{
//                                       NSLog(@"电子按钮");
//
//                                       weakSelf.navigationController.tabBarController.selectedIndex = 3;
//
//                                       UINavigationController *nav4 =  (UINavigationController *)weakSelf.tabBarController.viewControllers[3];
//
//                                              Log2ViewController *logVC = (Log2ViewController *)nav4.viewControllers[0];
//
//                                              [logVC selectedItemButton:0];
//
//                                       [weakSelf.navigationController popToRootViewControllerAnimated:YES];
//
//
//
//                                   }];
                   // weakSelf.img_package.hidden = NO;
                    
                    
                    
                }
            }
            
        
        }];
    }
}




//获取微信access_token
- (void)getWXAccessToken:(WXSubscribeMsgResp *)resp
{
    NSString *urlString = [NSString stringWithFormat:@"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%@&secret=%@",WXAppId,WXAppSecret];
    
    NSLog(@"获取微信access_token的url:%@",urlString);
    
    [CTAPIBaseManager GET:urlString params:nil completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"responseObject:%@",response);
            
            NSString *access_token = response[@"access_token"];
            
            if (![NSString blankString:access_token]) {
                [self sendMessage:resp accessToken:access_token];
            }
            
        }
        
        if (error) {
            NSLog(@"error:%@",error);
        }
    }];
}

- (NSDictionary *)getSubPushRequestPara:(WXSubscribeMsgResp *)resp accessToken:(NSString *)access_token
{
    
//    NSMutableDictionary* data = [NSMutableDictionary dictionary];
//      NSMutableDictionary* content = [NSMutableDictionary dictionary];
//      [content setValue:@"\n这是一个测试 \n 晚了" forKey:@"value"];
//      [content setValue:@"#EEEE00" forKey:@"color"];
//      [data setValue:content forKey:@"content"];
    NSDictionary *data =  @{
        @"content":@{
                @"value":@"\n就差一步!戳我扫码关注，实时了解社保政策指南!\n",
                @"color":@"#000000"
        }
    };
  
    
    NSDictionary *dic = @{
        @"touser":resp.openId,
        @"template_id":resp.templateId,
    @"url":@"http://nginx.weface.com.cn/wxbind/gzh.html",
        @"scene":[NSNumber numberWithUnsignedInt:resp.scene],
        @"title":@"点击关注公众号,接收认证通知",
        @"data":data
    };
    return dic;
}

//发送推送消息
- (void)sendMessage:(WXSubscribeMsgResp *)resp accessToken:(NSString *)access_token
{
    NSString *urlString = [NSString stringWithFormat:@"https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=%@",access_token];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager POST:urlString parameters:[self getSubPushRequestPara:resp accessToken:access_token] headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
}




#pragma mark - 创建本地数据库
- (BOOL)queryDataExist{
    
//    self.name = @"徐振东";
//    self.idNumber = @"110101199003075576";
//        self.name = @"小慧";
//        self.idNumber = @"110101199003077192";
    
    
    //姓名和身份证号码去空格
     self.name = [self.name stringByReplacingOccurrencesOfString:@" " withString:@""];
     self.idNumber = [self.idNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
     //加密
//     NSString *NameEnerypt =  [EnercryTool A:self.name];
     //身份证号AES加密
     NSString *IdentiftyEnerypt = self.idNumber;
    
    FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]){
       
        
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_rzUserNew WHERE userid='%@'  and idNumber='%@';",[NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]],IdentiftyEnerypt];
        FMResultSet *resultSet = [db executeQuery:sql];
        
        if (resultSet.next) {
            [db close];
            return YES;
        }else{
            [db close];
            return NO;
        }
    }
    
    [db close];
    
    return YES;
    
}



- (void)insertUserInfo{
    if (![self queryDataExist]) {
        FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
        //姓名和身份证号码去空格
        self.name = [self.name stringByReplacingOccurrencesOfString:@" " withString:@""];
        self.idNumber = [self.idNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
        //加密
        NSString *NameEnerypt =  self.name;
        //身份证号AES加密
        NSString *IdentiftyEnerypt = self.idNumber;
        
        if ([db open]) {
            
            NSString *sql = [NSString stringWithFormat:@"SELECT Count(1) FROM t_rzUserNew WHERE userid='%ld' ",[getPeopleID PeopleID]];
            NSUInteger count  = [db intForQuery:sql];
            NSLog(@"已添加数据:%ld",count);
            if (count >= 5) {
                
            NSString *sql2 = [NSString stringWithFormat:@"SELECT  id FROM t_rzUserNew WHERE userid='%ld' LIMIT 1  ;",[getPeopleID PeopleID]];
             NSInteger Id = [db intForQuery:sql2];
                
              NSString *sql3 = [NSString stringWithFormat:@"delete from t_rzUserNew where id = '%ld'",Id];
              BOOL reslut =   [db executeUpdate:sql3];
                if (reslut) {
                    NSString * sql4 = [NSString stringWithFormat:@"INSERT INTO t_rzUserNew (name,idNumber,userid,timeSp) VALUES (?, ?,?,?);"];
                    NSString *userid = [NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]];
                    NSString *timeSp = [NSString stringWithFormat:@"%ld",[self getNowTimeTimestamp3]];
                    
                    BOOL res =  [db executeUpdate:sql4,NameEnerypt,IdentiftyEnerypt,userid,timeSp];
                    

                    if (!res) {
                        NSLog(@"error to insert data");
                    }else{
                        NSLog(@"success to insert data");
                    }
                }
            }else{
                
                NSString * sql4 = [NSString stringWithFormat:@"INSERT INTO t_rzUserNew (name,idNumber,userid,timeSp) VALUES (?, ?,?,?);"];
                NSString *userid = [NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]];
                NSString *timeSp = [NSString stringWithFormat:@"%ld",[self getNowTimeTimestamp3]];
                
                BOOL res =  [db executeUpdate:sql4,NameEnerypt,IdentiftyEnerypt,userid,timeSp];
               if (!res) {
                   NSLog(@"error to insert data");
               }else{
                   NSLog(@"success to insert data");
               }
            }
            
           
            
            [db close];
        }
    }else{
        FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
        //姓名和身份证号码去空格
        self.name = [self.name stringByReplacingOccurrencesOfString:@" " withString:@""];
        self.idNumber = [self.idNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
        //加密
//        NSString *NameEnerypt =  [EnercryTool A:self.name];
        //身份证号AES加密
        NSString *IdentiftyEnerypt = self.idNumber;
         NSString *timeSp = [NSString stringWithFormat:@"%ld",[self getNowTimeTimestamp3]];
        if ([db open]) {
            NSString *sql = @"UPDATE t_rzUserNew SET timeSp = ? WHERE  idNumber = ?";
            BOOL res = [db executeUpdate:sql, timeSp, IdentiftyEnerypt];
            if (!res) {
                       NSLog(@"error to UPDATE data");
            }else {
                       NSLog(@"success to UPDATE data");
                      
            }
            [db close];
        }
    }
    
}


- (NSString *)getDBPath
{
     NSString *doc= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        return [doc stringByAppendingPathComponent:@"rzUserlist.sqlite"];

}
#pragma mark -tableView代理和数据源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}
//要
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.dataArray.count > 0) {
        return self.dataArray.count;
    }
    return self.defaultArr.count;
}
#pragma mark - cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.00;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
#pragma mark - 数据请求填充 cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataArray.count > 0) {
        SuccessItem3Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"SuccessItem3Cell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SuccessItem3Cell" owner:self options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//无高亮选中
        KKRedPackageClickEventModel *model = self.dataArray[indexPath.row];
        if (model.menuTag.length > 0) {
            NSDictionary *dic = [self dictionaryWithJsonString:model.menuTag];
            [cell.iconImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KKFindPackageIP,model.menuIcon]]];
            cell.titlelab.text = model.menuName;
            //cell.detailLab.text = dic[@"describe"];
            [cell.performBtn setTitle:dic[@"clickTitle"] forState:UIControlStateNormal];
            cell.performBtn.tag = indexPath.row;
            [cell.performBtn addTarget:self action:@selector(Cickbtn:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }else{
        SuccessItem3Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"SuccessItem3Cell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SuccessItem3Cell" owner:self options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//无高亮选中
        NSDictionary *dic = self.defaultArr[indexPath.row];
        cell.iconImg.image = [UIImage imageNamed:dic[@"icon"]];
        cell.titlelab.text = dic[@"title"];
        //cell.detailLab.text = dic[@"des"];
        [cell.performBtn setTitle:dic[@"perform"] forState:UIControlStateNormal];
        cell.performBtn.tag = indexPath.row;
        [cell.performBtn addTarget:self action:@selector(Cickbtn:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}
#pragma mark - 跳转到详情方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
#pragma mark - 去完成任务
- (void)Cickbtn:(UIButton *)button{
    if (self.dataArray.count > 0) {
        KKRedPackageClickEventModel *model = self.dataArray[button.tag];
        [NetworkRequest statisticsWithEventName:[NSString stringWithFormat:@"%@",model.ID]];
        switch (model.type.integerValue) {
            case 1001:
                //原生跳转
            {
                [[clickEvent instance] clickEventRooterVC:self model:model];
            }
                break;
            case 1002:
                //h5跳转
            {
                WebVC *vc = [[WebVC alloc]init];
                vc.title = model.menuName;
                vc.url = model.content;
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 1003:
                //微信小程序
            {
                if (![WXApi isWXAppInstalled]){
                    [Tools showMessage:@"请安装微信APP后重试"];
                    return;
                }
                
                NSDictionary *resourceInfoDic = [self dictionaryWithJsonString:model.content];
                if (resourceInfoDic&& resourceInfoDic.allKeys.count > 1) {
                    NSString *userName = resourceInfoDic[@"userId"];
                    NSString *path = resourceInfoDic[@"path"];
                    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                    launchMiniProgramReq.userName = userName; //拉起的小程序的username
                    launchMiniProgramReq.path = path; //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                        
                    }];
                }
               
            }
                break;
            case 1004:
                //其他
            {
            }
                break;
            case 1005:
            {
                [self getFederatedLoginRequestWithModel:model];
            }
                break;
            default:
                break;
        }
    }else{
        switch (button.tag) {
            case 0:
                //存钱罐
            {
                [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@""];
            }
                break;
            case 1:
                //微信订阅
            {
                [[clickEvent instance] clickEventRooterVC:self Content:@"sendWxSubscribeMessage" menuName:@""];
            }
                break;
            case 2:
                //领钱群
            {
                [[clickEvent instance] clickEventRooterVC:self Content:@"DaYiQun" menuName:@""];
            }
                break;
            case 3:
                //医保电子凭证
            {
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipays://"]]) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"alipays://platformapi/startapp?appId=2021001123625885&page=pages%2findex%2findex%3fprovideId%3d2088331168368991%26chInfo%3dXSbduanfanyong"] options:nil completionHandler:nil];
                    return;
                }
                if (![WXApi isWXAppInstalled]){
                    [Tools showMessage:@"请安装支付宝APP后重试"];
                    return;
                }
                
                WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                launchMiniProgramReq.userName = @"gh_45334679e384";  //拉起的小程序的username
                launchMiniProgramReq.path = @"pages/nhsa-code/index/index?channel=AAEKTLpkFoE88Zic8BqWR87_&cityCode=440300";    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                    
                }];
            }
                break;
            default:
                break;
        }
    }
}
#pragma mark - 获取联合登录链接
- (void)getFederatedLoginRequestWithModel:(KKRedPackageClickEventModel *)model
{
    NSString *url = [NSString stringWithFormat:@"%@",model.content];
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
    
    NSDictionary *params = @{
        @"uid":@([getPeopleID PeopleID]),
        @"tel":[getPeopleID PeopleIphoneNmber]
    };
    
    NSLog(@"联合登录url:%@",url);
    NSLog(@"params:%@",params);
    [KKLoadingAnimationView show];
    [NetworkRequest Get:url Params:params Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            NSString *url = [NSString stringWithFormat:@"%@",objc[@"result"]];
            WebVC *webvc = [[WebVC alloc]init];
            webvc.url = url;
            webvc.title = model.menuName;
            webvc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webvc animated:YES];
        }else{
            [self alertShow:describe];
        }

    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShow:@"网络异常"];
    }];
    
}
#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 - UICollectionViewDataSource
//- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
//{
//    return 1;
//}
//- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
//{
//        return self.dataArray.count;
//}
//
//// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
//- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//    SuccessItem2Cell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
//
//    if (isChange) {
//        KKRedPackageClickEventModel* item = self.dataArray[indexPath.item];
////        [cell.icon sd_setImageWithURL:[NSURL URLWithString:item.image] completed:nil];
////        cell.title.text = item.menuName;
//        cell.title.text = item.menuName;
//        [cell.icon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KKFindPackageIP,item.menuIcon]]];
//    }else{
//        cell.icon.image = [UIImage imageNamed:self.dataArray[indexPath.item]];
//        cell.title.text = self.titleArray[indexPath.item];
//    }
//
////    if (isChange) {
////        SuccessItem* item = self.dataArray[indexPath.item];
////        [cell.icon sd_setImageWithURL:[NSURL URLWithString:item.image] completed:nil];
////    }else{
////        cell.bgImg.image = [UIImage imageNamed:self.dataArray[indexPath.item]];
////    }
//    return cell;
//}
///**
// cell的大小
// */
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//
//
//        CGFloat width =  (CGRectGetWidth(collectionView.bounds) - 100 * WIDTHRADIU)  /3 ;
//        return CGSizeMake(width, 80 * WIDTHRADIU);
//}
///**
// 每个分区的内边距（上左下右）
// */
//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
//
//    return UIEdgeInsetsMake(0, 30 * WIDTHRADIU, 0, 30 * WIDTHRADIU);
//}
///**
// 分区内cell之间的最小行间距
// */
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//
//    return 20 * WIDTHRADIU;
//}
///**
// 分区内cell之间的最小列间距
// */
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//
//    return 0;
//}
//
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//    return nil;
//}
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//
//        return CGSizeZero;
//}
//
//- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (isChange) {
//        [self jumpVCByServeWithIndexPath:indexPath];
//    }else{
//        [self jumpVCWithIndexPath:indexPath];
//    }
//}
#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvSubscribeMsgResponse:(WXSubscribeMsgResp *)response
{
    if ([response.action isEqualToString:@"confirm"]) {
        [self getWXAccessToken:response];
    }
    
    
}
#pragma mark -
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        self.navigationController.navigationBar.translucent = YES;
        [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:27/255.0 green:132/255.0 blue:208/255.0 alpha:1.0]];
        [self.navigationController setNavigationBarHidden:NO animated:YES];
      
        
        [[NSNotificationCenter defaultCenter] postNotificationName:KKSBFiveRedPackageNotificationName object:nil userInfo:nil];
        
      

        [self.navigationController popToRootViewControllerAnimated:YES ];
        
        
    }
}
#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];
                
                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)jumpVCByServeWithIndexPath:(NSIndexPath *)indexPath {
    KKRedPackageClickEventModel* model = self.defaultArr[indexPath.item];
    switch (model.type.integerValue) {
        case 1001:
            //原生跳转
        {
            [[clickEvent instance] clickEventRooterVC:self Content:model.content menuName:model.menuName];
        }
            break;
        case 1002:
            //h5跳转
        {
            if ([model.menuTag isEqualToString:@"lingqianqun"]) {
                WebVC * vc = [WebVC new];
                vc.title= model.menuName;
                vc.fromSuccess = YES;
                vc.url = @"http://nginx.weface.com.cn/appH5/kefu/index.html";
                vc.verytype = 0;
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
                return;;
            }
            
            WebVC *vc = [[WebVC alloc]init];
            vc.title = model.menuName;
            vc.url = model.content;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1003:
            //小程序
        {
            if (![WXApi isWXAppInstalled]){
                [Tools showMessage:@"请安装微信APP后重试"];
                return;
            }
            NSDictionary *resourceInfoDic = [self dictionaryWithJsonString:model.content];
            
            if (resourceInfoDic&& resourceInfoDic.allKeys.count > 1) {
                NSString *userName = resourceInfoDic[@"userId"];
                NSString *path = resourceInfoDic[@"path"];
                WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                launchMiniProgramReq.userName = userName; //拉起的小程序的username
                launchMiniProgramReq.path = path; //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                    
                }];
            }
        }
            break;
        case 1004:
            //其他 反定向
        {
//            NSDictionary *dic = [self dictionaryWithJsonString:model.content];
//            if (dic) {
//                [self push:dic model:model];
//            }
        }
            break;
        case 1005:
        {
            [self getFederatedLoginRequestWithModel:model];
        }
            break;
        default:
            break;
    }
//    if ([item.resourceType isEqualToString:@"1"]) {
//
//        [self jumpVCWithItem:item];
//
//    }else if ([item.resourceType isEqualToString:@"2"]){
//        if ([item.menuName isEqualToString:@"科技扶贫"]) {
//            WebVC * vc = [WebVC new];
//            vc.title= item.menuName;
//            vc.url = item.resourceInfo;
//            vc.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:vc animated:YES];
//        }else if ([item.menuName isEqualToString:@"领钱群"]){
//
//            WebVC * vc = [WebVC new];
//            vc.title= item.menuName;
//            vc.fromSuccess = YES;
//            //vc.url = @"http://172.16.10.139/projects/html-nginx/html-nginx/appH5/kefu/index.html";
//            vc.url = @"http://nginx.weface.com.cn/appH5/kefu/index.html";
//            vc.provincename = [Tools isBlankString:self.province] ? @"" : self.province;
//            vc.cityname = [Tools isBlankString:self.city] ? @"" : self.city;
//            vc.countryname = [Tools isBlankString:self.county] ? @"" : self.county;
//            vc.verytype = 0;
//            vc.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:vc animated:YES];
//
//
//        }else if ([item.menuName isEqualToString:@"话费券"]){
//            WebVC *webvc = [[WebVC alloc]init];
//            webvc.url = @"http://www.qld02.com/t/blackcard/callFee/callFeeForH5.html?channel=shebao";
//            webvc.title = @"话费券";
//            [self.navigationController pushViewController:webvc animated:YES];
//        } else{
//            [self jumpToHTML5:item.resourceInfo andJAnalytics:item.menuName];
//        }
//
//
//    }else if ([item.resourceType isEqualToString:@"3"]) {
//
//        if ([WXApi isWXAppInstalled]) { //先判断是否安装微信
//
//            NSString *jsonStr = item.resourceInfo;
//
//            NSDictionary *resourceInfoDic = [self dictionaryWithJsonString:jsonStr];
//
//            if (resourceInfoDic&& resourceInfoDic.allKeys.count > 1) {
//                NSString *userName = resourceInfoDic[@"userId"];
//                NSString *path = resourceInfoDic[@"path"];
//
//                 WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
//                 launchMiniProgramReq.userName = userName;  //拉起的小程序的username-原始ID
//                 launchMiniProgramReq.path = path;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
//                 launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
//             [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
//
//             }];
//
//            }
//
//
//            }else{
//                //提示用户没有安装微信，不能拉起小程序
//                [Tools showMessage:@"未安装微信APP!"];
//            }
//    }else if ([item.resourceType isEqualToString:@"4"]) {
//        [self jumpVCWithItem:item];
//    }
}
//#pragma mark - app功能
//- (void)jumpVCWithItem:(SuccessItem *)item {
//    if ([item.menuName isEqualToString:@"认证查询"]) {
//        [self goToAuthHistoryVC];
//    }else if ([item.menuName isEqualToString:@"免费看病"]) {
//        [self goToFreeTreatmentVC];
//    }else if ([item.menuName isEqualToString:@"喜马拉雅"]) {
//        [self goToXMVC];
//    }else if ([item.menuName isEqualToString:@"赚红包"]){
//        [self goToTVVC];
//    }
//}
#pragma mark - 默认跳转
- (void)jumpVCWithIndexPath:(NSIndexPath *)indexPath {
//    WeakSelf
    if (indexPath.item == 0) {
        [self goToFreeTreatmentVC];
    }else if (indexPath.item == 1){
        
        [self goToTVVC];
        
    }else if (indexPath.item == 2){
        WebVC * vc = [WebVC new];
        vc.title= @"领钱答疑群";
        //vc.url = @"http://172.16.10.139/projects/html-nginx/html-nginx/appH5/kefu/index.html";
        vc.url = @"http://nginx.weface.com.cn/appH5/kefu/index.html";
        vc.fromSuccess = YES;
        vc.verytype = 0;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        //[self jumpToHTML5:@"http://nginx.weface.com.cn/appH5/active/popularize.html" andJAnalytics:@"科技扶贫"];
        
    }else if (indexPath.item == 3){
        
        [self goToXMVC];
    }
}


#pragma mark - 免费看病
- (void)goToFreeTreatmentVC{
    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];
        }
    }];
}

#pragma mark - 跳转到小视频
- (void)goToTVVC {
    
    KKSVideoViewController *oneVC = [[KKSVideoViewController alloc]initWithType:NO];
    oneVC.title = @"红包视频";
    oneVC.view.backgroundColor = [UIColor whiteColor];
    oneVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:oneVC animated:YES];
    
    /*
    KKTabBarViewController *tabBarVC = [[KKTabBarViewController alloc]initWithType:NO];
    
    
    
    LittleVideoViewController *twoVC = [[LittleVideoViewController alloc] init];
    twoVC.title = @"看视频赚红包";
    twoVC.view.backgroundColor = [UIColor whiteColor];
    twoVC.tabBarItem = [self getCustomItemWithTitle:@"更多" image:@"" selectedImage:@""];
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:twoVC];
    [tabBarVC addChildViewController:nav2];
    
    
    KKVideoViewController *oneVC = [[KKVideoViewController alloc] init];
    oneVC.title = @"看视频赚红包";
    oneVC.view.backgroundColor = [UIColor whiteColor];
    oneVC.tabBarItem = [self getCustomItemWithTitle:@"小视频" image:@"" selectedImage:@""];
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:oneVC];
    [tabBarVC addChildViewController:nav1];
    
    
    
    
    //修改主题的颜色
    tabBarVC.tabBar.tintColor = [UIColor colorWithHex:0x137ef6];
    
    
    [tabBarVC.navigationController setNavigationBarHidden:YES];
    tabBarVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:tabBarVC animated:YES];
     
     */
    
}

- (UITabBarItem *)getCustomItemWithTitle:(NSString *)title image:(NSString *)imageName selectedImage:(NSString *)selectedImageName
{
    UIImage *image = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage* selectedImage = [[UIImage imageNamed:selectedImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
     UITabBarItem *tabbarItem = [[UITabBarItem alloc] initWithTitle:title image:image selectedImage:selectedImage];
    [tabbarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHex:0x137ef6], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
    [tabbarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHex:0x7a7a7a], NSForegroundColorAttributeName,[UIFont systemFontOfSize:15],NSFontAttributeName, nil] forState:UIControlStateNormal];
    
    return tabbarItem;
}


#pragma mark - 跳转认证记录
- (void)goToAuthHistoryVC {
    
    WeiJianQueryViewController* vc = [WeiJianQueryViewController new];
    vc.title = @"认证查询";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 跳转到喜马拉雅
- (void)goToXMVC{
    KKLisenViewController*vc = [KKLisenViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    vc.fromHome = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 打开微信
- (void)openWxChat
{
    UIApplication *application = [UIApplication sharedApplication];
    NSURL * url = [NSURL URLWithString:@"weixin://"];
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
    
    if (canOpen) {
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [application openURL:url options:@{} completionHandler:^(BOOL success) {
                    
               
            }];
        } else {
            [application openURL:url];
             
        }
    }else{
        [Tools showMessage:@"请安装微信APP!"];
    }
}
#pragma mark - 获取当前时间戳

-(NSInteger )getNowTimeTimestamp3{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSInteger timeSp = [datenow timeIntervalSince1970]*1000;
    
    return timeSp;
}

// 判断是否是同一天
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}


#pragma mark 显示弹框
- (void)showPopAnimationWithAnimationStyle:(NSInteger)style
{
    ZJAnimationPopStyle popStyle = (style == 8) ? ZJAnimationPopStyleCardDropFromLeft : (ZJAnimationPopStyle)style;
    ZJAnimationDismissStyle dismissStyle = (ZJAnimationDismissStyle)style;
    
    // 1.初始化
    ZJAnimationPopView *popView = [[ZJAnimationPopView alloc] initWithCustomView:self.coinsView popStyle:popStyle dismissStyle:dismissStyle];
    
    // 2.设置属性，可不设置使用默认值，见注解
    // 2.1 显示时点击背景是否移除弹框
    popView.isClickBGDismiss = ![self.coinsView isKindOfClass:[PackageCoinsView class]];
    // 2.2 显示时背景的透明度
    popView.popBGAlpha = 0.5f;
    // 2.3 显示时是否监听屏幕旋转
    popView.isObserverOrientationChange = NO;
    // 2.4 显示时动画时长
        popView.popAnimationDuration = 1.0f;
    // 2.5 移除时动画时长
    //    popView.dismissAnimationDuration = 0.8f;
    
    // 2.6 显示完成回调
    WeakSelf
    popView.popComplete = ^{
        NSLog(@"显示完成");
        [weakSelf.coinsView showAnimation];
    
    };
    // 2.7 移除完成回调
    popView.dismissComplete = ^{
        NSLog(@"移除完成");
    };
    
    // 3.处理自定义视图操作事件
    [self handleCustomActionEnvent:popView];
    
    // 4.显示弹框
    [popView pop];
}

#pragma mark 处理自定义视图操作事件
- (void)handleCustomActionEnvent:(ZJAnimationPopView *)popView
{
    // 在监听自定义视图的block操作事件时，要使用弱对象来避免循环引用
    __weak typeof(popView) weakPopView = popView;
    __weak typeof(self) weakSlef = self;
    if ([self.coinsView isKindOfClass:[PackageCoinsView class]]) {
        weakSlef.coinsView.block = ^(BOOL skip) {
            
            if (skip) {
                [weakPopView dismiss];
                CoinsCenterViewController *vc = [[CoinsCenterViewController alloc]init];
                vc.title = @"金币中心";
                [weakSlef.navigationController pushViewController:vc animated:YES];
                return ;
            }else{
                [weakPopView dismiss];
            }
           
           
            
            
            
        };
    }
}

- (void)onClickImage
{
    self.navigationController.tabBarController.selectedIndex = 3;
                                          
    UINavigationController *nav4 =  (UINavigationController *)self.tabBarController.viewControllers[3];
                                                 
    Log2ViewController *logVC = (Log2ViewController *)nav4.viewControllers[0];
                                                 
    [logVC selectedItemButton:1];
                                          
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{
    WebViewController *tc=[WebViewController new];
    tc.URL =[NSURL URLWithString:url];
            tc.hidesBottomBarWhenPushed =YES;
    tc.janalytics = janalytics;
    [self.navigationController pushViewController:tc animated:YES];

}

#pragma mark - event response
- (void)authBtnClick:(UIButton *)sender {
    for (UIViewController*vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[AuthB1ViewController class]]) {
            AuthB1ViewController*currentVC  = (AuthB1ViewController *)vc;
            [currentVC clearText];
            [self.navigationController popToViewController:currentVC animated:YES];
            break;
        }
    }
    
 self.navigationController.navigationBar.translucent = YES;
        [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:27/255.0 green:132/255.0 blue:208/255.0 alpha:1.0]];
    if ([UIScreen mainScreen].bounds.size.height == 480) {
    
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        
    }
}

- (void)recordBtnClick:(UIButton *)sender {
    //[self goToAuthHistoryVC];
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KKSBFiveRedPackageNotificationName object:nil userInfo:nil];
    
//    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"fiveRedPackageLastTime"];
//
//    BOOL success = oldTime && [self isSameDay:[NSDate date] date2:oldTime];
//
//    if (!success) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:KKSBFiveRedPackageNotificationName object:nil userInfo:nil];
//    }
//
//    NSDate *oldDate = [NSDate date];
//    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"fiveRedPackageLastTime"];
//    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)backBtnClick:(UIButton *)sender {
    [self exitApplication];
}

-(void)exitApplication
{
    UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"确认返回首页?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    
    alert1.alertViewStyle = UIAlertActionStyleDefault;
    
    [alert1 show];
    
    //    [UIView animateWithDuration:1.0f animations:^{
    //        self.view.alpha =0;
    //        self.view.frame=CGRectMake(0, self.view.bounds.size.width, 0, 0);
    //    }completion:^(BOOL finished) {
    //
    //    }];
    
    
}

- (void)btnTelClick:(UIButton *)sender{
    
    NSString *callPhone = @"telprompt:400-002-1799";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    
}


- (void)saveQrBtnClick:(UIButton *)sender{
    
    [self showSaveQRAlertVC];
    
}

- (void)shareBtnClick:(UIButton *)sender{
    
    [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
}


#pragma mark - 保存图片到相册
- (void)showSaveQRAlertVC
{
    UIAlertController*alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确实是否要保存图片" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction*confirmAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
        UIImage* image = self.qrImg.image;
               
        //UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:confirmAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}
                        
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    
    if (error) {
        [Tools showMessage:@"保存失败"];
    }else{
        [Tools showMessage:@"保存成功"];
    }
}

#pragma mark -  微信分享
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }
    
//    WeakSelf
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    //创建网页内容对象
//    NSString* thumbURL =  UMS_THUMB_IMAGE;
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"领钱答疑群" descr:@"长按识别二维码，添加客服微信，进当地领钱答疑群" thumImage:[UIImage imageNamed:@"login_icon"]];
//    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"安全认证 轻松领钱" descr:@"限时抢购补贴口罩，就差你啦！" thumImage:[UIImage imageNamed:@"login_icon"]];
    //设置网页地址
    NSString *url = [NSString stringWithFormat:@"http://nginx.weface.com.cn/appH5/kefu/shareIndex.html?src=%@",self.qrUrlString];//外网
    //NSString *url = [NSString stringWithFormat:@"http://172.16.10.144/projects/html-nginx/html-nginx/lesson/award/share/index.html?userid=%ld&telephone=%@",(long)[getPeopleID PeopleID],[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]];//内网
    shareObject.webpageUrl = url;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
            
        }
        
    }];
}



#pragma mark - json字符串转dic
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark - 实现颜色渐变
- (void)addBgLayerWithView:(UIView *)theView {
    CAGradientLayer* gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = theView.bounds;
    [theView.layer addSublayer:gradientLayer];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1);
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHex:0x1986d4].CGColor,
                             (__bridge id)[UIColor colorWithHex:0x4481eb].CGColor];
    gradientLayer.locations = @[@(0.0f), @(1.0f)];
}
#pragma mark - getters
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _scrollView.contentSize = CGSizeMake(ScreenWidth, ScreenHeight);
        _scrollView.contentOffset = CGPointMake(0, 0);
        _scrollView.bounces = NO;
        _scrollView.backgroundColor = [UIColor colorWithHex:0x1986d4];

        
        
        CGFloat y = cl_kNavigationBarHeight > 64 ? 18 * WIDTHRADIU + cl_kStatusBarHeight  : 11 * WIDTHRADIU + cl_kStatusBarHeight;
        
        //顶部模块
        UIView* topView = [[UIView alloc]initWithFrame:CGRectMake(10 * WIDTHRADIU, y, 355 * WIDTHRADIU, cl_kNavigationBarHeight > 64 ? (375 * WIDTHRADIU + 47 * WIDTHRADIU) : 385 * WIDTHRADIU) ];
        topView.layer.cornerRadius = 15 * WIDTHRADIU;
        topView.layer.masksToBounds = YES;
        topView.backgroundColor = [UIColor whiteColor];
        self.topView = topView;
        [_scrollView addSubview:topView];
        
        //顶部背景图
        UIImageView *imageBg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100 * WIDTHRADIU)];
        imageBg.image = [UIImage imageNamed:@"auth_success_top_bkg"];
        [topView addSubview:imageBg];
        
    
        
        //相册
        UIImageView* leftImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 150* WIDTHRADIU, 150* WIDTHRADIU)];
        leftImg.contentMode = UIViewContentModeScaleAspectFill;
        [topView addSubview:leftImg];
        [leftImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(topView);
            make.top.offset(cl_kNavigationBarHeight > 64 ? 33 * WIDTHRADIU  : 23 * WIDTHRADIU);
           
        }];
        
        self.imageView_1 = leftImg;
    
        
        
        
        UIImageView *successIcon = [[UIImageView alloc]init];
        successIcon.image = [UIImage imageNamed:@"auth_success_title_icon"];
        [topView addSubview:successIcon];
        
        [successIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(topView);
            make.top.equalTo(leftImg.mas_bottom).offset(30 * WIDTHRADIU);
            
        }];
        
        
//        UIButton *successBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [successBtn setTitle:@"认证成功" forState:UIControlStateNormal];
//        [successBtn setImage:[UIImage imageNamed:@"as_yes"] forState:UIControlStateNormal];
//        [successBtn setTitleColor:[UIColor colorWithHex:0x1986d4] forState:UIControlStateNormal];
//        [successBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleTop imageTitleSpace:8];
//        successBtn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
//        [topView addSubview:successBtn];
//
//        [successBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.width.offset(85 * WIDTHRADIU);
//            make.top.height.equalTo(leftImg);
//            make.left.equalTo(leftImg.mas_right);
//        }];
        
        
      
        
        //认证类型

        UILabel* lb_address2 = [UILabel new];
        lb_address2.text = @"认证类型:社保认证";
        lb_address2.textColor = [UIColor colorWithHex:0x999999];
        lb_address2.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        lb_address2.lineBreakMode = UILineBreakModeWordWrap;
        lb_address2.numberOfLines = 0;
        lb_address2.textAlignment=NSTextAlignmentCenter;
        //lb_address.backgroundColor = [UIColor redColor];
        [topView addSubview:lb_address2];
        [lb_address2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(topView);
            make.top.equalTo(successIcon.mas_bottom).offset(30*WIDTHRADIU);
            make.width.offset(topView.width-60 * WIDTHRADIU);
        }];
        self.lb_address = lb_address2;
        self.lb_address.text=[NSString stringWithFormat:@"认证类型:%@",self.auth_type];
        
        UIButton* recordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        recordBtn.backgroundColor = [UIColor colorWithHex:0x19956D];
        recordBtn.layer.cornerRadius = 5 * WIDTHRADIU;
        [recordBtn setTitle:@"返回首页" forState:UIControlStateNormal];
        [recordBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        recordBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [recordBtn addTarget:self action:@selector(recordBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [topView addSubview:recordBtn];
        
        [recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(15 * WIDTHRADIU);
            make.top.equalTo(lb_address2.mas_bottom).offset(25 * WIDTHRADIU);
            make.width.offset(155 * WIDTHRADIU);
            make.height.offset(45 * WIDTHRADIU);
        }];
        
        UIButton* authBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        authBtn.backgroundColor = K_MainColor;
        authBtn.layer.cornerRadius = 5 * WIDTHRADIU;
        [authBtn setTitle:@"帮人认证" forState:UIControlStateNormal];
        [authBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        authBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [authBtn addTarget:self action:@selector(authBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [topView addSubview:authBtn];
        
        [authBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(recordBtn.mas_right).offset(17 * WIDTHRADIU);
            make.top.equalTo(recordBtn);
            make.width.offset(155 * WIDTHRADIU);
            make.height.offset(45 * WIDTHRADIU);
            //make.bottom.mas_greaterThanOrEqualTo(19 * WIDTHRADIU);
        }];
        
        
        
        
//        CGFloat bottomY = cl_kNavigationBarHeight > 64 ?(topView.maxY + 25 * WIDTHRADIU) :(topView.maxY + 15 * WIDTHRADIU);
        
        CGFloat bottomY = topView.maxY + 15 * WIDTHRADIU;
        //顶部模块
        //UIView* bottomView = [[UIView alloc]initWithFrame:CGRectMake(10 * WIDTHRADIU, bottomY,  355 * WIDTHRADIU, 147 * WIDTHRADIU)];
        UIView* bottomView = [[UIView alloc]init];
        bottomView.layer.cornerRadius = 15 * WIDTHRADIU;
        bottomView.layer.masksToBounds = YES;
        bottomView.backgroundColor = [UIColor whiteColor];
        bottomView.frame = CGRectMake(10 * WIDTHRADIU, bottomY,  355 * WIDTHRADIU, 60 * 3 + 30);
        self.bottomView = bottomView;
        [_scrollView addSubview:bottomView];
        
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, 355 * WIDTHRADIU, 60 * 3) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [bottomView addSubview:_tableView];
        [_tableView registerNib:[UINib nibWithNibName:@"SuccessItem3Cell" bundle:nil] forCellReuseIdentifier:@"SuccessItem3Cell"];
        
        //两个环
        UIImageView *leftCircleImg = [[UIImageView alloc]init];
        leftCircleImg.image = [UIImage imageNamed:@"guanlian"];
        [_scrollView addSubview:leftCircleImg];
        [leftCircleImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bottomView.mas_left).offset(30 * WIDTHRADIU);
            make.top.equalTo(topView.mas_bottom).offset( - 14 * WIDTHRADIU);
            make.width.offset(8 * WIDTHRADIU);
            make.height.offset( 43 * WIDTHRADIU);
        }];
        
        UIImageView *rightCircleImg = [[UIImageView alloc]init];
        rightCircleImg.image = [UIImage imageNamed:@"guanlian"];
        [_scrollView addSubview:rightCircleImg];
        [rightCircleImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(bottomView.mas_right).offset(-30 * WIDTHRADIU);
            make.top.equalTo(topView.mas_bottom).offset( - 14 * WIDTHRADIU);
            make.width.offset(8 * WIDTHRADIU);
            make.height.offset( 43 * WIDTHRADIU);
        }];
        
        _scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.bottomView.frame) + 10);
        
        
        
//        BOOL authQunShow = [UserDefault boolForKey:@"authQunShow"];
        
//        if (!authQunShow) {
//        if (0) {
//            bottomView.frame = CGRectMake(10 * WIDTHRADIU, bottomY,  355 * WIDTHRADIU, 197 * WIDTHRADIU);
//
//            UIImageView *qrImg = [[UIImageView alloc]init];
//            qrImg.image = [UIImage imageNamed:@"authQun"];
//            [bottomView addSubview:qrImg];
//
//            self.qrImg = qrImg;
//
//            [qrImg  mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.offset(20 * WIDTHRADIU);
//                make.top.offset(20 * WIDTHRADIU);
//                make.width.offset(105 * WIDTHRADIU);
//                make.height.offset(105 * WIDTHRADIU);
//            }];
//
//            UILabel *lb_qrTitle = [UILabel new];
//            lb_qrTitle.text = @"领钱加我";
//            lb_qrTitle.textColor = [UIColor colorWithHex:0x4d4d4d];
//            lb_qrTitle.font = [UIFont boldSystemFontOfSize:18 * WIDTHRADIU];
//            [bottomView addSubview:lb_qrTitle];
//            [lb_qrTitle mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(qrImg.mas_right).offset(15 * WIDTHRADIU);
//                make.top.equalTo(qrImg);
//            }];
//
//            UIView *qrLine = [UIView new];
//            qrLine.backgroundColor = [UIColor colorWithHex:0x808080];
//            [bottomView addSubview:qrLine];
//            [qrLine mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.top.equalTo(lb_qrTitle.mas_bottom).offset(12 * WIDTHRADIU);
//                make.left.equalTo(lb_qrTitle);
//                make.width.offset(40 * WIDTHRADIU);
//                make.height.offset(1);
//            }];
//
//            UILabel *lb_qrContent1 = [UILabel new];
//            lb_qrContent1.text = @"保存二维码，进入微信选择";
//            lb_qrContent1.textColor = [UIColor colorWithHex:0x808080];
//            lb_qrContent1.font = [UIFont systemFontOfSize:12 * WIDTHRADIU];
//            [bottomView addSubview:lb_qrContent1];
//            [lb_qrContent1 mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(qrImg.mas_right).offset(15 * WIDTHRADIU);
//                make.top.equalTo(qrLine.mas_bottom).offset(8 * WIDTHRADIU);
//            }];
//
//            UILabel *lb_qrContent2 = [UILabel new];
//            lb_qrContent2.text = @"扫码识别添加领钱群";
//            lb_qrContent2.textColor = [UIColor colorWithHex:0x808080];
//            lb_qrContent2.font = [UIFont systemFontOfSize:12 * WIDTHRADIU];
//            [bottomView addSubview:lb_qrContent2];
//            [lb_qrContent2 mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(qrImg.mas_right).offset(15 * WIDTHRADIU);
//                make.top.equalTo(lb_qrContent1.mas_bottom).offset(8 * WIDTHRADIU);
//            }];
//
//            UILabel *lb_qrContent3 = [UILabel new];
//            lb_qrContent3.text = @"客服联系电话:";
//            lb_qrContent3.textColor = [UIColor colorWithHex:0x808080];
//            lb_qrContent3.font = [UIFont systemFontOfSize:12 * WIDTHRADIU];
//            [bottomView addSubview:lb_qrContent3];
//            [lb_qrContent3 mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(qrImg.mas_right).offset(15 * WIDTHRADIU);
//                make.top.equalTo(lb_qrContent2.mas_bottom).offset(11 * WIDTHRADIU);
//            }];
//
//            UIButton *btnTel = [UIButton buttonWithType:UIButtonTypeCustom];
//            [btnTel setTitle:@"400-002-1799" forState:UIControlStateNormal];
//            [btnTel setTitleColor:K_MainColor forState:UIControlStateNormal];
//            btnTel.titleLabel.font = [UIFont systemFontOfSize:12 * WIDTHRADIU];
//            [btnTel addTarget:self action:@selector(btnTelClick:) forControlEvents:UIControlEventTouchUpInside];
//            [bottomView addSubview:btnTel];
//
//            [btnTel mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(lb_qrContent3.mas_right);
//                make.width.offset(95 * WIDTHRADIU);
//                make.height.offset(40 * WIDTHRADIU);
//                make.centerY.equalTo(lb_qrContent3);
//            }];
//
//
//            UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//
//            [saveBtn setTitle:@"保存二维码" forState:UIControlStateNormal];
//            [saveBtn setTitleColor:[UIColor colorWithHex:0x1986d4] forState:UIControlStateNormal];
//            saveBtn.titleLabel.font = [UIFont systemFontOfSize:17];
//            saveBtn.layer.borderWidth = 0.5;
//            saveBtn.layer.borderColor = [UIColor colorWithHex:0x1986d4].CGColor;
//            saveBtn.layer.cornerRadius = 5;
//            [saveBtn addTarget:self action:@selector(saveQrBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//
//            [bottomView addSubview:saveBtn];
//
//
//            UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//
//            [shareBtn setTitle:@"分享到微信" forState:UIControlStateNormal];
//            [shareBtn setTitleColor:[UIColor colorWithHex:0x1986d4] forState:UIControlStateNormal];
//            shareBtn.titleLabel.font = [UIFont systemFontOfSize:17];
//            shareBtn.layer.borderWidth = 0.5;
//            shareBtn.layer.borderColor = [UIColor colorWithHex:0x1986d4].CGColor;
//            shareBtn.layer.cornerRadius = 5;
//            [shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//
//            [bottomView addSubview:shareBtn];
//
//
//            [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(qrImg);
//                make.height.offset(45 * WIDTHRADIU);
//                make.top.equalTo(qrImg.mas_bottom).offset(10 * WIDTHRADIU);
//            }];
//
//            [shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(saveBtn.mas_right).offset(10 * WIDTHRADIU);
//                make.top.width.height.equalTo(saveBtn);
//                make.right.offset(- 20 * WIDTHRADIU);
//
//            }];
//
//
//
//        }else{
//            UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//             // 设置item的行间距和列间距
//            layout.minimumInteritemSpacing = 0;
//            layout.minimumLineSpacing = 0;
//            layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//
////            CGFloat width =  (ScreenWidth - 45 * WIDTHRADIU)  /2 ;
//
//
//
//            UICollectionView*collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 25 * WIDTHRADIU, 355 * WIDTHRADIU , 80 * WIDTHRADIU) collectionViewLayout:layout];
//            collectionView.backgroundColor = [UIColor clearColor];
//            collectionView.showsVerticalScrollIndicator = NO;   //是否显示滚动条
//            collectionView.scrollEnabled = YES;  //滚动使能
//            collectionView.delegate = self;
//            collectionView.dataSource = self;
//            [collectionView registerNib:[UINib nibWithNibName:@"SuccessItem2Cell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
//            [bottomView addSubview:collectionView];
//            self.collectionView = collectionView;
//
//
//            //电话
//            YYLabel* lb_phone = [YYLabel new];
//            [bottomView addSubview:lb_phone];
//            [lb_phone mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.centerX.equalTo(bottomView);
//                make.bottom.offset(-5);
//            }];
//
//
//            NSMutableAttributedString *text  = [[NSMutableAttributedString alloc] initWithString: @"如有疑问可联系客服：400-002-1799"];
//            text.yy_lineSpacing = 5;
//            text.yy_font = [UIFont systemFontOfSize:13 * WIDTHRADIU];
//            text.yy_color = [UIColor colorWithHex:0x808080];
//            [text yy_setTextHighlightRange:NSMakeRange(10, 12) color:[UIColor colorWithHex:0x1986d4] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
//               NSLog(@"xxx协议被点击了");
//                NSString *callPhone = @"telprompt:400-002-1799";
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
//            }];
//
//
//            lb_phone.attributedText = text;  //设置富文本
            
//        }

        /*
        //顶部背景色
        UIView* topView = [[UIView alloc]init];
        topView.backgroundColor = K_MainColor;
        [_scrollView addSubview:topView];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.offset(0);
            make.width.offset(ScreenWidth);
            make.height.offset(cl_kNavigationBarHeight > 64 ? 145 * WIDTHRADIU + cl_kNavigationBarHeight  :   115 * WIDTHRADIU + cl_kNavigationBarHeight);
        }];
        
        //对号
        UIImageView* successIcon = [[UIImageView alloc]init];
        successIcon.image = [UIImage imageNamed:@"authSuccessicon"];
        [topView addSubview:successIcon];
        [successIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(cl_kNavigationBarHeight > 64 ? cl_kStatusBarHeight + 30 * WIDTHRADIU : cl_kStatusBarHeight + 20 * WIDTHRADIU);
            make.left.offset((ScreenWidth - 200 * WIDTHRADIU)/2);
            make.width.height.offset(50 * WIDTHRADIU);
        }];
        
        //认证成功
        UILabel* lb_success = [UILabel new];
        lb_success.text = @"认证成功";
        lb_success.textColor = [UIColor whiteColor];
        lb_success.font = [UIFont boldSystemFontOfSize:22 * WIDTHRADIU];
        //lb_success.backgroundColor = [UIColor redColor];
        [topView addSubview:lb_success];
        [lb_success mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(successIcon);
            make.left.equalTo(successIcon.mas_right).offset(10 * WIDTHRADIU);
            make.width.offset(100 * WIDTHRADIU);
            make.height.offset(30 * WIDTHRADIU);
        }];
        
        //认证成功
        UILabel* lb_address = [UILabel new];
        lb_address.text = @"河北省邯郸市肥乡区";
        lb_address.textColor = [UIColor whiteColor];
        lb_address.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        //lb_address.backgroundColor = [UIColor redColor];
        [topView addSubview:lb_address];
        [lb_address mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lb_success.mas_bottom).offset(2 * WIDTHRADIU);
            make.left.equalTo(lb_success);
            make.width.offset(140 * WIDTHRADIU);
            make.height.offset(18 * WIDTHRADIU);
        }];
        self.provinceTitle = lb_address;
        
        
        UIView* photoView = [[UIView alloc]init];
        photoView.backgroundColor = [UIColor clearColor];
        [_scrollView addSubview:photoView];
        [photoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(cl_kNavigationBarHeight > 64 ? 120 * WIDTHRADIU + cl_kStatusBarHeight : 90 * WIDTHRADIU + cl_kStatusBarHeight);
            make.centerX.equalTo(self->_scrollView);
            make.width.offset(350 * WIDTHRADIU);
            make.height.offset(284 * WIDTHRADIU);
        }];
        
        //相册
        UIImageView* photoBg = [[UIImageView alloc]init];
        photoBg.image = [UIImage imageNamed:@"sbAuthbg"];
        [photoView addSubview:photoBg];
        [photoBg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        }];
        
        //相册
        UIImageView* leftImg = [[UIImageView alloc]init];
        leftImg.backgroundColor = [UIColor redColor];
        [photoView addSubview:leftImg];
        [leftImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(25 * WIDTHRADIU);
            make.left.offset(25 * WIDTHRADIU);
            make.width.offset(145 * WIDTHRADIU);
            make.height.offset(195 * WIDTHRADIU);
        }];
        
        self.imageView_1 = leftImg;
        
        UIImageView* rightImg = [[UIImageView alloc]init];
        rightImg.backgroundColor = [UIColor redColor];
        [photoView addSubview:rightImg];
        [rightImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(25 * WIDTHRADIU);
            make.left.equalTo(leftImg.mas_right).offset(10 * WIDTHRADIU);
            make.width.offset(145 * WIDTHRADIU);
            make.height.offset(195 * WIDTHRADIU);
        }];
        
        self.imageView_2 = rightImg;
        
        //认证时间
        UIImageView* timeImg = [[UIImageView alloc]init];
        timeImg.image = [UIImage imageNamed:@"sbAuthTime"];
        [photoView addSubview:timeImg];
        [timeImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(leftImg.mas_bottom).offset(12 * WIDTHRADIU);
            make.left.offset(25 * WIDTHRADIU);
        }];
        
        
        UILabel* lb_time = [UILabel new];
        lb_time.text = @"2020-10-18  17:32:11";
        lb_time.textColor = [UIColor colorWithHex:0x999999];
        lb_time.font = [UIFont systemFontOfSize:13 * WIDTHRADIU];
        //lb_address.backgroundColor = [UIColor redColor];
        [photoView addSubview:lb_time];
        [lb_time mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(timeImg);
            make.left.equalTo(timeImg.mas_right).offset(8 * WIDTHRADIU);
        }];
        
        self.lb_time = lb_time;
        
        
        //认证地址
        UIImageView* addressImg = [[UIImageView alloc]init];
        addressImg.image = [UIImage imageNamed:@"sbAuthLocation"];
        [photoView addSubview:addressImg];
        [addressImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lb_time.mas_bottom).offset(8 * WIDTHRADIU);
            make.left.offset(25 * WIDTHRADIU);
        }];
        
        
        UILabel* lb_address2 = [UILabel new];
        lb_address2.text = @"上海市浦东新区传奇广场";
        lb_address2.textColor = [UIColor colorWithHex:0x999999];
        lb_address2.font = [UIFont systemFontOfSize:13 * WIDTHRADIU];
        //lb_address.backgroundColor = [UIColor redColor];
        [photoView addSubview:lb_address2];
        [lb_address2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(addressImg);
            make.left.equalTo(addressImg.mas_right).offset(8 * WIDTHRADIU);
        }];
        self.lb_address = lb_address2;
        
        
        UIButton* authBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        authBtn.backgroundColor = [UIColor colorWithHex:0x19956D];
        authBtn.layer.cornerRadius = 5 * WIDTHRADIU;
        [authBtn setTitle:@"继续认证" forState:UIControlStateNormal];
        [authBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        authBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [authBtn addTarget:self action:@selector(authBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:authBtn];
        
        [authBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12.5 * WIDTHRADIU);
            make.top.equalTo(photoView.mas_bottom).offset(cl_kNavigationBarHeight > 64 ? 30 * WIDTHRADIU : 25 * WIDTHRADIU);
            make.width.offset((ScreenWidth - 45 * WIDTHRADIU)/2);
            make.height.offset(45 * WIDTHRADIU);
        }];
        
        UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.backgroundColor = [UIColor colorWithHex:0x19956D];
        backBtn.layer.cornerRadius = 5 * WIDTHRADIU;
        [backBtn setTitle:@"返回首页" forState:UIControlStateNormal];
        [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        backBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:backBtn];
        
        [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(authBtn.mas_right).offset(20 * WIDTHRADIU);
            make.top.equalTo(authBtn);
            make.width.offset((ScreenWidth - 45 * WIDTHRADIU)/2);
            make.height.offset(45 * WIDTHRADIU);
            make.bottom.mas_greaterThanOrEqualTo(10 * WIDTHRADIU);
        }];
        
        UIView* lineView = [[UIView alloc]initWithFrame:CGRectMake(12.5 * WIDTHRADIU, 0, ScreenWidth - 25* WIDTHRADIU, 1)];
        
        [_scrollView addSubview:lineView];
        
        [self drawDashLine:lineView lineLength:2 lineSpacing:1 lineColor:[UIColor colorWithHex:0xd9d9d9]];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12.5 * WIDTHRADIU);
            make.top.equalTo(backBtn.mas_bottom).offset(cl_kNavigationBarHeight > 64 ? 35 * WIDTHRADIU : 30 * WIDTHRADIU);
            make.width.offset(ScreenWidth - 25 * WIDTHRADIU);
            make.height.offset(1);
        }];
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
         // 设置item的行间距和列间距
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        CGFloat width =  (ScreenWidth - 45 * WIDTHRADIU)  /2 ;
         

        
        UICollectionView*collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 5, ScreenWidth, width * 63.0/165 + 15 * WIDTHRADIU) collectionViewLayout:layout];
        collectionView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        collectionView.showsVerticalScrollIndicator = NO;   //是否显示滚动条
        collectionView.scrollEnabled = YES;  //滚动使能
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerNib:[UINib nibWithNibName:@"SuccessItemCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        [_scrollView addSubview:collectionView];
        self.collectionView = collectionView;
        
        [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(0);
            make.top.equalTo(lineView.mas_bottom).offset(cl_kNavigationBarHeight > 64 ? 25 * WIDTHRADIU : 20 * WIDTHRADIU);
            make.width.offset(ScreenWidth);
            make.height.offset(width * 63.0/165 * 2 + 15 * WIDTHRADIU);
        }];
        
        */
        
        
        
    }
    return _scrollView;
}
- (NSArray *)defaultArr{
    if (_defaultArr == nil) {
        _defaultArr = @[@{@"icon":@"PiggyBankItem",@"title":@"老用户专享福利",@"des":@"短期理财优化3.85%年化率",@"perform":@"立即体验"},@{@"icon":@"certificationItem",@"title":@"关注“看看认证”公众号",@"des":@"实时接收认证通知",@"perform":@"立即关注"},@{@"icon":@"paidToAnswerItem",@"title":@"加入领钱群，获取优惠福利",@"des":@"",@"perform":@"去看看"},@{@"icon":@"MedicalItem",@"title":@"医保电子凭证",@"des":@"国家医疗保障局监制",@"perform":@"立即查看"}];
    }
    return _defaultArr;
}
- (NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

//- (NSArray *)titleArray
//{
//    if (!_titleArray) {
//        _titleArray = @[@"免费看病",@"赚红包",@"领钱答疑群"];
//    }
//    return _titleArray;
//}


#pragma mark - public methods

/**
 ** lineView:      需要绘制成虚线的view
 ** lineLength:    虚线的宽度 //2
 ** lineSpacing:        虚线的间距//1
 ** lineColor:    虚线的颜色
 **/
- (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor{
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
    
}

// 生成圆角图片
- (UIImage *)js_imageWithOriginalImage:(UIImage *)originalImage{
    CGRect rect = CGRectMake(0, 0, originalImage.size.width, originalImage.size.height);
    UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, 0.0);
//    UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
//    format.opaque = NO;
//    format.scale = 0.0;
//    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:originalImage.size format:format];
    CGFloat cornerRadius = MIN(originalImage.size.width, originalImage.size.height) * 0.5;
    [[UIBezierPath bezierPathWithRoundedRect:rect
                                cornerRadius:cornerRadius] addClip];
    [originalImage drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize and:(UIImage*)imageKs
{
    UIImage *sourceImage = imageKs;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    //UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:targetSize];
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

-(NSString*)KANKANTime{
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd  HH:mm:ss"];
    NSString *DateTime = [formatter stringFromDate:date];
    
    return DateTime;
}

#pragma mark - 获取底部功能按钮
- (void)getAllItemsRequest {
//    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipSuccessConfig],GETSuccessFunctionItemsRequest];
//
//    NSLog(@"获取成功页面button的url:%@",url);
//    NSLog(@"params:%@",[self getAllItemsRequestPara]);
//
//    [NetworkRequest Get:url Params:[self getAllItemsRequestPara] Success:^(id _Nonnull objc) {
//
//        NSLog(@"objc:%@",objc);
//        NSString* code = [NSString stringWithFormat:@"%@",objc[@"code"]];
//        if ([code isEqualToString:@"200"]) {
//            NSArray* array  = [SuccessItem mj_objectArrayWithKeyValuesArray:objc[@"result"]];
//            if (array.count > 0) {
//                self->isChange = YES;
//                self.dataArray = array;
//                [self.collectionView reloadData];
//            }
//        }
//    } Failure:^(NSError* error) {
//        NSLog(@"error:%@",error);
//    }];

    NSString*version = nil;
    NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSArray*vArr = [v componentsSeparatedByString:@"."];
    for (int i = 0; i < vArr.count; i++) {
        if (version == nil) {
            version = [NSString stringWithFormat:@"%@",vArr[i]];
        }else{
            version = [version stringByAppendingFormat:@"%@",vArr[i]];
        }
    }
    NSString *url1 = [NSString stringWithFormat:@"%@dynamic/menu/get",[NetworkConfig ipYinShuConfig]];
//    NSString *url1 = [NSString stringWithFormat:@"http://172.16.10.18:8017/dynamic/menu/get"];

    NSDictionary *params1 = @{
        @"configName":@"AuthSuccessBottom",
        @"appName":@"kksh",
        @"version":version,
        @"systemType":@"iOS"
    };
    typeof(self) wSelf = self;
    [NetworkRequest Post15:url1 Params:params1 Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];

            if ([state isEqualToString:@"200"]) {
                if ([objc[@"result"] isKindOfClass:[NSArray class]]) {
                    wSelf.dataArray = [NSMutableArray array];
                    for (NSDictionary *dic in objc[@"result"]) {
                        KKRedPackageClickEventModel *model = [KKRedPackageClickEventModel mj_objectWithKeyValues:dic];
                        [wSelf.dataArray addObject:model];
                        if ([model.menuName containsString:@"公众号"] && wSelf.Ispush) {
                            [wSelf.dataArray removeObject:model];
                        }
                    }
                }
                [wSelf refreshData];
               }
            }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
#pragma mark - 刷新数据
- (void)refreshData{
    CGFloat bottomY = self.topView.maxY + 15 * WIDTHRADIU;
    self.bottomView.frame = CGRectMake(10 * WIDTHRADIU, bottomY,  355 * WIDTHRADIU, 60 * self.dataArray.count + 30);
    self.tableView.frame = CGRectMake(0, 20, 355 * WIDTHRADIU, 60 * self.dataArray.count);
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, CGRectGetMaxY(self.bottomView.frame) + 20);
    [self.tableView reloadData];
}

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