//
//  XFBPayListViewController.m
//  XFBPayDemo
//
//  Created by chenwei on 15/11/17.
//  Copyright © 2015年 chenwei. All rights reserved.
//

#import "XFBPayListViewController.h"
#import "XFBPayModel.h"
#import "XFBPayApi.h"

#import "XFBPayWebViewController.h"

@interface XFBPayListViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *payMethodArray;
@property (nonatomic, assign) BOOL showOrderStatu;

@property (nonatomic, strong) XFBPayModel *payModel;
//@property (nonatomic, strong) NSString *tradeNo;

@end

@implementation XFBPayListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"支付订单";
    
    [self setupUI];
//    [[XFBPayApi defaultService] setDebugMode:YES];
    // Do any additional setup after loading the view.
}

- (void)setupUI
{
    [self.view addSubview:self.tableView];
    
    CGFloat screen_Width = [UIScreen mainScreen].bounds.size.width;
    
    //headerView
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screen_Width, 90)];
    headerView.backgroundColor = [UIColor whiteColor];
    _tableView.tableHeaderView = headerView;
    
    UILabel *orderNameLabel = [self createLabelWithFrame:CGRectMake(10, 10, screen_Width-2*10, 30)];
    UILabel *orderMoneyLabel = [self createLabelWithFrame:CGRectMake(10, 10+30+5, screen_Width-2*10, 30)];
    [headerView addSubview:orderNameLabel];
    [headerView addSubview:orderMoneyLabel];
    
    orderNameLabel.text = @"订单名称: 测试信息";
    if (self.money.length == 0) {
        self.money = @"0.01";
    }
    orderMoneyLabel.text = [NSString stringWithFormat:@"订单金额: ¥%@",self.money];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.showOrderStatu) {
        [self showOrderStatus];
    }
}


- (UILabel *)createLabelWithFrame:(CGRect)frame
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.textColor = [UIColor darkTextColor];
    label.font = [UIFont systemFontOfSize:16];
    return label;
}




- (void)showOrderStatus
{
    self.showOrderStatu = NO;
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"支付是否完成" delegate:self cancelButtonTitle:@"支付出现问题" otherButtonTitles:@"支付完成", nil];
    [alertView show];
}


- (NSString *)username
{
    NSString *user = [[NSUserDefaults standardUserDefaults] objectForKey:@"xfbpay"];
    if (user == nil) {
        user = [self generateTradeNO];
        [[NSUserDefaults standardUserDefaults] setValue:user forKey:@"xfbpay"];
    }
    return user;
}


- (void)inqurey
{
    if (self.payModel == nil) {
        return;
    }
    
    NSDictionary *dict = [[XFBPayApi defaultService] inquiryWithPayModel:self.payModel];
    if ([dict[@"tradestate"] isEqualToString:@"wait"]) {
        NSLog(@"等待支付 ");
        [self showInfo:@"等待支付 "];
    }
    else if ([dict[@"tradestate"] isEqualToString:@"completed"]) {
        NSLog(@"交易完成");
        [self showInfo:@"交易完成 "];
        
    } else {
        [self showInfo:dict[@"msg"]];

    }
    
    [[XFBPayApi defaultService] inquiryWithPayModel:self.payModel complete:^(NSString *status, NSString *response) {
       
        if ([status isEqualToString:XFBSuccessFalg]) {
            [self showInfo:@"支付成功"];
        } else {
            //一种就是网络网络请求失败（无网络，以及服务器异常以及其他原因） 一种就是请求成功，跳转微信
            if ([response isEqualToString:XFBURLErrorNotConnectedToInternet]) {
                [self showInfo:@"网络连接失败"];
                
            } else if ([response isEqualToString:XFBURLErrorUnknown]) {
                [self showInfo:@"网络请求失败"];
                
            } else {
                NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"失败原因--%@",dict);
                [self showInfo:dict[@"msg"]];
                
            }
            
        }
        
    }];

}


