//
//  DDSBCardListVC.m
//  Open
//
//  Created by 雷俊博 on 2020/10/16.
//  Copyright © 2020 黄江涛 . All rights reserved.
//
#import "SSTerminationViewController.h"
#import "DDSBCardListVC.h"
#import "FamilyListCell.h"
#import <esscsdk/esscsdk.h>
#import "EmptyView.h"
#import "DDSBCardViewController.h"
#import "AppDelegate.h"


#define cardBgImageScale 155/326
@interface DDSBCardListVC ()<UICollectionViewDelegate,UICollectionViewDataSource,EESBCallbackDelegate>
{
    EmptyView* emptyView;
}

@property (nonatomic, strong)UICollectionView* collectionView;

@end

@implementation DDSBCardListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor whiteColor];
    [self navConfig];
    [self.view addSubview:self.collectionView];
    //[self emptyViewInit];
    [self creatBottomView];
    //检测
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(kkBindESSCCardListRequest) name:KKSBESSCCARDRefreshNotificationName object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jiePing) name:UIApplicationUserDidTakeScreenshotNotification  object:nil];
    
}

- (void)creatBottomView
{
    CGFloat bottomViewHeight = cl_kNavigationBarHeight > 64 ? 53 * WIDTHRADIU  : 41 * WIDTHRADIU;
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(10*WIDTHRADIU, ScreenHeight - bottomViewHeight-10*WIDTHRADIU, ScreenWidth-10*WIDTHRADIU, bottomViewHeight-10*WIDTHRADIU)];
    [self.view addSubview:bottomView];
    UIButton *earnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    earnBtn.frame = CGRectMake(0, 0, ScreenWidth-20*WIDTHRADIU, bottomViewHeight-5*WIDTHRADIU);
    [earnBtn setTitle:@" 申请亲属电子社保卡" forState:UIControlStateNormal];
    [earnBtn setImage:[UIImage imageNamed:@"plus"]forState:UIControlStateNormal];
    [earnBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    earnBtn.titleLabel.font = [UIFont systemFontOfSize:17 * WIDTHRADIU];
    earnBtn.backgroundColor = [UIColor colorWithHex:0x086ed7];
    earnBtn.layer.cornerRadius=5;
    earnBtn.layer.masksToBounds=YES;
    [earnBtn addTarget:self action:@selector(moreEss) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:earnBtn];
}
-(void)moreEss{
    SSTerminationViewController * vc=[[SSTerminationViewController alloc] init];
    //DDSBCardListVC * vc=[[DDSBCardListVC alloc] init];
    vc.title=@"电子社保卡";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.noStart) {
        [self kkBindESSCCardListRequest];
    }
    
    [GTCountSDK trackCountEvent:@"home_ESSCard_cardListPage" withArgs:nil];
}




