//
//  SaveOrderListController.m
//  Open
//
//  Created by 雷俊博 on 2020/8/11.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "SaveOrderListController.h"
#import "SaveOrderListCell.h"
#import "SaveOrderModel.h"
#import "PayOrderDetailView.h"
#import "BCSaveOrderModel.h"

@interface SaveOrderListController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView* tableView;

@property (nonatomic, strong)NSMutableArray* dataArray;

@end

@implementation SaveOrderListController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:0 target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:bar];
    [GTCountSDK trackCountEvent:@"save_wudangOrderListCount" withArgs:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //init
    self.dataArray = [NSMutableArray array];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
         self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
    if (self.type == SaveFromTypeBiCai) {
        [self bcQueryTradeDetailRequest];
    }else{
        [self loadData];
    }
    
}

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

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.type == SaveFromTypeBiCai) {
        BCSaveOrderModel*model = self.dataArray[indexPath.section];
        SaveOrderListCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.lb_describe.text = model.transTypeName;
        cell.lb_date.text = model.operaDate;
        
        if ([model.transType isEqualToString:@"1"] || [model.transType isEqualToString:@"3"] || [model.transType isEqualToString:@"5"] || [model.transType isEqualToString:@"6"] ) {
            cell.lb_num.textColor = [UIColor colorWithHex:0xE7441E];
            cell.lb_num.text = [NSString stringWithFormat:@"+%@",model.transAmt];
        }else if ([model.transType isEqualToString:@"4"] || [model.transType isEqualToString:@"2"]){
            cell.lb_num.textColor = [UIColor colorWithHex:0x4d4d4d];
            cell.lb_num.text = [NSString stringWithFormat:@"-%@",model.transAmt];
        }
        
        
        
        return cell;
    }
    SaveOrderModel*model = self.dataArray[indexPath.section];
    SaveOrderListCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.lb_describe.text = [self getMessageWithCode:model.TRANTYPE message:model.NOTE];
    cell.lb_date.text = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:%@",[model.HS_INPD substringToIndex:4],[model.HS_INPD substringWithRange:NSMakeRange(4, 2)],[model.HS_INPD substringFromIndex:model.HS_INPD.length - 2],[model.HS_INPT substringToIndex:2],[model.HS_INPT substringWithRange:NSMakeRange(2, 2)],[model.HS_INPT substringWithRange:NSMakeRange(4, 2)]];
    
    if ([model.BILL_AMS isEqualToString:@"+"]) {
        cell.lb_num.textColor = [UIColor colorWithHex:0xE7441E];
    }else if ([model.BILL_AMS isEqualToString:@"-"]){
        cell.lb_num.textColor = [UIColor colorWithHex:0x4d4d4d];
    }
    
    cell.lb_num.text = [NSString stringWithFormat:@"%@%.2f",model.BILL_AMS,model.BILL_AMT.doubleValue];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.type == SaveFromTypeYinShu) {
        SaveOrderModel*model = self.dataArray[indexPath.section];
        [PayOrderDetailView showViewWithModel:model InVC:self];
    }
   
}

#pragma mark - 交易记录查询
- (void)loadData
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSOrderHistoryQueryRequest];
    
    NSDictionary*params = @{
        @"acctNo": [Tools isBlankString:self.cardModel.CARDNBR] ?@"" :self.cardModel.CARDNBR,
        @"startDate":[self getLastMonthTimeStamp],
        @"endDate":[self getCurrentTimeStamp],
    };
    
    NSLog(@"银数交易记录查询url:%@",url);
    NSLog(@"params:%@",params);
    
    [KKLoadingAnimationView show];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *strHeader = [NSString stringWithFormat:@"IOS#%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
    NSLog(@"strHeader:%@",strHeader);
    [manager.requestSerializer setValue:strHeader forHTTPHeaderField:@"User-Agent"];
       
    [manager POST:url parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
       
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       [KKLoadingAnimationView dismiss];
       NSLog(@"responseObject:%@",responseObject);
        NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
        NSString* result = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            NSDictionary*dic = [Tools dencode:result];
            NSLog(@"result:%@",[Tools dencode:result]);
            self.dataArray = [SaveOrderModel mj_objectArrayWithKeyValuesArray:dic[@"SUBPACKS"]];
            [self.tableView reloadData];
            //[self refreshPayViewData];
        }else{
           NSDictionary*dic = [Tools dictionaryWithJsonString:describe];
            NSLog(@"describe:%@",dic);
           NSString*code = nil;
           NSString*message = nil;
           if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"code"]]]) {
               code = [NSString stringWithFormat:@"%@",dic[@"code"]];
           }else if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"RETCODE"]]]){
               code = [NSString stringWithFormat:@"%@",dic[@"RETCODE"]];
           }
           
           if (code) {
               message = [KBankErrorCode showErrorMessageWithErrorCode:code];
               
               if (message) {
                   [SVProgressHUD showErrorWithStatus:message];
               }else{
                   [SVProgressHUD showErrorWithStatus:@"系统错误"];
               }
           }else{
               [SVProgressHUD showErrorWithStatus:@"系统错误"];
           }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

       NSLog(@"error:%@",error);
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

