//
//  NewRequestViewController.m
//  total
//
//  Created by 曹云霄 on 16/6/21.
//  Copyright © 2016年 free. All rights reserved.
//

#import "NewRequestViewController.h"
#import "TypeTableViewCell.h"
#import "OilTableViewCell.h"
#import "PriceTableViewCell.h"
#import "NumberTableViewCell.h"
#import "TimeSelectTableViewCell.h"
#import "SaveCommitView.h"
#import "TimeSelectTableViewCell.h"
#import "WYPopoverController.h"
#import "TimeSelectViewController.h"
#import "wareHouseView.h"
#import "SeeRequestViewController.h"
#import "PromptTableViewController.h"
#import "screeningButton.h"

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

/**
 *  popover
 */
@property (nonatomic,strong) WYPopoverController *settingsPopoverController;

/**
 *  配送区域数据源
 */
@property (nonatomic,strong) NSMutableArray *distributionArray;

/**
 *  油品列表信息
 */
@property (nonatomic,strong) NSArray *oilTypeListDatasArray;

/**
 *  记录油价信息
 */
@property (nonatomic,strong) QueryResult *oilPrice;

/**
 *  建仓单详情
 */
@property (nonatomic,strong) DepotRequestBill *orderDetails;



@end

@implementation NewRequestViewController

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

- (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.isSaveDetails) {
        [self PopToRootViewControllerAnimated:YES];
    }else {
        [self PopViewControllerAnimated:YES];
    }
}

#pragma mark -获取配送区域、油品信息、未提交详情
- (void)getOilTypeDistributionList
{
    __weak typeof(self) weakSelf = self;
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    dispatch_queue_t queue = dispatch_queue_create("顺序执行", DISPATCH_QUEUE_SERIAL);
    dispatch_group_t group = dispatch_group_create();
    //任务1->获取配送区域
    if (![[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
        dispatch_group_async(group, queue, ^{
            dispatch_suspend(queue);
            [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,DISTRIBUTION] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
                if ([returnValue[@"success"] isEqualToNumber:@1]) {
                    weakSelf.distributionArray = returnValue[@"data"];
                } else {
                    [IBTLoadingView showTextOnly:returnValue[@"message"]];
                }
                dispatch_resume(queue);
            } withFailed:^(NSError *failed) {
                dispatch_resume(queue);
                [IBTLoadingView showTextOnly:failed.localizedDescription];
            }];
        });
    }else {
        self.distributionArray = [NSMutableArray array];
        for (NSDictionary *dict in [ICRUserUtil sharedInstance].storeArray) {
            [self.distributionArray addObject:dict[@"deliveryArea"]];
        }
    }

    //任务二->获得油品信息
    dispatch_group_async(group, queue, ^{
        [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"];
            } else {
                [IBTLoadingView showTextOnly:returnValue[@"message"]];
            }
        } withFailed:^(NSError *failed) {
            
            [IBTLoadingView hideHUDWithText:nil];
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    });
    //获取建仓单详情
    if (self.isSaveDetails) {
        [self getOrderDetailsDatas];
        [self getOilPriceDatas];
    }
}

