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

#import "SettlementViewController.h"
#import "PayViewController.h"
#import "PromotionalDeductionModel.h"
#import "PromotionalGoodsModel.h"
#import "PromotionLuckyDrawModel.h"
#import "PromotionWeChatCardModel.h"
#import "PromotionJDECardModel.h"
#import "PromotionalReadPacketModel.h"

@interface SettlementViewController ()<ReturnTableviewcellIndexpathdelegate,UITextFieldDelegate>

/**
 *  支付宝二维码
 */
@property (nonatomic,copy) NSString *zhiFubaoLabe;

/**
 *  微信二维码
 */
@property (nonatomic,copy) NSString *weiXinLabe;

/**
 *  二维码界面
 */
@property (nonatomic,strong) PayViewController *payController;

/**
 总金额来源
 */
@property (nonatomic,copy) NSString *totalAmountSource;


@end

@implementation SettlementViewController


#pragma mark -初始化二维码显示
- (PayViewController *)payController
{
    if (!_payController) {
        _payController = [[PayViewController alloc]init];
    }
    return _payController;
}

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


#pragma mark -布局
- (void)uiConfigAction
{
    self.goodsAllNumberBackvie.layer.masksToBounds = YES;
    self.goodsAllNumberBackvie.layer.cornerRadius = kCornerRadius;
    self.goodsAllpriceBackView.layer.masksToBounds = YES;
    self.goodsAllpriceBackView.layer.cornerRadius = kCornerRadius;
    self.payTypeButton.layer.masksToBounds = YES;
    self.payTypeButton.layer.cornerRadius = kCornerRadius;
    self.WeixiPayButton.layer.masksToBounds = YES;
    self.WeixiPayButton.layer.cornerRadius = kCornerRadius;
    self.payTreasureButton.layer.masksToBounds = YES;
    self.payTreasureButton.layer.cornerRadius = kCornerRadius;
    self.ISinvoiceButton.layer.masksToBounds = YES;
    self.ISinvoiceButton.layer.cornerRadius = kCornerRadius;
    self.invoiceType.layer.masksToBounds = YES;
    self.invoiceType.layer.cornerRadius = kCornerRadius;
    self.invoiceBackView.layer.masksToBounds = YES;
    self.invoiceBackView.layer.cornerRadius = kCornerRadius;
    self.cancelButton.layer.masksToBounds = YES;
    self.cancelButton.layer.cornerRadius = kCornerRadius;
    self.sureButton.layer.masksToBounds = YES;
    self.sureButton.layer.cornerRadius = kCornerRadius;
    self.myScrollView.contentSize = CGSizeMake(0, self.view.frame.size.height);
    self.invoiceHeader.delegate = self;
}


#pragma mark -支付总金额，商品总数量
- (void)calculateGoodsTotalAmountAndTotalNumber
{
    NSInteger goodsAllNumber = 0;//总数量
    for (TOOrderdetailEntity *model in _goodsArray) {
        goodsAllNumber += [model.goodsNum integerValue];
    }
    CGFloat allPrice = 0;//实际支付金额
    NSDictionary *deductionPrice = nil;//抵扣金额
    NSDictionary *weChatPrice = nil;//微信卡劵
    NSDictionary *drawPrice = nil;//转盘抽奖
    for (TOOrderdetailEntity *model in _goodsArray) {
        allPrice += [model.goodsPrice floatValue]*[model.goodsNum floatValue];
    }
    //促销列表
    for (JSONModel *model in self.consumerPromotionalArray) {
            //微信卡劵
        if ([model isMemberOfClass:[PromotionWeChatCardModel class]]) {
            PromotionWeChatCardModel *weChatModel = (PromotionWeChatCardModel *)model;
            weChatPrice = @{@"price":[NSString stringWithFormat:@"%f",self.weChatModel.wxcardDenomation],@"priority":@(weChatModel.priority)};
            
        }else if ([model isMemberOfClass:[PromotionalDeductionModel class]]) {
            //抵扣
            PromotionalDeductionModel *deductionModel = (PromotionalDeductionModel *)model;
            deductionPrice = @{@"price":[NSString stringWithFormat:@"%f",deductionModel.total],@"priority":@(deductionModel.priority)};
            
        }else if ([model isMemberOfClass:[PromotionLuckyDrawModel class]]) {
            //抽奖
            PromotionLuckyDrawModel *drawModel = (PromotionLuckyDrawModel *)model;
            drawPrice = @{@"price":[NSString stringWithFormat:@"%@",self.resultModel.number],@"priority":@(drawModel.priority)};
            
        }else if ([model isMemberOfClass:[PromotionalGoodsModel class]]) {
            //送商品
            //PromotionalGoodsModel *goodsModel = (PromotionalGoodsModel *)model;
        }
    }
    CGFloat goodsAllPrice = [self promotionSorting:deductionPrice andWeChatPrice:weChatPrice andDrawPrice:drawPrice andAllPrice:allPrice];
    self.goodsAllNumber.text = [NSString stringWithFormat:@"%ld",goodsAllNumber];
    self.goodsAllPrice.text = [NSString stringWithFormat:@"￥%.2f",goodsAllPrice];
}

