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

#import "RechargeSuccessController.h"
#import "RechargeSuccessTopView.h"
#import "BuySuccessCardView.h"
#import "UIView+frameAdjust.h"
#import "KKActivityPackageModel.h"
#import "SaveWelfareAlertView.h"
#import "CTAPIBaseManager.h"

@interface RechargeSuccessController ()

@property (nonatomic, strong)UIView* topView;

@property (nonatomic, strong)UIView* cardView;

@end

@implementation RechargeSuccessController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    //禁止页面左侧滑动返回，注意，如果仅仅需要禁止此单个页面返回，还需要在viewWillDisapper下开放侧滑权限
       // 禁用返回手势
       //禁止手势返回
       id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
       UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
       [self.view addGestureRecognizer:pan];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.topView];
    
    [self.view addSubview:self.cardView];
    
    
    if (self.type == SaveFromTypeBiCai) {
        
    }else{
        NSData*data = [UserDefault objectForKey:@"activityPackageModel"];
           KKActivityPackageModel*model = nil;
           BOOL activityClick = [UserDefault boolForKey:@"activityClick"];
           BOOL openActivity = [UserDefault boolForKey:@"openActivity"];
           if (activityClick && openActivity) {
               if (data) {
                   model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
               }
               if (model) {
                   NSArray* timeArr = [model.activeTime componentsSeparatedByString:@"-"];
                   if (timeArr.count == 2) {
                       NSString*startDate = timeArr[0];
                       NSString* endDate = timeArr[1];
                       if ([self validateWithStartTime:startDate withExpireTime:endDate]) {
                           [UserDefault setBool:NO forKey:@"openActivity"];
                           [SaveWelfareAlertView showAlertViewWithVC:self];
                           [self saveOPenAndRechargeRequest:model];
                       }
                   }
                   
               }
               
           }
    }
    
    
}

#pragma mark - 保存开户和存款活动信息
//开户保存信息(int i = activeType * 100 + 1;   开户  int i = activeType * 100 + 2;  购买)
- (void)saveOPenAndRechargeRequest:(KKActivityPackageModel *)model
{
    NSString*province = [UserDefault objectForKey:@"locationProvince"];
    NSString*city = [UserDefault objectForKey:@"locationCity"];
    NSString*county = [UserDefault objectForKey:@"locationCounty"];
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSMarkActivitySuccessRequest];
    NSDictionary*params = @{
        @"activetype":@(model.activeType.intValue *100 + 2),
        @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
        @"amount":self.amount,
        @"areaProvince":[Tools isBlankString:province] ?@"" :province,
        @"areaCity":[Tools isBlankString:city] ?@"" :city,
        @"areaCounty":[Tools isBlankString:county] ?@"" :county,
        @"systemType":@"iOS"
    };
    
    NSLog(@"保存开户和存款活动信息url:%@",url);
    NSLog(@"params:%@",params);
    
    
    [NetworkRequest Post:url Params:params Success:^(id _Nonnull objc) {
        
        NSLog(@"objc:%@",objc);
        
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
    
}


#pragma mark - private methods
- (NSAttributedString *) attributedStrWithFaultCode:(NSString *)faultCode {
    NSMutableAttributedString * faultCode_ = [[NSMutableAttributedString alloc] initWithString:faultCode];
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    
    NSDictionary * faultCodeAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16 * WIDTHRADIU],NSParagraphStyleAttributeName:paraStyle,NSForegroundColorAttributeName:[UIColor whiteColor]};
    [faultCode_ setAttributes:faultCodeAttributes range:NSMakeRange(faultCode_.length - 1,1)];
    
    
    
    return faultCode_;
}

/**
 *  判断当前时间是否处于某个时间段内
 *
 *  @param startTime        开始时间
 *  @param expireTime       结束时间
 */

- (BOOL)validateWithStartTime:(NSString *)startTime withExpireTime:(NSString *)expireTime {
    NSDate *today = [NSDate date];
    
    startTime = [startTime stringByAppendingFormat:@" 00:00:00"];
    expireTime = [expireTime stringByAppendingFormat:@" 23:59:59"];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    // 时间格式,此处遇到过坑,建议时间HH大写,手机24小时进制和12小时禁止都可以完美格式化
    [dateFormat setDateFormat:@"yyyy.MM.dd HH:mm:ss"];
    [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*3600]];
    
    NSDate *start = [dateFormat dateFromString:startTime];
    NSDate *expire = [dateFormat dateFromString:expireTime];
    
    if ([today compare:start] == NSOrderedDescending && [today compare:expire] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}


