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

#import "OrderdetailsViewController.h"
#import "OrderInformationTableViewCell.h"
#import "PersonInformationTableViewCell.h"
#import "GoodsInformationTableViewCell.h"
#import "CommodityListTableViewCell.h"
#import "AllpriceTableViewCell.h"
#import "SettlementViewController.h"
#import "AdditionalTableViewCell.h"
#import <QuickLook/QuickLook.h>
#import "CustomWKWebViewController.h"
#import "ShareGoodsViewController.h"
#import "OrderDetailsSectionHeaderView.h"
#import "PromotionalDeductionModel.h"
#import "PromotionalGoodsModel.h"
#import "PromotionalTableViewCell.h"
#import "JDEcardViewController.h"
#import "WYPopoverController.h"
#import "RebateSuccessTableViewController.h"
#import "LuckyDrawModel.h"
#import "LuckDrawResultModel.h"
#import "AirPrintManager.h"
#import <WebKit/WebKit.h>


NSString *const PROMOTIONALSTRING = @"促销信息";



@interface OrderdetailsViewController ()<UITableViewDelegate,UITableViewDataSource,QLPreviewControllerDataSource,WKNavigationDelegate>
@property (nonatomic,strong) WKWebView *webView;

/**
 *  订单详情数据
 */
@property (nonatomic,strong) OrderBill *orderDetails;

/**
 *  本地存储地址
 */
@property (nonatomic,copy) NSString *PDFpath;

/**
 *  促销信息<商品、折扣>
 */
@property (nonatomic,strong) NSMutableArray *promotionalArray;

/**
 *  促销信息<转盘抽奖、京东E卡>
 */
@property (nonatomic,strong) NSMutableArray *luckyDrawAndJDECardArray;

/**
 *  京东E卡
 */
@property (nonatomic,strong) WYPopoverController *settingsPopoverController;

/**
 *  客户抽奖结果
 */
@property (nonatomic,strong) LuckDrawResultModel *customerDrawModel;


@end

@implementation OrderdetailsViewController

#pragma mark - lazy
- (NSMutableArray *)promotionalArray
{
    if (!_promotionalArray) {
        _promotionalArray = [NSMutableArray array];
    }
    return _promotionalArray;
}

- (NSMutableArray *)sectionTitle
{
    if (!_sectionTitle) {
        _sectionTitle = [NSMutableArray arrayWithObjects:@"订单信息",@"客户信息",@"收货信息",@"商品信息",@"附件信息", nil];
    }
    return _sectionTitle;
}

- (NSMutableArray *)luckyDrawAndJDECardArray
{
    if (!_luckyDrawAndJDECardArray) {
        _luckyDrawAndJDECardArray = [NSMutableArray array];
    }
    return _luckyDrawAndJDECardArray;
}

#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.isSliding) {
        self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        }
    }
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 开启
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self getOrderDetailsData:nil];
}

#pragma mark - UI
- (void)uiConfigAction
{
    self.orderDetailsTableview.dataSource = self;
    self.orderDetailsTableview.delegate = self;
    if (self.isShowHeaderView) {
       [self CreateTableviewHeaderView];
    }
    //附加信息cell
    [self.orderDetailsTableview registerNib:[UINib nibWithNibName:@"AdditionalTableViewCell" bundle:nil] forCellReuseIdentifier:@"fifthcell"];
    if (self.isShowPayButton) {
       [self CreateTableviewFooterView];
    }
}