#pragma mark - 通过优先级排列促销项
- (CGFloat)promotionSorting:(NSDictionary *)deductionPrice andWeChatPrice:(NSDictionary *)weChatPrice andDrawPrice:(NSDictionary *)drawPrice andAllPrice:(CGFloat)allPrice
{
    NSMutableArray *array = [NSMutableArray array];
    if (deductionPrice) {
        [array addObject:deductionPrice];
    }
    if (weChatPrice) {
        [array addObject:weChatPrice];
    }
    if (drawPrice) {
        [array addObject:drawPrice];
    }
    //安装权限降序排列
    NSArray *chooseArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
        if (obj1[@"priority"] < obj2[@"priority"]) {
            return NSOrderedDescending;
        }
        if (obj1[@"priority"] < obj2[@"priority"]) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
    //计算促销后的价格
    CGFloat newPrice = allPrice;
    NSMutableString *priceString = [NSMutableString stringWithFormat:@"原价 %.2f元",allPrice];
    for (NSDictionary *dict in chooseArray) {
        if ([dict isEqual:deductionPrice]) {
            CGFloat deduction = [dict[@"price"] floatValue];
            newPrice = newPrice - deduction;
            [priceString appendString:[NSString stringWithFormat:@" - 抵扣促销 %.2f元",deduction]];
            
        }else if ([dict isEqual:weChatPrice]){
            CGFloat weChat = [dict[@"price"] floatValue];
            newPrice = newPrice - weChat;
            [priceString appendString:[NSString stringWithFormat:@" - 微信卡劵 %.2f元",weChat]];
            
        }else if ([dict isEqual:drawPrice] && self.resultModel){
            CGFloat draw = [self.resultModel.number floatValue]/100.0;
            newPrice = newPrice * draw;
            [priceString appendString:[NSString stringWithFormat:@" X 转盘抽奖 %@",self.resultModel.descriptionString]];
        }
    }
    //判断促销是否为空
    if (chooseArray.count) {
        if (newPrice < 0) {
            newPrice = 0;
        }
        [priceString appendString:[NSString stringWithFormat:@" = %.2f元",newPrice]];
    }
    self.totalAmountSource = priceString;
    return newPrice;
}

