//
//  successViewController.m
//  Open
//
//  Created by gao on 2016/12/2.
//  Copyright © 2016年 黄江涛 . All rights reserved.
//

#import "successViewController.h"
#import "AppDelegate.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <AddressBookUI/AddressBookUI.h>
#import "XWLocationManager.h"
#import "NSDate+Helper.h"
#import "ZYSuspensionView.h"
#import "NSObject+ZYSuspensionView.h"
#import <CommonCrypto/CommonDigest.h>
#import <objc/runtime.h>

#import "CTAPIBaseManager.h"
#import "PackageCoinsView.h"
#import "Package2CoinsView.h"
#import <ZJAnimationPopView.h>
#import "uitableViewController.h"
#import "tabViewController.h"
#import "CoinsCenterViewController.h"
#import "Log2ViewController.h"



//广告
#import "WXApi.h"
#import "WXApiManager.h"
#import "PayAttentionToWXAlertView.h"

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


//banner广告
#import <GDTUnifiedBannerView.h>

#import "KKUserIdentifyViewController.h"


//static NSString* const UMS_Title = @"欢迎使用【看看智能社保】";
//static NSString* const UMS_Text = @"看看智能科技 是一家专注移动互联网的人工智能技术公司，多年从事人脸识别、虹膜识别以及数据安全的研究与应用，具备行业出色人脸识别、虹膜识别、高速活体检测、三维人脸识别算法和快速海量检索能力，拥有成熟、稳定的智慧城市、智慧村镇、智慧社保等综合解决方案。";
//
//static NSString* const UMS_THUMB_IMAGE = @"http://img.jdzj.com/UserDocument/2015c/kkrlsb/Picture/201612813446.jpg";
//static NSString* const UMS_IMAGE = @"http://img.jdzj.com/UserDocument/2015c/kkrlsb/Picture/201612813446.jpg";
//
//static NSString* const UMS_WebLink = @"http://www.weface.com.cn/about/about.html";
//
//static NSString *UMS_SHARE_TBL_CELL = @"UMS_SHARE_TBL_CELL";

@interface successViewController ()<UIApplicationDelegate,UIAlertViewDelegate,WXApiDelegate,WXApiManagerDelegate,GDTUnifiedBannerViewDelegate>


@property (weak, nonatomic) IBOutlet UIImageView *imageView_1;
@property (weak, nonatomic) IBOutlet UIImageView *imageView_2;
//titile - 社保认证地址省 市
@property (weak, nonatomic) IBOutlet UILabel *provinceTitle;
//title - 社保认证地址 区 社保局
@property (weak, nonatomic) IBOutlet UILabel *socialSecurityAdminstration;
//社保的认证时间
@property (weak, nonatomic) IBOutlet UILabel *socialTime;
//社保的认证地址
@property (weak, nonatomic) IBOutlet UILabel *soicialAddress;
//专门为4s的布局改变社保局背后的标题高低
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *socialSecurityTopHeight;
//专门为4s的布局改变社保局背后的改变中间的view的高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *socialSecurityMiddleHeight;

//雷俊博
@property (nonatomic, strong)CTAPIBaseManager *manager;
//弹框
@property (nonatomic, strong)UIView *backgroundView;

@property (nonatomic, strong)PackageCoinsView *coinsView;
/*
 * 第一个显示时间图标top的高度
 *第二个控制背景图片top的高度
 *把到导航栏的高度上移动64个像素
 */

@property (weak, nonatomic) IBOutlet UIImageView *imageView_3;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backguardPictureTopHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *timerTopHeightyy;
/*
 * 新的界面分享
 1.分享的view
 2.按钮微信
 3.按钮支付宝
  */

//分享的文字





@property(nonatomic,strong)NSString *document;


@property (weak, nonatomic) IBOutlet UIView *bottmView;
@property (weak, nonatomic) IBOutlet UIImageView *img_package;



@property(nonatomic,strong)FMDatabase *db;

@property (nonatomic, strong) GDTUnifiedBannerView *bannerView;

@end

