//
//  ProductPurchaseController.m
//  Open
//
//  Created by 雷俊博 on 2020/7/30.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "ProductPurchaseController.h"
#import "ProductPurchaseTopView.h"
#import "ProductPurchaseValueView.h"
#import "ProductPurchasePayWayView.h"
#import "ProductPurchaseFuliView.h"
#import "ProductPurchaseBottomView.h"
#import "ProductRechargeController.h"
#import "SaveAccountCardInfo.h"

#import "AgreementPresentView.h"


#import "SMSVerificationController.h"

#import "UIImageView+WebCache.h"
#import "BCNewActivitySheetView.h"
#import "BCNewActivityCriterionModel.h"

@interface ProductPurchaseController ()<UITextFieldDelegate>


@property (nonatomic, strong)UIScrollView* scrollView;

@property (nonatomic, strong)ProductPurchaseTopView* topView;

@property (nonatomic, strong)ProductPurchaseValueView* valueView;

@property (nonatomic, strong)ProductPurchasePayWayView* payView;

@property (nonatomic, strong)ProductPurchaseFuliView* fuliView;

@property (nonatomic, strong)ProductPurchaseBottomView* bottomView;

@property (nonatomic, assign)BOOL textIsEmpty;

@property (nonatomic, strong) SaveAccountCardInfo* cardModel;

@property (nonatomic, strong)NSArray* agreementArray;

@property (nonatomic, strong)BCNewActivityCriterionModel* fuliModel;



@end

@implementation ProductPurchaseController
- (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_wudangProductPurchaseCount" withArgs:@{}];//个推统计
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.scrollView];
    [self creatBottomView];
    
    
    //初始化
    self.textIsEmpty = YES;
    [self setButtonState];
    
    if (self.type == SaveFromTypeYinShu) {
        //检测产品购买
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshBalanceData) name:KKSBGETBalanceNotificationName object:nil];
        [self getPayAccountInfoRequest];
    }else if (self.type == SaveFromTypeBiCai) {
        [self getAllOPENAccountAgreementRequest];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(bcGetEleAccountInfoRequest) name:KKSBBCGETBalanceNotificationName object:nil];
    }
    
    
    if (self.showFuli) {
        [self getActivityCriterionRequest];
    }
    
}

- (void)creatBottomView
{
    ProductPurchaseBottomView* bottomView = [self getXiblWithClassName:@"ProductPurchaseBottomView"];
    bottomView.buyBtn.backgroundColor = [UIColor colorWithHex:0x137ef6];
    [bottomView.buyBtn addTarget:self action:@selector(buyClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView.xieyiBtn addTarget:self action:@selector(xieyiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView.checkBtn addTarget:self action:@selector(checkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.left.mas_equalTo(0);
      make.width.mas_equalTo(ScreenWidth);
      make.height.offset(148);
      make.bottom.mas_equalTo(0);
   }];
    self.bottomView = bottomView;
}
#pragma mark - 通知绑定方法
- (void)refreshBalanceData
{
    [self getPayAccountInfoRequest];
}

#pragma mark - 获取支付账户信息
- (void)getPayAccountInfoRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSGETAccountInfoRequest];
    
    SaveAccountSubUserInfoModel*infoModel = self.infoModel.SUBPACKS[0];
    
    NSDictionary*params = @{
        @"accNo": infoModel.CARDNBR
    };
    
    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.cardModel = [SaveAccountCardInfo mj_objectWithKeyValues:dic];
            [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) {
       [KKLoadingAnimationView dismiss];
       NSLog(@"error:%@",error);
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}



#pragma mark - 刷新数据
- (void)refreshPayViewData
{
    self.payView.lb_bankName.text = [NSString stringWithFormat:@"乌当农商银行电子账户(%@)",[self.cardModel.CARDNBR substringFromIndex:self.cardModel.CARDNBR.length - 4]];
    self.payView.lb_amount.attributedText = [self attributedStrWithFaultCode:self.cardModel.AVAIL_BAL];
}

#pragma mark - 比财刷新数据
- (void)refreshBCPayViewData
{
    self.payView.lb_amount.attributedText = [self attributedStrWithFaultCode:self.bcInfoModel.balance];
}



#pragma mark - 比财产品购买协议
- (void)getAllOPENAccountAgreementRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCQueryPurchaseAgreementsRequest];
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:self.bcInfoModel.orgId forKey:@"orgId"];
    [params setObject:@(self.bcProInfoModel.productId) forKey:@"prdIndexId"];
    
    NSLog(@"比财购买协议url:%@",url);
    NSLog(@"params:%@",params);
    
    
    [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.agreementArray = [BCSubModel mj_objectArrayWithKeyValuesArray:objc[@"result"][@"agreementList"]];
            
            
            
            
        }else{
            [self alertShow:describe];
        }

    } Failure:^(NSError* error) {
        
        NSLog(@"error:%@",error);
        
        [Tools showMessage:@"网络出小差了,请稍后重试"];
        
    }];
}