- (void)showInfo:(NSString *)message
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, (height-50)/2, width-2*50, 50)];
    
    label.backgroundColor = [UIColor grayColor];
    label.textColor = [UIColor whiteColor];
    label.text = message;
    label.textAlignment = NSTextAlignmentCenter;
    label.clipsToBounds = YES;
    label.adjustsFontSizeToFitWidth = YES;
    label.minimumScaleFactor = 0.6;
    label.layer.cornerRadius = 7;
    [[UIApplication sharedApplication].keyWindow addSubview:label];

    [UIView animateWithDuration:0.25 delay:4 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        label.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [label removeFromSuperview];
    }];
}


//==============================================================================================
#pragma mark - TableViewDataSource
//==============================================================================================
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"支付宝";
        cell.imageView.image = [UIImage imageNamed:@"pay_zfb"];
    } else if (indexPath.row == 1) {
        cell.textLabel.text = @"微信支付";
        cell.imageView.image = [UIImage imageNamed:@"pay_weixin"];
        
    } else if (indexPath.row == 2) {
        cell.textLabel.text = @"快捷支付";
        cell.imageView.image = [UIImage imageNamed:@"pay_zfb"];
        
    }  else {
        cell.textLabel.text = @"支付宝网页支付";
        cell.imageView.image = [UIImage imageNamed:@"pay_zfb"];
        
    }
    
    return cell;
}


//==============================================================================================
#pragma mark - TableViewDelegate
//==============================================================================================
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
 
    if (indexPath.row == 0) {
        [self alipayAction];
    }
    
    if (indexPath.row == 1) {
        [self weixinAction];
    }
    
    
    if (indexPath.row == 2) {
        [self kjzfAction];
    }
    
    if (indexPath.row == 3) {
        [self alipayWebViewAction];
    }
    
}


- (void)alipayAction
{
    self.payModel = [self currentPayModelWithType:@"zfbapp"];
#warning 支付宝需要配置URL Scheme
    [[XFBPayApi defaultService] doPayAction:self.payModel appURLScheme:@"alipayDemo" withCompletion:^(NSString *status, NSString *result) {

        if ([status isEqualToString:XFBSuccessFalg]) {
            [self showInfo:@"支付成功"];
        } else {
            
            //一种就是网络网络请求失败（无网络，以及服务器异常以及其他原因） 一种就是请求成功，跳转微信
            if ([result isEqualToString:XFBURLErrorNotConnectedToInternet]) {
                [self showInfo:@"网络连接失败"];
                
            } else if ([result isEqualToString:XFBURLErrorUnknown]) {
                [self showInfo:@"网络请求失败"];
                
            }  else if ([result isEqualToString:XFBErrorCancelled]) {
                [self showInfo:@"用户取消"];
                
            }  else if ([result isEqualToString:XFBErrorPayProcess]) {
                [self showInfo:@"订单正在处理中"];
                
            }  else if ([result isEqualToString:XFBErrorPayFail]) {
                [self showInfo:@"订单支付失败"];
            }
            
            else {
                NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"失败原因--%@",dict);
                [self showInfo:dict[@"msg"]];
                
            }
        }
        
    }];
}

- (void)weixinAction
{
    self.payModel = [self currentPayModelWithType:@"wxapp"];
    [[XFBPayApi defaultService] doPayAction:self.payModel appURLScheme:@"" withCompletion:^(NSString *status, NSString *result) {
        
        
        if ([status isEqualToString:XFBSuccessFalg]) {
            [self showInfo:@"支付成功"];
        } else {
            
            //一种就是网络网络请求失败（无网络，以及服务器异常以及其他原因） 一种就是请求成功，跳转微信
            if ([result isEqualToString:XFBURLErrorNotConnectedToInternet]) {
                [self showInfo:@"网络连接失败"];
                
            } else if ([result isEqualToString:XFBURLErrorUnknown]) {
                [self showInfo:@"网络请求失败"];
                
            } else if ([result isEqualToString:XFBErrorWxNotInstalled]) {
                [self showInfo:@"微信未安装"];

            } else if ([result isEqualToString:XFBErrorWxAppNotSupported]) {
                [self showInfo:@"微信不支持"];
                
            } else if ([result isEqualToString:XFBErrorCancelled]) {
                [self showInfo:@"用户取消"];

            }  else if ([result isEqualToString:XFBErrorPayUnknown]) {
                [self showInfo:@"微信其他错误"];
                
            } else {
                NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"失败原因--%@",dict);
                [self showInfo:dict[@"msg"]];

            }
            
            
        }
        
        
        
        
    }];
    
}