@implementation successViewController
{
    int ingeerr;
    
}
-(NSString *)document{
    if (!_document) {
        _document=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
    }
    return _document;
}
-(void)imageLoca{
    
    
    //雷俊博更改
    //判断从哪个页面进入
    if (self.GGImage) {
        self.imageView_1.hidden = YES;
        self.imageView_2.hidden = YES;
        
        NSData *dataBase64 =[[NSData alloc]initWithBase64EncodedString:self.GGImage options:0];
        
        self.imageView_3.image = [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:[UIImage imageWithData:dataBase64]];
        NSString*provinceCityStr =[NSString stringWithFormat:@"%@%@",self.province,self.county];
         self.provinceTitle.text =  MHSafeStrings(provinceCityStr);
        
    }else{
        self.imageView_3.hidden = YES;
       self.imageView_1.image =  [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:self.imageView1];
       self.imageView_2.image = [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:self.imageView2];
        
    }
    return;
    
    
    
    NSMutableArray *array2array =[[NSMutableArray alloc]init];;
       
    

    if(self.imageView1  == nil){
        /////////这里面保存所以之前成功的数据
        [array2array removeAllObjects];
  NSString *targetPath=[ NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)[0] stringByAppendingPathComponent:@"imageLocation0.jpg"];
        NSFileManager *file_manager = [NSFileManager defaultManager];
        if( [file_manager fileExistsAtPath:targetPath]){
        for (int i = 0;  i <2; i ++ ) {
            NSString *documentPaths =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)[0];
            NSString *targetPath_33=[documentPaths stringByAppendingPathComponent:[NSString stringWithFormat:@"imageLocation%d.jpg",i]];
            [array2array addObject:[UIImage imageWithContentsOfFile:targetPath_33]];
            
        }
        
        
        self.imageView_1.image =  [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:array2array[0]];
        self.imageView_2.image = [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and: array2array[1]];
        //读取省份

            
            self.imageView_2.hidden = YES;
            self.imageView_1.hidden = YES;
            if (_GGImage) {
                      self.imageView_3.image =  [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:[UIImage imageWithData:[[NSData alloc] initWithBase64EncodedString:_GGImage options:NSDataBase64DecodingIgnoreUnknownCharacters]]];
            }else{
                self.imageView_3.image = [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:array2array[0]];
                
            }
            
            
            
            
    
            

            
            
                         //无法变成直角清明之后再研究一下
    
            
      
            
            
            
        }
             AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
        self.provinceTitle.text =  MHSafeStrings(delegate.successProvince);

        //title - 社保认证地址 区 社保局
        self.socialSecurityAdminstration.text =MHSafeStrings(delegate.successVillage);
            /////////
            
    } else if(self.imageView_1 ){
        self.imageView_3.hidden =YES;
        self.imageView_1.image =  [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:self.imageView1];
        self.imageView_2.image = [self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:self.imageView2];
        //保存一下数据

        
        
        
            NSString *documentPath =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)[0];
            NSString *targetPath_3333=[documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"imageLocation0.jpg"]];
            [UIImagePNGRepresentation(self.imageView_1.image) writeToFile:targetPath_3333 atomically:YES];
            NSString *targetPath_33333=[documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"imageLocation1.jpg"]];
            [UIImagePNGRepresentation(self.imageView_1.image) writeToFile:targetPath_33333 atomically:YES];
        
    }

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



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"验证成功";
    NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
    NSString *names =[userDefault objectForKey:@"name"];
//    NSString *identifity =[userDefault objectForKey:@"identityNumber"];
    self.nameShare.text = names;
    self.shareTextField.text =[NSString stringWithFormat:@"\t我们家乡%@%@%@可以刷脸社保认证了，足不出户、足不出村、放心领钱！\n\t看看生活，科技惠民、科技便民，人工智能走入寻常百姓家。", MHSafeStrings(self.province),MHSafeStrings(self.city),MHSafeStrings(self.county) ];
    
    
    //雷俊博注释
    //前面开发者写的去银联领红包弹框
   // [self dataa];
    self.navigationItem.hidesBackButton = YES;
    
    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]];

    
   [self imageLoca];

    
    //开启分享视图

   //v添加一个毛玻璃效果
[self  ufffblackground];
    //将数据导入到整个界面中
    [self showView];
    //布局所有的苹果的手机
    [self  getLayoutForAllIphone];
    

//    if([getPeopleID getpeopleLimited] == NO){
//        self.view_f.hidden = NO;
//        self.shareHide.hidden = NO;
//    }else{
//        self.view_f.hidden = YES;
//        self.shareHide.hidden = YES;
//    }
    
     //非权限用户
   // if (![getPeopleID getpeopleLimited]) {
        //认证成功送金币
           [self loadData];
   // }
    
    if (self.name) {
        [self queryAttentionIsOrNot];
    }
   
    
   
   
    
  
    

    
    UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickImage)];
    [self.img_package addGestureRecognizer:singleTap];
    
    
    
    
    
    [WXApiManager sharedManager].delegate = self;
    
    //如果认证成功,就把信息存储到本地
    
    [self insertUserInfo];
    
    
    
   // [self creatADBanner];
    
    
}

