ExchangeViewController.m 12.5 KB
//
//  ExchangeViewController.m
//  IVTMeLiveTwo
//
//  Created by xrg on 16/9/29.
//  Copyright © 2016年 QLQ. All rights reserved.
//

#import "ExchangeViewController.h"
#import "IVTMyAccountTableViewCell.h"


static int mitang;


@interface ExchangeViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIActionSheetDelegate>

@property (nonatomic, strong) UITableView *accountTableview;

@property (nonatomic, strong) UILabel *accountText;

@property (nonatomic, strong) UIImageView *goldImg;

@property (nonatomic, strong) UILabel *accountNumber;

@property (nonatomic, strong) NSMutableArray *listArr;



@end

@implementation ExchangeViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self request];
    [self creatTableView];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"返回键"] style:UIBarButtonItemStylePlain target:self action:@selector(backToTopPage:)];
    leftBarButton.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    [self exchangeBySelf];
    _listArr = [[NSMutableArray alloc] init];
    

}

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

#pragma mark - 创建tableview
- (void)creatTableView
{
    _accountTableview = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    _accountTableview.delegate = self;
    _accountTableview.dataSource = self;
    _accountTableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _accountTableview.scrollEnabled = NO;

    [self.view addSubview:_accountTableview];
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    headView.backgroundColor = [UIColor whiteColor];
    _accountTableview.tableHeaderView = headView;
    _accountText = [[UILabel alloc] initWithFrame:CGRectZero];
    _accountText.text = @"中国币余额";
    _accountText.textColor = [UIColor IVTMainTextColor];
    
    _accountText.font = [UIFont IVTH3Font];
    [_accountText sizeToFit];
    _accountText.center = CGPointMake(16+_accountText.frame.size.width/2, headView.frame.size.height/2);

    [headView addSubview:_accountText];
    
    _accountNumber = [[UILabel alloc] initWithFrame:CGRectMake(_accountText.frame.size.width + 10, 10, 100, 30)];
    _accountNumber.text = [NSString stringWithFormat:@"%.0f", [[IVTAccountTool getMeCoinBalance] floatValue]];
    _accountNumber.textColor = [UIColor IVTMainTextColor];
    _accountNumber.font = [UIFont IVTH3Font];
    _accountNumber.textAlignment = 1;
    [headView addSubview:_accountNumber];
}

- (void)exchangeBySelf
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor colorWithRed:0.7765 green:0.0 blue:0.3137 alpha:1.0];
    button.titleLabel.font = [UIFont systemFontOfSize:13.0];
    button.titleLabel.tintColor = [UIColor whiteColor];
    button.frame = CGRectMake(kScreenWidth / 2 - 50, 300,100, 40);
    button.layer.cornerRadius = 20;

    [button setTitle:@"自定义金额" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(exchangeBySelfFunc:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

}


- (IBAction)exchangeBySelfFunc:(id)sender {
    
    UILabel * mitangLabel = [[UILabel alloc] init];
    mitangLabel.text = [NSString stringWithFormat:@"蜜糖 =      0中国币"];
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"兑换中国币"
                                                                              message: [NSString stringWithFormat:@"账户余额%.0f蜜糖", [[IVTAccountTool getMeCoinBalance] floatValue]]
                                                                       preferredStyle:UIAlertControllerStyleAlert];

    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"0";
        textField.keyboardType = UIKeyboardTypePhonePad;
        textField.textColor = [UIColor blueColor];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.borderStyle = UITextBorderStyleRoundedRect;
        [textField addTarget:self action:@selector(uernameChange:) forControlEvents:UIControlEventEditingChanged];
    }];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if ([[IVTAccountTool getMeCoinBalance] floatValue] - mitang < 0) {
            [SVProgressHUD showErrorWithStatus:@"蜜糖币余额不足,无法完成支付"];
        }else{
            [SVProgressHUD showWithStatus:@"充值中…"];

            NSMutableDictionary * paramDict =[[NSMutableDictionary alloc] init];
            [paramDict setObject:[IVTAccountTool getUserId] forKey:@"username"];
            [paramDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
            [paramDict setObject:[NSString stringWithFormat:@"%zd",mitang] forKey:@"money"];
            [paramDict setObject:@"meWithdrawSuccess" forKey:@"withdrawMark"];
            
            [[IVTNetworkAPIClient sharedClient] withdrawMarkSuccess:paramDict success:^(NSDictionary *successData) {
                if ([successData[@"data"] isEqualToString:@"0"]) {
                    [IVTAccountTool setMeCoinBalance:_accountNumber.text];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                _accountNumber.text = [NSString stringWithFormat:@"%.0f", [[IVTAccountTool getMeCoinBalance] floatValue] - mitang];
                    [IVTAccountTool setMeCoinBalance:_accountNumber.text];

                });
                [SVProgressHUD showSuccessWithStatus:@"充值成功"];
            } error:^(NSDictionary *successData) {
                NSString *msg = successData[@"description"];
                [SVProgressHUD setMinimumDismissTimeInterval:2];
                [SVProgressHUD showErrorWithStatus:msg];
                
            } failure:^(NSError *failureError) {
                
            }];

        }
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];

}

