//
//  OrderDetailsViewController.m
//  total
//
//  Created by 曹云霄 on 16/6/27.
//  Copyright © 2016年 Delevin. All rights reserved.
//

#import "OrderDetailsViewController.h"
#import "NewOrderTableViewCell.h"
#import "HeaderView.h"
#import "screeningButton.h"
#import "SaveCommitView.h"
#import "PromptTableViewController.h"
#import "BookingTableViewCell.h"
#import "KMDatePicker.h"
#import "DetailTimeViewController.h"
#import "WYPopoverController.h"
#import "OrderDetailsView.h"
#import "CommitTableViewCell.h"







@interface OrderDetailsViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>


/**
 *  选择框
 */
@property (nonatomic,strong) WYPopoverController *settingsPopoverController;

/**
 *  当前油站
 */
@property (nonatomic,strong) screeningButton *locationButton;

/**
 *  订单详情数据源
 */
@property (nonatomic,strong) NSMutableArray *orderDetailsArray;

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

/**
 *  是否可编辑
 */
@property (nonatomic,assign) BOOL isEditing;

@end

@implementation OrderDetailsViewController


- (NSMutableArray *)orderDetailsArray
{
    if (!_orderDetailsArray) {
        _orderDetailsArray = [NSMutableArray array];
    }
    return _orderDetailsArray;
}


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