#pragma mark - 比财 充值校验
- (void)checkBCRechargeRequest{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCCheckRechargeRequest];
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:self.bcInfoModel.orgId forKey:@"orgId"];
    
    NSLog(@"比财充值校验url:%@",url);
    NSLog(@"params:%@",params);
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            
            
            ProductRechargeController*vc = [ProductRechargeController new];
            vc.title = @"充值";
            vc.hidesBottomBarWhenPushed = YES;
            vc.bcInfoModel = self.bcInfoModel;
            vc.type = self.type;
            [self.navigationController pushViewController:vc animated:YES];
            return;
            
            
        }else{
            
            NSString* code = [NSString stringWithFormat:@"%@",objc[@"result"][@"code"]];
            if ([code isEqualToString:@"Y00010"]) {
               // [self alertShow:[NSString stringWithFormat:@"%@暂不支持在线充值，请使用手机银行APP、网银或银行网点进行转账。",self.bcProInfoModel.orgName]];
                [self doNotSupportChargeAlerShow:[NSString stringWithFormat:@"%@暂不支持在线充值,请复制%@卡号，并使用其绑定的银行卡进行转账",self.bcProInfoModel.orgName,self.bcProInfoModel.orgName]];
            }else{
                [self alertShow:describe];
            }
            
            
            
            
        }

    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        
        NSLog(@"error:%@",error);
        [self alertShow:@"网络出小差了,请稍后重试"];
        
    }];
}

#pragma mark - 比财 电子账户信息详情
- (void)bcGetEleAccountInfoRequest {
    
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCGETAccountInfoRequest];
    NSLog(@"比财电子账户详情url:%@",url);
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:self.bcInfoModel.orgId forKey:@"orgId"];
    
    
    NSLog(@"params:%@",params);
    
    [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"]) {
           
            BCAccountInfoModel* model = [BCAccountInfoModel mj_objectWithKeyValues:objc[@"result"]];
            
            self.bcInfoModel = model;
            
            [self refreshBCPayViewData];
            
        } else{
            [self alertShow:describe];
        }
        
    } Failure:^(NSError* error) {
       
        NSLog(@"error:%@",error);
        
        [self alertShow:@"网络出小差了,请稍后重试"];
        
    }];
    
}

#pragma mark - 我的福利
- (void)getActivityCriterionRequest {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],SaveActivityCriterionRequest];
    NSDictionary* params = @{
        @"userId":@([getPeopleID PeopleID])
    };
    
    NSLog(@"存钱罐福利url:%@",url);
    NSLog(@"params:%@",params);
    
    [NetworkRequest Post:url Params:params Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
        
        NSString*state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        
        if ([state isEqualToString:@"200"]) {
            BCNewActivityCriterionModel* model = [BCNewActivityCriterionModel mj_objectWithKeyValues:objc[@"result"]];
            
            self.fuliModel = model;
            
            for (BCNewActivityCriterionSubModel* subModel in self.fuliModel.criterion) {
                if ([subModel.status isEqualToString:@"1"]) {
                    self.fuliView.lb_message.text = [NSString stringWithFormat:@"存满15天送%@元",subModel.aWardInfo];
                }
            }
            self.fuliView.hidden = NO;
            
        }
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
    
    
}



