//
//  AuthenticationButieFinishVC.m
//  Open
//
//  Created by qinxuyang on 2022/2/11.
//  Copyright © 2022 QXY. All rights reserved.
//

#import "AuthenticationButieFinishVC.h"
#import "SuccessItem3Cell.h"
#import "CLAmplifyView.h"
#import "WXApiManager.h"
#import "CTAPIBaseManager.h"
#import <WXApi.h>
#import "PayAttentionToWXAlertView.h"
@interface AuthenticationButieFinishVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, assign) BOOL Ispush;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) NSArray *defaultArr;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *footerView;
@end

@implementation AuthenticationButieFinishVC
- (NSArray *)defaultArr{
    if (_defaultArr == nil) {
        _defaultArr = @[@{@"icon":@"PiggyBankItem",@"title":@"老用户专享福利",@"des":@"短期理财优化3.85%年化率",@"perform":@"立即体验"},@{@"icon":@"certificationItem",@"title":@"关注“看看认证”公众号",@"des":@"实时接收认证通知",@"perform":@"立即关注"}];
    }
    return _defaultArr;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //禁止手势返回
       id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
       UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
       [self.view addGestureRecognizer:pan];
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
    //隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [GTCountSDK trackCountEvent:@"home_BTAuth_successPage" withArgs:@{}];
    
}

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

    // 开启返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAuthenticationAssistant" object:nil userInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    };
    
    self.Ispush = NO;
    
    [WXApiManager sharedManager].delegate = self;
    if (self.model.personName && ![Tools isBlankString:self.recordId]) {
        //查询微信绑定
        [self queryAttentionIsOrNot];
    }else{
        //获取地步按钮
    }
    [self insertUserInfo2];
    [self getAllItemsRequest];
}
- (void)insertUserInfo2
{
    
    if (![self queryDataExist2]) {
        FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
         //加密
            NSString *NameEnerypt =  [self.model.personName stringByReplacingOccurrencesOfString:@" " withString:@""];
            //身份证号AES加密
            NSString *IdentiftyEnerypt =  [self.model.identityNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        if ([db open]) {
            NSInteger userId = [UserDefault integerForKey:@"userId"];
            NSString *sql = [NSString stringWithFormat:@"SELECT Count(1) FROM t_rzUser3 WHERE userid='%ld' ",userId];
            NSUInteger count  = [db intForQuery:sql];
            NSLog(@"已添加数据:%ld",count);
            if (count >= 5) {
                
            NSString *sql2 = [NSString stringWithFormat:@"SELECT  id FROM t_rzUser3 WHERE userid='%ld' LIMIT 1  ;",userId];
             NSInteger Id = [db intForQuery:sql2];
                
              NSString *sql3 = [NSString stringWithFormat:@"delete from t_rzUser3 where id = '%ld'",Id];
              BOOL reslut =   [db executeUpdate:sql3];
                if (reslut) {
                    NSString * sql4 = [NSString stringWithFormat:@"INSERT INTO t_rzUser3 (name,idNumber,userid,timeSp) VALUES (?, ?,?,?);"];
                    NSString *userid = [NSString stringWithFormat:@"%ld",userId];
                    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_rzUser3 (name,idNumber,userid,timeSp) VALUES (?, ?,?,?);"];
                NSString *userid = [NSString stringWithFormat:@"%ld",userId];
                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]];
        //加密
//        NSString *NameEnerypt =  [self.model.personName stringByReplacingOccurrencesOfString:@" " withString:@""];
        //身份证号AES加密
        NSString *IdentiftyEnerypt =  [self.model.identityNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
         NSString *timeSp = [NSString stringWithFormat:@"%ld",[self getNowTimeTimestamp3]];
        if ([db open]) {
            NSString *sql = @"UPDATE t_rzUser3 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];
        }
    }
    
}

//补贴认证
- (BOOL)queryDataExist2
{
//    self.name = @"徐振东";
//    self.idNumber = @"110101199003075576";
//        self.name = @"小慧";
//        self.idNumber = @"110101199003077192";

   //加密
//    NSString *NameEnerypt =  [self.model.personName stringByReplacingOccurrencesOfString:@" " withString:@""];
    //身份证号AES加密
    NSString *IdentiftyEnerypt =  [self.model.identityNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]){
       
        NSInteger userId = [UserDefault integerForKey:@"userId"];
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_rzUser3 WHERE userid='%@'  and idNumber='%@';",[NSString stringWithFormat:@"%ld",userId],IdentiftyEnerypt];
        FMResultSet *resultSet = [db executeQuery:sql];
        
        if (resultSet.next) {
            [db close];
            return YES;
        }else{
            [db close];
            return NO;
        }
    }
    
    [db close];
    
    return YES;
    
}
- (NSString *)getDBPath
{
     NSString *doc= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        return [doc stringByAppendingPathComponent:@"rzUserlist.sqlite"];

}
#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;
}
- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"SuccessItem3Cell" bundle:nil] forCellReuseIdentifier:@"SuccessItem3Cell"];
    }
    return _tableView;
}
- (UIView *)headerView{
    if (_headerView == nil) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 520 * WIDTHRADIU)];
        _headerView.backgroundColor = [UIColor whiteColor];
        
        //导航栏view
        UIView* navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
        navView.backgroundColor = [UIColor colorWithHex:0x1986d4];
        [_headerView addSubview:navView];
        
        //title
        UILabel* lb_title = [[UILabel alloc]init];
        lb_title.textColor = [UIColor whiteColor];
        lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
        lb_title.textAlignment = NSTextAlignmentCenter;
        [navView addSubview:lb_title];
        lb_title.text = @"认证完成";
        [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(navView);
            make.height.offset(25);
            make.top.offset(cl_kStatusBarHeight + 9.5);
        }];
        
        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(navView.frame), ScreenWidth, 272 * WIDTHRADIU)];
        backView.backgroundColor = [UIColor colorWithHex:0x1986d4];;
        [_headerView addSubview:backView];
        
        
        UIView *cardView = [[UIView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(navView.frame) + 15, ScreenWidth - 30, 323 * WIDTHRADIU)];
        cardView.backgroundColor = [UIColor whiteColor];
        cardView.layer.cornerRadius = 15 * WIDTHRADIU;