#pragma mark -获取经营者支付二维码
- (void)getPayQrCode
{
    WS(weakSelf);
    [[NetworkRequestClassManager manager ] networkWithDictionaryRequestWithURL:SERVERREQUESTURL(QRCODE)  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        if (RESULT(returnValue)) {
            
            NSLog(@"获取二维码成功");
            weakSelf.zhiFubaoLabe = RESPONSE(returnValue)[@"zhifubao"];
            weakSelf.weiXinLabe = RESPONSE(returnValue)[@"weixin"];
            
        }else
        {
            NSLog(@"获取二维码失败");
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.superview.layer.cornerRadius = 0;
}


#pragma mark -取消支付
- (IBAction)CancelButtonClick:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -确认支付
- (IBAction)SureButtonClick:(UIButton *)sender {
    
    if ([self.payTypeButton.currentTitle isEqualToString:@"现金、支票、转账、刷卡"] && !self.payTreasureButton.selected && !self.WeixiPayButton.selected) {
        [XBLoadingView showHUDViewWithText:@"请选择一种支付方式"];
        
    }else if ([self.invoiceType.currentTitle isEqualToString:@"公司发票"] && [[self class] isBlankString:self.invoiceHeader.text])
    {
        [XBLoadingView showHUDViewWithText:@"请输入发票抬头"];
    }else
    {
      [self surePayRequest];
    }
}

#pragma amrk -支付方式选择
- (IBAction)payTypeButtonClick:(UIButton *)sender {
    
    NSArray *arr = @[@"现金",@"支票",@"转账",@"刷卡"];
    [self showPopoverViewController:CGSizeMake(100, 200) withdatas:arr showButton:sender selectedIndex:0 getTitle:YES];
}

#pragma mark -微信支付
- (IBAction)WechatButtonClick:(UIButton *)sender {
    
    [self.payController dismissViewControllerAnimated:NO completion:nil];
    if ([self.weiXinLabe isKindOfClass:[NSNull class]]) {
        [XBLoadingView showHUDViewWithText:@"微信支付二维码为空,暂停使用!"];return;
    }
    self.showPayQrCodeImageView.hidden = NO;
    sender.selected = NO;
    [self.showPayQrCodeImageView sd_setImageWithURL:[NSURL URLWithString:self.weiXinLabe] placeholderImage:REPLACEIMAGE];
    self.payTreasureButton.selected = NO;
    [self.payTypeButton setTitle:@"现金、支票、转账、刷卡" forState:UIControlStateNormal];
    [self BringPayController:YES withButton:sender];
}


#pragma mark -支付宝支付
- (IBAction)ZhifubaoPayButtonClick:(UIButton *)sender {
    
    [self.payController dismissViewControllerAnimated:NO completion:nil];
    if ([self.zhiFubaoLabe isKindOfClass:[NSNull class]]) {
        [XBLoadingView showHUDViewWithText:@"支付宝支付二维码为空,暂停使用!"];return;
    }
    self.showPayQrCodeImageView.hidden = NO;
    sender.selected = NO;
    [self.showPayQrCodeImageView sd_setImageWithURL:[NSURL URLWithString:self.zhiFubaoLabe] placeholderImage:REPLACEIMAGE];
    self.WeixiPayButton.selected = NO;
    [self.payTypeButton setTitle:@"现金、支票、转账、刷卡" forState:UIControlStateNormal];
    [self BringPayController:NO withButton:sender];
}


#pragma mark -调出二维码支付框
- (void)BringPayController:(BOOL)weichat withButton:(UIButton *)sender
{
    
    self.payController.preferredContentSize = CGSizeMake(281, 387);
    self.payController.modalPresentationStyle = UIModalPresentationPopover;
    sender.selected = YES;
    UIPopoverPresentationController *pop = self.payController.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionLeft;
    pop.sourceView = self.payController.view;
    pop.sourceRect = [self.view convertRect:CGRectMake(sender.mj_x, sender.mj_y-30, sender.mj_w, sender.mj_h) toView:self.view.window];
    self.payController.dealersName.text = weichat?@"微信支付":@"支付宝支付";
    self.payController.dealersName.textColor = weichat?RGB(30, 198, 34,1):RGB(88, 172, 220,1);
    [self.payController.dealersImageView sd_setImageWithURL:[NSURL URLWithString:weichat?self.weiXinLabe:self.zhiFubaoLabe] placeholderImage:REPLACEIMAGE];
    self.payController.payTypeBackimageView.image = weichat?TCImage(@"weixinpay"):TCImage(@"zhifubaopay");
    [self presentViewController:self.payController animated:NO completion:nil];
}


#pragma mark -是否开票
- (IBAction)isinvoiceButtonClick:(UIButton *)sender {
    
    NSArray *arr = @[@"是",@"否"];
    [self showPopoverViewController:CGSizeMake(50, 150) withdatas:arr showButton:sender selectedIndex:1 getTitle:YES];
}


#pragma mark -发票类型
- (IBAction)invoiceTypeButtonClick:(UIButton *)sender {
    
    if ([self.ISinvoiceButton.currentTitle isEqualToString:@"否"]) {
        [XBLoadingView showHUDViewWithText:@"请选择开票"];
        return;
    }
    NSArray *arr = @[@"个人发票",@"公司发票"];
    [self showPopoverViewController:CGSizeMake(100, 150) withdatas:arr showButton:sender selectedIndex:2 getTitle:YES];
}


#pragma mark -弹出popover视图控制器
- (void)showPopoverViewController:(CGSize)size withdatas:(NSArray *)datasArray showButton:(UIButton *)button selectedIndex:(NSInteger)index getTitle:(BOOL )istitle
{
    PopoverViewController *popover = [[PopoverViewController alloc]init];
    popover.datasArray = datasArray;
    popover.delegate = self;
    popover.selectedindex = index;
    popover.isString = YES;
    popover.contentSize = size;
    popover.preferredContentSize = size;
    popover.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *pop = popover.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionUp;
    pop.sourceView = popover.view;
    pop.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    [self presentViewController:popover animated:YES completion:nil];
}


/**
 *  选中筛选条件对象typecode
 *
 *  @param index NSString
 */
- (void)returnCellindexpathwithrow:(NSString *)type withCellTitle:(NSString *)title withSelected:(NSInteger)selected
{
    switch (selected) {
        case 0://支付方式
        {
            [self.payTypeButton setTitle:title forState:UIControlStateNormal];
            self.payTreasureButton.selected = NO;
            self.WeixiPayButton.selected = NO;
            self.showPayQrCodeImageView.hidden = YES;
        }
            break;
        case 1://是否开票
        {
            [self.ISinvoiceButton setTitle:title forState:UIControlStateNormal];
        }
            break;
        case 2://发票类型
        {
            [self.invoiceType setTitle:title forState:UIControlStateNormal];
        }
            break;
            
        default:
            break;
    }
}


#pragma mark -确认支付请求
- (void)surePayRequest
{
    OrderPayRequest *order = [[OrderPayRequest alloc]init];
    order.orderNumber =  self.orderCode;
    order.fnewstate =  PAID;
    order.oldstate =  UNPAID;
    order.realAmount = [NSNumber numberWithFloat:[[self.goodsAllPrice.text substringFromIndex:1] floatValue]];
    // 查询是否有京东E卡促销、是否有导购抽奖
    NSInteger totalNumber = 0;
    NSMutableArray *readPacketArray = [NSMutableArray array];
    for (id object in self.guidePromotionArray) {
        if ([object isKindOfClass:[PromotionJDECardModel class]]) {
            PromotionJDECardModel *model = (PromotionJDECardModel *)object;
            if ([model.type isEqualToString:JDECardAction] && [model.body isEqualToString:GUIDE]) {
                totalNumber += model.total;
            }
        }
        if ([object isKindOfClass:[PromotionLuckyDrawModel class]]) {
            PromotionLuckyDrawModel *model = (PromotionLuckyDrawModel *)object;
            if ([model.body isEqualToString:GUIDE]) {
                order.lotteryId = model.lottery.uuid;
            }
        }
        if ([object isKindOfClass:[PromotionalReadPacketModel class]]) {
            PromotionalReadPacketModel *model = (PromotionalReadPacketModel *)object;
            if ([model.body isEqualToString:GUIDE]) {
                RedPackageDetail *entity = [[RedPackageDetail alloc] init];
                entity.money = [NSNumber numberWithFloat:model.total];
                entity.promotionBillNumber = model.promotionBillNumber;
                entity.redPrority = [NSString stringWithFormat:@"%ld",model.priority];
                [readPacketArray addObject:entity];
            }
        }        
    }
    order.redPackageDetails = (NSArray<RedPackageDetail> *)readPacketArray;
    order.jdCardDenomation = totalNumber;
    // 查询是否有消费者抽奖促销、微信卡劵促销、抵扣金额、商品促销
    CGFloat promotionMoney = 0;
    NSInteger deductionPrority = 0;//抵扣优先级
    NSInteger goodsPrority = 0;//商品促销优先级
    NSMutableArray *goodsArray = [NSMutableArray array];
    for (id object in self.consumerPromotionalArray) {
        if ([object isKindOfClass:[PromotionLuckyDrawModel class]]) {
            PromotionLuckyDrawModel *model = (PromotionLuckyDrawModel *)object;
            if ([model.body isEqualToString:CONSUMER]) {
                order.drawId = self.resultModel.drawId;
                order.drawPrority = model.priority;
            }
        }
        if ([object isKindOfClass:[PromotionWeChatCardModel class]]) {
            PromotionWeChatCardModel *model = (PromotionWeChatCardModel *)object;
            if ([model.body isEqualToString:CONSUMER]) {
                if (![[self class] isBlankString:self.weChatModel.wxcardNumber]) {
                    order.wxcardNumber = self.weChatModel.wxcardNumber;
                    order.wxcardDenomation = [NSNumber numberWithFloat:self.weChatModel.wxcardDenomation];
                    order.wxCardPrority = model.priority;
                }
            }
        }
        if ([object isKindOfClass:[PromotionalDeductionModel class]]) {
            PromotionalDeductionModel *model = (PromotionalDeductionModel *)object;
            if (model.isSelected) {
                promotionMoney += model.total;
                deductionPrority = model.priority;
            }
        }
        if ([object isKindOfClass:[PromotionalGoodsModel class]]) {
            PromotionalGoodsModel *model = (PromotionalGoodsModel *)object;
            if (model.isSelected) {
                PromotionGoods *goods = [[PromotionGoods alloc]init];
                UCN *goodDetails = [[UCN alloc]init];
                goodDetails.code = model.goods.code;
                goodDetails.uuid = model.goods.uuid;
                goodDetails.name = model.goods.name;
                goods.goods = goodDetails;
                goods.promotionNumber = [NSNumber numberWithInteger:model.count];
                [goodsArray addObject:goods];
            }
            goodsPrority = model.priority;
        }
    }
    order.promotionMoney = @(promotionMoney);
    order.deductionPrority = deductionPrority;
    order.promotionGoods = (NSArray<PromotionGoods> *)goodsArray;
    order.goodsPrority = goodsPrority;
    //支付类型
    if (self.payTreasureButton.selected) {
       order.payType =  @"005";
    }else if (self.WeixiPayButton.selected){
        order.payType = @"006";
    }else{
        order.payType =  [self PayTypeSelected:self.payTypeButton.currentTitle];
    }
    //是否开票
    if ([self.ISinvoiceButton.currentTitle isEqualToString:@"是"]) {
        order.isbill = @"Y";
    }
    else if ([self.ISinvoiceButton.currentTitle isEqualToString:@"否"]){
       order.isbill =  @"N";
    }
    //发票类型
    if ([self.invoiceType.currentTitle isEqualToString:@"公司发票"] && [order.isbill isEqualToString:@"Y"]) {
        order.billType =  @"002";
        if (self.invoiceHeader.text.length == 0 || !self.invoiceHeader.text) {
            [XBLoadingView showHUDViewWithText:@"发票抬头不能为空"];
            return;
        }
        order.billTitle = self.invoiceHeader.text;
    }else if ([self.invoiceType.currentTitle isEqualToString:@"个人发票"] && [order.isbill isEqualToString:@"Y"])
    {
        order.billType =  @"001";
    }
    [XBLoadingView showHUDViewWithDefault];
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(CONFIRMPAY)  withRequestType:ZERO withParameter:order withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                if (weakSelf.PaySuccessReturnBlock) {
                    weakSelf.PaySuccessReturnBlock();
                }
            }];
        }else{
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark -支付方式选择
- (NSString *)PayTypeSelected:(NSString *)selecte
{
    NSString *payCode = nil;
    if ([selecte isEqualToString:@"现金"]) {
        return payCode = @"001";
    }
    if ([selecte isEqualToString:@"刷卡"]) {
        return payCode = @"002";
    }
    if ([selecte isEqualToString:@"转账"]) {
        return payCode = @"003";
    }
    if ([selecte isEqualToString:@"支票"]) {
        return payCode = @"004";
    }
    return nil;
}


#pragma mark -开始编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([self.ISinvoiceButton.currentTitle isEqualToString:@"否"]) {
        [XBLoadingView showHUDViewWithText:@"请选择开票"];
        return NO;
    }
    return YES;
}

#pragma mark -结束编辑
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.myScrollView.contentOffset = CGPointMake(0, 0);
}

#pragma mark - 价格疑问
- (IBAction)priceQuestionButtonClickAction:(UIButton *)sender {
        
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:self.totalAmountSource preferredStyle:UIAlertControllerStyleAlert];
    [alertVc addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVc animated:YES completion:nil];
}




@end