- (void)createBackBtn{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    btn.frame  = CGRectMake(0, 0, 12, 20);
    [btn addTarget:self action:@selector(backClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = back;
}

#pragma mark -返回
- (void)backClicked {
    if (self.boolValue) {
        [self PopToRootViewControllerAnimated:YES];
    }else {
        [self PopViewControllerAnimated:YES];
    }
}

#pragma mark -传入订单信息OrderBill对象
- (void)setOrderDetails:(OrderBill *)orderDetails
{
    _orderDetails = orderDetails;
    NSDictionary *dict = [_orderDetails toDictionary];
    [self.orderDetailsArray removeAllObjects];
    for (NSDictionary *dtls in dict[@"dtls"]) {
        NSMutableDictionary *information = [NSMutableDictionary dictionary];
        [information setValue:dtls[@"item"] forKey:@"oilType"];
        [information setValue:dtls[@"receiveTime"] forKey:@"orderTime"];
        [information setValue:dtls[@"quantity"] forKey:@"orderNumber"];
        [information setValue:dtls[@"uuid"] forKey:@"orderUuid"];
        [self.orderDetailsArray addObject:information];
    }
    [self.oilOrderDetailsTableview reloadData];
}


#pragma mark -获取订单详情信息
- (void)getOrderBillDetailsInformation
{
    __weak typeof(self) weakSelf = self;
    [IBTLoadingView showProgressLabel:@"加载中..."];
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/orderBill/get/%@",HTTP_REST_API_BASE_URL,self.orderUUIDString] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
        
        [IBTLoadingView hideHUDWithText:nil];
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            weakSelf.orderDetails = [[OrderBill alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.isEditing = [weakSelf.orderDetails.state isEqualToString:@"initial"];
            [weakSelf setupHeaderViewAndFootView];
        } else {
            [IBTLoadingView showTextOnly:returnValue[@"message"]];
        }
        
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
    
    //获得油品信息
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,OILTYPE] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
        
        [IBTLoadingView hideHUDWithText:nil];
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            weakSelf.oilTypeListDatasArray = returnValue[@"data"];
        }
    } withFailed:^(NSError *failed) {
        
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}



#pragma mark -UI
- (void)uiConfigAction
{
    self.oilOrderDetailsTableview.dataSource = self;
    self.oilOrderDetailsTableview.delegate = self;
}

#pragma mark -设置头视图，尾视图
- (void)setupHeaderViewAndFootView
{
    //头视图
    OrderDetailsView *detailView = [OrderDetailsView initializeView];
    detailView.frame = CGRectMake(0, 0, ScreenSize.width, 200);
    detailView.commitState.text = [GTOCommonTools returnOrderStateString:self.orderDetails.state];
    detailView.commitState.textColor = [GTOCommonTools returnOrderSateColor:self.orderDetails.state];
    detailView.orderNumber.text = self.orderDetails.billnumber;
    detailView.model = self.orderDetails;
    UIView *headerView = [[UIView alloc]initWithFrame:detailView.frame];
    [headerView addSubview:detailView];
    self.oilOrderDetailsTableview.tableHeaderView = headerView;
//    //尾视图
//    if ([self.orderDetails.state isEqualToString:@"initial"]) {
//        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 100)];
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//        [footerView addSubview:button];
//        button.layer.borderWidth = 1.0f;
//        button.layer.cornerRadius = TCcornerRadius;
//        button.layer.masksToBounds = YES;
//        button.layer.borderColor = RGBA(12, 96, 163, 1).CGColor;
//        [button setTitleColor:RGBA(12, 96, 163, 1) forState:UIControlStateNormal];
//        [button setTitle:@"添加" forState:UIControlStateNormal];
//        [button addTarget:self action:@selector(addCellAction) forControlEvents:UIControlEventTouchUpInside];
//        [button mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(footerView.mas_left).mas_offset(60);
//            make.right.equalTo(footerView.mas_right).mas_offset(-60);
//            make.center.equalTo(footerView);
//            make.height.mas_equalTo(40);
//        }];
//        self.oilOrderDetailsTableview.tableFooterView = footerView;
//    }
    //保存、提交
    if (![self.orderDetails.state isEqualToString:@"canceled"] && ![self.orderDetails.state isEqualToString:@"accomplished"] && ![self.orderDetails.state isEqualToString:@"shipping"] && ![self.orderDetails.state isEqualToString:@"shipped"]) {
        SaveCommitView *commitView = [self.orderDetails.state isEqualToString:@"initial"]?[SaveCommitView initializeTwo]:[SaveCommitView initializeThird];
        commitView.frame = CGRectMake(0,ScreenSize.height-164, ScreenSize.width,100);
        //删除
        [commitView setDelectButtonBlock:^{
            [self deleteOrderBill];
        }];
        //提交
        [commitView setCommitButtonBlock:^{
            [self commitOilOrder];
        }];
        //保存
        [commitView setSaveButtonBlock:^{
            [self saveOilOrder:^(NSDictionary *returnSaveuuid, OrderBill *order) {
                
            } isPushDetails:YES];
        }];
        //作废
        [commitView setInvalidButtonBlock:^{
            [self cancelOrderBill];
        }];
        [self.view addSubview:commitView];
    }else {
        self.oilOrderDetailsTableview.frame = CGRectMake(0, 0, ScreenSize.width, ScreenSize.height-64);
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //已提交
    if (![self.orderDetails.state isEqualToString:@"initial"]) {
        CommitTableViewCell *commitcell = [tableView dequeueReusableCellWithIdentifier:@"CommitTableViewCell" forIndexPath:indexPath];
        NSDictionary *dict = self.orderDetailsArray[indexPath.row];
        [commitcell.selectOilTypeButton setTitle:dict[@"oilType"][@"name"] forState:UIControlStateNormal];
        commitcell.bookingNumberField.text = [NSString stringWithFormat:@"%.6lf",[dict[@"orderNumber"] doubleValue]];
        commitcell.userInteractionEnabled = self.isEditing;
        [commitcell.arriveTimeButton setTitle:dict[@"orderTime"] forState:UIControlStateNormal];
        return commitcell;
    }
    //已保存
    CommitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommitTableViewCell" forIndexPath:indexPath];
    cell.bookingNumberField.tag = indexPath.row;
    cell.selectOilTypeButton.tag = indexPath.row;
    cell.arriveTimeButton.tag = indexPath.row;
    [cell.arriveTimeButton addTarget:self action:@selector(detailsTimeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.selectOilTypeButton addTarget:self action:@selector(selectOilTypeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    NSDictionary *dict = self.orderDetailsArray[indexPath.row];
    [cell.selectOilTypeButton setTitle:dict[@"oilType"][@"name"]?dict[@"oilType"][@"name"]:@"请输入" forState:UIControlStateNormal];
    cell.bookingNumberField.text = [NSString stringWithFormat:@"%.6lf",[dict[@"orderNumber"] doubleValue]];
    [cell.bookingNumberField addTarget:self action:@selector(textFieldEndEditing:) forControlEvents:UIControlEventEditingChanged];
    cell.bookingNumberField.placeholder = @"请输入";
    [cell.arriveTimeButton setTitle:dict[@"orderTime"]?dict[@"orderTime"]:@"请输入" forState:UIControlStateNormal];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.orderDetailsArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 142;
}


#pragma mark -添加cell
- (void)addCellAction
{
    if (self.oilTypeListDatasArray.count == self.orderDetailsArray.count) {
        [IBTLoadingView showTextOnly:[NSString stringWithFormat:@"只能添加%ld个油品",self.orderDetailsArray.count]];return;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [self.orderDetailsArray addObject:dict];
    [self.oilOrderDetailsTableview beginUpdates];
    [self.oilOrderDetailsTableview insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.orderDetailsArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [self.oilOrderDetailsTableview endUpdates];
}



#pragma mark -删除cell<删除某个油品>
- (void)delectCellButtonClick:(UIButton *)btn
{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"请确认是否删除" preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(self) weakSelf = self;
    [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.orderDetailsArray removeObjectAtIndex:btn.tag];
        [self.oilOrderDetailsTableview beginUpdates];
        [self.oilOrderDetailsTableview deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btn.tag inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        [self.oilOrderDetailsTableview endUpdates];
        [self.oilOrderDetailsTableview reloadData];
    }]];
    [self presentViewController:alertView animated:YES completion:nil];
}



#pragma mark -到油时间选择
- (void)detailsTimeButtonClick:(UIButton *)btn
{
    __weak typeof(self) weakSelf = self;
    DetailTimeViewController *dateView = [[DetailTimeViewController alloc]init];
    dateView.defaultTime = [self dateAsString:[GTOCommonTools dateWithString:[btn currentTitle]]];
    [dateView setReturnSelectDate:^(NSString *dateString) {
        [weakSelf.orderDetailsArray[btn.tag] setValue:dateString forKey:@"orderTime"];
        [btn setTitle:dateString forState:UIControlStateNormal];
    }];
    dateView.preferredContentSize = CGSizeMake(ScreenSize.width, 200);
    self.settingsPopoverController = [[WYPopoverController alloc] initWithContentViewController:dateView];
    self.settingsPopoverController.popoverLayoutMargins = UIEdgeInsetsMake(10, 20, 10, 20);
    self.settingsPopoverController.wantsDefaultContentAppearance = NO;
    [self.settingsPopoverController presentPopoverAsDialogAnimated:YES
                                                           options:WYPopoverAnimationOptionFadeWithScale];
}

#pragma mark -油品选择监听
- (void)selectOilTypeButtonClick:(UIButton *)btn
{
    __weak typeof(self) weakSelf = self;
    PromptTableViewController *promptVoew = [[PromptTableViewController alloc]init];
    [promptVoew setSelectCellTitle:^(NSString *title,NSInteger cellindex) {
        [btn setTitle:title forState:UIControlStateNormal];
        [weakSelf.orderDetailsArray[btn.tag] setValue:weakSelf.oilTypeListDatasArray[cellindex] forKey:@"oilType"];
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    NSMutableArray *nameArray = [NSMutableArray array];
    for (NSDictionary *dict in self.oilTypeListDatasArray) {
        [nameArray addObject:dict[@"name"]];
    }
    //已经选中的油品
    NSMutableArray *selecteArray = [NSMutableArray array];
    if (self.orderDetailsArray.count) {
        for (int i=0; i<self.orderDetailsArray.count; i++) {
            NSDictionary *dict = self.orderDetailsArray[i];
            if (![[dict allKeys] count]) break;
            [selecteArray addObject:dict[@"oilType"][@"name"]];
        }
        promptVoew.selecteArray = selecteArray;
    }
    promptVoew.datasArray = nameArray;
    promptVoew.currentTitle = [btn currentTitle];
    IBTUINavigationController *nav = [[IBTUINavigationController alloc]initWithRootViewController:promptVoew];
    promptVoew.title = @"请选择油品";
    [self presentViewController:nav animated:YES completion:nil];
}


#pragma mark -保存订油单(uuid为空新增、不为空修改)
- (void)saveOilOrder:(void(^)(NSDictionary *returnSaveuuid,OrderBill *order))saveSuccess isPushDetails:(BOOL)boolValue
{
    for (NSDictionary *dict in self.orderDetailsArray) {
        NSArray *keyArray = [dict allKeys];
        if (![keyArray containsObject:@"oilType"]) {
            [IBTLoadingView showTextOnly:@"油品不能为空"];
            return;
        }
        if (![keyArray containsObject:@"orderNumber"]) {
            [IBTLoadingView showTextOnly:@"油品数量不能为空"];
            return;
        }
        if (![keyArray containsObject:@"orderTime"]) {
            [IBTLoadingView showTextOnly:@"到油时间不能为空"];
            return;
        }
    }
    [IBTLoadingView showProgressLabel:@"正在保存..."];
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    //生成订单
    OrderBill *order = [[OrderBill alloc]init];
    //油站经营类型
    order.operatingType = self.orderDetails.operatingType;
    //订单状态
    order.state = @"initial";
    order.version = self.orderDetails.version;
    order.uuid = self.orderDetails.uuid;
    order.billnumber = self.orderDetails.billnumber;
    //所属业主公司
    UCN *company = [[UCN alloc]init];
    company.code = user.orgCode;
    company.name = user.orgName;
    company.uuid = user.orguuid;
    order.org = company;
    //所属油站
    UCN *store = [[UCN alloc]init];
    store.code = self.orderDetails.store.code;
    store.name = self.orderDetails.store.name;
    store.uuid = self.orderDetails.store.uuid;
    order.store = store;
    //创建人
    OperateInfo2 *createinfo = [[OperateInfo2 alloc]init];
    createinfo.time = [GTOCommonTools GetCurrenttime];
    Operator *info = [[Operator alloc]init];
    info.operName = user.f_user_name;
    info.fid = user.f_user_uuid;
    createinfo.operator = info;
    order.createInfo = createinfo;
    //订单详情
    NSMutableArray *orderArray = [NSMutableArray array];
    for (NSDictionary *dict in self.orderDetailsArray) {
        OrderBillDtl *billDetails = [[OrderBillDtl alloc]init];
        UCN *item = [[UCN alloc]init];
        item.code = dict[@"oilType"][@"code"];
        item.name = dict[@"oilType"][@"name"];
        item.uuid = dict[@"oilType"][@"uuid"];
        billDetails.item = item;
        billDetails.quantity = [NSNumber numberWithDouble:[dict[@"orderNumber"] doubleValue]];
        billDetails.receiveTime = dict[@"orderTime"];
        billDetails.uuid = dict[@"orderUuid"];
        [orderArray addObject:billDetails];
    }
    __weak typeof(self) weakSelf = self;
    order.dtls = (NSArray<OrderBillDtl> *)orderArray;
    order.quantity = [NSNumber numberWithInteger:self.orderDetailsArray.count];
    NSString *urlString = [NSString stringWithFormat:@"%@/orderBill/save?operId=%@&operName=%@&time=%@",HTTP_REST_API_BASE_URL,user.f_user_uuid,user.f_user_name,[GTOCommonTools GetCurrenttime]];
    //把URL中的汉字转成UTF8格式
    NSString *string = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *orderDict = [order toDictionary];
    [HttpRequestManager requestNetworkwithURL:string withRequestType:ZERO withParameter:orderDict  withSuccess:^(id returnValue) {
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            
            if (!boolValue) {
                [IBTLoadingView hideHUDWithText:nil];
                saveSuccess(returnValue[@"data"],order);return;
            }
            [IBTLoadingView hideHUDWithText:@"保存成功"];
            [weakSelf gotoOrderDetail:returnValue[@"data"][@"uuid"]];
        }else
        {
            [IBTLoadingView hideHUDWithText:returnValue[@"message"]];
        }
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:@"保存失败"];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}

#pragma mark -订单详情
- (void)gotoOrderDetail:(NSString *)uuid
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        OrderDetailsViewController *orderDetail = [self.storyboard instantiateViewControllerWithIdentifier:@"OrderDetailsViewController"];
        orderDetail.orderUUIDString = uuid;
        orderDetail.oilTypeListDatasArray = self.oilTypeListDatasArray;
        orderDetail.title = @"订油单详情";
        orderDetail.boolValue = YES;
        [self PushViewController:orderDetail animated:YES];
    });
}


#pragma mark -提交订油单
- (void)commitOilOrder
{
    //先调用保存接口
    __weak typeof(self) weakSelf = self;
    [self saveOilOrder:^(NSDictionary *returnSaveuuid, OrderBill *order) {
        [weakSelf saveOrderRequest:returnSaveuuid orderDetails:order];
    } isPushDetails:NO];
}

#pragma mark -提交订单请求
- (void)saveOrderRequest:(NSDictionary *)dict orderDetails:(OrderBill *)order
{
    __weak typeof(self) weakSelf = self;
    [self showAlertViewController:@"确定提交该订油单吗？" withCompleted:^{
        [IBTLoadingView showProgressLabel:@"正在提交..."];
        ICRUserUtil *user = [ICRUserUtil sharedInstance];
        RsOperateInfo *commit = [[RsOperateInfo alloc]init];
        commit.operId = user.f_user_uuid;
        commit.operName = user.f_user_name;
        commit.time = [GTOCommonTools GetCurrenttime];
        commit.enterprise = user.f_enterprise_uuid;
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/orderBill/submit/%@",HTTP_REST_API_BASE_URL,dict[@"uuid"]] withRequestType:ZERO withParameter:[commit toDictionary] withSuccess:^(id returnValue) {
            
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                [IBTLoadingView hideHUDWithText:@"提交成功"];
                [weakSelf gotoOrderDetail:dict[@"uuid"]];
                
            } else {
                [IBTLoadingView hideHUDWithText:returnValue[@"message"]];
                [weakSelf gotoOrderDetail:dict[@"uuid"]];
            }
            
        } withFailed:^(NSError *failed) {
            [IBTLoadingView hideHUDWithText:@"提交失败"];
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    }];
}

#pragma mark - 订油量输入
- (void)textFieldEndEditing:(UITextField *)textField
{
    if (![self isPureInt:textField.text]) {
        [IBTLoadingView showTextOnly:@"格式不正确"];
        textField.text = nil;
        return;
    }
    [self.orderDetailsArray[textField.tag] setValue:textField.text forKey:@"orderNumber"];
}


#pragma mark - 判断是否是纯数字
- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    double val;
    if (string.length == 1 && ([string isEqualToString:@"."])) {
        return NO;
    }
    return[scan scanDouble:&val] && [scan isAtEnd];
}



#pragma mark -删除订油单
- (void)deleteOrderBill
{
    __weak typeof(self) weakSelf = self;
    [self showAlertViewController:@"确定删除该订油单吗？" withCompleted:^{
        [weakSelf userSureDeleteOrCancelOperation:@"删除" returnBlock:^{
            
            [IBTLoadingView showProgressLabel:@"删除中..."];
            ICRUserUtil *user = [ICRUserUtil sharedInstance];
            //操作人信息
            RsOperateInfo *info = [[RsOperateInfo alloc]init];
            info.operId = user.f_user_uuid;
            info.time = [GTOCommonTools GetCurrenttime];
            info.operName = user.f_user_name;
            info.enterprise = user.f_enterprise_uuid;
            [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/orderBill/remove/%@",HTTP_REST_API_BASE_URL,weakSelf.orderDetails.uuid] withRequestType:ZERO withParameter:[info toDictionary] withSuccess:^(id returnValue) {
                
                if ([returnValue[@"success"] isEqualToNumber:@1]) {
                    [IBTLoadingView hideHUDWithText:@"删除成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        if (weakSelf.boolValue) {
                            [weakSelf PopToRootViewControllerAnimated:YES];
                        } else {
                            [weakSelf returnUUIDsingAfterDeleteOrCancel:YES];
                            [weakSelf PopViewControllerAnimated:YES];
                        }
                    });
                } else {
                    [IBTLoadingView hideHUDWithText:@"删除失败"];
                }
                
            } withFailed:^(NSError *failed) {
                [IBTLoadingView hideHUDWithText:@"删除失败"];
                [IBTLoadingView showTextOnly:failed.localizedDescription];
            }];
        }];
    }];
}

