//
//  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 "PDFViewController.h"
#import "ShareGoodsViewController.h"

@interface OrderdetailsViewController ()<UITableViewDelegate,UITableViewDataSource,QLPreviewControllerDataSource>


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

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



@end

@implementation OrderdetailsViewController


#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];
}



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


#pragma mark -获取订单详情
- (void)getOrderDetailsData
{
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",SERVERREQUESTURL(ORDERDETAILS),self.orderCode] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            self.orderDetails = [[OrderBill alloc]initWithDictionary:returnValue[@"data"] error:nil];
            [self.orderDetailsTableview reloadData];
            //默认弹出支付框
            if (self.isShowPayButton && [self.orderDetails.order.orderState isEqualToString:@"001"]) {
                [self PayButtonClick];
            }
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
    }];
}

#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.isDelectedButton?@"撤销订单":@"预览" 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.isDelectedButton) {
     
        //打印
        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(PayButtonClick) forControlEvents:UIControlEventTouchUpInside];
    payButton.backgroundColor = kMainBlueColor;
    payButton.layer.masksToBounds = YES;
    payButton.layer.cornerRadius = kCornerRadius;
    [footerView addSubview:payButton];
    self.orderDetailsTableview.tableFooterView = footerView;
}


#pragma mark -调出支付框
- (void)PayButtonClick
{
    SettlementViewController *settlement = [[SettlementViewController alloc]init];
    //支付成功
    __weak typeof(self) weakSelf = self;
    [settlement setPaySuccessReturnBlock:^{
        
        weakSelf.isDelectedButton = NO;
        weakSelf.isShowattachment = YES;
        self.sectionTitle = @[@"订单信息",@"客户信息",@"收货信息",@"商品清单",@"附件信息"];
        [weakSelf CreateTableviewHeaderView];
        [weakSelf getOrderDetailsData];
        weakSelf.orderDetailsTableview.tableFooterView = nil;
        if (weakSelf.DelecteAndPayButtonBlock) {
            weakSelf.DelecteAndPayButtonBlock(_cellindex,@"002");
        }
    }];
    settlement.preferredContentSize = CGSizeMake(380, 500);
    settlement.goodsArray = self.orderDetails.orderdetailList;
    settlement.orderCode = _orderCode;
    settlement.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = settlement.popoverPresentationController;
    pop.sourceView = settlement.view;
    [self presentViewController:settlement animated:YES completion:nil];
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    switch (section) {
        case 0:
        {
            return 1;
        }
            break;
        case 1:
        {
            return 1;
        }
            break;
        case 2:
        {
            return 1;
        }
            break;
        case 3:
        {
            return self.orderDetails.orderdetailList.count+1;
        }
            break;
        case 4:
        {
           return 1;
        }
            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.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://附件信息
        {
            //是否显示
            if (_isShowattachment) {
             
                AdditionalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fifthcell" forIndexPath:indexPath];
                cell.model = self.orderDetails.order;
                return cell;
            }
        }
            break;
        default:
            break;
    }
    return nil;
}


- (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:
        {
            //是否显示附件信息
            if (!_isShowattachment) {
                
                return 0;
            }
            return 75;
        }
            break;
            
        default:
            break;
    }
    return 100;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
        
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
    //区头文字
    UILabel *Titlelabe = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, ScreenWidth, 50)];
    Titlelabe.text = [NSString stringWithFormat:@"       %@",[self.sectionTitle objectAtIndex_opple:section]];
    view.backgroundColor = kTCColor(236, 236, 236);
    Titlelabe.backgroundColor = [UIColor whiteColor];
    Titlelabe.font = [UIFont systemFontOfSize:13];
    [view addSubview:Titlelabe];
    return view;
}



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



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


#pragma mark -打印订单
- (void)AirprintButtonClick:(UIButton *)button
{
    [self DownloadPDF:^(id Value) {
        
        [self CreateMBProgressHUDLoding];
        [[NetworkRequestClassManager Manager] DownloadPDFdatasWithURL:Value WithReturnValueBlock:^(id returnValue) {
            
            [self RemoveMBProgressHUDLoding];
            [self callAirprintWithdata:returnValue SuccessBlock:^{
                [self SuccessMBProgressView:@"打印完成"];
            } ErrorBlock:^{
                [self ErrorMBProgressView:@"打印失败"];
            }];
            
        } WithErrorCodeBlock:^(id errorCodeValue) {
            
        } WithFailureBlock:^(id error) {
            [self RemoveMBProgressHUDLoding];
        }];
    }];
}


#pragma mark -下载PDF
- (void)DownloadPDF:(void(^)(id returnValue))success
{
    
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",SERVERREQUESTURL(DOWNLOADPDF),_orderCode] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        NSString *url = [NSString stringWithFormat:@"%@",returnValue[@"data"]];
        success(url);

        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [self RemoveMBProgressHUDLoding];
        [self ErrorMBProgressView:@"网络中断"];
    } WithFailureBlock:^(id error) {
        [self RemoveMBProgressHUDLoding];
    }];
}


#pragma mark -预览订单、撤销订单
- (void)PreviewButtonClick:(UIButton *)button
{
    if ([button.currentTitle isEqualToString:@"预览"]) {
        
        __weak typeof(self) weakSelf = self;
        [self DownloadPDF:^(id returnValue) {
            
//            self.PDFpath = returnValue;
//            QLPreviewController *previewController = [[QLPreviewController alloc] init];
//            previewController.dataSource = weakSelf;
//            previewController.navigationController.navigationBarHidden = YES;
//            [weakSelf presentViewController:previewController animated:YES completion:nil];
            
            PDFViewController *pdfvc = [[PDFViewController alloc]init];
            pdfvc.pdfURLString = returnValue;
            [weakSelf presentViewController:pdfvc animated:YES completion:nil];
        }];
        
    }else if ([button.currentTitle isEqualToString:@"撤销订单"])
    {
        __weak typeof(self) weakSelf = self;
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请确认是否撤销订单" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
        {
            [self CreateMBProgressHUDLoding];
            [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@/%@/%@",SERVERREQUESTURL(RESETORDER),_orderCode,@"001",@"005"] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
                [self RemoveMBProgressHUDLoding];
                if ([returnValue[@"code"] isEqualToNumber:@0]) {
                    [self SuccessMBProgressView:@"撤销成功"];
                    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
                    self.orderDetailsTableview.tableHeaderView = view;
                    self.orderDetailsTableview.tableFooterView = nil;
                    self.orderDetails.order.orderState = @"005";
                    [self.orderDetailsTableview reloadData];
                    if (self.DelecteAndPayButtonBlock) {
                        self.DelecteAndPayButtonBlock(_cellindex,@"005");
                    }
                }
                else
                {
                    [self ErrorMBProgressView:returnValue[@"message"]];
                }
                
            } WithErrorCodeBlock:^(id errorCodeValue) {
                
            } WithFailureBlock:^(id error) {
                
                [self RemoveMBProgressHUDLoding];
            }];
        }]];
        [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
