//
//  AuthenticationFinishController.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2019/11/28.
//  Copyright © 2019 雷俊博. All rights reserved.
//

#import "AuthenticationFinishController.h"
#import "CLAmplifyView.h"
#import "UIImageView+WebCache.h"

#import "DistrictAuthenticationPersonalInfoController.h"

#import "WXApiManager.h"

#import "PayAttentionToWXAlertView.h"
#import "CTAPIBaseManager.h"
#import <WXApi.h>

@interface AuthenticationFinishController ()<WXApiDelegate,WXApiManagerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *cardView;
@property (weak, nonatomic) IBOutlet UIImageView *lefImg;
@property (weak, nonatomic) IBOutlet UIImageView *rightImg;
@property (weak, nonatomic) IBOutlet UILabel *lb_time;
@property (weak, nonatomic) IBOutlet UILabel *lb_address;
@property (weak, nonatomic) IBOutlet UIView *backView;

@end

@implementation AuthenticationFinishController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // self.edgesForExtendedLayout = 0;
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    self.navigationController.navigationBar.shadowImage = [UIImage new];
    
    

    self.cardView.layer.cornerRadius = 8;

    [self addShadowToView:_cardView withColor:K_MainColor];
    
    self.backView.backgroundColor = K_MainColor;
    self.navigationItem.hidesBackButton = YES;
    

    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];
        
        self.rightImg.image = image;
        
    }
    
    if (![Tools isBlankString:self.defaultPhoto]) {
        [self.lefImg 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];
            
            self.lefImg.image = image;
            
        }
    }
    
    self.lb_time.text = [Tools getCurrentTimes];
    self.lb_address.text = self.location;
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImageView:)];
       
       [self.lefImg addGestureRecognizer:tap1];
       UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImageView:)];
          
          [self.rightImg addGestureRecognizer:tap2];
    [WXApiManager sharedManager].delegate = self;
    if (self.model.personName && ![Tools isBlankString:self.recordId]) {
        [self queryAttentionIsOrNot];
    }
    
    //如果认证成功,就把信息存储到本地
    if ([self.type isEqualToString:@"butie"]) {
        [self insertUserInfo2];
    }else{
        [self insertUserInfo];
    }
    
    
}

- (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    // 阴影颜色
    theView.layer.shadowColor = theColor.CGColor;
    // 阴影偏移，默认(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度，默认0
    theView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    theView.layer.shadowRadius = 5;
    
}


- (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;
    }
    
    [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];
}

//查询是否用户是否绑定微信
- (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;
}

- (void)queryAttentionIsOrNot
{
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipPushConfig],QueryAttentionOrNotWXRequest];
    
    NSLog(@"查询绑定微信url:%@",urlString);
    NSLog(@"params:%@",[self requestPara]);
    
    [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"]) {
                   
                    
                }else{
                    
                    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);
        }
    }];
}

//获取微信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 (![Tools isBlankString: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 - WXApiManagerDelegate
- (void)managerDidRecvSubscribeMsgResponse:(WXSubscribeMsgResp *)response
{
    if ([response.action isEqualToString:@"confirm"]) {
        [self getWXAccessToken:response];
    }
    
    
}


#pragma mark - 创建本地数据库
- (BOOL)queryDataExist
{
    
//    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_rzUser2 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;
    
}



- (void)insertUserInfo
{
    
    if (![self queryDataExist]) {
        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_rzUser2 WHERE userid='%ld' ",userId];
            NSUInteger count  = [db intForQuery:sql];
            NSLog(@"已添加数据:%ld",count);
            if (count >= 5) {
                
            NSString *sql2 = [NSString stringWithFormat:@"SELECT  id FROM t_rzUser2 WHERE userid='%ld' LIMIT 1  ;",userId];
             NSInteger Id = [db intForQuery:sql2];
                
              NSString *sql3 = [NSString stringWithFormat:@"delete from t_rzUser2 where id = '%ld'",Id];
              BOOL reslut =   [db executeUpdate:sql3];
                if (reslut) {
                    NSString * sql4 = [NSString stringWithFormat:@"INSERT INTO t_rzUser2 (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_rzUser2 (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_rzUser2 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;
    
}



- (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];
        }
    }
    
}


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

}



#pragma mark - event reponse

- (IBAction)competeBtn:(UIButton *)sender {
//    self.navigationController.navigationBar.translucent = NO;
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
//    self.navigationController.navigationBar.shadowImage = nil;
    
    for (UIViewController*vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[DistrictAuthenticationPersonalInfoController class]]) {
            DistrictAuthenticationPersonalInfoController*dVC = (DistrictAuthenticationPersonalInfoController *)vc;
            [dVC cleartText];
            break;
        }
    }
    
    [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
}
- (void)clickImageView:(UITapGestureRecognizer *)tap
{
    CLAmplifyView *amplifyView = [[CLAmplifyView alloc]initWithFrame:self.view.bounds andGesture:tap andSuperView:self.view];
    [[UIApplication sharedApplication].keyWindow addSubview:amplifyView];
}

#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 - 获取当前时间戳

-(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;
}



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