#pragma mark -获取配送区域、油品的油价数据
- (void)getOilPriceDatas
{
    __weak typeof(self) weakSelf = self;
    if (!self.oilTypeDict || !self.distributionDict) {
        return;
    }
    QueryDefinition2 *query = [[QueryDefinition2 alloc]init];
    query.pageSize = 10;
    //配送区域
    QueryCondition *condition = [[QueryCondition alloc]init];
    condition.operation = @"deliveryAreaUuidEquals";
    condition.parameters = @[self.distributionDict[@"uuid"]];
    //油品信息
    QueryCondition *oilType = [[QueryCondition alloc]init];
    oilType.operation = @"gasItemUuidEquals";
    oilType.parameters = @[self.oilTypeDict[@"uuid"]];
    //价格类别
    QueryCondition *priceCategory = [[QueryCondition alloc]init];
    priceCategory.operation = @"categoryEquals";
    priceCategory.parameters = @[@"generalTradePrice"];
    
    TimeSelectTableViewCell *timeCell = [self.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    //开始时间
    QueryCondition *beginDate = [[QueryCondition alloc]init];
    beginDate.operation = @"effectiveStartTimeLess";
    beginDate.parameters = @[[NSString stringWithFormat:@"%@ 00:00:00",timeCell.beginTimeButton.currentTitle]];
    //结束时间
    QueryCondition *endDate = [[QueryCondition alloc]init];
    endDate.operation = @"effectiveEndTimeMore";
    endDate.parameters = @[[NSString stringWithFormat:@"%@ 23:59:59",timeCell.endTimeButton.currentTitle]];
    
    query.conditions = (NSArray<QueryCondition> *)@[condition,oilType,priceCategory,beginDate,endDate];
    NSLog(@"%@",[query toDictionary]);
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,DEPOTREQUEST] withRequestType:ZERO withParameter:[query toDictionary] withSuccess:^(id returnValue) {
        
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            weakSelf.oilPrice = [[QueryResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            PriceTableViewCell *cell = [weakSelf.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
            NumberTableViewCell *numberCell = [weakSelf.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
            //建仓价
            cell.contentLabe.text = [[weakSelf.oilPrice.records firstObject][@"salePrice"] stringValue];
            //申请总额
            if (numberCell.createNumberField.text.length != 0) {
               PriceTableViewCell *cell = [weakSelf.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:0]];
                CGFloat price = [[weakSelf.oilPrice.records firstObject][@"salePrice"] doubleValue] * [numberCell.createNumberField.text doubleValue];
                cell.contentLabe.text = [NSString stringWithFormat:@"%.2f",price];
            }
            
        } else {
            [IBTLoadingView showTextOnly:returnValue[@"message"]];
        }
    } withFailed:^(NSError *failed) {
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}

#pragma mark -获取未提交建仓申请详情
- (void)getOrderDetailsDatas
{
    __weak typeof(self) weakSelf = self;
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/depotRequest/get/%@",HTTP_REST_API_BASE_URL,self.orderUUID] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
        
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            weakSelf.orderDetails = [[DepotRequestBill alloc]initWithDictionary:returnValue[@"data"] error:nil];
            [weakSelf setupHeaderViewAndSaveCommitDelete];
            [weakSelf.createWarehouseTableView reloadData];
        } else {
            [IBTLoadingView showTextOnly:returnValue[@"message"]];
        }
        
    } withFailed:^(NSError *failed) {
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}


#pragma mark -UI
- (void)uiConfigAction
{
    self.createWarehouseTableView.delegate = self;
    self.createWarehouseTableView.dataSource = self;
    self.createWarehouseTableView.tableFooterView = [UIView new];
    [self setupHeaderViewAndSaveCommitDelete];
}

#pragma mark -设置headerView、保存、提交、删除
- (void)setupHeaderViewAndSaveCommitDelete
{
    //headerView
    if (self.isSaveDetails) {
        wareHouseView *headerView = [wareHouseView InitializeView];
        headerView.frame = CGRectMake(0, 0, ScreenSize.width, 80);
        UIView *loadHeaderView = [[UIView alloc]initWithFrame:headerView.frame];
        headerView.orderNumberLabe.text = self.orderDetails.billnumber;
        headerView.orderSateLabe.text = [GTOCommonTools returnOrderStateString:self.orderDetails.state];
        headerView.orderSateLabe.textColor = [GTOCommonTools returnOrderSateColor:self.orderDetails.state];
        [loadHeaderView addSubview:headerView];
        self.createWarehouseTableView.tableHeaderView = loadHeaderView;
    }
    //保存、提交
    __weak typeof(self) weakSelf = self;
    //保存详情界面
    SaveCommitView *commitView = self.isSaveDetails?[SaveCommitView initializeTwo]:[SaveCommitView initializeOne];
    commitView.frame = CGRectMake(0,ScreenSize.height-164, ScreenSize.width,self.isSaveDetails?100:164);
    [commitView setCommitButtonBlock:^{//提交
        [weakSelf commitOrder];
    }];
    [commitView setSaveButtonBlock:^{//保存
        [weakSelf saveOrderBill:YES returnSaveSateBlock:^(NSDictionary *dict, DepotRequestBill *orderbBill) {
        }];
    }];
    [commitView setDelectButtonBlock:^{//删除
        [weakSelf deleteOrder];
    }];
    [self.view addSubview:commitView];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0://类型
        {
            TypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TypeTableViewCell" forIndexPath:indexPath];
            cell.titleLabe.text = @"类型:";
            cell.contentLabe.text = @"普通";
            if (self.isSaveDetails) {
                [self.orderDetails.type isEqualToString:@"general"]?(cell.contentLabe.text = @"普通"):(cell.contentLabe.text = @"请选择");
            }
            return cell;
        }
            break;
        case 1://配送区域
        {
            TypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TypeTableViewCell" forIndexPath:indexPath];
            cell.titleLabe.text = @"配送区域:";
            //只有一个配送区域情况
            if (self.distributionArray.count == 1) {
                self.distributionDict = [self.distributionArray firstObject];
                cell.contentLabe.text = self.distributionDict[@"name"];
            }
            //无配送区域情况
            if (!self.distributionArray.count) {
                cell.contentLabe.text = @"无";
            }
            cell.userInteractionEnabled = self.distributionArray.count > 1;
            if (self.isSaveDetails) {
                cell.contentLabe.text = self.orderDetails.deliveryArea.name;
            }
            return cell;
        }
            break;
        case 2://时间
        {
            TimeSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TimeSelectTableViewCell" forIndexPath:indexPath];
            [cell.beginTimeButton addTarget:self action:@selector(beginTimeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [cell.endTimeButton addTarget:self action:@selector(endTimeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [cell.beginTimeButton setTitle:[[[GTOCommonTools GetCurrenttime] componentsSeparatedByString:@" "] firstObject] forState:UIControlStateNormal];
            [cell.endTimeButton setTitle:[[[GTOCommonTools GetCurrenttime] componentsSeparatedByString:@" "] firstObject] forState:UIControlStateNormal];
            if (self.isSaveDetails) {
                NSArray *beginTime = [self.orderDetails.deliveryTime.beginDateTime componentsSeparatedByString:@" "];
                NSArray *endTime = [self.orderDetails.deliveryTime.endDateTime componentsSeparatedByString:@" "];
                [cell.beginTimeButton setTitle:[beginTime firstObject] forState:UIControlStateNormal];
                [cell.endTimeButton setTitle:[endTime firstObject] forState:UIControlStateNormal];
            }
            return cell;
        }
            break;
        case 3://油品
        {
            OilTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OilTableViewCell" forIndexPath:indexPath];
            if (self.isSaveDetails) {
                cell.contentLabe.text = self.orderDetails.item.name;
            }
            return cell;
        }
            break;
        case 4://申请价格
        {
            PriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PriceTableViewCell" forIndexPath:indexPath];
            cell.headerImageView.image = TCImage(@"P");
            cell.titleLabe.text = @"申请价格";
            cell.unitLabe.text = @"元/吨";
            if (self.isSaveDetails) {
                cell.contentLabe.text = [self.orderDetails.reqPrice stringValue];
            }
            return cell;
        }
            break;
        case 5://申请数量
        {
            NumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NumberTableViewCell" forIndexPath:indexPath];
            cell.createNumberField.delegate = self;
            [cell.createNumberField addTarget:self action:@selector(changeTextfieldString:) forControlEvents:UIControlEventEditingChanged];
            if (self.isSaveDetails) {
                cell.createNumberField.text = [self.orderDetails.quantity stringValue];
            }
            return cell;
        }
            break;
        case 6://申请总额
        {
           PriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PriceTableViewCell" forIndexPath:indexPath];
            cell.headerImageView.image = TCImage(@"¥");
            cell.titleLabe.text = @"申请总额";
            cell.unitLabe.text = @"元";
            if (self.isSaveDetails) {
                cell.contentLabe.text = [NSString stringWithFormat:@"%.2f",[self.orderDetails.quantity doubleValue]*[self.orderDetails.reqPrice doubleValue]];
            }
            return cell;
        }
            break;
            
        default:
            break;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        return 90;
    }
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    switch (indexPath.row) {
        case 0://类型
        {
//            TypeTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//            PromptTableViewController *selectArea = [[PromptTableViewController alloc]init];
//            selectArea.title = @"选择建仓单类型";
//            selectArea.datasArray = @[@"普通"];
//            selectArea.currentTitle = cell.contentLabe.text;
//            //选择配送区后回调
//            [selectArea setSelectCellTitle:^(NSString *title,NSInteger cellindex) {
//                cell.contentLabe.text = title?title:@"请选择";
//                [weakSelf dismissViewControllerAnimated:YES completion:nil];
//            }];
//            IBTUINavigationController *nav = [[IBTUINavigationController alloc]initWithRootViewController:selectArea];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self presentViewController:nav animated:YES completion:nil];
//            });
        }
            break;
        case 1://配送区域
        {

            TypeTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            if (![ICRUserUtil sharedInstance].storeArray.count) {
                [IBTLoadingView showTextOnly:@"当前用户没有所属油站，不能选择配送区域"];return;
            }
            PromptTableViewController *selectArea = [[PromptTableViewController alloc]init];
            selectArea.title = @"选择配送区域";
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *dict in self.distributionArray) {
                if (![tempArray containsObject:dict[@"name"]]) {
                    [tempArray addObject:dict[@"name"]];
                }
            }
            selectArea.datasArray = tempArray;
            //选择配送区后回调
            [selectArea setSelectCellTitle:^(NSString *title,NSInteger cellindex) {
                cell.contentLabe.text = title?title:@"请选择";
                weakSelf.distributionDict = weakSelf.distributionArray[cellindex];
                [weakSelf getOilPriceDatas];
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }];
            IBTUINavigationController *nav = [[IBTUINavigationController alloc]initWithRootViewController:selectArea];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf presentViewController:nav animated:YES completion:nil];
            });
        }
            break;
        case 3://油品
        {
            OilTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            PromptTableViewController *promptVoew = [[PromptTableViewController alloc]init];
            [promptVoew setSelectCellTitle:^(NSString *title,NSInteger cellindex) {
                cell.contentLabe.text = title?title:@"请选择";
                weakSelf.oilTypeDict = weakSelf.oilTypeListDatasArray[cellindex];
                [weakSelf getOilPriceDatas];
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }];
            NSMutableArray *nameArray = [NSMutableArray array];
            for (NSDictionary *dict in self.oilTypeListDatasArray) {
                [nameArray addObject:dict[@"name"]];
            }
            promptVoew.datasArray = nameArray;
            promptVoew.currentTitle = cell.contentLabe.text;
            IBTUINavigationController *nav = [[IBTUINavigationController alloc]initWithRootViewController:promptVoew];
            promptVoew.title = @"请选择油品";
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf presentViewController:nav animated:YES completion:nil];
            });
        }
            break;
            
        default:
            break;
    }
}