#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSMutableString * changedString=[[NSMutableString alloc] initWithString:textField.text];
    [changedString replaceCharactersInRange:range withString:string];
  
    NSString * str = [NSString stringWithFormat:@"%@%@",textField.text,string];
    //匹配以0开头的数字
    NSPredicate * predicate0 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^[0][0-9]+$"];
    //匹配两位小数、整数
    NSPredicate * predicate1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"(\\+|\\-)?(([0]|(0[.]\\d{0,3}))|([1-9]\\d{0,7}(([.]\\d{0,0})?)))?"];
    BOOL sucess = ![predicate0 evaluateWithObject:str] && [predicate1 evaluateWithObject:str] &&[self validateNumber:string] ? YES : NO;
    
    
    
    if (textField.text.length == 0) {
         self.textIsEmpty = YES;
     }else{
         self.textIsEmpty = NO;
     }

    // 实时监测文本框的编辑状态
     [self setButtonState];
    
    return sucess;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    if (textField.text.length == 0) {
         self.textIsEmpty = YES;
     }else{
         self.textIsEmpty = NO;
     }

    // 实时监测文本框的编辑状态
     [self setButtonState];
    
    return YES;
}


- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

#pragma mark - 刷新按钮状态
- (void)setButtonState {
    
    
    
    
    if (self.textIsEmpty == NO) {
        
        BOOL isFit = NO;
        if (self.fuliModel.criterion.count > 0) {
            NSString* value = self.valueView.tf_count.text;
            if (value.intValue < 5000) {
                for (BCNewActivityCriterionSubModel* subModel in self.fuliModel.criterion) {
                    if ((subModel.minAmount.intValue <= value.intValue) && (subModel.maxAmount.intValue > value.intValue) ) {
                        self.fuliView.lb_message.text = [NSString stringWithFormat:@"存满15天送%@元",subModel.aWardInfo];
                        isFit = YES;
                        break;
                    }
                }
            }else{
                
                BCNewActivityCriterionSubModel* subModel = self.fuliModel.criterion.lastObject;
                self.fuliView.lb_message.text = [NSString stringWithFormat:@"存满15天送%@元",subModel.aWardInfo];
                isFit = YES;
            }
           
        }
        
        if (isFit == NO) {
            self.fuliView.lb_message.text = @"最高送100元";
        }
        
        self.bottomView.buyBtn.userInteractionEnabled = YES;
        self.bottomView.buyBtn.alpha = 1;
    } else {
        self.bottomView.buyBtn.userInteractionEnabled = NO;
        self.bottomView.buyBtn.alpha = 0.5;
    }
}

- (void)setXieYiButtonState
{
    if (self.bottomView.xieyiBtn.selected) {
        [self.bottomView.xieyiBtn setImage:[UIImage imageNamed:@"xieyi_selected"] forState:UIControlStateNormal];
    }else{
        [self.bottomView.xieyiBtn setImage:[UIImage imageNamed:@"xieyi_unselected"] forState:UIControlStateNormal];
    }
}

#pragma mark - private methods
- (NSAttributedString *) attributedStrWithFaultCode:(NSString *)faultCode {
    
    NSString* text = [NSString stringWithFormat:@"账户余额%.2lf元",faultCode.doubleValue];
    NSMutableAttributedString * faultCode_ = [[NSMutableAttributedString alloc] initWithString:text];
    
    
    NSDictionary * faultCodeAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithHex:0x137ef6]};
    [faultCode_ setAttributes:faultCodeAttributes range:NSMakeRange(4,text.length - 5)];
    

    return faultCode_;
}