- (void)creatADBanner
{
     if (self.bannerView.superview) {
             [self.bannerView removeFromSuperview];
      }
         [self.view addSubview:self.bannerView];
          
         [self.bannerView loadAdAndShow];
}



- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [ZYSuspensionManager destroyAllWindow];
    
    self.navigationController.navigationBar.translucent = NO;
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

- (void)dealloc
{
    NSLog(@"认证成功页面销毁了");
}


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


//查询是否用户是否绑定微信
- (NSDictionary *)requestPara
{
   
    NSString *name =  [self.name 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/index.html?vid=%@&name=%@&time=%@",self.bak,name,time];
    
    NSDictionary *params = @{
        @"name":self.name,
        @"pre":@"看看生活认证结果",
        @"result":@"认证成功",
        @"telephone":[getPeopleID PeopleIphoneNmber],
        @"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) {
                                
                            }];
                        }
                    }];
                    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 (![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 = [EnercryTool A:self.idNumber];
    
    FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]){
       
        
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_rzUser 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 =  [EnercryTool A:self.name];
        //身份证号AES加密
        NSString *IdentiftyEnerypt = [EnercryTool A:self.idNumber];
        
        if ([db open]) {
            
            NSString *sql = [NSString stringWithFormat:@"SELECT Count(1) FROM t_rzUser WHERE userid='%ld' ",[getPeopleID PeopleID]];
            NSUInteger count  = [db intForQuery:sql];
            NSLog(@"已添加数据:%ld",count);
            if (count >= 5) {
                
            NSString *sql2 = [NSString stringWithFormat:@"SELECT  id FROM t_rzUser WHERE userid='%ld' LIMIT 1  ;",[getPeopleID PeopleID]];
             NSInteger Id = [db intForQuery:sql2];
                
              NSString *sql3 = [NSString stringWithFormat:@"delete from t_rzUser where id = '%ld'",Id];
              BOOL reslut =   [db executeUpdate:sql3];
                if (reslut) {
                    NSString * sql4 = [NSString stringWithFormat:@"INSERT INTO t_rzUser (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_rzUser (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 = [EnercryTool A:self.idNumber];
         NSString *timeSp = [NSString stringWithFormat:@"%ld",[self getNowTimeTimestamp3]];
        if ([db open]) {
            NSString *sql = @"UPDATE t_rzUser 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 - private methods

// 判断是否是同一天
- (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];
}






#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvSubscribeMsgResponse:(WXSubscribeMsgResp *)response
{
    if ([response.action isEqualToString:@"confirm"]) {
        [self getWXAccessToken:response];
    }
    
    
}

#pragma mark - GDTUnifiedBannerViewDelegate
- (void)unifiedBannerViewDidLoad:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}
- (void)unifiedBannerViewFailedToLoad:(GDTUnifiedBannerView *)unifiedBannerView error:(NSError *)error
{
    
}
- (void)unifiedBannerViewWillExpose:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}
- (void)unifiedBannerViewClicked:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}
- (void)unifiedBannerViewWillPresentFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}
- (void)unifiedBannerViewDidPresentFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}
- (void)unifiedBannerViewWillDismissFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}
- (void)unifiedBannerViewDidDismissFullScreenModal:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}
- (void)unifiedBannerViewWillLeaveApplication:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}
- (void)unifiedBannerViewWillClose:(GDTUnifiedBannerView *)unifiedBannerView
{
    
}






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