#pragma mark -开始时间
- (void)beginTimeButtonClick:(UIButton *)btn
{
    [self showTimeSelectViewwithButton:btn];
}

#pragma mark -结束时间
- (void)endTimeButtonClick:(UIButton *)btn
{
    [self showTimeSelectViewwithButton:btn];
}


#pragma mark -弹出时间选择框
- (void)showTimeSelectViewwithButton:(UIButton *)btn
{
    TimeSelectViewController *timeSelectView = [[TimeSelectViewController alloc]init];
    timeSelectView.defaultDate = [GTOCommonTools dateTwoWithString:[btn currentTitle]];
    //拿到选中时间
    [timeSelectView setReturnSelectTime:^(NSString *dateString) {
        [btn setTitle:dateString forState:UIControlStateNormal];
    }];
    timeSelectView.preferredContentSize = CGSizeMake(ScreenSize.width, 200);
    self.settingsPopoverController = [[WYPopoverController alloc] initWithContentViewController:timeSelectView];
    self.settingsPopoverController.popoverLayoutMargins = UIEdgeInsetsMake(10, 20, 10, 20);
    self.settingsPopoverController.wantsDefaultContentAppearance = NO;
    [self.settingsPopoverController presentPopoverAsDialogAnimated:YES
                                                      options:WYPopoverAnimationOptionFadeWithScale];
}