#pragma mark - event response
- (void)buyClick:(UIButton *)sender
{
    
    
    if (self.type == SaveFromTypeYinShu) {
        if (self.cardModel == nil) {
            [self alertShow:@"网络加载失败,请退出重进!"];
            return;
        }
        
        if (self.bottomView.xieyiBtn.selected == NO) {
            [Tools showMessage:@"请勾选相关协议"];
            return;
        }
        
        if ((self.valueView.tf_count.text.intValue > self.cardModel.AVAIL_BAL.intValue) || (self.cardModel.AVAIL_BAL.intValue <= 0)) {
            [self rechargeAlerShow];
            return;
        }
        
        if (self.valueView.tf_count.text.doubleValue <= 0) {
            [self alertShow:@"起购金额不能为0"];
            return;
        }
        
        if (self.valueView.tf_count.text.doubleValue < self.model.MIN_AMT.doubleValue) {
            [self alertShow:[NSString stringWithFormat:@"购买金额不得少于%@元",self.model.MIN_AMT]];
            return;
        }
        
        
        int dValue = self.valueView.tf_count.text.intValue -  self.model.MIN_AMT.intValue;
        
        int mValue = dValue % self.model.UNI_AMT.intValue;
        
        if (mValue != 0) {
            [self alertShow:[NSString stringWithFormat:@"起购金额为%@,递增金额必须是%@的倍数",self.model.MIN_AMT,self.model.UNI_AMT]];
            return;
        }
        [GTCountSDK trackCountEvent:@"save_productBuySMSCount" withArgs:nil];
        SMSVerificationController*vc = [SMSVerificationController new];
        vc.title = @"产品购买短信验证";
        vc.infoModel = self.infoModel;
        vc.productModel = self.model;
        vc.amount = self.valueView.tf_count.text;
        vc.type = SMSSendTypeProPurchase;
        
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }else if (self.type == SaveFromTypeBiCai) {
     
        
        if (self.bottomView.xieyiBtn.selected == NO) {
            [Tools showMessage:@"请勾选相关协议"];
            return;
        }
        
        if ((self.valueView.tf_count.text.intValue > self.bcInfoModel.balance.intValue) || (self.bcInfoModel.balance.intValue <= 0)) {
            [self rechargeAlerShow];
            return;
        }
        
        if (self.valueView.tf_count.text.doubleValue <= 0) {
            [self alertShow:@"起购金额不能为0"];
            return;
        }
        
        if (self.valueView.tf_count.text.doubleValue < self.bcProInfoModel.minPurchaseAmount.doubleValue) {
            [self alertShow:[NSString stringWithFormat:@"购买金额不得少于%@元",self.bcProInfoModel.minPurchaseAmount]];
            return;
        }
        
        
        int dValue = self.valueView.tf_count.text.intValue -  self.bcProInfoModel.minPurchaseAmount.intValue;
        
        int mValue = dValue % self.bcProInfoModel.increaseAmount.intValue;
        
        if (mValue != 0) {
            [self alertShow:[NSString stringWithFormat:@"起购金额为%@,递增金额必须是%@的倍数",self.bcProInfoModel.minPurchaseAmount,self.bcProInfoModel.increaseAmount]];
            return;
        }
        
        SMSVerificationController*vc = [SMSVerificationController new];
        vc.title = @"产品购买短信验证";
        vc.bcAccountInfoModel = self.bcInfoModel;
        vc.bcInfoModel = self.bcProInfoModel;
        vc.amount = self.valueView.tf_count.text;
        vc.type = SMSSendTypeBCProPurchase;
        
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
   
    
    
    
}

- (void)xieyiBtnClick:(UIButton *)sender
{

    sender.selected = !sender.selected;
    
    [self setXieYiButtonState];
}

- (void)buyAllBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeYinShu) {
        if (self.cardModel == nil) {
            [self alertShow:@"网络加载失败,请退出重进!"];
            return;
        }
        
        if (self.cardModel.AVAIL_BAL.doubleValue < self.model.MIN_AMT.doubleValue) {
            [self rechargeAlerShow];
           return;
       }
        
        self.valueView.tf_count.text = [NSString stringWithFormat:@"%d",self.cardModel.AVAIL_BAL.intValue];
        self.textIsEmpty = NO;
        [self setButtonState];
    }else if (self.type == SaveFromTypeBiCai) {
        if (self.bcInfoModel.balance.doubleValue < self.bcProInfoModel.minPurchaseAmount.doubleValue) {
            [self rechargeAlerShow];
           return;
       }
        
        self.valueView.tf_count.text = [NSString stringWithFormat:@"%d",self.bcInfoModel.balance.intValue];
        self.textIsEmpty = NO;
        [self setButtonState];
    }
    
    
}






