//
//  UPViewController.m
//  UPPayDemo
//
//  Created by szwang on 16-03-30.
//  Copyright (c) 2016年 China UnionPay. All rights reserved.
//

#import "UPViewController.h"
#import "UPPaymentControl.h"


#define kVCTitle                @"商户测试"
#define kBtnFirstTitle          @"获取订单，开始测试"
#define kWaiting                @"正在获取TN,请稍后..."
#define kNote                   @"提示"
#define kConfirm                @"确定"
#define kErrorNet               @"网络错误"
#define kResult                 @"支付结果：%@"

#define KBtn_width              160
#define KBtn_height             40
#define KXOffSet                (self.view.frame.size.width - KBtn_width) / 2
#define KYOffSet                120
#define kWithNavigation         44
#define kCellHeight_Normal      50
#define kCellHeight_Manual      145

//商户需要换用自己的mertchantID
#define kAppleMerchantID        @"merchant.com.am.gu"

//生产环境:固定为一分钱订单         mode=00
#define kURL_TN_Product         @"http://101.231.114.216:1725/sim/getacptn"

//测试环境:不会产生真实交易         mode=01
#define kURL_TN_ATest           @"http://101.231.204.84:8091/sim/getacptn"
#define kURL_TN_UTest           @"http://101.231.204.84:8091/sim/getacptn"


@interface UPViewController ()
{
    UIAlertView*                _alertView;
    NSMutableData*              _responseData;
    CGFloat                     _maxWidth;
    CGFloat                     _maxHeight;
    UITableView*                _tableView;
    UITextField*                _tnField;
    UITextField*                _modeField;
}

@property(nonatomic, copy)NSString *tnMode;
@property BOOL isApplePay;

- (void)extendedLayout;
- (void)showAlertWait;
- (void)showAlertMessage:(NSString*)msg;
- (void)hideAlert;
- (void)startNetWithURL:(NSURL *)url;

@end

@implementation UPViewController
@synthesize tnMode;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = kVCTitle;
    [self extendedLayout];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _maxWidth, _maxHeight)];
    [self.view addSubview:_tableView];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
}


- (void)startNetWithURL:(NSURL *)url
{
    [self showAlertWait];
    NSMutableURLRequest *request;
    request=[[NSMutableURLRequest alloc]initWithURL:url
                                        cachePolicy:0
                                    timeoutInterval:60.0f];
    [NSURLConnection        sendAsynchronousRequest:request
                                              queue:[NSOperationQueue mainQueue]
                                  completionHandler:^(NSURLResponse *response,
                                                      NSData *data,
                                                      NSError *connectionError) {
                                      
       if(connectionError){
            NSLog(@"请求错误%@",connectionError);
        }
                                  
       else {
             [self hideAlert];
             NSString* tn = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             if (tn != nil && tn.length > 0)
             {
//                 //iOS9.2以上系统
//                BOOL supportApplePay = [PKPaymentAuthorizationViewController
//                                         canMakePaymentsUsingNetworks:@[PKPaymentNetworkChinaUnionPay]];
//
//
//                NSString *currentSystemVersion = [[UIDevice currentDevice] systemVersion];
//                BOOL versionResult = [currentSystemVersion compare:@"9.2"] != NSOrderedAscending;
//               if(self.isApplePay && versionResult) {
//
//                   //Apple Pay
//                   if(supportApplePay){
//                       [UPAPayPlugin startPay:tn
//                                         mode:self.tnMode
//                               viewController:self
//                                     delegate:self
//                               andAPMechantID:kAppleMerchantID];
//                    }
//
//                   else{
//                       [self showAlertMessage:@"设备或系统不支持"];
//
//                   }
//
//               }
           
//               else if (self.isApplePay && versionResult == NO){
//                    [self showAlertMessage:@"设备或系统不支持"];
//               }
                 
//               else {
                    //unionpay
                    [[UPPaymentControl defaultControl] startPay:tn
                                                     fromScheme:@"controldemo"
                                                           mode:self.tnMode
                                                 viewController:self];
                    }
//              }
         }
    }];
}