#pragma mark -UITextField监听
- (void)changeTextfieldString:(UITextField *)textField
{
    if (!self.oilPrice.records.count) {
        [IBTLoadingView showTextOnly:@"油品价格异常"];
        textField.text = nil;
        return;
    }
    if (![self isPureInt:textField.text]) {
        [IBTLoadingView showTextOnly:@"只支持整数、浮点数"];
        textField.text = nil;
        return;
    }
    //申请总额
     NumberTableViewCell *numberCell = [self.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
    if (numberCell.createNumberField.text.length != 0) {
        PriceTableViewCell *cell = [self.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:0]];
        cell.contentLabe.text = [NSString stringWithFormat:@"%.2lf",[[GTOCommonTools calculateTwoStringMultiplyingOneString:[[self.oilPrice.records firstObject][@"salePrice"] stringValue] stringTwo:numberCell.createNumberField.text] doubleValue]];
    }
}


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

#pragma mark -保存建仓单
- (void)saveOrderBill:(BOOL)isPushDetails returnSaveSateBlock:(void(^)(NSDictionary *dict,DepotRequestBill *orderbBill))block
{
    __weak typeof(self) weakSelf = self;
    if (!self.distributionDict) {
        [IBTLoadingView showTextOnly:@"请选择配送区域"]; return;
    }
    if (!self.oilTypeDict) {
        [IBTLoadingView showTextOnly:@"请选择油品"]; return;
    }
    TypeTableViewCell *typeCell = [self.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if ([typeCell.contentLabe.text isEqualToString:@"请选择"]) {
        [IBTLoadingView showTextOnly:@"请选择类型"]; return;
    }
    TimeSelectTableViewCell *cell = [self.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    DepotRequestBill *orderBill = [[DepotRequestBill alloc]init];
    orderBill.version = self.orderDetails.version;
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    //状态
    orderBill.state = @"initial";
    //类型
    orderBill.type = @"general";
    //配送区域
    UCN *deliveryArea = [[UCN alloc]init];
    deliveryArea.name = self.distributionDict[@"name"];
    deliveryArea.code = self.distributionDict[@"code"];
    deliveryArea.uuid = self.distributionDict[@"uuid"];
    orderBill.deliveryArea = deliveryArea;
    //建仓单位
    UCN *org = [[UCN alloc]init];
    org.code = user.orgCode;
    org.name = user.orgName;
    org.uuid = user.orguuid;
    orderBill.org = org;
    //油品
    UCN *item = [[UCN alloc]init];
    item.code = self.oilTypeDict[@"code"];
    item.name = self.oilTypeDict[@"name"];
    item.uuid = self.oilTypeDict[@"uuid"];
    orderBill.item = item;
    //操作人信息
    OperateInfo2 *information = [[OperateInfo2 alloc]init];
    information.time = [GTOCommonTools GetCurrenttime];
    Operator *person = [[Operator alloc]init];
    person.operName = user.f_user_name;
    person.fid = user.f_user_uuid;
    information.operator = person;
    orderBill.createInfo = information;
    //配送时间
    DateTimeRange *time = [[DateTimeRange alloc]init];
    NSDate *beginDate = [GTOCommonTools dateTwoWithString:[cell.beginTimeButton currentTitle]];
    NSDate *endDate = [GTOCommonTools dateTwoWithString:[cell.endTimeButton currentTitle]];
    if ([endDate timeIntervalSinceDate:beginDate] < 0) {
        [IBTLoadingView showTextOnly:@"开始时间不能大于结束时间"];return;
    }
    time.beginDateTime = [NSString stringWithFormat:@"%@ 00:00:00",[cell.beginTimeButton currentTitle]];
    time.endDateTime = [NSString stringWithFormat:@"%@ 23:59:59",[cell.endTimeButton currentTitle]];
    orderBill.deliveryTime = time;
    //申请价格
    orderBill.reqPrice = [NSNumber numberWithDouble:[[self.oilPrice.records firstObject][@"salePrice"] doubleValue]];
    NumberTableViewCell *numberCell = [self.createWarehouseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
    if ([orderBill.reqPrice isEqualToNumber:@0]) {
        [IBTLoadingView showTextOnly:@"价格异常"];return;
    }
    //申请数量
    orderBill.quantity = [NSNumber numberWithDouble:[numberCell.createNumberField.text doubleValue]];
    if ([orderBill.quantity isEqualToNumber:@0]) {
        [IBTLoadingView showTextOnly:@"数量异常"];return;
    }
    //单号、UUID
    orderBill.uuid = self.orderDetails.uuid;
    orderBill.billnumber = self.orderDetails.billnumber;
    NSString *urlString = [NSString stringWithFormat:@"%@/depotRequest/save?operId=%@&operName=%@&time=%@",HTTP_REST_API_BASE_URL,user.f_user_uuid,user.f_user_name,[GTOCommonTools GetCurrenttime]];
    NSString *string = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [IBTLoadingView showProgressLabel:@"保存中..."];
    NSLog(@"%@",[orderBill toDictionary]);
    [HttpRequestManager requestNetworkwithURL:string withRequestType:ZERO withParameter:[orderBill toDictionary] withSuccess:^(id returnValue) {
        
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            if (!isPushDetails) {
                [IBTLoadingView hideHUDWithText:nil];
                block(returnValue[@"data"],orderBill);return;
            }
            [IBTLoadingView hideHUDWithText:@"保存成功"];
            [weakSelf saveOrderSuccess:returnValue[@"data"][@"uuid"]];
        }
        else {
            [IBTLoadingView hideHUDWithText:returnValue[@"message"]];
        }
        
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:@"保存失败"];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}

#pragma mark -保存成功
- (void)saveOrderSuccess:(NSString *)uuidString
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NewRequestViewController *details = [self.storyboard instantiateViewControllerWithIdentifier:@"NewRequestViewController"];
        details.orderUUID = uuidString;
        details.isSaveDetails = YES;
        details.title = @"建仓申请单明细";
        details.oilTypeDict = self.oilTypeDict;
        details.distributionDict = self.distributionDict;
        [self PushViewController:details animated:YES];
    });
}

