//
//  RebateViewController.m
//  Lighting
//
//  Created by 曹云霄 on 16/8/26.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "RebateViewController.h"
#import "RebateDetailsViewController.h"
#import "WithdrawalTableViewController.h"
#import "CardViewController.h"
#import "CardDetailsViewController.h"
#import "LuckyDrawViewController.h"
#import "LuckyDrawDetailsViewController.h"
#import "PaymentWithdrawalMainViewController.h"
#import "BindingBankCARDViewController.h"
#import "ReadPacketViewController.h"
#import "ReadPacketStateViewController.h"
#import "LuckyDrawMainViewController.h"
#import "ReadPacketMainViewController.h"

@interface RebateViewController ()

/**
 *  头像
 */
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;

/**
 *  总资产
 */
@property (weak, nonatomic) IBOutlet UILabel *currentAmountLabel;
/*******************************/
/**
 *  产品返利
 */
@property (weak, nonatomic) IBOutlet UILabel *productRebateAmountLabel;

/**
 *  昨日收益
 */
@property (weak, nonatomic) IBOutlet UILabel *productRebateYesterdayAmountLabel;

/**
 *  历史收益
 */
@property (weak, nonatomic) IBOutlet UILabel *productRebateHistoryAmountLabel;

/**
 *  冻结金额
 */
@property (weak, nonatomic) IBOutlet UILabel *productRebateFreezeAmountLabel;

/**
 提现
 */
@property (weak, nonatomic) IBOutlet UIButton *productRebateButton;

/*******************************/
/**
 *  欧普奖励
 */
@property (weak, nonatomic) IBOutlet UILabel *oppleRewardAmountLabel;

/**
 *  昨日收益
 */
@property (weak, nonatomic) IBOutlet UILabel *oppleRewardYesterdayAmountLabel;

/**
 *  历史收益
 */
@property (weak, nonatomic) IBOutlet UILabel *oppleRewardHistoryAmountLabel;

/**
 *  冻结金额
 */
@property (weak, nonatomic) IBOutlet UILabel *oppleRewardFreezeAmountLabel;

/**
 提现
 */
@property (weak, nonatomic) IBOutlet UIButton *oppleRewardButton;

/*******************************/

/**
 *  我的卡劵包
 */
@property (weak, nonatomic) IBOutlet UIView *cardBackgroundView;

/**
 *  我的抽奖
 */
@property (weak, nonatomic) IBOutlet UIView *drawBackgroundView;

/**
    我的红包
 */
@property (weak, nonatomic) IBOutlet UIView *readPacketBackgroundView;

/**
 返利数据
 */
@property (nonatomic,strong) EarningsResponse *resultEntity;

@end


@implementation RebateViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getRebateDatasFromUser];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupChildViewController];
    [self uiConfigAction];
}

#pragma mark - UI
- (void)uiConfigAction
{
    [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:[Shoppersmanager manager].shoppers.employee.picture] placeholderImage:GuideReplaceImage];
}

#pragma mark - 添加卡劵、抽奖控制器、红包
- (void)setupChildViewController
{
    // 我的卡劵
    CardViewController *cardVc = [CardViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    [self addChildViewController:cardVc];
    [self.cardBackgroundView addSubview:cardVc.view];
    [cardVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.cardBackgroundView.mas_left).offset(10);
        make.right.equalTo(self.cardBackgroundView.mas_right).offset(-10);
        make.top.equalTo(self.cardBackgroundView.mas_top).offset(40);
        make.bottom.equalTo(self.cardBackgroundView.mas_bottom).offset(-10);
    }];
    
    // 我的抽奖
    LuckyDrawMainViewController *draw = [LuckyDrawMainViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    [self addChildViewController:draw];
    [self.drawBackgroundView addSubview:draw.view];
    [draw.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.drawBackgroundView.mas_left).offset(10);
        make.right.equalTo(self.drawBackgroundView.mas_right).offset(-10);
        make.top.equalTo(self.drawBackgroundView.mas_top).offset(40);
        make.bottom.equalTo(self.drawBackgroundView.mas_bottom).offset(-10);
    }];
    
    // 红包
    ReadPacketMainViewController *readPacket = [ReadPacketMainViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];;
    [self addChildViewController:readPacket];
    [self.readPacketBackgroundView addSubview:readPacket.view];
    [readPacket.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.readPacketBackgroundView.mas_left).offset(10);
        make.right.equalTo(self.readPacketBackgroundView.mas_right).offset(-10);
        make.top.equalTo(self.readPacketBackgroundView.mas_top).offset(40);
        make.bottom.equalTo(self.readPacketBackgroundView.mas_bottom).offset(-10);
    }];
}