- (void)extendedLayout
{
    BOOL iOS7 = [UIDevice currentDevice].systemVersion.floatValue >= 7.0;
    if (iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    CGFloat offset = iOS7 ? 64 : 44;
    _maxWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
    _maxHeight = CGRectGetHeight([UIScreen mainScreen].bounds)-offset;
    self.navigationController.navigationBar.translucent = NO;
}

#pragma UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return (section==2)?1:2;
    
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString* title;
    switch (section) {
        case 0:
            title = @"Apple Pay";
            break;
        case 1:
            title = @"银联支付";
            break;
        case 2:
            title = @"校验时使用";
            break;
        default:
            break;
    }
    
    return title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = kCellHeight_Normal;
    if (indexPath.section==2) {
        height = kCellHeight_Manual;
    }
    return  height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.isApplePay = (indexPath.section==0)?YES:NO;
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    self.tnMode = @"00";
                    [self startNetWithURL:[NSURL URLWithString:kURL_TN_Product]];
                    [tableView deselectRowAtIndexPath:indexPath animated:YES];
                    break;
                    
                case 1:
                    self.tnMode = @"01";
                    [self startNetWithURL:[NSURL URLWithString:kURL_TN_ATest]];
                    [tableView deselectRowAtIndexPath:indexPath animated:YES];
                    break;
                    
                default:
                    break;
            }
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                    self.tnMode = @"00";
                    [self startNetWithURL:[NSURL URLWithString:kURL_TN_Product]];
                    [tableView deselectRowAtIndexPath:indexPath animated:YES];
                    break;
                    
                case 1:
                    self.tnMode = @"01";
                    [self startNetWithURL:[NSURL URLWithString:kURL_TN_UTest]];
                    [tableView deselectRowAtIndexPath:indexPath animated:YES];
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
    
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                {
                    cell.textLabel.text = @"ApplePay-生产环境";
                    cell.detailTextLabel.text = @"mode=00";
                }
                    break;
                    
                case 1:
                {
                    cell.textLabel.text = @"ApplePay-测试环境";
                    cell.detailTextLabel.text = @"mode=01";
                }
                    break;
                default:
                    break;
            }
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                {
                    cell.textLabel.text = @"银联支付-生产环境";
                    cell.detailTextLabel.text = @"mode=00";
                }
                    break;
                case 1:
                {
                    cell.textLabel.text = @"银联支付-测试环境";
                    cell.detailTextLabel.text = @"mode=01";
                }
                    break;
                default:
                    break;
            }
            break;
            
        case 2:
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            
            CGRect urlFrame = CGRectMake(10, 10, CGRectGetWidth(tableView.frame)-20, 35);
            _tnField = [self textFieldWithFrame:urlFrame placeHolder:@"TN"];
            _tnField.tag = 11;
            [cell.contentView addSubview:_tnField];
            
            CGRect modeFrame = CGRectMake(10, 55, CGRectGetWidth(tableView.frame)-20, 35);
            _modeField = [self textFieldWithFrame:modeFrame placeHolder:@"mode"];
            _modeField.tag = 12;
            [cell.contentView addSubview:_modeField];
            
            CGRect AFrame = CGRectMake(CGRectGetWidth(tableView.frame)/4-60, 100,120, 35);
            UIButton *Abutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            Abutton.frame = AFrame;
            Abutton.tag = 111;
            [Abutton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [Abutton setTitle:@"Apple Pay" forState:UIControlStateNormal];
            [cell.contentView addSubview:Abutton];
            
            CGRect BFrame = CGRectMake(CGRectGetWidth(tableView.frame)*0.75-60, 100,120, 35);
            UIButton *Bbutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            Bbutton.frame = BFrame;
            Bbutton.tag = 222;
            [Bbutton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [Bbutton setTitle:@"Union Pay" forState:UIControlStateNormal];
            [cell.contentView addSubview:Bbutton];
            
            CGRect rect = CGRectMake(CGRectGetWidth(tableView.frame)/2, 100, 5, 35);
            UILabel *label = [[UILabel alloc] initWithFrame:rect];
            label.text = @"|";
            label.font = [UIFont systemFontOfSize:25];
            [cell.contentView addSubview:label];
        }
            break;
        default:
            break;
    }
    
    return cell;
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _tableView.frame = CGRectMake(0, -_maxHeight/2, _maxWidth, _maxHeight);
}

