//
//  ApplyStateQueryViewController.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2020/4/16.
//  Copyright © 2020 雷俊博. All rights reserved.
//

#import "ApplyStateQueryViewController.h"
#import "ApplyStateQueryCell.h"
#import "ApplayStateModel.h"

#import "UIView+frameAdjust.h"

#import "JinDuAlertView.h"

#import "EmptyView.h"

#import "LoginVC.h"



@interface ApplyStateQueryViewController ()<UITableViewDelegate,UITableViewDataSource,ApplyStateQueryCellDelegate>
{
    NSString* idNumberStr;
    
     EmptyView *emptyView;
}

@property (nonatomic, strong)UIView* topView;

@property (nonatomic, strong)UITableView* tableView;

@property (nonatomic, strong)NSMutableArray* stateArray;


@end

@implementation ApplyStateQueryViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    [GTCountSDK trackCountEvent:@"home_zhengwu_dengjiProgressQuery" withArgs:@{}];//个推统计
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configUI];
    
    [self shenbaojinduRequest];
    
}

- (void)configUI
{
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    self.stateArray = [NSMutableArray array];
    
//    for (int i = 0; i < 10; i++) {
//        ApplayStateModel*model = [[ApplayStateModel alloc]init];
//        model.personName = @"雷俊博";
//        model.identityNumber = @"411522199109276910";
//        model.dataState = @"审核中";
//        NSMutableArray*dateArray = [NSMutableArray array];
//        for (int j = 0; j< 2; j++) {
//            ApplayDateModel*dateModel = [[ApplayDateModel alloc]init];
//            dateModel.role = @"乡村街道审核安全";
//            dateModel.examineTime = @"2020-02-27 11:35:59";
//            [dateArray addObject:dateModel];
//        }
//        model.progresses = dateArray;
//
//        [self.stateArray addObject:model];
//    }
    
    //[self.view addSubview:self.topView];
    [self.view addSubview:self.tableView];
     [self emptyViewInit];
   JinDuAlertView* alertView = [[JinDuAlertView alloc]initWithVC:self origialY:cl_kNavigationBarHeight];
    WeakSelf
    alertView.block = ^(NSString * _Nonnull IdCardStr) {
      NSLog(@"IdCardStr:%@",IdCardStr);
        self->idNumberStr = IdCardStr;
        [weakSelf shenbaojinduRequest];
    };
   
}

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

#pragma mark - load data
- (NSDictionary *)shenbaojinduRequestParams
{
    NSDictionary*params = nil;
    NSInteger userId = [getPeopleID PeopleID];
    if (idNumberStr) {
        params = @{
          @"identityNumber":[EnercryTool AES256Encrypt:idNumberStr key:MZAESKEY],
          @"verifyType":@"10"
        };
    }else{
        params = @{
         @"userId":@(userId),
         @"verifyType":@"10"
        };
    }
    return params;
}
- (void)shenbaojinduRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],ShenBaoJinDuQueryRequest];
    NSLog(@"申报进度查询url:%@",url);
    NSLog(@"params:%@",[self shenbaojinduRequestParams]);
    NSString* token =  [UserDefault objectForKey:@"token"];
    [SVProgressHUD show];
    WeakSelf
    [NetworkRequest Get6:url Params:[self shenbaojinduRequestParams] Token:token Success:^(id  _Nonnull responseObject) {
           [SVProgressHUD dismiss];
           NSLog(@"responseObject:%@",responseObject);
           
           if ([responseObject isKindOfClass:[NSDictionary class]]) {
               NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
               NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
               if ([state isEqualToString:@"200"]) {
                   
                   
                   NSArray* result = responseObject[@"result"];
                   
                   weakSelf.stateArray = [ApplayStateModel mj_objectArrayWithKeyValuesArray:result];

                   if (result.count > 0) {
                       [weakSelf showTable];
                   }else{
                       [weakSelf noDataShow];
                   }
                   
                   [weakSelf.tableView reloadData];
               }else if ([state isEqualToString:@"700"]){
                        [self refreshRequest];

               }else if ([state isEqualToString:@"500"]){
                   
                   [SVProgressHUD showInfoWithStatus:describe];
                   [weakSelf.stateArray  removeAllObjects];
                    [weakSelf noDataShow];
                   [weakSelf.tableView reloadData];
               } else{
                   [SVProgressHUD showInfoWithStatus:describe];
               }
           }else{
               [SVProgressHUD showInfoWithStatus:@"服务器异常"];
           }
           
       } Failure:^(NSError * _Nonnull error) {
           [SVProgressHUD dismiss];
           NSLog(@"error:%@",error);
           [SVProgressHUD showInfoWithStatus:@"网络异常"];
       }];
}

- (void)refreshRequest
{
    [self aiDaTokenRequest:^(bool success, NSString *token) {
        if (success) {
            [UserDefault setObject:token forKey:@"token"];
            [self shenbaojinduRequest];
        }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];
    }
}

- (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:@"网络异常"];
    }];
}


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



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ApplyStateQueryCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.delegate = self;
    
    UIImage *backImage = [UIImage imageNamed:@"weizhankai_arrow"];
     
    //改变该图片的方向
    
     ApplayStateModel*model = self.stateArray[indexPath.section];
    if (model.show) {
        backImage = [UIImage imageWithCGImage:backImage.CGImage
              scale:backImage.scale
        orientation:UIImageOrientationRight];
        [cell.btn setImage:backImage forState:UIControlStateNormal];
    }else{
        [cell.btn setImage:backImage forState:UIControlStateNormal];
    }
    
    
    [cell setModel:model];
    
    
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ApplayStateModel*model = self.stateArray[indexPath.section];
    if (model.show) {
        ApplayDateModel*dModel = model.progresses.lastObject;
        if (dModel && ![Tools isBlankString:dModel.examineRemark]) {
            return 73 + 60 * model.progresses.count + 40;
        }
        
       return 73 + 60 * model.progresses.count;
    }else{
        return 73;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     
     ApplayStateModel*model = self.stateArray[indexPath.section];
     
     model.show = !model.show;
     

    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}


#pragma mark - ApplyStateQueryCellDelegate
- (void)btnClickWithCell:(ApplyStateQueryCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    ApplayStateModel*model = self.stateArray[indexPath.section];
    
    model.show = !model.show;
    
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
    
}

#pragma mark - show and hidden
- (void)showTable
{
    self.tableView.hidden = NO;
    emptyView.hidden = YES;
}

- (void)noDataShow
{
    self.tableView.hidden = YES;
    emptyView.hidden = NO;
}


#pragma mark - event response
- (void)btnClck:(UIButton *)sender
{
    
}





#pragma mark - getters and setters
- (UIView *)topView
{
    if (!_topView) {
        _topView = [[UIView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 40)];
        
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"条件筛选" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"pullDownImage"] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        [btn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleRight imageTitleSpace:4];
        [btn addTarget:self action:@selector(btnClck:) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:btn];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.height.equalTo(self->_topView);
            make.width.offset(120);
        }];
        
    }
    return _topView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight + 40, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - 40) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        
        [_tableView registerNib:[UINib nibWithNibName:@"ApplyStateQueryCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        
        _tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
    }
    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