#pragma mark - 查询返利信息
- (void)getRebateDatasFromUser
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    NSString *url = [NSString stringWithFormat:@"%@/%@",REBATE,[Shoppersmanager manager].shoppers.employee.fid];
    [HTTP networkWithDictionaryRequestWithURL:SERVERREQUESTURL(url) withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            weakSelf.resultEntity = [[EarningsResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf setUpRichTextString:weakSelf.resultEntity];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 设置富文本字符串<赋值>
- (void)setUpRichTextString:(EarningsResponse *)response
{
    //总资产
    NSMutableAttributedString *totalAssets = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%2f",[response.accountTotal floatValue]+[response.redPackageAccountTotal floatValue]]];
    [totalAssets addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(totalAssets.length-3, 3)];
    self.currentAmountLabel.attributedText = totalAssets;
    //产品返利
    NSMutableAttributedString *productRebate = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f",[response.accountTotal floatValue]]];
    [productRebate addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(productRebate.length-3, 3)];
    self.productRebateAmountLabel.attributedText = productRebate;
    //欧普奖励
    NSMutableAttributedString *oppleReward = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f",[response.redPackageAccountTotal floatValue]]];
    [oppleReward addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(oppleReward.length-3, 3)];
    self.oppleRewardAmountLabel.attributedText = oppleReward;
    self.currentAmountLabel.text = [NSString stringWithFormat:@"%.2f",[response.redPackageAccountTotal floatValue] + [response.accountTotal floatValue]];
    self.productRebateAmountLabel.text = [NSString stringWithFormat:@"%.2f",[response.accountTotal floatValue]];
     self.productRebateYesterdayAmountLabel.text = [NSString stringWithFormat:@"昨日收益：%.2f",[response.yesterdayEarnings floatValue]];
     self.productRebateHistoryAmountLabel.text = [NSString stringWithFormat:@"历史收益：%.2f",[response.historyEarning floatValue]];
    self.productRebateFreezeAmountLabel.text = [NSString stringWithFormat:@"提现中：%.2f",[response.applytotal floatValue]];
    self.oppleRewardYesterdayAmountLabel.text = [NSString stringWithFormat:@"昨日收益：%.2f",[response.redPackageYesterdayEarnings floatValue]];
    self.oppleRewardHistoryAmountLabel.text = [NSString stringWithFormat:@"历史收益：%.2f",[response.redPackageHistoryEarning floatValue]];
    self.oppleRewardFreezeAmountLabel.text = [NSString stringWithFormat:@"提现中：%.2f",[response.redPackageApplytotal floatValue]];
    self.oppleRewardAmountLabel.text = [NSString stringWithFormat:@"%.2f",[response.redPackageAccountTotal floatValue]];
}


#pragma mark - 提现<tag == 100 产品返利><tag == 101 欧普奖励>
- (IBAction)withdrawalButtonClickAction:(UIButton *)sender {

    if (!self.resultEntity.isUsable && sender.tag == 101) {
        ShowAlertView(@"提示", self.resultEntity.showApplyMessage, @[@"我知道了"], UIAlertControllerStyleAlert, nil);
        return;
    }
    if (!self.resultEntity.bankCards.count && sender.tag == 101) {
        [self showUnboundedAlertView];
    }
    WS(weakSelf);
    RebateDetailsViewController *rebateDetails = [RebateDetailsViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    rebateDetails.rebateAmount = (sender.tag == 100)?[self.resultEntity.accountTotal floatValue]:[self.resultEntity.redPackageAccountTotal floatValue];
    rebateDetails.billType = (sender.tag == 100)?COMMISSION:REDPACKAGE;
    rebateDetails.bankCardNumber = [[self.resultEntity.bankCards firstObject] bankAccount];
    [rebateDetails setShowApplyDetails:^(TOApplyBillEntity *entity) {
        WithdrawalTableViewController *detailVC = [WithdrawalTableViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
        detailVC.model = entity;
        [weakSelf pushViewController:detailVC animated:YES];
    }];
    [self pushViewController:rebateDetails animated:YES];
}

#pragma mark - 收支明细
- (IBAction)paymentDetailsClickAction:(UIButton *)sender {
    
    PaymentWithdrawalMainViewController *controller = [PaymentWithdrawalMainViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    [self pushViewController:controller animated:YES];
}

#pragma mark - 提现账户
- (IBAction)withdrawalAccountClickAction:(UIButton *)sender {
    
    if (self.resultEntity.bankCards.count) {
        [self haveBindingBankCARDS];
    }else {
        [self showUnboundedAlertView];
    }
}

#pragma mark - 未绑定银行卡
- (void)showUnboundedAlertView
{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:@"您还没有绑定提现账户" preferredStyle:UIAlertControllerStyleAlert];
    [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"去绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        BindingBankCARDViewController *bindingVC = [BindingBankCARDViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
        [self pushViewController:bindingVC animated:YES];
    }]];
    [self presentViewController:alertView animated:YES completion:nil];
}

#pragma mark - 已绑定银行卡
- (void)haveBindingBankCARDS
{
    TOBankCardEntity *entity = self.resultEntity.bankCards[0];
    NSString *bankCard = [NSString stringWithFormat:@"您已绑定提现账户\n%@\n%@****%@",entity.bankCardType,[entity.bankAccount substringWithRange:NSMakeRange(0, 4)],[entity.bankAccount substringWithRange:NSMakeRange(entity.bankAccount.length-4, 4)]];
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:bankCard preferredStyle:UIAlertControllerStyleAlert];
    [alertView addAction:[UIAlertAction actionWithTitle:@"解除绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self removeBindingBankCARDS];
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"重新绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        BindingBankCARDViewController *bindingVC = [BindingBankCARDViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
        [self pushViewController:bindingVC animated:YES];
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertView animated:YES completion:nil];
}

#pragma mark - 解除绑定银行卡
- (void)removeBindingBankCARDS
{
    [XBLoadingView showHUDViewWithDefault];
    WS(weakSelf);
     TOBankCardEntity *entity = self.resultEntity.bankCards[0];
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(UNBINDING),entity.bankAccount] withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [XBLoadingView showHUDViewWithSuccessText:@"解除绑定成功" completeBlock:^{
                [weakSelf getRebateDatasFromUser];
            }];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark - 更多卡劵
- (IBAction)moreCardButtonClickAction:(UIButton *)sender {
    
    CardDetailsViewController *cardDetails = [CardDetailsViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    [self pushViewController:cardDetails animated:YES];
}

#pragma mark - 更多抽奖信息
- (IBAction)moreDrawButtonClickAction:(UIButton *)sender {
    
    LuckyDrawViewController *luckDrawDetails = [LuckyDrawViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    [self pushViewController:luckDrawDetails animated:YES];
}

#pragma mark - 更多红包信息
- (IBAction)moreReadPacketButtonClickAction:(UIButton *)sender {
    
    ReadPacketStateViewController *luckDrawDetails = [ReadPacketStateViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    [self pushViewController:luckDrawDetails animated:YES];
}





@end