- (UITextField *)textFieldWithFrame:(CGRect)frame placeHolder:(NSString *)placeHolder
{
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    textField.placeholder = placeHolder;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.backgroundColor = [UIColor clearColor];
    textField.delegate = self;
    return textField;
}


//处理键盘return键事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    _tableView.frame = CGRectMake(0, 0, _maxWidth, _maxHeight);
    [textField resignFirstResponder];
    return YES;
}
//处理输入完毕事件
- (void)textFieldDidEndEditing:(UITextField *)textField{
    _tableView.frame = CGRectMake(0, 0, _maxWidth, _maxHeight);
    [textField resignFirstResponder];
}

-(BOOL)validateTN:(NSString* )tn
{
    NSString *Regex = @"^[0-9]{21}$";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    return [test evaluateWithObject:tn];
}

-(BOOL)validateMode:(NSString* )mode
{
    NSString *Regex = @"^[0-1]{2}$";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    return [test evaluateWithObject:mode];
}
- (void)buttonAction:(id)sender
{
    if ([self validateTN:_tnField.text]&&[self validateMode:_modeField.text]) {
        if ([sender tag]==111) {
//            [UPAPayPlugin startPay:_tnField.text
//                              mode:_modeField.text
//                    viewController:self
//                          delegate:self
//                    andAPMechantID:kAppleMerchantID];
        }
        
        else{
            [[UPPaymentControl defaultControl] startPay:_tnField.text
                                             fromScheme:@"controldemo"
                                                   mode:_modeField.text
                                         viewController:self];
        }
    }
    else{
        [self showAlertMessage:@"tn或mode输入有误"];
    }
}


//#pragma mark 响应Apple Pay返回的支付结果
//- (void)UPAPayPluginResult:(UPPayResult *)result
//{
//    if(result.paymentResultStatus == UPPaymentResultStatusSuccess) {
//        NSString *otherInfo = result.otherInfo?result.otherInfo:@"";
//        NSString *successInfo = [NSString stringWithFormat:@"支付成功\n%@",otherInfo];
//        [self showAlertMessage:successInfo];
//    }
//    else if(result.paymentResultStatus == UPPaymentResultStatusCancel){
//
//        [self showAlertMessage:@"支付取消"];
//    }
//    else if (result.paymentResultStatus == UPPaymentResultStatusFailure) {
//
//        NSString *errorInfo = [NSString stringWithFormat:@"%@",result.errorDescription];
//        [self showAlertMessage:errorInfo];
//    }
//    else if (result.paymentResultStatus == UPPaymentResultStatusUnknownCancel)  {
//
//        //TODO UPPAymentResultStatusUnknowCancel表示发起支付以后用户取消，导致支付状态不确认，需要查询商户后台确认真实的支付结果
//        NSString *errorInfo = [NSString stringWithFormat:@"支付过程中用户取消了，请查询后台确认订单"];
//        [self showAlertMessage:errorInfo];
//
//    }
//}


#pragma mark - Alert

- (void)showAlertWait
{
    [self hideAlert];
    _alertView = [[UIAlertView alloc] initWithTitle:kWaiting message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [_alertView show];
    UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    aiv.center = CGPointMake(_alertView.frame.size.width / 2.0f - 15, _alertView.frame.size.height / 2.0f + 10 );
    [aiv startAnimating];
    [_alertView addSubview:aiv];
}

- (void)showAlertMessage:(NSString*)msg
{
    [self hideAlert];
    _alertView = [[UIAlertView alloc] initWithTitle:kNote message:msg delegate:self cancelButtonTitle:kConfirm otherButtonTitles:nil, nil];
    [_alertView show];
}

- (void)hideAlert
{
    if (_alertView != nil)
    {
        [_alertView dismissWithClickedButtonIndex:0 animated:NO];
        _alertView = nil;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    _alertView = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