- (void)checkBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeYinShu) {
        NSArray*array = @[
            @{
                @"name":[NSString stringWithFormat:@"贵州乌当农商银行\"%@\"存款产品协议",self.model.NOTE],
                @"url":[NSString stringWithFormat:@"http://nginx.weface.com.cn/agreement/ckxy.html?cp=%@&jf=%@",self.model.NOTE,self.infoModel.NAME]
            },@{
                @"name":@"贵州乌当农商银行电子账户协议",
                @"url":[NSString stringWithFormat:@"http://nginx.weface.com.cn/agreement/dzzh.html?jf=%@",self.infoModel.NAME]
            },@{
                @"name":@"贵州乌当农商银行账户委托扣款授权书",
                @"url":[NSString stringWithFormat:@"http://nginx.weface.com.cn/agreement/zhkk.html?name=%@&idcard=%@&time=%@",self.infoModel.NAME,self.infoModel.CUSTID,[self getCurrentDate]]
            },@{
                @"name":@"贵州乌当农商银行平台服务协议",
                @"url":@"http://nginx.weface.com.cn/agreement/kkshbank.html"
            },
        ];
        
        [AgreementPresentView showBankListWithVC:self type:AgreementPresentViewTypeWuDang bankArray:array block:^(id  _Nonnull model) {
            NSString* name = model[@"name"];
            NSString* url = model[@"url"];
            [self jumpToWebVCWithUrl:url title:name];
        }];
    }else if (self.type == SaveFromTypeBiCai) {
        
        if (!self.agreementArray) {
            [self getAllOPENAccountAgreementRequest];
        }else{
            [AgreementPresentView showBankListWithVC:self type:AgreementPresentViewTypeBiCai bankArray:self.agreementArray block:^(BCSubModel*  _Nonnull model) {
                NSString* name = model.agreementTitle;
                NSString* url = model.agreementUrl;
                [self jumpToWebVCWithUrl:url title:name];
            }];
        }
        
        
    }
    
 
}

- (void)rechargeBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeYinShu) {
        if (self.cardModel == nil) {
            [self alertShow:@"网络加载失败,请退出重进!"];
            return;
        }
        
        ProductRechargeController*vc = [ProductRechargeController new];
        vc.title = @"充值";
        vc.hidesBottomBarWhenPushed = YES;
        vc.infoModel = self.infoModel;
        vc.cardModel = self.cardModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (self.type == SaveFromTypeBiCai) {
        
        [self checkBCRechargeRequest];
    }
    
    
}

- (void)inputBtnClick:(UIButton *)sender {
    if (sender.tag == 200) {
        self.valueView.tf_count.text = @"500";
        
        self.fuliView.lb_message.text = @"存满15天送30元";
    }else if (sender.tag == 201) {
        self.valueView.tf_count.text = @"2000";
        self.fuliView.lb_message.text = @"存满15天送66元";
    }else if (sender.tag == 202) {
        self.valueView.tf_count.text = @"5000";
        self.fuliView.lb_message.text = @"存满15天送100元";
    }
    
    self.textIsEmpty = NO;
    
    [self setButtonState];
    
}

- (void)flBtnClick:(UIButton *)sender {
    
    if (self.fuliModel) {
        [BCNewActivitySheetView  showWithVC:self model:self.fuliModel block:^{
            
        }];
        return;
    }else{
        [self getActivityCriterionRequest];
    }
    
}


- (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 - 余额不足提示充值
- (void)rechargeAlerShow {
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的余额不足，请先充值" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"立即充值" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self rechargeBtnClick:nil];
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }
}

#pragma mark - 不支持在线充值提示
- (void)doNotSupportChargeAlerShow:(NSString*)message {
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           
        }];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"复制卡号" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIPasteboard *pab = [UIPasteboard generalPasteboard];
            pab.string = self.bcInfoModel.bankElecAccountNum;
            if (pab == nil) {
                [Tools showMessage:@"复制失败"];
            } else {
                [Tools showMessage:@"已复制"];
            }
        }];
        
        [alertV addAction:cancel];
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }
}