//        cardView.layer.masksToBounds = YES;
        cardView.layer.shadowColor = [UIColor colorWithHex:0x333333].CGColor;
        cardView.layer.shadowOffset = CGSizeMake(0, 0);
        cardView.layer.shadowOpacity = 0.5;
        cardView.layer.shadowRadius = 5;
        [_headerView addSubview:cardView];
        CGFloat width=(ScreenWidth-30-45)/2;
        UIImageView *leftImg = [[UIImageView alloc]initWithFrame:CGRectMake(15, 15, width, 226 * WIDTHRADIU)];
        leftImg.contentMode = UIViewContentModeScaleAspectFill;
        leftImg.clipsToBounds=YES;
        //leftImg.backgroundColor=[UIColor colorWithHex:0x1986d4];
        if (![Tools isBlankString:self.defaultPhoto]) {
            [leftImg sd_setImageWithURL:[NSURL URLWithString:self.defaultPhoto]];
        }else{
            if (self.imagesArray.count > 0) {
                NSString *imageStr = self.imagesArray[0];
                NSData *data = [imageStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
                NSData *imageData = [GTMBase64 decodeData:data];
                UIImage *image = [UIImage imageWithData:imageData];
                
                leftImg.image = image;
                
            }
        }
        leftImg.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImageView:)];
        [leftImg addGestureRecognizer:tap1];
        [cardView addSubview:leftImg];
        
        
        UIImageView *rightImg = [[UIImageView alloc]initWithFrame:CGRectMake(width + 30, 15, width, 226 * WIDTHRADIU)];
        rightImg.contentMode = UIViewContentModeScaleAspectFill;
        leftImg.clipsToBounds=YES;
        //rightImg.backgroundColor=[UIColor colorWithHex:0x1986d4];
        if (self.imagesArray.count > 0) {
            NSString *imageStr = self.imagesArray[0];
            NSData *data = [imageStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSData *imageData = [GTMBase64 decodeData:data];
            UIImage *image = [UIImage imageWithData:imageData];
            
            rightImg.image = image;
            
        }
        rightImg.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImageView:)];
        [rightImg addGestureRecognizer:tap2];
        [cardView addSubview:rightImg];
        
        UIImageView *imgTime = [[UIImageView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(leftImg.frame) + 15, 10, 10)];
        imgTime.image = [UIImage imageNamed:@"sbAuthTime"];
        [cardView addSubview:imgTime];
        
        UILabel *labeTime = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, cardView.width - 45, 30)];
        labeTime.centerY = imgTime.centerY;
        labeTime.textColor = [UIColor colorWithHex:0x999999];
        labeTime.font = [UIFont systemFontOfSize:13 * WIDTHRADIU];
        labeTime.text = [Tools getCurrentTimes];
        [cardView addSubview:labeTime];
        
        UIImageView *imgAddress = [[UIImageView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(labeTime.frame), 10, 11.5)];
        imgAddress.image = [UIImage imageNamed:@"sbAuthLocation"];
        [cardView addSubview:imgAddress];
        
        UILabel *labeAddress = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, cardView.width - 45, 30)];
        labeAddress.centerY = imgAddress.centerY;
        labeAddress.textColor = [UIColor colorWithHex:0x999999];
        labeAddress.font = [UIFont systemFontOfSize:13 * WIDTHRADIU];
        labeAddress.text = self.location;
        [cardView addSubview:labeAddress];
        
        UIImageView *districtauth_yes = [[UIImageView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(cardView.frame) - 32, 64, 64)];
        districtauth_yes.image = [UIImage imageNamed:@"认证成功-对勾-"];
        districtauth_yes.centerX = _headerView.centerX;
        [_headerView addSubview:districtauth_yes];

        
        UILabel *TishiLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(districtauth_yes.frame), ScreenWidth, 40)];
        TishiLabel.textAlignment = NSTextAlignmentCenter;
        TishiLabel.text = @"恭喜您已经完成认证";
        TishiLabel.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
        TishiLabel.textColor = [UIColor colorWithHex:0x1986d4];
        [_headerView addSubview:TishiLabel];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_headerView.frame) - 10, ScreenWidth, 10)];
        line.backgroundColor = [UIColor colorWithHex:0xf5f5f5];
        [_headerView addSubview:line];
    }
    return _headerView;
}
- (UIView *)footerView{
    if (_footerView == nil) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
        
        UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, ScreenWidth - 20, 45)];
        [backBtn setTitle:@"返回首页" forState:UIControlStateNormal];
        backBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.0];
        [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        backBtn.backgroundColor = [UIColor colorWithHex:0x1986d4];
        backBtn.layer.cornerRadius = 5.0;
        backBtn.layer.masksToBounds = YES;
        [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_footerView addSubview:backBtn];
    }
    return _footerView;
}
- (void)clickImageView:(UITapGestureRecognizer *)tap
{
    CLAmplifyView *amplifyView = [[CLAmplifyView alloc]initWithFrame:self.view.bounds andGesture:tap andSuperView:self.view];
    [[UIApplication sharedApplication].keyWindow addSubview:amplifyView];
}
#pragma mark - 返回首页
- (void)backBtnClick{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#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{
    SuccessItem3Cell *cell = [tableView cellForRowAtIndexPath:indexPath];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
//查询是否用户是否绑定微信
- (NSDictionary *)requestPara
{
//    NSString *name =  [self.model.personName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

//    NSString *time = [formatter stringFromDate:[NSDate date]];

  
    
    NSString *url = [NSString stringWithFormat:@"http://nginx.weface.com.cn/authRecord/kkmz.html?vid=%@&appName=%@",self.recordId,@"看看生活"];
//    NSString *url = [NSString stringWithFormat:@"http://172.16.10.133/projects/html-nginx/html-nginx/authRecord/kkmz.html?vid=%@&appName=%@",self.recordId,@"看看生活"];
    
    //url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString* pre = @"优抚认证结果";
    if ([self.type isEqualToString:@"butie"]) {
        pre = @"补贴认证结果";
    }
    NSDictionary *params = @{
        @"name": [EnercryTool AES256Decrypt:self.model.personName key:MZAESKEY] ? [EnercryTool AES256Decrypt:self.model.personName key:MZAESKEY] : @"",
        @"pre":pre,
        @"result":@"认证成功",
        @"telephone":self.phone,
        @"url":url
    };
    
    return params;
}
#pragma mark - 查询绑定微信
- (void)queryAttentionIsOrNot
{
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipPushConfig],QueryAttentionOrNotWXRequest];
    
    NSLog(@"查询绑定微信url:%@",urlString);
    NSLog(@"params:%@",[self requestPara]);
    typeof(self) wSelf = self;
    [CTAPIBaseManager GET:urlString params:[self requestPara] completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
    
        if (responseObject) {
            if ([responseObject isKindOfClass:[NSData class]]) {
                
                
                NSDictionary* reponse = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"responseObject:%@",reponse);
                
                NSString *state = [NSString stringWithFormat:@"%@",reponse[@"state"]];
                
                if ([state isEqualToString:@"200"]) {
                   
                    wSelf.Ispush = YES;
                }else{
                    wSelf.Ispush = NO;
//                    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"attentionWXLastTime"];
//
//                    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
//                        return;
//                    }
//
//                    NSDate *oldDate = [NSDate date];
//                    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"attentionWXLastTime"];
//                    [[NSUserDefaults standardUserDefaults]synchronize];
//
//
//                    [PayAttentionToWXAlertView showAlertView:^(BOOL success) {
//                        if (success) {
//                            WXSubscribeMsgReq *req = [[WXSubscribeMsgReq alloc] init];
//                            req.scene = 1000;
//                            req.templateId = @"8sUnXOU18na6qaXvsiDCuvEgBFjZJ9QZJHi1OHHvmPk";
//                            req.reserved = @"kankan";
//                            [WXApi sendReq:req completion:^(BOOL success) {
//                                if (success) {
//                                    NSLog(@"订阅消息发送成功");
//                                }else{
//                                    NSLog(@"订阅消息发送失败");
//                                }
//                            }];
//
//                        }
//                    }];
//                    return;
                }
            }else{
                 NSLog(@"responseObject:%@",responseObject);
            }
           
        }
        
        if (error) {
            NSLog(@"error:%@",error);
        }
    }];
}
#pragma mark - getters and setters
// 判断是否是同一天
- (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)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;
            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];
    }
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }

    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)getAllItemsRequest {
    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":@"AuthSuccessBottomBT",
        @"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.tableView reloadData];
            }
        }

    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
/*
#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