#pragma mark -做废订油单
- (void)cancelOrderBill
{
    __weak typeof(self) weakSelf = self;
    [self userSureDeleteOrCancelOperation:@"作废" returnBlock:^{
        [IBTLoadingView showProgressLabel:@"作废中..."];
        ICRUserUtil *user = [ICRUserUtil sharedInstance];
        //操作人信息
        RsOperateInfo *info = [[RsOperateInfo alloc]init];
        info.operId = user.f_user_uuid;
        info.time = [GTOCommonTools GetCurrenttime];
        info.operName = user.f_user_name;
        info.enterprise = user.f_enterprise_uuid;
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/orderBill/cancel/%@",HTTP_REST_API_BASE_URL,self.orderDetails.uuid] withRequestType:ZERO withParameter:[info toDictionary] withSuccess:^(id returnValue) {
            
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                [IBTLoadingView hideHUDWithText:@"作废成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (weakSelf.boolValue) {
                        [weakSelf PopToRootViewControllerAnimated:YES];
                    } else {
                        [weakSelf returnUUIDsingAfterDeleteOrCancel:NO];
                        [weakSelf PopViewControllerAnimated:YES];
                    }
                });
            } else {
                [IBTLoadingView hideHUDWithText:@"作废失败"];
            }
            
        } withFailed:^(NSError *failed) {
            [IBTLoadingView hideHUDWithText:@"作废失败"];
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    }];
}


#pragma mark -删除或者作废后返回此订单UUID
- (void)returnUUIDsingAfterDeleteOrCancel:(BOOL)isDelete
{
    if (self.deleteAndCancelOrderBillblock) {
        self.deleteAndCancelOrderBillblock(self.orderUUIDString,isDelete);
    }
}

#pragma mark -删除、作废用户确认
- (void)userSureDeleteOrCancelOperation:(NSString *)title returnBlock:(void(^)())complete
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"请确认是否执行%@操作",title] preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(self) weakSelf = self;
    [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        complete();
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -矫正时区的影响(少8小时)
- (NSDate*)dateAsString:(NSDate*)date {
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    formatter.dateFormat=@"yy-MM-dd HH:mm:ss";
    NSTimeZone *timeZone=[NSTimeZone systemTimeZone];
    NSInteger seconds=[timeZone secondsFromGMTForDate:date];
    NSDate *newDate=[date dateByAddingTimeInterval:seconds];
    return newDate;
    
}

@end