// 这两种比较相似
- (void)kjzfAction
{
    self.payModel = [self currentPayModelWithType:@"kjzf"];
    [[XFBPayApi defaultService] doPayAction:self.payModel appURLScheme:@"" withCompletion:^(NSString *status, NSString *result) {
        
        //成功
        if ([status isEqualToString:XFBSuccessFalg]) {
            self.showOrderStatu = YES;
            XFBPayWebViewController *payVC = [[XFBPayWebViewController alloc] init];
            NSString *encodedString = [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            payVC.url = encodedString;
            [self.navigationController pushViewController:payVC animated:YES];
        } else {
           //失败
           //一种就是网络网络请求失败（无网络，以及服务器异常以及其他原因） 一种就是请求成功，这个可以直接去msg
            if ([result isEqualToString:XFBURLErrorNotConnectedToInternet]) {
                [self showInfo:@"网络连接失败"];

            } else if ([result isEqualToString:XFBURLErrorUnknown]) {
                [self showInfo:@"网络请求失败"];

            } else {
                NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"失败原因--%@",dict);
                [self showInfo:dict[@"msg"]];

            }
            
        }
    
        
    }];
}

- (void)alipayWebViewAction
{
    self.payModel = [self currentPayModelWithType:@"zfb-mobilewap"];
    [[XFBPayApi defaultService] doPayAction:self.payModel appURLScheme:@"" withCompletion:^(NSString *status, NSString *result) {
        
        //成功
        if ([status isEqualToString:XFBSuccessFalg]) {
            self.showOrderStatu = YES;
            XFBPayWebViewController *payVC = [[XFBPayWebViewController alloc] init];
            payVC.url = result;
            [self.navigationController pushViewController:payVC animated:YES];
        } else {
            //失败
            //一种就是网络网络请求失败（无网络，以及服务器异常以及其他原因） 一种就是请求成功，这个可以直接去msg
            if ([result isEqualToString:XFBURLErrorNotConnectedToInternet]) {
                [self showInfo:@"网络连接失败"];
                
            } else if ([result isEqualToString:XFBURLErrorUnknown]) {
                [self showInfo:@"网络请求失败"];
                
            } else {
                NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"失败原因--%@",dict);
                [self showInfo:dict[@"msg"]];
                
            }
            
        }
        
        
    }];
}




- (XFBPayModel *)currentPayModelWithType:(NSString *)type
{
    XFBPayModel *object = [[XFBPayModel alloc] init];
#warning 添加支付信息
    object.merId = @"XXXXXXXXX";
    
    object.tradeNo = self.tradeNo;
    object.subject = @"测试";
    object.body = @"妹纸一枚";
    object.totalfee = self.money;
    object.paymethod = type;
    object.notifyUrl = @"http://www.xiangfubao.com.cn";
#warning 添加支付信息
    object.paykey = @"XXXXXXXXX";
    
    object.returnUrl = @"http://www.xiangfubao.com.cn";

    object.userId = @"199212224512";
    return object;
}


- (NSString *)generateTradeNO
{
    NSString *resultStr1 = [NSString stringWithFormat:@"%ld",time(NULL)];
    return resultStr1;
    
    static int kNumber = 20;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIGLKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = arc4random() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}



//==============================================================================================
#pragma mark - AlertViewDelegate
//==============================================================================================
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self inqurey];
    }
}



//==============================================================================================
#pragma mark - GetUI
//==============================================================================================
- (UITableView *)tableView
{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        
    }
    return _tableView;
}


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

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