- (void)uernameChange:(UITextField *)textField
 {
     mitang = [textField.text intValue];
        LRLog(@"-------------------------%d",mitang);
}


#pragma mark - 请求数据
- (void)request
{
    __weak __typeof(self)vc = self;
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:[IVTAccountTool getUserId] forKey:@"username"];
    
    [[IVTNetworkAPIClient sharedClient] getConversionPrice:dict success:^(NSDictionary *successData) {
        NSArray *listArray = [successData objectForKey:@"list"];
        
        for (NSMutableDictionary *dict in listArray) {
            IVTMyAccountTableViewModel *accountModel = [[IVTMyAccountTableViewModel alloc] initWithDictionary:dict];
            [vc.listArr addObject:accountModel];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [vc.accountTableview reloadData];
        });
        
    } error:^(NSDictionary *successData) {
        
    } failure:^(NSError *failureError) {
        
    }];
}





#pragma mark - delegate&datasorce
//  设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 48;
}

- ( CGFloat )tableView:( UITableView *)tableView heightForHeaderInSection:( NSInteger )section

{
    return 36.0 ;
}



//  设置标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    self.title = @"兑换";
    return self.title;
}

//1、确定tableView中的分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//2、确定每个section中的cell数量

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listArr.count;
}
//3、确定Cell中的内容

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    IVTMyAccountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[IVTMyAccountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.charge.frame = CGRectMake(kScreenWidth - 110, 10, 100, 25);
    
    IVTMyAccountTableViewModel *accountTableViewModel = [_listArr objectAtIndex:indexPath.row];
    cell.accountModel = accountTableViewModel;
    if (indexPath.row == 0) {

        [cell.charge setTitle:@"1200蜜糖" forState:UIControlStateNormal];
        
    }else if(indexPath.row == 1) {
        [cell.charge setTitle:@"6000蜜糖" forState:UIControlStateNormal];
        
    }else if(indexPath.row == 2) {
       
        [cell.charge setTitle:@"18000蜜糖" forState:UIControlStateNormal];
    }
    return cell;
}

//4、点击cell时

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    IVTMyAccountTableViewModel * newModel = _listArr[indexPath.row];
    
    if (indexPath.row == 0) {
        mitang = 1200;
    }else if (indexPath.row == 1){
        mitang = 6000;
    }else if (indexPath.row == 2){
         mitang = 18000;
    }
    UIAlertView * alertV = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"你确定要用%zd蜜糖兑换%.0f中国币?", mitang,[newModel.chineseCoin floatValue]] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];;
    [alertV show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        
        if ([[IVTAccountTool getMeCoinBalance] floatValue] - mitang < 0) {
            [SVProgressHUD showErrorWithStatus:@"蜜糖币余额不足,无法完成支付"];
        }else{
            [SVProgressHUD showWithStatus:@"充值中…"];
            
            NSMutableDictionary * paramDict =[[NSMutableDictionary alloc] init];
            [paramDict setObject:[IVTAccountTool getUserId] forKey:@"username"];
            [paramDict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
            [paramDict setObject:[NSString stringWithFormat:@"%d",mitang] forKey:@"money"];
            [paramDict setObject:@"meWithdrawSuccess" forKey:@"withdrawMark"];
            
            [[IVTNetworkAPIClient sharedClient] withdrawMarkSuccess:paramDict success:^(NSDictionary *successData) {
                if ([successData[@"data"] isEqualToString:@"0"]) {
                    [IVTAccountTool setMeCoinBalance:_accountNumber.text];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [IVTAccountTool setMeCoinBalance:[NSString stringWithFormat:@"%.f",[[IVTAccountTool getMeCoinBalance] floatValue] + (mitang * [[IVTAccountTool getAppInfoByType:7] floatValue]) * 100]];
                    _accountNumber.text = [NSString stringWithFormat:@"%.0f", [[IVTAccountTool getMeCoinBalance] floatValue] - mitang];
                    [IVTAccountTool setMeCoinBalance:_accountNumber.text];

                });
                [SVProgressHUD showSuccessWithStatus:@"充值成功"];
            } error:^(NSDictionary *successData) {
                NSString *msg = successData[@"description"];
                [SVProgressHUD setMinimumDismissTimeInterval:2];
                [SVProgressHUD showErrorWithStatus:msg];

            } failure:^(NSError *failureError) {
                [HUDUtil showError:@"网络异常"];
            }];
        }
    }else {

    }
}

#pragma mark - 按钮点击事件
//返回按钮点击
-(void)backToTopPage:(id)sender
{
    if (self.accountNumberEdit) {
        self.accountNumberEdit(_accountNumber.text);
    }
    [self.navigationController popViewControllerAnimated:YES];
    [SVProgressHUD dismiss];
}

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