#pragma mark - 比财 资产交易明细
- (void)bcQueryTradeDetailRequest {
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCQueryTradeDetailRequest];
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:self.bcCardModel.orgId forKey:@"orgId"];
    [params setObject:@(1) forKey:@"currentPage"];
    [params setObject:@(0) forKey:@"queryType"];
    [params setObject:@(10) forKey:@"pageSize"];
    [params setObject:[self getLastThreeMonthTimeStamp] forKey:@"startDate"];
    [params setObject:[self getCurrentTimeStamp2] forKey:@"endDate"];
    
    NSLog(@"比财充值校验url:%@",url);
    NSLog(@"params:%@",params);
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
        
        NSLog(@"objc:%@",objc);
        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
          
            self.dataArray = [BCSaveOrderModel mj_objectArrayWithKeyValuesArray:objc[@"result"][@"retList"]];
            [self.tableView reloadData];
            
            
        }else{
            [self alertShow:describe];
        }
        [KKLoadingAnimationView dismiss];
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        
        NSLog(@"error:%@",error);
        [self alertShow:@"网络出小差了,请稍后重试"];
        
    }];
}

#pragma mark - 提示
- (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 - 获取当前时间戳
- (NSString *)getCurrentTimeStamp
{
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制

    [formatter setDateFormat:@"yyyyMMdd"];

    NSDate *dateNow = [NSDate date];

    //把NSDate按formatter格式转成NSString

    NSString *currentTime = [formatter stringFromDate:dateNow];

    return currentTime;
}
- (NSString *)getCurrentTimeStamp2
{
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制

    [formatter setDateFormat:@"yyyy-MM-dd"];

    NSDate *dateNow = [NSDate date];

    //把NSDate按formatter格式转成NSString

    NSString *currentTime = [formatter stringFromDate:dateNow];

    return currentTime;
}
#pragma mark - 获取一个月前时间戳
- (NSString *)getLastMonthTimeStamp
{
//    NSDate *currentdata = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:-30];
    NSDate *dateNow = [NSDate date];
    NSDate *mDate = [calendar dateByAddingComponents:comps toDate:dateNow options:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制

    [formatter setDateFormat:@"yyyyMMdd"];


    //把NSDate按formatter格式转成NSString

    NSString *agoString = [formatter stringFromDate:mDate];
    
    return agoString;
}

#pragma mark - 获取三个月前时间戳
- (NSString *)getLastThreeMonthTimeStamp
{
//    NSDate *currentdata = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:-90];
    NSDate *dateNow = [NSDate date];
    NSDate *mDate = [calendar dateByAddingComponents:comps toDate:dateNow options:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制

    [formatter setDateFormat:@"yyyyMMdd"];


    //把NSDate按formatter格式转成NSString

    NSString *agoString = [formatter stringFromDate:mDate];
    
    return agoString;
}

- (NSString *)getMessageWithCode:(NSString *)code message:(NSString *)message
{
    NSString* returnMessage = nil;
    if ([code isEqualToString:@"2822"]) {
        returnMessage = @"提现";
    }else if ([code isEqualToString:@"7822"]){
        returnMessage = @"充值";
    }else if ([code isEqualToString:@"2894"]){
        returnMessage = @"购买";
    }else if ([code isEqualToString:@"7894"]){
        returnMessage = @"赎回";
    }else{
        returnMessage = message;
    }
    return returnMessage;
}



#pragma mark - getters
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 30;
        _tableView.estimatedSectionFooterHeight = 10;
        _tableView.estimatedSectionHeaderHeight = 10;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"SaveOrderListCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    }
    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