#pragma mark - 跳转web页面
- (void)jumpToWebVCWithUrl:(NSString *)url title:(NSString *)title
{
    if (self.type == SaveFromTypeYinShu) {
        
        url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
    }else if (self.type == SaveFromTypeBiCai) {
        
        NSArray* urlArray = [url componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"?"]];
        url = nil;
        
        for (int i = 0; i < urlArray.count; i++) {
            if (i == 0) {
                url = urlArray[0];
            }else{
                if (i == (urlArray.count - 1)) {
                    url = [url stringByAppendingFormat:@"?%@",[urlArray[i] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
                }else{
                    url = [NSString stringWithFormat:@"%@?%@",url,urlArray[i]];
                }
            }
        }
        
    }
    
    WebVC * vc = [WebVC new];
    vc.title= title;
    vc.url = url;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 当前日期
- (NSString *)getCurrentDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    formatter.dateFormat = @"yyyy年MM月dd日";
    
    NSTimeZone* zone = [NSTimeZone timeZoneWithName:@"Asia/beijing"];
    
    [formatter setTimeZone:zone];

    NSString *time = [formatter stringFromDate:[NSDate date]];


    return time;
}


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

#pragma mark - getters
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - cl_kTabBarHeight)];
        _scrollView.showsVerticalScrollIndicator = NO;
        //_scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(ScreenWidth, 0);
        _scrollView.backgroundColor  = [UIColor colorWithHex:0xf4f4f4];
        
        //银行信息
        ProductPurchaseTopView* topView = [self getXiblWithClassName:@"ProductPurchaseTopView"];
        [_scrollView addSubview:topView];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(0);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.mas_greaterThanOrEqualTo(50);
        }];
        self.topView = topView;
        
        //购买金额
        ProductPurchaseValueView* valueView = [self getXiblWithClassName:@"ProductPurchaseValueView"];
        valueView.tf_count.delegate = self;
        [valueView.btn1 addTarget:self action:@selector(inputBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [valueView.btn2 addTarget:self action:@selector(inputBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [valueView.btn3 addTarget:self action:@selector(inputBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [valueView.payBtn addTarget:self action:@selector(buyAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:valueView];
        [valueView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topView.mas_bottom).offset(0);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.mas_greaterThanOrEqualTo(50);
        }];
        
        self.valueView = valueView;
        //分割区
        UIView*lineView = [[UIView alloc]init];
        lineView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        [_scrollView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(valueView.mas_bottom).offset(0);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.offset(10);
        }];
        
        //支付方式
        ProductPurchasePayWayView* payView = [self getXiblWithClassName:@"ProductPurchasePayWayView"];
        [payView.rechargeBtn addTarget:self action:@selector(rechargeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:payView];
        
        if (!self.showFuli) {
            [payView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(lineView.mas_bottom).offset(0);
                make.left.mas_equalTo(0);
                make.width.mas_equalTo(ScreenWidth);
                make.height.mas_greaterThanOrEqualTo(50);
                make.bottom.mas_equalTo(0);
            }];
        }else{
            [payView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(lineView.mas_bottom).offset(0);
                make.left.mas_equalTo(0);
                make.width.mas_equalTo(ScreenWidth);
                make.height.mas_greaterThanOrEqualTo(50);
            }];
            
            
            ProductPurchaseFuliView* flView = [self getXiblWithClassName:@"ProductPurchaseFuliView"];
            [flView.checkBtn addTarget:self action:@selector(flBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            flView.hidden = YES;
            [_scrollView addSubview:flView];
            
            [flView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(payView.mas_bottom).offset(10);
                make.left.mas_equalTo(0);
                make.width.mas_equalTo(ScreenWidth);
                make.height.mas_greaterThanOrEqualTo(50);
                make.bottom.mas_equalTo(0);
            }];
            
            self.fuliView = flView;
            
        }
        
        self.payView = payView;
        
        
        //赋值
        if (self.type == SaveFromTypeYinShu) {
            topView.lb_bank.text = @"乌当农商银行|定期存款产品";
            valueView.lb_rate.text = [NSString stringWithFormat:@"%.2f%%",self.model.RATE.doubleValue];
            valueView.tf_count.placeholder = [NSString stringWithFormat:@"%@元起购,%@元递增",self.model.MIN_AMT,self.model.UNI_AMT];
        }else if (self.type == SaveFromTypeBiCai) {
            topView.lb_bank.text = [NSString stringWithFormat:@"%@|定期存款产品",self.bcInfoModel.orgName];
            valueView.lb_rate.text = [NSString stringWithFormat:@"%@%%",self.bcProInfoModel.interestRate];
            valueView.tf_count.placeholder = [NSString stringWithFormat:@"%@元起购,%@元递增",self.bcProInfoModel.minPurchaseAmount,self.bcProInfoModel.increaseAmount];;
            payView.lb_bankName.text = [NSString stringWithFormat:@"%@(%@)",self.bcInfoModel.orgName,[self.bcInfoModel.bankElecAccountNum substringFromIndex:self.bcInfoModel.bankElecAccountNum.length - 4]];
            payView.lb_amount.attributedText = [self attributedStrWithFaultCode:self.bcInfoModel.balance];
            [payView.icon sd_setImageWithURL:[NSURL URLWithString:self.bcInfoModel.orgLogo]];
        }
        
        
        
        
        //_scrollView.contentSize = CGSizeMake(ScreenWidth, topView.maxY + 10);
    }
    return _scrollView;
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:KKSBGETBalanceNotificationName object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:KKSBBCGETBalanceNotificationName object:nil];
}
/*
#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