-(void)showView{
    //获取省份和市区
    
    
    self.provinceTitle.text = [NSString stringWithFormat:@"%@%@",[NSString validBlankStr:self.province],[NSString validBlankStr:self.city]];
    self.socialSecurityAdminstration.text  = [[NSString validBlankStr:self.county] stringByAppendingString:@"人力资源和社会保障局"];
    
    if (self.GGtime) {
        self.socialTime.text = self.GGtime;
    }else{
    self.socialTime.text =  [self KANKANTime];
    }
    
    
    //获取当前的地址
    //[self KANKANAddress];
    
    
    if (self.GGaddress) {
        self.soicialAddress.text =
              MHSafeStrings(self.GGaddress);
    }else{
        self.soicialAddress.text =
              MHSafeStrings([[NSUserDefaults standardUserDefaults]valueForKey:@"gdfdsgdfght"]);
    }
    
    
   
    
    return;
   
    self.provinceTitle.text = [[[NSUserDefaults standardUserDefaults]objectForKey:@"successProvinceKankan"] stringByAppendingString:[[NSUserDefaults standardUserDefaults]objectForKey:@"successareaKankan"]] ;
    //获取乡镇
    self.socialSecurityAdminstration.text = [[[NSUserDefaults standardUserDefaults]objectForKey:@"successdowntownKankan"] stringByAppendingString:@"人力资源和社会保障局"];
    //获取当前的时间
   

    
    if (self.GGtime) {
        self.socialTime.text =      self.GGtime;
    }else{
    self.socialTime.text =  [self KANKANTime];
    }
    
    
   
    //获取当前的地址
    [self KANKANAddress];

    
    
    //保存省份
     AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
     delegate.successProvince = self.provinceTitle.text;
    delegate.successVillage = [[NSUserDefaults standardUserDefaults]objectForKey:@"successdowntownKankan"];
    
    
}






-(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;
}
-(void)KANKANAddress{
    
    
    
    if (self.GGaddress) {
        self.soicialAddress.text =
        MHSafeStrings(self.GGaddress);
    }else{
        self.soicialAddress.text =
        MHSafeStrings([[NSUserDefaults standardUserDefaults]valueForKey:@"gdfdsgdfght"]);
    }
    
    self.shareTextField.text = [NSString stringWithFormat:@"\t我们家乡%@可以刷脸社保认证了，足不出户、足不出村、放心领钱！\t看看生活，科技惠民、科技便民，人工智能走入寻常百姓家", MHSafeStrings(self.socialSecurityAdminstration.text) ];
 
}

-(void)getLayoutForAllIphone{
    //布局各个iphone的尺寸
    self.socialSecurityTopHeight.constant =  272* [[UIScreen mainScreen]bounds].size.width /375;
    self.socialSecurityMiddleHeight.constant =  288* [[UIScreen mainScreen]bounds].size.height /667;
    
    if ([UIScreen mainScreen].bounds.size.height == 480) {
        //1.设置最上上面的top
        //4S的手机
        self.backguardPictureTopHeight.constant =-64;
        self.timerTopHeightyy.constant = 11;
//        [self.navigationController setNavigationBarHidden:YES animated:YES];
        self.socialSecurityMiddleHeight.constant =240;
    }else if([UIScreen mainScreen].bounds.size.height == 736){
        //7p的手机
        self.socialSecurityMiddleHeight.constant =320;
    }else if([UIScreen mainScreen].bounds.size.height == 568){
        self.socialSecurityMiddleHeight.constant =270;
    }else if ([UIScreen mainScreen].bounds.size.height == 896){
        self.socialSecurityMiddleHeight.constant =320;
    }else if ([UIScreen mainScreen].bounds.size.height == 812){
        self.socialSecurityMiddleHeight.constant =300;
    }
}

-(void)exitApplication
{
    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"确认返回首页?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    
    UIAlertAction* confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        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];
        if ([UIScreen mainScreen].bounds.size.height == 480) {
            
   //

        }
      

        [self.navigationController popToRootViewControllerAnimated:YES ];
    }];
    
    [alertVC addAction:cancel];
    [alertVC addAction:confirm];
    
    [self presentViewController:alertVC animated:YES completion:nil];
    
//    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)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)exitButton:(id)sender {
    [self exitApplication];
    
    
}
- (IBAction)backtorootView:(id)sender {
    
    //    [self.navigationController popToRootViewControllerAnimated:YES ];
    //    UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //    PhotoViewController *tcs=[sb instantiateViewControllerWithIdentifier:@"Photo"];
    //[self.navigationController ]
    
    for (UIViewController*vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[KKUserIdentifyViewController class]]) {
            KKUserIdentifyViewController*currentVC  = (KKUserIdentifyViewController *)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)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];
        if ([UIScreen mainScreen].bounds.size.height == 480) {
            
   //

        }
      

        [self.navigationController popToRootViewControllerAnimated:YES ];
        
        
    }
}
- (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;
}
#define mark - 微信分享
- (IBAction)cloaseAll:(UIButton *)sender {
    
    switch (sender.tag) {
        case 9905:
            //微信聊天
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
            break;
        case 9906:
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
            break;
        case 9907:
            //关闭
            self.shareHide.hidden = YES;
            //            [self.view_f removeFromSuperview];
            self.view_f.hidden =YES;
            
            [self backMain];
            break;
        default:
            break;
    }
    
    
}