#pragma mark -提交建仓单
- (void)commitOrder
{
    __weak typeof(self) weakSelf = self;
    [self showAlertViewController:@"确定提交该建仓申请单吗?" withCompleted:^{
       
        [weakSelf saveOrderBill:NO returnSaveSateBlock:^(NSDictionary *dict, DepotRequestBill *orderbBill) {
            
            [IBTLoadingView showProgressLabel:@"提交中..."];
            RsOperateInfo *submitOrder = [[RsOperateInfo alloc]init];
            ICRUserUtil *user = [ICRUserUtil sharedInstance];
            submitOrder.operId = user.f_user_uuid;
            submitOrder.operName = user.f_user_name;
            submitOrder.time = [GTOCommonTools GetCurrenttime];
            submitOrder.enterprise = user.f_enterprise_uuid;
            NSLog(@"%@",[submitOrder toDictionary]);
            [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/depotRequest/submit/%@",HTTP_REST_API_BASE_URL,dict[@"uuid"]] withRequestType:ZERO withParameter:[submitOrder 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(), ^{
                        SeeRequestViewController *details = [weakSelf.storyboard instantiateViewControllerWithIdentifier:@"SeeRequestViewController"];
                        details.orderUUID = dict[@"uuid"];
                        details.title = @"查看建仓单详情";
                        details.boolValue = YES;
                        [weakSelf PushViewController:details animated:YES];
                    });
                    
                } else {
                    [IBTLoadingView hideHUDWithText:returnValue[@"message"]];
                    [weakSelf saveOrderSuccess:dict[@"uuid"]];
                }
            } withFailed:^(NSError *failed) {
                [IBTLoadingView hideHUDWithText:nil];
                [IBTLoadingView showTextOnly:failed.localizedDescription];
            }];
        }];
    }];
}


#pragma mark -删除建仓单
- (void)deleteOrder
{
    __weak typeof(self) weakSelf = self;
    [self userSureDeleteOrCancelOperation:@"删除" returnBlock:^{
        
        [IBTLoadingView showProgressLabel:@"删除中..."];
        //操作人
        RsOperateInfo *infomation = [[RsOperateInfo alloc]init];
        ICRUserUtil *user = [ICRUserUtil sharedInstance];
        infomation.operId = user.f_user_uuid;
        infomation.operName = user.f_user_name;
        infomation.enterprise = user.f_enterprise_uuid;
        infomation.time = [GTOCommonTools GetCurrenttime];
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/depotRequest/remove/%@",HTTP_REST_API_BASE_URL,self.orderUUID] withRequestType:ZERO withParameter:[infomation 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(), ^{
                    weakSelf.isSaveDetails?[weakSelf PopToRootViewControllerAnimated:YES]:[weakSelf PopViewControllerAnimated:YES];
                });
                
            } else {
                [IBTLoadingView hideHUDWithText:nil];
                [IBTLoadingView showTextOnly:returnValue[@"message"]];
            }
            
        } withFailed:^(NSError *failed) {
            [IBTLoadingView hideHUDWithText:nil];
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    }];
}


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







@end
