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

#import "AuthenticationListViewController.h"
#import "DropDownMenuView.h"
#import "UIView+frameAdjust.h"

#import "AuthenticationListCell.h"
#import "AuthenticationListModel.h"

#import "EmptyView.h"


@interface AuthenticationListViewController ()<DropDownMenuViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    EmptyView *emptyView;
}



@property (nonatomic, strong)DropDownMenuView *topView;

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSMutableArray <AuthenticationListModel *> * dataArray;

@end

@implementation AuthenticationListViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    if ([self.type isEqualToString:@"butie"]) {
        [GTCountSDK trackCountEvent:@"home_BTAuth_authHistoryList" withArgs:@{}];
    }else{
        [GTCountSDK trackCountEvent:@"home_YFAuth_authHistoryList" withArgs:@{}];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.topView];
    [self emptyViewInit];
    self.dataArray = [[NSMutableArray alloc]init];
    [self loadData];
    [self.tableView.mj_header beginRefreshing];
}

- (void)configNav
{
   UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = [UIColor colorWithHex:0x1986d4];
    [self.view addSubview:nav];
    
    UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"nav_back"] 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 = self.title;
    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);
    }];
    
    
}



- (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);
    [self.view addSubview:emptyView];
}

#pragma mark - loadData
- (void)loadData
{
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],GetAuthenticationtypesRequest];
    NSLog(@"认证类型查询urlString:%@",urlString);
    WeakSelf
    [NetworkRequest Get:urlString Params:nil Success:^(id _Nonnull responseObject) {
        NSLog(@"responseObject:%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString *describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                if ([responseObject[@"result"] isKindOfClass:[NSArray class]]) {
                    NSArray* result = responseObject[@"result"];
                    NSMutableArray*resultArray = [NSMutableArray array];
                    for (NSDictionary* dic in result) {
                        NSString*value = dic[@"value"];
                        
                        if ([self.type isEqualToString:@"butie"]) {
                            if (![value containsString:@"军"]) {
                                [resultArray addObject:dic];
                            }
                        }else{
                            if ([value containsString:@"军"]) {
                                [resultArray addObject:dic];
                            }
                        }
                        
                    }
                    
                    weakSelf.topView.types = resultArray;
                    //[weakSelf queryDataRequest:@"" verifyType:@"" matchState:@""];
                }
            }else{
                [self alertShow:describe];
            }
        }else{
            [self alertShow:@"服务器异常"];
        }
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
}

- (NSDictionary *)requestParams:(NSString *)idNumber verifyType:(NSString *)verifyType matchState:(NSString *)matchState
{
    NSDictionary *params = @{
       
        @"idCard":[EnercryTool AES256Decrypt:idNumber key:MZAESKEY],
        @"matchState":matchState,
        @"verifyType":verifyType
    };
    return params;
}

- (void)queryDataRequest:(NSString *)idNumber verifyType:(NSString *)verifyType matchState:(NSString *)matchState
{
    WeakSelf
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],GetAuthenticationListRequest];
    NSLog(@"民政查询urlString:%@",urlString);
    NSLog(@"params:%@",[self requestParams:idNumber verifyType:verifyType matchState:matchState]);
     NSString *token = [UserDefault objectForKey:@"token"];
    [SVProgressHUD show];
    [NetworkRequest Get2:urlString Params:[self requestParams:idNumber verifyType:verifyType matchState:matchState] Token:token Success:^(id  _Nonnull responseObject) {
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
        NSLog(@"responseObject:%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString *des = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                if ([responseObject[@"result"] isKindOfClass:[NSArray class]]) {
                    weakSelf.dataArray = [AuthenticationListModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
                    
                    if (weakSelf.dataArray.count != 0) {
                        self->emptyView.hidden = YES;
                    }else{
                        self->emptyView.hidden = NO;
                    }
                    
                    [weakSelf.tableView reloadData];
                }else{
                    weakSelf.dataArray = nil;
                    self->emptyView.hidden = NO;
                    [weakSelf.tableView reloadData];
                }
            }else if ([state isEqualToString:@"700"]){
                [weakSelf reloadData:idNumber verifyType:verifyType matchState:matchState];
            }else{
                [weakSelf alertShow:des];
            }
        }else{
            [weakSelf alertShow:@"服务器异常"];
        }
        
    } Failure:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
        NSLog(@"error:%@",error);
        [weakSelf alertShow:@"网络异常"];
    }];
}