-(void)tapAvatarVw{
    self.shareHide.hidden = YES;

    //    [self.navigationController popToRootViewControllerAnimated:YES];
    
    [self backMain];
    
    
}
-(void)backMain{
    //    dispatch_async(dispatch_get_main_queue(), ^{
    self.shareHide.hidden =YES;
    self.view_f.hidden =YES;
    
//    [self.navigationController popToRootViewControllerAnimated:YES];
    
    //    });
    
}
-(void)ufffblackground
{
    //分享的
    self.view_f = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.view_f.backgroundColor =[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.5];
    //添加一个动画,渐变的效果
    CATransition *applicationLoadViewIn =[CATransition animation];
    [applicationLoadViewIn setDuration:0.4];
    [applicationLoadViewIn setType:kCATransitionReveal];
    [applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    //you view need to replace
    

    
    
    [[self.view_f layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
    [[self.shareHide layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
    
    UITapGestureRecognizer * tap_=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarVw)];
    [self.view_f addGestureRecognizer:tap_];
//    [self.view addSubview:self.view_f];
//    [self.view bringSubviewToFront:self.shareHide];
    
    
    UIWindow * window = [UIApplication sharedApplication].windows[0];
    [window addSubview: self.view_f];
    [window addSubview:self.shareHide];
    [window bringSubviewToFront:self.shareHide];
    //改
    [self.shareHide mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.centerY.mas_equalTo(0);
    }];
      [self.view setNeedsUpdateConstraints];
    
    
    self.view_f.hidden = YES;
}




-(void)shared:(UMShareWebpageObject*)shareObject andM:(UMSocialMessageObject*)messageObject andP:(UMSocialPlatformType)platformType
{
    
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }
    
    //设置网页地址
    shareObject.webpageUrl = UMS_WebLink;
    
    //分享消息对象设置分享内容对象
    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);
            }
        }
        [self alertWithError:error];
    }];
    
    
}
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    NSString* thumbURL =  UMS_THUMB_IMAGE;
    if (platformType  == UMSocialPlatformType_WechatSession) {
        
            UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:UMS_Title descr:self.shareTextField.text thumImage:thumbURL];

        [self shared:shareObject andM:messageObject andP:platformType];
        
    }else if (platformType == UMSocialPlatformType_WechatTimeLine){
          UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.shareTextField.text descr:self.shareTextField.text thumImage:thumbURL];
         [self shared:shareObject andM:messageObject andP:platformType];
    }

}


- (void)alertWithError:(NSError *)error
{
    NSString *result = nil;
    if (!error) {
        result = [NSString stringWithFormat:@"分享成功"];
    
    }
    else{
        NSMutableString *str = [NSMutableString string];
        if (error.userInfo) {
            for (NSString *key in error.userInfo) {
                [str appendFormat:@"%@ = %@\n", key, error.userInfo[key]];
            }
        }
        if (error) {
            result = [NSString stringWithFormat:@"Share fail with error code: %d\n%@",(int)error.code, str];
            result = [NSString stringWithFormat:@"分享失败"];
    self.shareHide.hidden = YES;
        }
        else{
            result = [NSString stringWithFormat:@"Share fail"];
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:result
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"确定", @"确定")
                                          otherButtonTitles:nil];
    [alert show];
}


-(void)dataa{
    NSDate *now = [NSDate date];
    
    NSString *oldDate =  [now transferStrngDate];
    
    BOOL ist =  [now isSameWeekAsDate:[now zipFornowDate:oldDate]];
    //->YES 表示日期就是本周之内所以就直接不调用红包
    //-> BNO 表示不在本周内就调用红包
    
    if(ist == YES){
        if([oldDate isEqualToString:@"首次显示"]){
            
            [self circleAnimal];
        }else{
            
            NSLog(@"不显示红包");
           //[self circleAnimal];
        }
    }else{
        
        
        //显示红包+
        
        [self circleAnimal];
        //将数据存进去
    }
    
    
}
-(void)circleAnimal{
//    UIColor *color = [UIColor clearColor];
    
//    ZYSuspensionView *sus2 = [[ZYSuspensionView alloc] initWithFrame:CGRectMake(     [UIScreen mainScreen].bounds.size.width-110-10
//                                                                                , [UIScreen mainScreen].bounds.size.height-250 , 100, 100)
//                                                               color:color
//                                                            delegate:self];
//
//    [sus2 setBackgroundImage:[UIImage imageNamed:@"catchMoney.gif"] forState:0];
//    sus2.leanType = ZYSuspensionViewLeanTypeHorizontal;
//    [sus2 setTitle:@"" forState:UIControlStateNormal];
//    [sus2 show];
    
    
}