#pragma mark - event response
- (void)closeBtnClick:(UIButton *)sender
{
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)checkBtnClick:(UIButton *)sender
{
    [self.navigationController setNavigationBarHidden:NO];
    self.navigationController.tabBarController.selectedIndex = 1;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)confirmBtnClick:(UIButton *)sender
{
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - public methods
-(id)getXiblWithClassName:(NSString *)className
{
    return [[NSBundle mainBundle]loadNibNamed:className owner:self options:nil].lastObject;
}

#pragma mark - 获取转换后的日期模式
- (NSString *)getNewStyleWithDateStr:(NSString *)dateString1
{
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    // 设置日期格式
    [formatter1 setDateFormat:@"yyyyMMdd"];

    // NSDate形式的日期
    NSDate *date =[formatter1 dateFromString:dateString1];
    
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
    [formatter2 setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString2 = [formatter2 stringFromDate:date ];
    NSLog(@"%@",dateString2);
    
    return dateString2;
}
  

#pragma mark - getters
- (UIView *)topView
{
    if (!_topView) {
        _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 244 * WIDTHRADIU + cl_kStatusBarHeight)];
        //顶部背景色
        UIView* bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 189* WIDTHRADIU + cl_kStatusBarHeight)];
        bgView.backgroundColor = [UIColor colorWithHex:0x137ef6];
        [_topView addSubview:bgView];
        
        //底部圆弧
        UIImageView*bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, bgView.maxY, ScreenWidth, 55 * WIDTHRADIU)];
        bgImageView.image = [UIImage imageNamed:@"savesuccess_bg"];
        [_topView addSubview:bgImageView];
        
        
        //完成按钮
        UIButton* closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [closeBtn setTitle:@"完成" forState:UIControlStateNormal];
        [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        closeBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:closeBtn];
        [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(cl_kStatusBarHeight);
            make.right.offset(0);
            make.width.offset(60);
            make.height.offset(44);
        }];
        
        //成功图标
        UIImageView* successImg = [[UIImageView alloc]init];
        successImg.image = [UIImage imageNamed:@"buySuccess"];
        [_topView addSubview:successImg];
        [successImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self->_topView);
            make.top.offset(cl_kStatusBarHeight + 20 * WIDTHRADIU);
            make.width.height.offset(75 * WIDTHRADIU);
        }];
        //购买成功
        UILabel*lb_success = [[UILabel alloc]init];
        lb_success.text = @"购买成功";
        lb_success.textColor = [UIColor whiteColor];
        lb_success.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
        lb_success.textAlignment = NSTextAlignmentCenter;
        [_topView addSubview:lb_success];
        [lb_success mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self->_topView);
            make.top.equalTo(successImg.mas_bottom).offset(10 * WIDTHRADIU);
        }];
        
        //购买金额
        UILabel*lb_money = [[UILabel alloc]init];
        lb_money.font = [UIFont boldSystemFontOfSize:30 * WIDTHRADIU];
        lb_money.textColor = [UIColor whiteColor];
        lb_money.textAlignment = NSTextAlignmentCenter;
        [_topView addSubview:lb_money];
        [lb_money mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self->_topView);
            make.top.equalTo(lb_success.mas_bottom).offset(20 * WIDTHRADIU);
        }];
        
        if (self.type == SaveFromTypeBiCai) {
            lb_money.attributedText = [self attributedStrWithFaultCode:[NSString stringWithFormat:@"%.2f元",self.resultModel.amount.doubleValue]];
        }else{
            lb_money.attributedText = [self attributedStrWithFaultCode:[NSString stringWithFormat:@"%.2f元",self.amount.doubleValue]];
        }
        
    }
    return _topView;
}

- (UIView *)cardView
{
    if (!_cardView) {
        _cardView = [[UIView alloc]initWithFrame:CGRectMake(10 * WIDTHRADIU, self.topView.maxY - 50 * WIDTHRADIU, ScreenWidth - 20 * WIDTHRADIU, ScreenHeight - (self.topView.maxY - 50 * WIDTHRADIU))];
        _cardView.backgroundColor = [UIColor whiteColor];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_cardView.bounds
                                                                    byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight
                                                                          cornerRadii:CGSizeMake(12, 12)];
       CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
       maskLayer.frame = _cardView.bounds;
       maskLayer.path = maskPath.CGPath;
       _cardView.layer.mask = maskLayer;
        
       BuySuccessCardView*infoView = [self getXiblWithClassName:@"BuySuccessCardView"];
        [infoView.checkBtn addTarget:self action:@selector(checkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [infoView.confirmBtn addTarget:self action:@selector(confirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
       [_cardView addSubview:infoView];
        [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.offset(0);
            make.height.mas_greaterThanOrEqualTo(50);
        }];
        
        if (self.type == SaveFromTypeBiCai) {
            infoView.lb_time.text = self.resultModel.buyResult.revenueDate;
        }else{
            infoView.lb_time.text = [self getNewStyleWithDateStr:self.detailModel.BEG_INT];
        }
        
        
        
    }
    return _cardView;
}

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