- (NSDictionary *)aiDaTokenRequestPara
{
    NSDictionary* params = @{
        @"loginId":[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue,
        @"telephone":[getPeopleID PeopleIphoneNmber]
    };
    return params;
}

- (void)aiDaTokenRequest:(void (^)(bool success, NSString*token))response
{
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaConfig],AiDaTokenRequest];
    NSLog(@"爱达token的url:%@",url);
    
    NSLog(@"params:%@",[self aiDaTokenRequestPara]);
    
    [NetworkRequest Get3:url Params:[self aiDaTokenRequestPara] Success:^(id _Nonnull responseObject) {
        
        NSLog(@"responseObject:%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*token = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                
                response(YES,token);
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}


- (void)reloadData:(NSString *)idNumber verifyType:(NSString *)verifyType matchState:(NSString *)matchState
{
    WeakSelf
    
    [self aiDaTokenRequest:^(bool success, NSString *token) {
        if (success) {
            [UserDefault setObject:token forKey:@"token"];
            [weakSelf queryDataRequest:idNumber verifyType:verifyType matchState:matchState];
        }else{
             [self alertShow:@"请求失败"];
        }
    }];
}

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

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AuthenticationListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AuthenticationListCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    AuthenticationListModel *model = self.dataArray[indexPath.section];
    
    if (model.matchState.integerValue == 0) {
        cell.lb_state.text = @"认证成功";
        cell.lb_state.textColor = [UIColor colorWithHex:0x0FA680];
    }else if (model.matchState.integerValue == 2){
        cell.lb_state.text = @"认证失败";
        cell.lb_state.textColor = [UIColor redColor];
    }else if (model.matchState.integerValue == 3){
        cell.lb_state.text = @"认证审核中";
        cell.lb_state.textColor = [UIColor colorWithHex:0xf08326];
    }
    
    cell.lb_name.text = [NSString stringWithFormat:@"用户姓名:   %@",[EnercryTool AES256Decrypt:[NSString validBlankStr:model.name] key:MZAESKEY]];
    NSString* idNo = [EnercryTool AES256Decrypt:[NSString validBlankStr:model.idCard] key:MZAESKEY];
    if ([IDCardNumber_Validate isValidateIDCardString:idNo]) {
        cell.lb_card.text = [NSString stringWithFormat:@"身份证号:   %@**********%@",[idNo substringToIndex:4],[idNo substringFromIndex:idNo.length - 4]];
    }
    
    cell.lb_time.text = [NSString stringWithFormat:@"%@",[NSString validBlankStr:model.recordTime]];;
    
    cell.lb_address.text = [NSString stringWithFormat:@"%@",[NSString validBlankStr:model.recordAddress]];
    
    cell.lb_type.text = [NSString stringWithFormat:@"认证类型:  %@",[NSString validBlankStr:model.recordType]];
    cell.lb_reason.text =  [Tools isBlankString:model.bak01] ? nil:  [NSString stringWithFormat:@"失败原因:  %@",[NSString validBlankStr:model.bak01]];
    
    
    
    
    
    return cell;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//     AuthenticationListModel *model = self.dataArray[indexPath.section];
//
//   NSString* str =  [NSString stringWithFormat:@"认证地址:  %@",[NSString returnAboutblankStr:model.recordAddress]];
//
//
//    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
//
//    NSString* str2 =  [NSString stringWithFormat:@"认证类型:  %@",[NSString returnAboutblankStr:model.recordType]];
//
//
//
//    CGSize sizeFrame = [str boundingRectWithSize:CGSizeMake(ScreenWidth - 20, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
//     CGSize sizeFrame2 = [str2 boundingRectWithSize:CGSizeMake(ScreenWidth - 20, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
//
//    CGFloat addressHeight = sizeFrame.height >= 18.0 ? sizeFrame.height  : 18.0;
//
//    CGFloat  typeHeight = sizeFrame2.height >= 18.0 ? sizeFrame2.height  : 18.0;
//
//    return 112 + addressHeight + typeHeight;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    return view;
}


#pragma mark - DropDownMenuViewDelegate
- (void)queryDataWithIdNumber:(NSString *)idNumber verifyType:(NSString *)verifyType matchState:(NSString *)matchState
{
    NSLog(@"idNumber=%@    verifyType=%@     matchState=%@",idNumber,verifyType,matchState);
    
    [self queryDataRequest:idNumber verifyType:verifyType matchState:matchState];
}

#pragma mark - getters and setters
- (DropDownMenuView *)topView
{
    if (!_topView) {
        _topView = [[DropDownMenuView alloc]init];
        _topView.delegate = self;
    }
    return _topView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.maxY, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - self.topView.height) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
         _tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        _tableView.estimatedSectionFooterHeight = 10;
        _tableView.estimatedSectionHeaderHeight = 10;
        _tableView.estimatedRowHeight = 50;
        
        [_tableView registerNib:[UINib nibWithNibName:@"AuthenticationListCell" bundle:nil] forCellReuseIdentifier:@"AuthenticationListCell"];
        _tableView.tableFooterView = [UIView new];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            NSString*typeStr = @"81,82,83,84,85,86,87,88,89,90,91";
            
            if ([self.type isEqualToString:@"butie"]) {
                typeStr = @"10,11,12,13,14,15,16,99,19,18,22,21,20,23,24,25,26";
            }
            [self queryDataRequest:@"" verifyType:typeStr matchState:@""];
        } ];
    }
    return _tableView;
}

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