- (void)navConfig
{
    UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
     nav.backgroundColor = [UIColor colorWithHex:0x086ed7];
     [self.view addSubview:nav];
     
     UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     [backBtn setTitle:@"返回" forState:UIControlStateNormal];
     [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
     [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
     [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
     [nav addSubview:backBtn];
     
     [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.offset(0);
         make.top.offset(cl_kStatusBarHeight);
         make.width.offset(80);
         make.height.offset(44);
     }];
     
     UILabel*titleLabel = [[UILabel alloc]init];
     titleLabel.textColor = [UIColor whiteColor];
     titleLabel.textAlignment = NSTextAlignmentCenter;
     titleLabel.text = @"亲属列表";
     titleLabel.font = [UIFont boldSystemFontOfSize:17];
     [nav addSubview:titleLabel];
     
     [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
         make.centerX.offset(0);
         make.top.offset(cl_kStatusBarHeight);
         make.width.offset(80);
         make.height.offset(44);
     }];
     
     UIButton *orderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     orderBtn.frame = CGRectMake(ScreenWidth - 100, cl_kStatusBarHeight, 100, 44);
     //[orderBtn setTitle:@"新增" forState:UIControlStateNormal];
     [orderBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     orderBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
     [orderBtn addTarget:self action:@selector(plusnewEss) forControlEvents:UIControlEventTouchUpInside];
     [nav addSubview:orderBtn];
}

- (void)plusnewEss{
    SSTerminationViewController * vc=[[SSTerminationViewController alloc] init];
    //DDSBCardListVC * vc=[[DDSBCardListVC alloc] init];
    vc.title=@"电子社保卡";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)emptyViewInit
{
    emptyView = [[[NSBundle mainBundle]loadNibNamed:@"EmptyView" owner:nil options:nil] lastObject];
    
    emptyView.frame = CGRectMake((ScreenWidth - 152)/2, (ScreenHeight - 160)/2 - cl_kNavigationBarHeight + 44 , 152, 160);
    emptyView.hidden = YES;
    [self.view addSubview:emptyView];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:KKSBESSCCARDRefreshNotificationName object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}



#pragma mark - 电子社保卡绑定列表请求
-(NSDictionary *)kkBindESSCCardListRequestPara
{
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"phone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
                             };
    return params;
}

- (void)kkBindESSCCardListRequest
{
       NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipKKSBConfig],KKESSCBindCardListRequest];
       NSLog(@"绑定电子社保卡列表url:%@",urlString);
       NSLog(@"params:%@",[self kkBindESSCCardListRequestPara]);
    
    NSString *url = [[NSString stringWithFormat:@"%@/electronic/social/issuance/bindListNoTransfer",CSL_url]  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [NetworkRequest PostNomal:url Params:[self kkBindESSCCardListRequestPara] Success:^(id _Nonnull objc) {
        NSLog(@"申领人员:%@",objc);
        NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        if ([state isEqualToString:@"200"]) {
            if ([objc[@"result"] isKindOfClass:[NSArray class]]){
                NSArray *list=[FamilyListmodel mj_objectArrayWithKeyValuesArray:objc[@"result"]];
                self.dataArray = list;
                [self.collectionView reloadData];
            }
        }
    } Failure:^(NSError* error) {
        [SVProgressHUD dismiss];
        NSLog(@"error:%@",error);
    }];
    
}



#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.dataArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FamilyListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    FamilyListmodel *model = self.dataArray[indexPath.section];
    NSString *deName=model.name;
    NSString *name=[EnercryTool decryptUseDES:deName key:DESKEY];
    NSString *idCard=[EnercryTool decryptUseDES:model.idCard key:DESKEY];
    NSString *remake=model.remark;
    cell.lb_remake.text=remake;
    cell.lb_first.text = [NSString stringWithFormat:@"%@",[name substringToIndex:1]];
    int i=name.length;
    NSString *showName;
    if (i==1) {
        showName=name;
    }else if(i==2){
        showName=[NSString stringWithFormat:(@"%@*"),[name substringToIndex:1]];
    }else{
        showName=[NSString stringWithFormat:@"%@*%@",[name substringToIndex:1],[name substringFromIndex:i-1]];
    }
    cell.lb_name_id.text = [NSString stringWithFormat:@"%@ | %@********%@",showName,[idCard substringToIndex:2],[idCard substringFromIndex:idCard.length - 2]];
    cell.layer.cornerRadius=10;
    cell.layer.masksToBounds=YES;
    int tem=indexPath.section;
    int yy=tem % 4;
    if(yy==0){
        cell.backgroundColor = [UIColor colorWithHex:0x086ed7];
    }else if (yy==1){
        cell.backgroundColor = [UIColor colorWithHex:0xa16df1];
    }else if (yy==2){
        cell.backgroundColor = [UIColor colorWithHex:0xff9081];
    }else{
        cell.backgroundColor = [UIColor colorWithHex:0xfa9405];
    }
    return cell;
}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(ScreenWidth - 50* WIDTHRADIU, ScreenHeight/6);
    
}

/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    
    return UIEdgeInsetsMake(10 * WIDTHRADIU, 10 * WIDTHRADIU, 5 * WIDTHRADIU, 10 * WIDTHRADIU);
}