#pragma mark -获取订单详情、查询促销信息
- (void)getOrderDetailsData:(void(^)())finish
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [self CreateMBProgressHUDLoding];
    WS(weakSelf);
    /// 订单详情
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",SERVERREQUESTURL(ORDERDETAILS),self.orderCode] WithCallClass:weakSelf WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
         dispatch_group_leave(group);
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            weakSelf.orderDetails = [[OrderBill alloc]initWithDictionary:returnValue[@"data"] error:nil];
        }else{
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
        dispatch_group_leave(group);
        [weakSelf ErrorMBProgressView:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        dispatch_group_leave(group);
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
    
    /// 未支付的订单查询实时促销，否则查询历史促销
    if (self.isShowPayButton) {
        /// 查询实时促销信息
        dispatch_group_enter(group);
        [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(PROMOTIONAL),self.orderCode] WithCallClass:weakSelf  WithRequestType:ONE WithParameter:nil WithReturnValueBlock:^(id returnValue) {
            
            dispatch_group_leave(group);
            [weakSelf RemoveMBProgressHUDLoding];
            if ([returnValue[@"code"] isEqualToNumber:@0]) {
                NSArray *promotionalArray = returnValue[@"data"][@"actions"];
                [weakSelf.promotionalArray removeAllObjects];
                [weakSelf.luckyDrawAndJDECardArray removeAllObjects];
                for (NSDictionary *dict in promotionalArray) {
                    NSString *type = dict[@"type"];
                        /// 折扣金额
                    if ([type isEqualToString:deductionAction]) {
                        PromotionalDeductionModel *deductionModel = [[PromotionalDeductionModel alloc]initWithDictionary:dict error:nil];
                        deductionModel.isSelected = YES;
                        if (promotionalArray.count && ![weakSelf.sectionTitle containsObject:PROMOTIONALSTRING]) {
                            [weakSelf.sectionTitle addObject:PROMOTIONALSTRING];
                        }
                        [weakSelf.promotionalArray addObject:deductionModel];
                        /// 赠送商品
                    }else if ([type isEqualToString:goodsAction]){
                        PromotionalGoodsModel *goodsModel = [[PromotionalGoodsModel alloc]initWithDictionary:dict error:nil];
                        goodsModel.isSelected = YES;
                        if (promotionalArray.count && ![weakSelf.sectionTitle containsObject:PROMOTIONALSTRING]) {
                            [weakSelf.sectionTitle addObject:PROMOTIONALSTRING];
                        }
                        [weakSelf.promotionalArray addObject:goodsModel];
                        /// 京东E卡
                    }else if ([type isEqualToString:JDECardAction]){
                        PromotionalDeductionModel *deductionModel = [[PromotionalDeductionModel alloc]initWithDictionary:dict error:nil];
                        [weakSelf.luckyDrawAndJDECardArray addObject:deductionModel];
                        /// 转盘抽奖
                    }else if ([type isEqualToString:lotteryAction]){
                        LuckyDrawModel *model = [[LuckyDrawModel alloc]initWithDictionary:dict error:nil];
                        [weakSelf.luckyDrawAndJDECardArray addObject:model];
                    }
                }
            }else{
                [weakSelf ErrorMBProgressView:returnValue[@"message"]];
            }
            
        } WithErrorCodeBlock:^(id errorCodeValue) {
            dispatch_group_leave(group);
            [weakSelf RemoveMBProgressHUDLoding];
            [weakSelf ErrorMBProgressView:NETWORK];
        } WithFailureBlock:^(NSError *error) {
            dispatch_group_leave(group);
            [weakSelf RemoveMBProgressHUDLoding];
            [weakSelf ErrorMBProgressView:error.localizedDescription];
        }];

    }else {
        /// 查询历史促销信息
        dispatch_group_enter(group);
        [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(OLDPROMOTIONAL),self.orderCode] WithCallClass:weakSelf  WithRequestType:ONE WithParameter:nil WithReturnValueBlock:^(id returnValue) {
            
            dispatch_group_leave(group);
            [weakSelf RemoveMBProgressHUDLoding];
            if ([returnValue[@"code"] isEqualToNumber:@0]) {
                NSArray *promotion = returnValue[@"data"];
                [weakSelf.promotionalArray removeAllObjects];
                [weakSelf.luckyDrawAndJDECardArray removeAllObjects];
                for (NSDictionary *dict in promotion) {
                    TOOrderPromotionEntity *oldPromotion = [[TOOrderPromotionEntity alloc]initWithDictionary:dict error:nil];
                         /// 赠送商品
                    if (![BaseViewController isBlankString:oldPromotion.goodsName]) {
                        if (![weakSelf.sectionTitle containsObject:PROMOTIONALSTRING]) {
                            [weakSelf.sectionTitle addObject:PROMOTIONALSTRING];
                        }
                        PromotionalGoodsModel *goodsModel = [[PromotionalGoodsModel alloc]init];
                        goodsModel.count = [oldPromotion.promotionNumber integerValue];
                        Goods *goods = [[Goods alloc]init];
                        goods.name = oldPromotion.goodsName;
                        goodsModel.goods = goods;
                        goodsModel.isSelected = YES;
                        [weakSelf.promotionalArray addObject:goodsModel];
                        
                    } else if (![BaseViewController isBlankString:[oldPromotion.promotionMoney stringValue]]) {
                        /// 促销金额
                        if (![weakSelf.sectionTitle containsObject:PROMOTIONALSTRING]) {
                            [weakSelf.sectionTitle addObject:PROMOTIONALSTRING];
                        }
                        PromotionalDeductionModel *deductionModel = [[PromotionalDeductionModel alloc]init];
                        deductionModel.total = [oldPromotion.promotionMoney integerValue];
                        deductionModel.isSelected = YES;
                        deductionModel.type = @"deductionAction";
                        [weakSelf.promotionalArray addObject:deductionModel];
                        
                    } else if (![BaseViewController isBlankString:[oldPromotion.jdecardDenomation stringValue]]) {
                        /// 判断京东E卡
                        PromotionalDeductionModel *model = [[PromotionalDeductionModel alloc]init];
                        model.total = [oldPromotion.jdecardDenomation integerValue];
                        model.body = GUIDE;
                        model.type = JDECardAction;
                        [weakSelf.luckyDrawAndJDECardArray addObject:model];
        
                    } else if (![BaseViewController isBlankString:[oldPromotion.redPackageCount stringValue]]) {
                        /// 导购抽奖数
                        LuckyDrawModel *model = [[LuckyDrawModel alloc]init];
                        model.body = GUIDE;
                        [weakSelf.luckyDrawAndJDECardArray addObject:model];
                    }
                }
            }
            
        } WithErrorCodeBlock:^(id errorCodeValue) {
            dispatch_group_leave(group);
            [weakSelf RemoveMBProgressHUDLoding];
            [weakSelf ErrorMBProgressView:NETWORK];
        } WithFailureBlock:^(NSError *error) {
            dispatch_group_leave(group);
            [weakSelf RemoveMBProgressHUDLoding];
            [weakSelf ErrorMBProgressView:error.localizedDescription];
        }];
    }
    /// 查询客户订单抽奖状态
    __block RsAwardDraw *resultModel = nil;
    dispatch_group_enter(group);
    RsLotteryRequest *queryDrawState = [[RsLotteryRequest alloc]init];
    /// 判断订单是否支付
    if (!self.isShowPayButton) {
       queryDrawState.orderNumberEquals = self.orderCode;
    }
    queryDrawState.winnerIdEquals = self.consumerID?self.consumerID:[Customermanager manager].model.fid;
    queryDrawState.stateEquals = self.isShowPayButton?ACCOMPLISHED:USED;
    DataPage *page = [[DataPage alloc]init];
    page.page = ZERO;
    page.rows = ONE;
    queryDrawState.page = page;
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(LOTTERYED) WithCallClass:weakSelf WithRequestType:ZERO WithParameter:queryDrawState WithReturnValueBlock:^(id returnValue) {
        dispatch_group_leave(group);
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            NSDictionary *dict = [returnValue[@"data"][@"list"] firstObject];
            resultModel = [[RsAwardDraw alloc]initWithDictionary:dict error:nil];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        dispatch_group_leave(group);
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        dispatch_group_leave(group);
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
    /// 完成后回调
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        /// 消费者抽奖成功后若没有支付，后面支付时可以继续享受奖品折扣
        if ([resultModel.draw.state isEqualToString:ACCOMPLISHED]) {
            for (JSONModel *model in weakSelf.luckyDrawAndJDECardArray) {
                if ([model isMemberOfClass:[LuckyDrawModel class]]) {
                    LuckyDrawModel *consumerModel = (LuckyDrawModel *)model;
                    if ([consumerModel.body isEqualToString:CONSUMER]) {
                        weakSelf.customerDrawModel = [LuckDrawResultModel initializeWith:resultModel];break;
                    }
                }
            }
        }
        /// 支付完成后
        if (self.isShowPrintButton && resultModel.award) {
            weakSelf.customerDrawModel = [LuckDrawResultModel initializeWith:resultModel];
        }
        /// 默认弹出支付框
        if (weakSelf.isShowPayButton && [weakSelf.orderDetails.order.orderState isEqualToString:NOTPAY]) {
            /// 找出客户抽奖
            for (int i=0;i<weakSelf.luckyDrawAndJDECardArray.count;i++) {
                id object = weakSelf.luckyDrawAndJDECardArray[i];
                if ([object isKindOfClass:[LuckyDrawModel class]] && !resultModel) {
                    LuckyDrawModel *model = (LuckyDrawModel *)object;
                    if ([model.body isEqualToString:CONSUMER]) {
                        [weakSelf queryConsumerLuckyDrawChance:model];
                        break;
                    }
                }
                /// 有促销无抽奖情况
                if (i == weakSelf.luckyDrawAndJDECardArray.count-1) {
                    [weakSelf payButtonClickAction];
                }
            }
            /// 无促销情况
            if (!weakSelf.luckyDrawAndJDECardArray.count) {
                [weakSelf payButtonClickAction];
            }
        }
        if (finish) {
            finish();
        }
        [weakSelf.orderDetailsTableview reloadData];
    });
}


