//
//  AccountViewController.m
//  Car
//
//  Created by Javen on 2017/2/8.
//  Copyright © 2017年 上海勾芒信息科技. All rights reserved.
//

#import "AccountViewController.h"
#import "UMSocialManager.h"
#import <UMSocialCore/UMSocialCore.h>
#import "AccountRecordViewController.h"
@interface AccountViewController ()

/**
 工分总额
 */
@property (weak, nonatomic) IBOutlet UILabel *labelTotalScore;

/**
 可换工分
 */
@property (weak, nonatomic) IBOutlet UILabel *labelValidScore;

/**
 工分
 */
@property (weak, nonatomic) IBOutlet UITextField *textFieldScore;

/**
 工分提现说明
 */
@property (weak, nonatomic) IBOutlet UILabel *labelInfo;

/**
 提醒绑定微信提示
 */
@property (weak, nonatomic) IBOutlet UILabel *labelToWechatInfo;
@property (weak, nonatomic) IBOutlet UIView *scoreView;
@property (weak, nonatomic) IBOutlet UIButton *btnBottom;

/**
 请求体
 */
@property (strong, nonatomic) DrawCashBillEntity *param;

@end

@implementation AccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    switch (self.type) {
        case AccountViewControllerTypeUnBing:
            [self unBinding];
            break;
        case AccountViewControllerTypeBinding:
            [self isBinding];
            break;
        default:
            break;
    }

    // Do any additional setup after loading the view.
}

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

//已绑定
- (void)isBinding {
    self.scoreView.hidden = NO;
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"提现记录" style:UIBarButtonItemStyleDone target:self action:@selector(actionRecods)];
    self.navigationItem.rightBarButtonItem = rightBtn;
    [self.btnBottom setTitle:@"提交申请" forState:UIControlStateNormal];
    [self httpGetWorkPoint];
}

//未绑定
- (void)unBinding {
    self.scoreView.hidden = YES;
}

//界面设置
- (void)configUI {
    self.title = @"工分提现";
    //未绑定微信的底部的提示
    NSString *contentStr = @"亲，您还没有绑定微信哦，工分提现需要先绑定微信哦，我们的提现金额会提到微信钱包中。";
    NSRange range = [contentStr rangeOfString:@"提现金额会提到微信钱包中"];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:contentStr];
    //设置：在0-3个单位长度内的内容显示成红色
    [str addAttribute:NSForegroundColorAttributeName value:kMainColor range:range];
    self.labelToWechatInfo.attributedText = str;

    //输入工分动态计算金额
    [self.textFieldScore addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventAllEditingEvents];
}

- (void)textFieldDidChange:(UITextField *)textField {
    NSDecimalNumber *number = [CalculateHelper mul:textField.text num2:@(0.01)];
    NSString *money = [CalculateHelper getMoneyStringFrom:number];
    NSString *info = [NSString stringWithFormat:@"对应金额  %@元", money];
    self.labelInfo.text = info;
}

#pragma mark - actions
- (void)actionRecods {
    AccountRecordViewController *recordVC = [AccountRecordViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    [self.navigationController pushViewController:recordVC animated:YES];
}

- (IBAction)actionBottom:(id)sender {
    switch (self.type) {
        case AccountViewControllerTypeUnBing: {

            [self bindWeChat];
            
            
        } break;
        case AccountViewControllerTypeBinding: {
            WS(weakSelf);
            kCanNotBeNil(self.textFieldScore.text, @"请输入提现工分！");
            
            if ([self.textFieldScore.text doubleValue] > [self.labelValidScore.text doubleValue]) {
                [MBProgressHUD j_error:@"可用工分不足！" complete:nil];
                break;
            }
            [self alertTitle:@"确认提交？"
                         msg:nil
                    okAction:^(UIAlertAction *_Nullable action) {

                        [weakSelf httpSubmit];
                    }
                cancelAction:nil];

            break;
        }

        default:
            break;
    }
}


/**
 绑定微信 第三方登录
 */
- (void)bindWeChat {
    WS(weakSelf);
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error) {
        if (error) {
            [MBProgressHUD j_error:@"绑定出错，请重试！" complete:nil];
            return ;
        }
        
        UMSocialUserInfoResponse *resp = result;
        
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);
        [weakSelf httpUploadUnionId:resp.uid];
        NSLog(@" openid: %@", resp.openid);
        NSLog(@" accessToken: %@", resp.accessToken);
        NSLog(@" refreshToken: %@", resp.refreshToken);
        NSLog(@" expiration: %@", resp.expiration);
        
        // 用户数据
        NSLog(@" name: %@", resp.name);
        NSLog(@" iconurl: %@", resp.iconurl);
        NSLog(@" gender: %@", resp.gender);
        
        // 第三方平台SDK原始数据
        NSLog(@" originalResponse: %@", resp.originalResponse);
    }];
}

- (void)httpUploadUnionId:(NSString *)uid {
    NSDictionary *param = @{@"userId":kUser.fid,
                            @"unionId":uid};
    WS(weakSelf);
    [kHttp POST:kModifyUserWxUid parameters:param complete:^(id  _Nullable response, NSError * _Nullable error) {
        if (kRsSuccess(response)) {
            [MBProgressHUD j_success:@"绑定成功！" complete:^{
                kUser.wxOpenId = response[@"data"];
                weakSelf.type = AccountViewControllerTypeBinding;
                [weakSelf isBinding];
            }];
        }else{
            kFalseHttpTips;
        }
    }];
}

- (void)httpSubmit {
    [MBProgressHUD j_loading];
    WS(weakSelf);
    [kHttp POST:kCashApply
        parameters:[self.param toDictionary]
          complete:^(id _Nullable response, NSError *_Nullable error) {
              if (kRsSuccess(response)) {
                  [MBProgressHUD j_success:@"提交成功！" complete:nil];
                  weakSelf.labelInfo.text = @"对应金额  0.00元";
                  weakSelf.textFieldScore.text = nil;
                  [weakSelf httpGetWorkPoint];
              } else {
                  kFalseHttpTips;
              }
          }];
}

- (void)httpGetWorkPoint {
    NSDictionary *param = @{ @"userId" : kUser.fid };
    WS(weakSelf);
    [kHttp GET:kAccountGetUrl
        parameters:param
          complete:^(id _Nullable response, NSError *_Nullable error) {
              if (kRsSuccess(response)) {
                  StationUserAcctEntity *acc = [[StationUserAcctEntity alloc] initWithDictionary:response[@"data"] error:nil];
                  weakSelf.labelTotalScore.text = [NSString stringWithFormat:@"%@", acc.balance];
                  weakSelf.labelValidScore.text = [NSString stringWithFormat:@"%@", acc.drawBalance ? acc.drawBalance : @"0"];
              }
          }];
}

- (DrawCashBillEntity *)param {
    if (!_param) {
        _param = [[DrawCashBillEntity alloc] init];
        _param.applicantId = kUser.fid;
        _param.applicantName = kUser.realName;
    }

    _param.workpoint = [NSDecimalNumber decimalNumberWithString:self.textFieldScore.text];
    _param.cash = [CalculateHelper mul:self.textFieldScore.text num2:@(0.01)];
    return _param;
}

- (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