/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    
    return 0.5;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.5;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    FamilyListmodel *model = self.dataArray[indexPath.section];
    NSString *y_name=[EnercryTool decryptUseDES:model.name key:DESKEY];
    NSString *y_idCard=[EnercryTool decryptUseDES:model.idCard key:DESKEY];
    NSString *url = [[NSString stringWithFormat:@"%@/electronic/social/issuance/jbxSign",CSL_url]  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *name=[GMSm4Utils ecbEncryptText:y_name key:SMKey].lowercaseString;
    NSString *idNum=[GMSm4Utils ecbEncryptText:y_idCard key:SMKey].lowercaseString;
    NSString *phone=[GMSm4Utils ecbEncryptText:[getPeopleID PeopleIphoneNmber] key:SMKey].lowercaseString;
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"name":name,
                             @"idCard":idNum,
                             @"phone":phone
                             };
    [[NSUserDefaults standardUserDefaults]setObject:name forKey:@"essCardName"];//保存name
    [[NSUserDefaults standardUserDefaults]setObject:idNum forKey:@"essCardIdNum"];//保存id
    [SVProgressHUD show];
    [NetworkRequest PostNomal:url Params:params Success:^(id _Nonnull objc) {
        NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        if ([state isEqualToString:@"200"]) {
            NSDictionary *result=objc[@"result"];
            NSString* token = [NSString stringWithFormat:@"%@",result[@"token"]];//更新token
            [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"essCardToken"];//保存token
            NSString* bindStatus = [NSString stringWithFormat:@"%@",result[@"bindStatus"]];//状态
            NSDictionary *data=result[@"data"];
            NSString* returnUrl = [NSString stringWithFormat:@"%@",data[@"returnUrl"]];//社保卡url
            NSString *ess_token=[GMSm4Utils ecbDecryptText:returnUrl key:SMKey];
            NSString *url = [[SSCPublicHeader sharedSSCTool] webUrlWith:SSCServiceType_Main
            signStr:ess_token];
            [[SSCPublicHeader sharedSSCTool] presentWebVCFrom:self esscUrl:url
            esscDelegate:self];
        }
        [SVProgressHUD dismiss];
    } Failure:^(NSError* error) {
        [SVProgressHUD dismiss];
        NSLog(@"error:%@",error);
    }];
    // todo 
}

- (void)backResponseResult:(NSString *)responseResult{
    NSLog(@"%@",responseResult);
    NSDictionary *dic = [NSDictionary dictionaryWithJsonString:responseResult];
    NSString *actionType = dic[@"actionType"];
    NSString *signNo=[GMSm4Utils ecbEncryptText:dic[@"signNo"] key:SMKey].lowercaseString;
    NSString *busiSeq=[GMSm4Utils ecbEncryptText:dic[@"busiSeq"] key:SMKey].lowercaseString;
    if ([actionType isEqualToString:@"001"]||[actionType isEqualToString:@"002"]) {//申领 和 当前渠道签发
        [self essUpdateStatus:@"BIND" signNo:signNo busiSeq:busiSeq type:@"3"];
    }else if([actionType isEqualToString:@"003"]){//解绑
        [self essUpdateStatus:@"UNBIND" signNo:signNo busiSeq:busiSeq type:@"3"];
    }else if([actionType isEqualToString:@"014"]){//待遇认证
        [self essAuthResult];
    }
}


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

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

#pragma mark - 通知绑定方法
- (void)jiePing {
    [self alertShowMessage:@"[安全提醒]内含身份信息，只适合当面使用。不要截图或分享给他人以保障信息安全。"];
}

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



#pragma mark - getters and setters
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
        CGFloat bottomViewHeight = cl_kNavigationBarHeight > 64 ? 53 * WIDTHRADIU  : 41 * WIDTHRADIU;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight-bottomViewHeight-20*WIDTHRADIU) collectionViewLayout:fl];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
       
        // _collectionView.backgroundColor = K_GrayColor;
       
        _collectionView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        //布局
        fl.minimumLineSpacing = 0.5;
        fl.minimumInteritemSpacing = 0.5;
       
        //cell注册
        [_collectionView registerNib:[UINib nibWithNibName:@"FamilyListCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        
    }
    return _collectionView;
}

@end