#pragma mark - 卡劵领取成功
- (void)rebateApplySuccess:(NSString *)message
{
    RebateSuccessTableViewController *success = [self.getStoryboardWithName instantiateViewControllerWithIdentifier:@"RebateSuccessTableViewController"];
    success.titleArray = @[message,@"查看账户",@"我知道了"];
    [success setClickEvent:^(NSIndexPath *indexPath) {
        if (indexPath.row == 1) {
            /// 我知道了
        }else if (indexPath.row == 0)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:OPENCONTROLLER object:@(3)];
        }
    }];
    success.preferredContentSize = CGSizeMake(315, 320);
    success.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = success.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = success.view;
    [self presentViewController:success animated:YES completion:nil];
}

#pragma mark - 显示京东E卡
- (void)showJDECard
{
    WS(weakSelf);
    JDEcardViewController *jdeCard = [[self getStoryboardWithName] instantiateViewControllerWithIdentifier:@"JDEcardViewController"];
    [jdeCard setDismissJDECardBlock:^{
        [weakSelf.settingsPopoverController dismissPopoverAnimated:YES];
    }];
    jdeCard.preferredContentSize = CGSizeMake(400, 247);
    self.settingsPopoverController = [[WYPopoverController alloc] initWithContentViewController:jdeCard];
    self.settingsPopoverController.popoverLayoutMargins = UIEdgeInsetsMake(10, 20, 10, 20);
    self.settingsPopoverController.wantsDefaultContentAppearance = NO;
    self.settingsPopoverController.theme.fillBottomColor = [UIColor clearColor];
    self.settingsPopoverController.theme.fillTopColor = [UIColor clearColor];
    self.settingsPopoverController.theme.glossShadowColor = [UIColor clearColor];
    [self.settingsPopoverController presentPopoverAsDialogAnimated:YES
                                                           options:WYPopoverAnimationOptionFadeWithScale];
}