#pragma mark - ZYSuspensionViewDelegate
- (void)suspensionViewClick:(ZYSuspensionView *)suspensionView
{
    //NSLog(@"click %@",suspensionView.titleLabel.text);
    
    
    
    
    [ZYSuspensionManager destroyAllWindow];
    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 jumpToHTML5:@"https://render.alipay.com/p/f/jfxb4alj/pages/receive-redpacket/index.html?partnerId=&sharedUserId=&shareUserId=2088331168368991&__webview_options__=ttb%253Dauto&shareChannel=QRCode&sceneCode=KF_DYW04" andJAnalytics:@"支付宝抢红包"];
    
    ingeerr++;
    
    
    if(ingeerr % 2 == 0){
        
        WKSuperViewController *tc=[[WKSuperViewController alloc]init];
        tc.titleStr=@"支付宝抢红包";
        tc.pathStr=@"https://render.alipay.com/p/f/jfxb4alj/pages/receive-redpacket/index.html?partnerId=&sharedUserId=&shareUserId=2088331168368991&__webview_options__=ttb%253Dauto&shareChannel=QRCode&sceneCode=KF_DYW04";
        tc.hidesBottomBarWhenPushed =YES;
        [self.navigationController pushViewController:tc animated:YES];
        
        
        //                WKSuperViewController *tc=[[WKSuperViewController alloc]init];
        //                tc.titleStr=@"支付宝抢红包";
        //                tc.pathStr=@"http://www.pearvideo.com/?from=intro";
        //                tc.hidesBottomBarWhenPushed =YES;
        //                [self.navigationController pushViewController:tc animated:YES];
        
    }else{
        
        WKSuperViewController *tc=[[WKSuperViewController alloc]init];
        tc.titleStr=@"银联抢红包";
        tc.pathStr=@"https://wallet.95516.com/s/wl/webV3/activity/vInvite/html/snsIndex.html?code=bdyx&from=groupmessage&isappinstalled=0";
        tc.hidesBottomBarWhenPushed =YES;
        [self.navigationController pushViewController:tc animated:YES];
        
    }
    
    
    
    
    
    
    
    
    
    
}
-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{
   
    
    Web2ViewController*tc = [Web2ViewController new];
    tc.skipUrl =[NSURL URLWithString:url];
    tc.hidesBottomBarWhenPushed =YES;
    tc.title = janalytics;
    [self.navigationController pushViewController:tc animated:YES];
    
    
    
}

//转成json
- (NSString *)toJsonString:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    str = [NSString stringWithFormat:@"%@",str];
    return str;
}


#pragma mark - getters and setters
- (CTAPIBaseManager *)manager
{
    if (!_manager) {
        _manager = [[CTAPIBaseManager alloc]init];
    }
    return _manager;
}

- (PackageCoinsView *)coinsView
{
    if (!_coinsView) {
        _coinsView = [[PackageCoinsView alloc]initWithFrame:CGRectMake(0 , 0, ScreenWidth, 480)];
    }
    return _coinsView;
}

- (UIView *)backgroundView
{
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _backgroundView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.4];
    }
    return _backgroundView;
}

- (GDTUnifiedBannerView *)bannerView
{
  if (!_bannerView) {
      CGRect rect = {CGPointMake(15, ScreenHeight - 15 - (ScreenWidth - 30) * (64/345.0)), CGSizeMake(ScreenWidth - 30, (ScreenWidth - 30) * (64/345.0))};
//      _bannerView = [[GDTUnifiedBannerView alloc]
//                     initWithFrame:rect appId:@"1110119875"
//                     placementId:@"8061217118113631"
//                     viewController:self];
      _bannerView = [[GDTUnifiedBannerView alloc]initWithFrame:rect placementId:@"8061217118113631" viewController:self];
      _bannerView.animated = YES;
      _bannerView.autoSwitchInterval = 20;
      _bannerView.delegate = self;
  }
  return _bannerView;
}

@end