#pragma mark -TableviewHeader------根据不同的订单状态判断是否显示
- (void)CreateTableviewHeaderView
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
    //预览
    UIButton *previewButton = [UIButton buttonWithType:UIButtonTypeSystem];
    previewButton.frame = CGRectMake(50, 15, 150, 30);
    [previewButton setTitle:self.isShowPayButton?@"撤销订单":@"预览" forState:UIControlStateNormal];
    previewButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [previewButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [previewButton addTarget:self action:@selector(PreviewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    previewButton.backgroundColor = kMainBlueColor;
    previewButton.layer.masksToBounds = YES;
    previewButton.layer.cornerRadius = kCornerRadius;
    [headerView addSubview:previewButton];
    
    //显示支付按钮的情况下，不显示打印按钮
    if (!self.isShowPayButton) {
     
        //打印
        UIButton *printButton = [UIButton buttonWithType:UIButtonTypeSystem];
        printButton.frame = CGRectMake(ScreenWidth-50-150, 15, 150, 30);
        [printButton setTitle:@"打印" forState:UIControlStateNormal];
        [printButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        printButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [printButton addTarget:self action:@selector(AirprintButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        printButton.layer.masksToBounds = YES;
        printButton.layer.cornerRadius = kCornerRadius;
        printButton.backgroundColor = kMainBlueColor;
        [headerView addSubview:printButton];
        
        //分享
        UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
        shareButton.frame = CGRectMake(ScreenWidth-50-350, 15, 150, 30);
        [shareButton setTitle:@"分享" forState:UIControlStateNormal];
        [shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        shareButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [shareButton addTarget:self action:@selector(ShareButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        shareButton.layer.masksToBounds = YES;
        shareButton.layer.cornerRadius = kCornerRadius;
        shareButton.backgroundColor = kMainBlueColor;
        [headerView addSubview:shareButton];
    }
    //横线
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 59, ScreenWidth, 1)];
    lineView.backgroundColor = kTCColor(193, 193, 193);
    [headerView addSubview:lineView];
    self.orderDetailsTableview.tableHeaderView = headerView;
}

#pragma mark -TableviewFooterView------根据不同的订单状态判断支付按钮是否显示
- (void)CreateTableviewFooterView
{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
    //支付
    UIButton *payButton = [UIButton buttonWithType:UIButtonTypeSystem];
    payButton.frame = CGRectMake((ScreenWidth-150)/2, 30, 150, 40);
    [payButton setTitle:@"支付" forState:UIControlStateNormal];
    payButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [payButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [payButton addTarget:self action:@selector(payButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    payButton.backgroundColor = kMainBlueColor;
    payButton.layer.masksToBounds = YES;
    payButton.layer.cornerRadius = kCornerRadius;
    [footerView addSubview:payButton];
    self.orderDetailsTableview.tableFooterView = footerView;
}

#pragma mark - 查询客户抽奖机会
- (void)queryConsumerLuckyDrawChance:(LuckyDrawModel *)model
{
    WS(weakSelf);
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:nil message:@"恭喜您获得一次大转盘抽奖机会!" preferredStyle:UIAlertControllerStyleAlert];
    [alertControl addAction:[UIAlertAction actionWithTitle:@"马上参与" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf showLuckyDrawControl:model.lottery.uuid andOrderNumber:weakSelf.orderCode luckyDrawFinish:^(NSDictionary *dict) {
            id json = [NSJSONSerialization JSONObjectWithData:[dict[@"body"] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            if (json) {
                if ([json isKindOfClass:[NSDictionary class]]) {
                    weakSelf.customerDrawModel = [[LuckDrawResultModel alloc]initWithDictionary:json error:nil];
                    if ([BaseViewController isBlankString:weakSelf.customerDrawModel.awardId]) {
                        [weakSelf SHOWPrompttext:@"未中奖"];
                    }else {
                        [weakSelf SHOWPrompttext:[NSString stringWithFormat:@"恭喜你获得了 %@",weakSelf.customerDrawModel.descriptionString]];
                    }
                }
            }
            return;
        }];
    }]];
    [self presentViewController:alertControl animated:YES completion:nil];
}

#pragma mark - 查询导购抽奖机会
- (void)queryGuideLuckyDrawChanceisTrue:(void(^)())finish
{
    /// 查询是否有导购抽奖机会
    for (id object in self.luckyDrawAndJDECardArray) {
        if ([object isKindOfClass:[LuckyDrawModel class]]) {
            LuckyDrawModel *model = (LuckyDrawModel *)object;
            if ([model.body isEqualToString:GUIDE]) {
                finish();
                break;
            }
        }
    }
}

#pragma mark -调出支付框
- (void)payButtonClickAction
{
    SettlementViewController *settlement = [[SettlementViewController alloc]init];
    settlement.preferredContentSize = CGSizeMake(380, 500);
    settlement.goodsArray = self.orderDetails.orderdetailList;
    settlement.promotionalArray = self.promotionalArray;
    settlement.luckyDrawAndJDECardArray = self.luckyDrawAndJDECardArray;
    settlement.orderCode = self.orderCode;
    settlement.resultModel = self.customerDrawModel;
    settlement.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = settlement.popoverPresentationController;
    pop.sourceView = settlement.view;
    [self presentViewController:settlement animated:YES completion:nil];
    ///支付成功
    WS(weakSelf);
    [settlement setPaySuccessReturnBlock:^{

        if (weakSelf.DelecteAndPayButtonBlock) {
            weakSelf.DelecteAndPayButtonBlock(_cellindex,PAYSUCCESS);
        }
        [weakSelf SuccessMBProgressView:@"支付成功"];
        weakSelf.isShowPayButton = NO;
        weakSelf.isUserInteractionEnabled = NO;
        weakSelf.isShowHeaderView = YES;
        [weakSelf CreateTableviewHeaderView];
        weakSelf.orderDetailsTableview.tableFooterView = nil;
        __block BOOL isJDEcard = NO;//促销中是否有京东E卡；
        __block BOOL isGuideDraw = NO;//促销中是否有导购抽奖机会
        /// 刷新数据成功
        [weakSelf getOrderDetailsData:^{
            /// 先判断促销中有无E卡，有则认为发放成功
            for (id object in weakSelf.luckyDrawAndJDECardArray) {
                if ([object isKindOfClass:[PromotionalDeductionModel class]]) {
                    PromotionalDeductionModel *model = (PromotionalDeductionModel *)object;
                    if ([model.body isEqualToString:GUIDE] && [model.type isEqualToString:JDECardAction]) {
                        isJDEcard = YES;break;
                    }
                }
            }
            /// 查询导购抽奖机会
            [weakSelf queryGuideLuckyDrawChanceisTrue:^{
                isGuideDraw = YES;
            }];
            /// 弹出框
            if (isJDEcard && isGuideDraw) {
                [weakSelf rebateApplySuccess:@"京东E卡、抽奖机会已放到你的账户"];
            }else if (isJDEcard && !isGuideDraw) {
                [weakSelf rebateApplySuccess:@"京东E卡已放到你的账户"];
            }else if (!isJDEcard && isGuideDraw) {
                [weakSelf rebateApplySuccess:@"抽奖机会已放到你的账户"];
            }
        }];
    }];
}

#pragma mark - 抽奖界面
- (void)showLuckyDrawControl:(NSString *)lotteryId andOrderNumber:(NSString *)orderNumber luckyDrawFinish:(void(^)(NSDictionary *dict))complete
{
    WS(weakSelf);
    CustomWKWebViewController *wkWebView = [[CustomWKWebViewController alloc]init];
    NSString *server = [NSString stringWithFormat:SERVERREQUESTURL(DRAW),lotteryId,@"",orderNumber];
     NSString *newServer = [server stringByReplacingOccurrencesOfString:@"/app" withString:@""];
    wkWebView.pdfURLString = newServer;
    [wkWebView setLuckyDrawFinishBlock:^(NSDictionary *result) {
        complete(result);
    }];
    [wkWebView setDismissLuckyDrawController:^{
        [weakSelf payButtonClickAction];
    }];
    [self presentViewController:wkWebView animated:YES completion:nil];
}



#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    switch (section) {
        case 0:
        case 1:
        case 2:
        case 4:
            return 1;
            break;
        case 3:
        {
            return self.orderDetails.orderdetailList.count+1;
        }
            break;
        case 5:
        {
            return self.promotionalArray.count;
        }
            break;
        default:
            break;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0://订单信息
        {
            OrderInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"firstcell" forIndexPath:indexPath];
            cell.model = self.orderDetails;
            return cell;
        }
            break;
        case 1://客户信息
        {
            PersonInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"secondcell" forIndexPath:indexPath];
            cell.model = self.orderDetails.consumer;
            return cell;
        }
            break;
        case 2://收货信息
        {
            GoodsInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"thirdcell" forIndexPath:indexPath];
            cell.model = self.orderDetails.order;
            return cell;
        }
            break;
        case 3://商品清单
        {
            if (indexPath.row == self.orderDetails.orderdetailList.count) {
                
                //商品总计
                AllpriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sixthcell" forIndexPath:indexPath];
                cell.model = self.customerDrawModel;
                cell.promotionalArray = self.promotionalArray;
                cell.goodsArray = self.orderDetails.orderdetailList;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
                
            }else
            {
                //单个商品
                CommodityListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fourthcell" forIndexPath:indexPath];
                cell.orderDetailslist = [self.orderDetails.orderdetailList objectAtIndex_opple:indexPath.row];
                return cell;
            }
        }
            break;
        case 4://附件信息
        {
            
                AdditionalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fifthcell" forIndexPath:indexPath];
                cell.model = self.orderDetails.order;
                return cell;
        }
            break;
        case 5://促销信息
        {
            PromotionalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PromotionalTableViewCell" forIndexPath:indexPath];
            NSString *describe = nil;
            cell.userInteractionEnabled = self.isUserInteractionEnabled;
            id object = self.promotionalArray[indexPath.row];
            if ([object isKindOfClass:[PromotionalGoodsModel class]]) {
                PromotionalGoodsModel *goodsModel = object;
                cell.accessoryType = goodsModel.isSelected?UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
                describe = [NSString stringWithFormat:@"赠送商品:%@%ld",goodsModel.goods.name,goodsModel.count];
            }else if ([object isKindOfClass:[PromotionalDeductionModel class]]){
                PromotionalDeductionModel *deductionModel = self.promotionalArray[indexPath.row];
                cell.accessoryType = deductionModel.isSelected?UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
                describe = [NSString stringWithFormat:@"抵扣金额:%ld",deductionModel.total];
            }
            cell.promotionalTitleLabel.text = describe;
            return cell;
        }
            break;
            
        default:
            break;
    }
    return [UITableViewCell new];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            return 84;
        }
            break;
        case 1:
        {
            return 110;
        }
            break;
        case 2:
        {
            return 90;
        }
            break;
        case 3:
        {
            //商品总计
            if (indexPath.row == self.orderDetails.orderdetailList.count) {
                
                return 50;
            }
            else
            {
            //单个商品
               return 80;
            }
        }
            break;
        case 4:
        {
            return 75;
        }
            break;
        case 5:
        {
            return 44;
        }
            break;
            
        default:
            break;
    }
    return 100;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    OrderDetailsSectionHeaderView *headerView = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailsSectionHeaderView"];
    headerView.sectionHeaderTitleLabel.text = [self.sectionTitle objectAtIndex_opple:section];
    return headerView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 5 && self.isUserInteractionEnabled) {
        PromotionalTableViewCell *promotionalCell = [tableView cellForRowAtIndexPath:indexPath];
        id object = self.promotionalArray[indexPath.row];
        if ([object isKindOfClass:[PromotionalGoodsModel class]]) {
            PromotionalGoodsModel *goodsModel = object;
            goodsModel.isSelected = !goodsModel.isSelected;
            promotionalCell.accessoryType = goodsModel.isSelected?UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
        }else if ([object isKindOfClass:[PromotionalDeductionModel class]]){
            PromotionalDeductionModel *deductionModel = object;
            deductionModel.isSelected = !deductionModel.isSelected;
            promotionalCell.accessoryType = deductionModel.isSelected?UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
            /// 刷新总金额
            [self.orderDetailsTableview reloadData];
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionTitle.count;
}

#pragma mark -打印订单
- (void)AirprintButtonClick:(UIButton *)button
{
    NSString *server = [NSString stringWithFormat:SERVERREQUESTURL(ORDERDETAILSURL),[Shoppersmanager manager].Shoppers.employee.departid,self.orderCode];
    NSString *newServer = [server stringByReplacingOccurrencesOfString:@"/app" withString:@""];
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:newServer]]];
    self.webView.navigationDelegate = self;
}

#pragma mark - <WKNavigationDelegate>
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    [self CreateMBProgressHUDLoding];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self RemoveMBProgressHUDLoding];
    WS(weakSelf);
    [AirPrintManager printOrderWithdataSoure:[webView viewPrintFormatter] printSuccess:^{
        [weakSelf SuccessMBProgressView:@"打印成功"];
    } printError:^{
        [weakSelf ErrorMBProgressView:@"打印失败"];
    }];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [self ErrorMBProgressView:@"操作失败"];
}


#pragma mark -预览订单、撤销订单
- (void)PreviewButtonClick:(UIButton *)button
{
    WS(weakSelf);
    if ([button.currentTitle isEqualToString:@"预览"]) {
        NSString *server = [NSString stringWithFormat:SERVERREQUESTURL(ORDERDETAILSURL),[Shoppersmanager manager].Shoppers.employee.departid,self.orderCode];
        NSString *newServer = [server stringByReplacingOccurrencesOfString:@"/app" withString:@""];
        CustomWKWebViewController *pdfvc = [[CustomWKWebViewController alloc]init];
        pdfvc.pdfURLString = newServer;
        [weakSelf presentViewController:pdfvc animated:YES completion:nil];
        
    }else if ([button.currentTitle isEqualToString:@"撤销订单"])
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请确认是否撤销订单" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
        {
            [weakSelf CreateMBProgressHUDLoding];
            [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@/%@/%@",SERVERREQUESTURL(RESETORDER),_orderCode,@"001",@"005"] WithCallClass:weakSelf WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
                [weakSelf RemoveMBProgressHUDLoding];
                if ([returnValue[@"code"] isEqualToNumber:@0]) {
                    [weakSelf SuccessMBProgressView:@"撤销成功"];
                    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.01)];
                    [weakSelf.orderDetailsTableview beginUpdates];
                    weakSelf.orderDetailsTableview.tableHeaderView = view;
                    weakSelf.orderDetailsTableview.tableFooterView = nil;
                    [weakSelf.orderDetailsTableview endUpdates];
                    weakSelf.orderDetails.order.orderState = @"005";
                    weakSelf.isUserInteractionEnabled = NO;
                    [weakSelf.orderDetailsTableview reloadData];
                    if (weakSelf.DelecteAndPayButtonBlock) {
                        weakSelf.DelecteAndPayButtonBlock(_cellindex,@"005");
                    }
                } else {
                    [weakSelf ErrorMBProgressView:returnValue[@"message"]];
                }
                
            } WithErrorCodeBlock:^(id errorCodeValue) {
                [weakSelf RemoveMBProgressHUDLoding];
                [weakSelf ErrorMBProgressView:NETWORK];
            } WithFailureBlock:^(NSError *error) {
                [weakSelf RemoveMBProgressHUDLoding];
                [weakSelf ErrorMBProgressView:error.localizedDescription];
            }];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}

- (id)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    return self.PDFpath;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - 分享订单
- (void)ShareButtonClick:(UIButton *)sender
{
    ShareGoodsViewController *shareController = [[ShareGoodsViewController alloc]init];
    shareController.isShareOrderbill = YES;
    shareController.orderBillNumber = self.orderCode;
    shareController.shareImage = [UIImage imageNamed:@"Icon-83.5"];
    shareController.preferredContentSize = CGSizeMake(290, 120);
    shareController.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *popover = shareController.popoverPresentationController;
    popover.permittedArrowDirections = UIPopoverArrowDirectionUp;
    popover.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:sender];
    [self presentViewController:shareController animated:YES completion:nil];
}



@end
