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

#import "NewObtainViewController.h"
#import "OilHeaderView.h"
#import "FirstTableViewCell.h"
#import "SecondTableViewCell.h"
#import "ThirdTableViewCell.h"
#import "FourthTableViewCell.h"
#import "screeningButton.h"
#import "SourceOrderSectionView.h"
#import "SaveCommitView.h"
#import "DeleteSectionView.h"
#import "PromptTableViewController.h"
#import "SeeObtainHeaderView.h"
#import "OilOrderDetailTableViewCell.h"
#import "SelectOrderViewController.h"
#import "SeeObtainViewController.h"
#import "selectTimeCell.h"
#import "DetailTimeViewController.h"
#import "NoteTableViewCell.h"
#import "OilNumberTableViewCell.h"
#import "LossNumberTableViewCell.h"
#import "SerialNumberTableViewCell.h"

#define COUNT 12


@interface NewObtainViewController ()<UITableViewDelegate,UITableViewDataSource>


/**
 *  图片、文本数据源
 */
@property (nonatomic,strong) NSMutableArray *imageAndTitleArray;

/**
 *  控制Section开关
 */
@property (nonatomic,strong) NSMutableArray *controlZoomArray;

/**
 *  油罐数据源
 */
@property (nonatomic,strong) NSMutableArray *oilDatasArray;

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

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

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

/**
 *  tableview头视图
 */
@property (nonatomic,strong) OilHeaderView *tableviewHeaderView;

/**
 *  记录用户输入<收油量、销售、密度等>
 */
@property (nonatomic,strong) NSMutableArray *userInputArray;

/**
 *  记录用户选择油罐
 */
@property (nonatomic,strong) NSMutableArray *tankInputArray;

/**
 *  保存选中的油站字典
 */
@property (nonatomic,strong) NSDictionary *recordSelectGasStation;

/**
 *  保存选中的配油单
 */
@property (nonatomic,strong) NSDictionary *recordSelectOrder;

/**
 *  保存相应油站的油罐信息
 */
@property (nonatomic,strong) QueryResult *tankResult;

/**
 *  记录添加的油罐数（判断是否允许继续添加,默认为1）;
 */
@property (nonatomic,assign) NSInteger tankNumber;

/**
 *  配油单存在时为1，否则为0
 */
@property (nonatomic,assign) NSInteger numberValue;

@end

@implementation NewObtainViewController


- (NSMutableArray *)imageAndTitleArray
{
    if (!_imageAndTitleArray) {
        _imageAndTitleArray = [NSMutableArray array];
        for (int i=0; i<3; i++) {
            NSMutableArray *array = [NSMutableArray array];
            [_imageAndTitleArray addObject:array];
        }
        //送货人信息
        NSArray *imageArray = [NSArray arrayWithObjects:@"car1",@"Friends",@"图层-2New",@"图层-2New",@"班",@"wNew",@"ρNew",@"car1",@"Friends",@"car1",@"car1",nil];
        NSArray *titleArray = [NSArray arrayWithObjects:@"车牌号:",@"司机:",@"实际到油时间:",@"到油营业日期:",@"班次号:",@"发油公斤数:",@"发油密度:",@"发油升数:",@"损耗升数:",@"出库编码:",@"备注:", nil];
        for (int i=0; i<imageArray.count; i++) {
            NSDictionary *dict = @{@"image":[imageArray objectAtIndex:i],@"title":[titleArray objectAtIndex:i]};
            [_imageAndTitleArray[0] addObject:dict];
        }
        //油罐
        _imageAndTitleArray[1] = self.oilDatasArray[0];
        //删除区
//      NSDictionary *dict = @{@"title":@"删除区"};
//      [_imageAndTitleArray[2] addObject:dict];
    }
    return _imageAndTitleArray;
}

- (NSMutableArray *)oilDatasArray
{
    if (!_oilDatasArray) {
        _oilDatasArray = [NSMutableArray array];
        for (int i=0; i<2; i++) {
            NSMutableArray *array = [NSMutableArray array];
            [_oilDatasArray addObject:array];
        }
        //2
        NSArray *secondimageArray = [NSArray arrayWithObjects:@"前",@"后",@"售",@"ρ",@"",@"",nil];
        NSArray *secondtitleArray = [NSArray arrayWithObjects:@"收油前油量",@"收油后油量",@"期间销售",@"实测密度",@"",@"", nil];
        for (int i=0; i<secondimageArray.count; i++) {
            NSDictionary *dict = @{@"image":[secondimageArray objectAtIndex:i],@"title":[secondtitleArray objectAtIndex:i]};
            [_oilDatasArray[0] addObject:dict];
        }
    }
    return _oilDatasArray;
}

- (NSMutableArray *)controlZoomArray
{
    if (!_controlZoomArray) {
        _controlZoomArray = [NSMutableArray array];
        for (int i=0; i<3; i++) {
            [_controlZoomArray addObject:@"1"];
        }
        //@"1",表示打开   @"0",表示关闭
    }
    return _controlZoomArray;
}

- (NSMutableArray *)userInputArray
{
    if (!_userInputArray) {
        _userInputArray = [NSMutableArray array];
        for (int i=0; i<3; i++) {
            [_userInputArray addObject:[NSMutableArray array]];
        }
        //司机、车牌
        for (int i=0; i<11; i++) {
            [_userInputArray[0] addObject:@""];
        }
        //油罐信息
        for (int i=0; i<6; i++) {
            [_userInputArray[1] addObject:@""];
        }
        
    }
    return _userInputArray;
}

- (NSMutableArray *)tankInputArray
{
    if (!_tankInputArray) {
        _tankInputArray = [NSMutableArray array];
        for (int i=0; i<3; i++) {
            [_tankInputArray addObject:@""];
        }
    }
    return _tankInputArray;
}


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

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

- (void)backClicked {
    [self PopViewControllerAnimated:YES];
}


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


#pragma mark -获取油站列表
- (void)getGasStationList
{
    __weak typeof(self) weakSelf = self;
    //获取油站列表
    [IBTLoadingView showProgressLabel:@"加载中..."];
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/mdata/store/getsByUser2/%@",HTTP_REST_API_BASE_URL,[ICRUserUtil sharedInstance].f_user_uuid] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
        
        [IBTLoadingView hideHUDWithText:nil];
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            weakSelf.oilListDatas = returnValue[@"data"];
            [self newOilOrderHeader];
        } else {
            [IBTLoadingView showTextOnly:nil];
        }
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}


#pragma mark -获取选择油站下油罐信息
- (void)getUserTankDatas:(NSDictionary *)dict
{

    QueryDefinition2 *condtion = [[QueryDefinition2 alloc]init];
    //油站
    QueryCondition *query = [[QueryCondition alloc]init];
    query.operation = @"storeUuidEquals";
    query.parameters = @[dict[@"uuid"]];
    //油品
    QueryCondition *typeQuery = [[QueryCondition alloc]init];
    typeQuery.operation = @"itemUuidEquals";
    typeQuery.parameters = @[self.recordSelectOrder[@"item"][@"uuid"]];
    condtion.pageSize = 999;
    condtion.pageNumber = 0;
    condtion.conditions = (NSArray<QueryCondition> *)@[query,typeQuery];
    NSLog(@"%@",[condtion toDictionary]);
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/mdata/gasTank/queryDefinition",HTTP_REST_API_BASE_URL] withRequestType:ZERO withParameter:[condtion toDictionary] withSuccess:^(id returnValue) {
        
        [IBTLoadingView hideHUDWithText:nil];
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            self.tankResult = [[QueryResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
        } else {
            [IBTLoadingView hideHUDWithText:returnValue[@"message"]];
        }
        
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}

#pragma mark -新建收油单header
- (void)newOilOrderHeader
{
    //header
    OilHeaderView *headerView = [OilHeaderView initialize];
    self.tableviewHeaderView = headerView;
    [headerView.selectOilOrderButton addTarget:self action:@selector(selectOilOrderButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    headerView.frame = CGRectMake(0, 0, ScreenSize.width, 130);
    UIView *loadHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 130)];
    [loadHeaderView addSubview:headerView];
    self.createOilOrderTableview.tableHeaderView = loadHeaderView;
    self.locationButton = [screeningButton buttonWithType:UIButtonTypeCustom];
    [self.locationButton addTarget:self action:@selector(selectedGasStation:) forControlEvents:UIControlEventTouchUpInside];
    self.locationButton.frame = CGRectMake(0, 20, ScreenSize.width, 40);
    [self.locationButton setTitle:@"请选择油站" forState:UIControlStateNormal];
    if (self.oilListDatas.count) {
        NSDictionary *dict = [self.oilListDatas firstObject];
        self.recordSelectGasStation = [self.oilListDatas firstObject];
        [self.locationButton setTitle:dict[@"name"] forState:UIControlStateNormal];
    }
    [self.locationButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.locationButton setImage:TCImage(@"34") forState:UIControlStateNormal];
    [loadHeaderView addSubview:self.locationButton];
    //保存、提交
    __weak typeof(self) weakSelf = self;
    SaveCommitView *commitView = [SaveCommitView initializeOne];
    commitView.frame = CGRectMake(0,ScreenSize.height-164, ScreenSize.width,100);
    [commitView setCommitButtonBlock:^{
        [weakSelf commitRecevieOrder];
    }];
    [commitView setSaveButtonBlock:^{
        [weakSelf saveReceiveOrder:^(NSString *uuidString) {
        } isPushDetails:YES];   
    }];
    [self.view addSubview:commitView];
    //尾视图
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 100)];
    footerView.backgroundColor = RGBA(238, 238, 238, 1);
    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.createOilOrderTableview.tableFooterView = footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        //判断是否新增了配油单
        if ([self.imageAndTitleArray[0] count] == COUNT && indexPath.row == 0) {
            OilOrderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OilOrderDetailTableViewCell" forIndexPath:indexPath];
            cell.orderDetailsDict = self.imageAndTitleArray[indexPath.section][indexPath.row];
            return cell;
        }
        if (indexPath.row == 2 + self.numberValue || indexPath.row == 3 + self.numberValue) {//实际到油时间、到油营业时间
            SelectTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelectTimeCell" forIndexPath:indexPath];
            [cell.selecteArriveTimeButton addTarget:self action:@selector(detailsTimeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            cell.headerView.image = TCImage([[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"image"]);
            cell.titleLabel.text = [[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"];
            cell.selecteArriveTimeButton.tag = indexPath.row;
            return cell;
        }
        if (indexPath.row == 5 + self.numberValue) {//发油公斤数
            SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondTableViewCell" forIndexPath:indexPath];
            cell.titleLabe.text = [[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"];
            cell.unitLabe.text = @"公斤";
            [cell.userInputTextField addTarget:self action:@selector(firstTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
            cell.headerView.image = TCImage([[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"image"]);
            cell.userInputTextField.tag = indexPath.row;
            return cell;
        }
        if (indexPath.row == 6 + self.numberValue) {//发油密度
            SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondTableViewCell" forIndexPath:indexPath];
            cell.titleLabe.text = [[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"];
            cell.unitLabe.text = @"kg/L";
            cell.headerView.image = TCImage([[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"image"]);
            [cell.userInputTextField addTarget:self action:@selector(firstTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
            cell.userInputTextField.tag = indexPath.row;
            
            return cell;
        }
        if (indexPath.row == 7 + self.numberValue) {//发油升数
            OilNumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OilNumberTableViewCell" forIndexPath:indexPath];
            cell.oilNumberLabel.text = self.userInputArray[indexPath.section][indexPath.row];
            return cell;
        }
        if (indexPath.row == 8 + self.numberValue) {//损耗升数
            LossNumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LossNumberTableViewCell" forIndexPath:indexPath];
            cell.lossNumberLabel.text = self.userInputArray[indexPath.section][indexPath.row];
            return cell;
        }
        if (indexPath.row == 9 + self.numberValue) {//出库编码
            SerialNumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SerialNumberTableViewCell" forIndexPath:indexPath];
            [cell.codingTextField addTarget:self action:@selector(firstTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
            cell.codingTextField.tag = indexPath.row;
            cell.codingTextField.text = self.userInputArray[indexPath.section][indexPath.row];;
            return cell;
        }
        if (indexPath.row == 10 + self.numberValue) {//备注
            NoteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoteTableViewCell" forIndexPath:indexPath];
            [cell.userInputTextField addTarget:self action:@selector(firstTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
            cell.userInputTextField.tag = indexPath.row;
            cell.userInputTextField.text = self.userInputArray[indexPath.section][indexPath.row];;
            return cell;
        }
        FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstTableViewCell" forIndexPath:indexPath];
        cell.headerView.image = TCImage([[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"image"]);
        cell.userInputTextField.tag = indexPath.row;
        cell.userInputTextField.text = self.userInputArray[indexPath.section][indexPath.row];
        [cell.userInputTextField addTarget:self action:@selector(firstTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
        cell.titleLabe.text = [[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"];
        if (indexPath.row == 4 + self.numberValue) {//班次号
            CGRect frame = cell.headerView.frame;
            frame.size = CGSizeMake(20, 20);
            cell.headerView.frame = frame;
            cell.userInputTextField.placeholder = @"请输入";
        } else {
            CGRect frame = cell.headerView.frame;//车牌号、司机
            frame.size = CGSizeMake(20, 15);
            cell.headerView.frame = frame;
        }
        return cell;

    } else {

        if (indexPath.row == 4) {
            ThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ThirdTableViewCell" forIndexPath:indexPath];
            cell.userInputTextField.text = self.userInputArray[indexPath.section][indexPath.row];
            return cell;
            
        } else if (indexPath.row == 5) {
            FourthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FourthTableViewCell" forIndexPath:indexPath];
            cell.userInputTextField.text = self.userInputArray[indexPath.section][indexPath.row];
            return cell;
        }
        SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondTableViewCell" forIndexPath:indexPath];
        cell.userInputTextField.tag = indexPath.row;
        [cell.userInputTextField addTarget:self action:@selector(secondTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
        cell.userInputTextField.text = self.userInputArray[indexPath.section][indexPath.row];
        cell.headerView.image = TCImage([[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"image"]);
        cell.titleLabe.text = [[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"];
        if (indexPath.row == 3) {
            cell.unitLabe.text = @"kg/L";
        }else {
            cell.unitLabe.text = @"升";
        }
        return cell;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    BOOL boolValue = [[self.controlZoomArray objectAtIndex:section] boolValue];
    if (boolValue) {
        return [self.imageAndTitleArray[section] count];
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 10)];
        view.backgroundColor = RGBA(238, 238, 238, 1);
        return view;
    }
    if (section%2 == 0) {
        DeleteSectionView *deleteView = [DeleteSectionView initialize];
        deleteView.frame = CGRectMake(0, 0, ScreenSize.width, 44);
        deleteView.deleteButton.tag = section;
        deleteView.zoomButton.tag = section;
        [deleteView.deleteButton addTarget:self action:@selector(deleteSectionAction:) forControlEvents:UIControlEventTouchUpInside];
        [deleteView.zoomButton addTarget:self action:@selector(zoomSectionAction:) forControlEvents:UIControlEventTouchUpInside];
        return deleteView;
    }
    SourceOrderSectionView *sectionView = [SourceOrderSectionView initializeOne];
    //监听
    [sectionView.selectetankButton addTarget:self action:@selector(selectetankButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    if ([self.tankInputArray[section] isKindOfClass:[NSDictionary class]]) {//油罐信息
        [sectionView.selectetankButton setTitle:self.tankInputArray[section][@"name"] forState:UIControlStateNormal];
    } else {
       [sectionView.selectetankButton setTitle:@"请选择" forState:UIControlStateNormal];
    }
    sectionView.selectetankButton.tag = section;
    sectionView.zoomButton.tag = section;
    sectionView.zoomButton.selected = ![[self.controlZoomArray objectAtIndex:section] boolValue];
    [sectionView.zoomButton addTarget:self action:@selector(zoomSectionAction:) forControlEvents:UIControlEventTouchUpInside];
    sectionView.frame = CGRectMake(0, 0, ScreenSize.width, 54);
    return sectionView;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }
    if (section%2 == 0) {
        return 44;
    }
    return 54;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.imageAndTitleArray[0] count] == COUNT && indexPath.section == 0 ) {
        if (indexPath.row == 0) {
            return 170;
        }
    }
    return 44;
}


#pragma mark - 添加Section
- (void)addCellAction
{
    if (self.tankResult.records.count == self.tankNumber) {
        [IBTLoadingView showTextOnly:[NSString stringWithFormat:@"只能添加%ld个油罐",self.tankNumber]];return;
    }
    //content
    NSMutableIndexSet *indexset = [[NSMutableIndexSet alloc]init];
    NSUInteger index = self.imageAndTitleArray.count;
    for (int i=0; i<self.oilDatasArray.count; i++) {
        [self.imageAndTitleArray addObject:[self.oilDatasArray objectAtIndex:i]];
    }
    [indexset addIndex:index];
    [indexset addIndex:index+1];
    //control
    for (int i=0; i<2; i++) {
        [self.controlZoomArray addObject:@"1"];
        //油罐编号
        [self.tankInputArray addObject:@""];
    }
    //油罐信息
    for (int i=0; i<2; i++) {
       [self.userInputArray addObject:[NSMutableArray array]];
    }
    //油罐信息占位
    for (int i=0; i<6; i++) {
        [_userInputArray[index] addObject:@""];
    }
    [self.createOilOrderTableview beginUpdates];
    [self.createOilOrderTableview insertSections:indexset withRowAnimation:UITableViewRowAnimationFade];
    [self.createOilOrderTableview endUpdates];
    self.tankNumber ++;
}


#pragma mark -取消section的停留
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.createOilOrderTableview)
    {
        CGFloat sectionHeaderHeight = 54; //sectionHeaderHeight
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

#pragma mark -删除区
- (void)deleteSectionAction:(UIButton *)btn
{
    if (self.tankNumber <= 1) {
        [IBTLoadingView showTextOnly:@"默认保留一个油罐"];return;
    }
    NSInteger index = btn.tag;
    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) {
        
        [weakSelf.controlZoomArray removeObjectAtIndex:index];
        [weakSelf.controlZoomArray removeObjectAtIndex:index-1];
        [weakSelf.imageAndTitleArray removeObjectAtIndex:index];
        [weakSelf.imageAndTitleArray removeObjectAtIndex:index-1];
        [weakSelf.tankInputArray removeObjectAtIndex:index];
        [weakSelf.tankInputArray removeObjectAtIndex:index-1];
        [weakSelf.userInputArray removeObjectAtIndex:index];
        [weakSelf.userInputArray removeObjectAtIndex:index-1];
        NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc]init];
        [indexSet addIndex:index];
        [indexSet addIndex:index-1];
        [weakSelf.createOilOrderTableview deleteSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
        [weakSelf.createOilOrderTableview reloadData];
        self.tankNumber --;
    }]];
    [self presentViewController:alertView animated:YES completion:nil];
}

#pragma mark -新建收油单缩放 or  收油单详情（未提交、已提交）油罐区缩放控制
- (void)zoomSectionAction:(UIButton *)btn
{
    NSInteger index = btn.tag-1;
    BOOL boolValue = [[self.controlZoomArray objectAtIndex:index] boolValue];
    if (boolValue) {
        self.controlZoomArray[index] = @"0";
        btn.selected = YES;
    }else{
        self.controlZoomArray[index] = @"1";
        btn.selected = NO;
    }
    [self.createOilOrderTableview beginUpdates];
    [self.createOilOrderTableview reloadSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationFade];
    [self.createOilOrderTableview endUpdates];
}

#pragma mark -油站选择
- (void)selectedGasStation:(UIButton *)btn
{
    if (!self.recordSelectOrder) {
        [IBTLoadingView showTextOnly:@"请先选择配油单"];return;
    }
    PromptTableViewController *promptVoew = [[PromptTableViewController alloc]init];
    promptVoew.isBoolValue = YES;
    __weak typeof(self) weakSelf = self;
    [promptVoew setSelectCellTitle:^(NSString *string,NSInteger cellindex) {
        [weakSelf.locationButton setTitle:string forState:UIControlStateNormal];
        weakSelf.recordSelectGasStation = (NSDictionary *)[weakSelf.oilListDatas objectAtIndex:cellindex];
        [weakSelf getUserTankDatas:weakSelf.recordSelectGasStation];//获取油罐信息
        [weakSelf.settingsPopoverController dismissPopoverAnimated:YES completion:^{
            weakSelf.settingsPopoverController = nil;
        }];
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    promptVoew.preferredContentSize = CGSizeMake(250, 300);
    NSMutableArray *nameArray = [NSMutableArray array];
    for (NSDictionary *dict in self.oilListDatas) {
        [nameArray addObject:dict[@"name"]];
    }
    promptVoew.datasArray = nameArray;
    promptVoew.currentTitle = [btn currentTitle];
    self.settingsPopoverController = [[WYPopoverController alloc] initWithContentViewController:promptVoew];
    self.settingsPopoverController.popoverLayoutMargins = UIEdgeInsetsMake(10, 10, 10, 10);
    self.settingsPopoverController.wantsDefaultContentAppearance = NO;
    [self.settingsPopoverController presentPopoverFromRect:btn.bounds
                                                    inView:btn
                                  permittedArrowDirections:WYPopoverArrowDirectionAny
                                                  animated:YES
                                                   options:WYPopoverAnimationOptionFadeWithScale];
}

#pragma mark -选择配油单
- (void)selectOilOrderButtonClickAction:(UIButton *)button
{
    if ([self.locationButton.currentTitle isEqualToString:@"请选择油站"]) {
        [IBTLoadingView showTextOnly:@"请先选择油站"];return;
    }
    SelectOrderViewController *seleOrder = [self.storyboard instantiateViewControllerWithIdentifier:@"SelectOrderViewController"];
    //新增配油单cell
    __weak typeof(self) weakSelf = self;
    [seleOrder setCompleteSelectBlock:^(NSDictionary * dict) {
        self.recordSelectOrder = dict;//记录选中配油单
        self.numberValue = self.recordSelectOrder?1:0;
        [weakSelf.tableviewHeaderView.selectOilOrderButton setTitle:dict[@"billnumber"] forState:UIControlStateNormal];
        [weakSelf dismissViewControllerAnimated:YES completion:^{
            if ([weakSelf.imageAndTitleArray[0] count] == COUNT) {
                //若有则刷新
                weakSelf.imageAndTitleArray[0][0] = dict;
                [weakSelf.createOilOrderTableview beginUpdates];
                [weakSelf.createOilOrderTableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
                   [weakSelf.createOilOrderTableview reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
                [weakSelf.createOilOrderTableview endUpdates];
            }else {
                //若没有则新增
                [weakSelf.imageAndTitleArray[0] insertObject:dict atIndex:0];
                //占位
                [weakSelf.userInputArray[0] insertObject:@"" atIndex:0];
                [weakSelf.createOilOrderTableview beginUpdates];
                [weakSelf.createOilOrderTableview insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
                [weakSelf.createOilOrderTableview reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
                [weakSelf.createOilOrderTableview endUpdates];
            }
            //获取匹配配油单的油罐
            [weakSelf getUserTankDatas:[weakSelf.oilListDatas firstObject]];
        }];
    }];
    BaseNavigationViewController *nav = [[BaseNavigationViewController alloc]initWithRootViewController:seleOrder];
    [self presentViewController:nav animated:YES completion:nil];
}


#pragma mark -油罐选择
-  (void)selectetankButtonClickAction:(UIButton *)btn
{
    if (!self.recordSelectGasStation) {
        [IBTLoadingView showTextOnly:@"请先选择油站"]; return;
    }
    if (!self.recordSelectOrder) {
        [IBTLoadingView showTextOnly:@"请先选择配油单"];return;
    }
    PromptTableViewController *selectArea = [[PromptTableViewController alloc]init];
    selectArea.title = @"选择油罐";
    NSMutableArray *array = [NSMutableArray array];
    for (NSDictionary *dict in self.tankResult.records) {
        [array addObject:dict[@"name"]];
    }
    if (!array.count) {
        [IBTLoadingView showTextOnly:@"无油罐信息"];return;
    }
    //已经选中的油罐
    NSMutableArray *selecteArray = [NSMutableArray array];
    if (self.tankInputArray.count > 3) {
        for (int i=1; i<self.tankInputArray.count; i+=2) {
            if (![self.tankInputArray[i] isKindOfClass:[NSDictionary class]]) continue;
            NSDictionary *dict = self.tankInputArray[i];
            [selecteArray addObject:dict[@"name"]];
        }
        selectArea.selecteArray = selecteArray;
    }
    selectArea.datasArray = array;
    selectArea.currentTitle = [btn currentTitle];
    //选择配送区后回调
    __weak typeof(self) weakSelf = self;
    [selectArea setSelectCellTitle:^(NSString *title,NSInteger cellindex) {
        [btn setTitle:title?title:@"请选择" forState:UIControlStateNormal];
        self.tankInputArray[btn.tag] = self.tankResult.records[cellindex];//加入油罐数组
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    BaseNavigationViewController *nav = [[BaseNavigationViewController alloc]initWithRootViewController:selectArea];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:nav animated:YES completion:nil];
    });  
}


#pragma mark -监听车牌号、司机姓名录入
- (void)firstTableViewCellInputString:(UITextField *)textField
{
    //过滤车牌号输入、司机姓名输入、备注输入、班次号、出库编码
    if (!(textField.tag == (0 + self.numberValue) || textField.tag == (1 + self.numberValue) || textField.tag == (4 + self.numberValue) || textField.tag == (9 + self.numberValue) || textField.tag == (10 + self.numberValue))) {
        if (![self isPureInt:textField.text]) {
            textField.text = nil;
            return;
        }
    }
    NSInteger index = textField.tag;
    self.userInputArray[0][index] = textField.text;
    NSMutableArray *array = [NSMutableArray arrayWithObjects:self.userInputArray[0][5 + self.numberValue],self.userInputArray[0][6 + self.numberValue], nil];
    if ([array containsObject:@""]) {//判断发油公斤数和发油密度是否为空
        self.userInputArray[0][7 + self.numberValue] = @"";
    }else
    {
        double result = [array[0] doubleValue]/[array[1] doubleValue];
        self.userInputArray[0][7 + self.numberValue] = [NSString stringWithFormat:@"%.6lf",result];
        [self calculateReceivedAndLoss];
    }
    [self.createOilOrderTableview beginUpdates];
    [self.createOilOrderTableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:7 + self.numberValue inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self.createOilOrderTableview endUpdates];
}

#pragma mark -监听收油前油量、收油后油量、期间销售、实测密度录入
- (void)secondTableViewCellInputString:(UITextField *)textField
{
    if (![self isPureInt:textField.text]) {
        textField.text = nil;
       return;
    }
    self.userInputArray[self.userInputArray.count-2][textField.tag] = textField.text;
    [self calculateReceivedAndLoss];
}


#pragma mark -计算实际收油升、公斤、损耗升数
- (void)calculateReceivedAndLoss
{
    //实际收油
    NSMutableArray *array = self.userInputArray[self.userInputArray.count-2];
    NSArray *arr = [array subarrayWithRange:NSMakeRange(0, 4)];
    if (![arr containsObject:@""]) {
        [self calculatechargeOrderNumber];
        //实际收油（升）
        NSDecimalNumber *subtractingResult = [GTOCommonTools calculateTwoStringSubtractingOneString:array[1] stringTwo:array[0]];
        NSDecimalNumber *addingResult = [GTOCommonTools calculateTwoStringAddingOneString:[subtractingResult stringValue] stringTwo:array[2]];
        array[array.count-2] = [NSString stringWithFormat:@"%.6lf",[addingResult doubleValue]];
        //实际收油（公斤）
        array[array.count-1] = [NSString stringWithFormat:@"%.6lf",[array[array.count-2] doubleValue] * [array[3] doubleValue]];
        //损耗升数
        self.userInputArray[0][8 + self.numberValue] = [NSString stringWithFormat:@"%.6lf",[addingResult doubleValue] - [self.userInputArray[0][7 + self.numberValue] doubleValue]];
        
        [self.createOilOrderTableview beginUpdates];
        [self.createOilOrderTableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:self.userInputArray.count-2],[NSIndexPath indexPathForRow:5 inSection:self.userInputArray.count-2]] withRowAnimation:UITableViewRowAnimationNone];
        [self.createOilOrderTableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:8 + self.numberValue inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        [self.createOilOrderTableview endUpdates];
    }
}


#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)calculatechargeOrderNumber
{
    double receivedNumber = 0.0;
    for (int i=1; i<self.userInputArray.count; i+=2) {
        NSArray *array = self.userInputArray[i];
        receivedNumber += [array[5] doubleValue];
    }
    //损耗升数
    NSString *string = [NSString stringWithFormat:@"%.6lf",receivedNumber - [self.userInputArray[0][7 + self.numberValue] doubleValue]];
    if ([string isEqualToString:@"0.000000"]) {
        return;
    }
    self.userInputArray[0][8 + self.numberValue] = string;
    [self.createOilOrderTableview beginUpdates];
    [self.createOilOrderTableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:8 + self.numberValue inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self.createOilOrderTableview endUpdates];
}

#pragma mark -保存收油单
- (void)saveReceiveOrder:(void(^)(NSString *uuidString))block isPushDetails:(BOOL)boolValue
{
    //判空
    if (!self.recordSelectOrder) {
        [IBTLoadingView showTextOnly:@"请选择配油单"];return;
    }
    if (!self.recordSelectGasStation) {
        [IBTLoadingView showTextOnly:@"请选择油站"];return;
    }
    if ([self.userInputArray[0][5 + self.numberValue] isEqualToString:@""]) {
        [IBTLoadingView showTextOnly:@"请输入发油公斤数"];return;
    }
    if ([self.userInputArray[0][6 + self.numberValue] isEqualToString:@""]) {
        [IBTLoadingView showTextOnly:@"请输入发油密度"];return;
    }
    if ([self.userInputArray[0][2 + self.numberValue] isEqualToString:@"请选择"]) {
        [IBTLoadingView showTextOnly:@"请选择实际到油时间"];return;
    }
    if ([self.userInputArray[0][3 + self.numberValue] isEqualToString:@"请选择"]) {
        [IBTLoadingView showTextOnly:@"请选择到油营业日期"];return;
    }
    if ([self.userInputArray[0][4 + self.numberValue] isEqualToString:@""]) {
        [IBTLoadingView showTextOnly:@"请输入班次号"];return;
    }
    if ([self.userInputArray[0][9 + self.numberValue] isEqualToString:@""]) {
        [IBTLoadingView showTextOnly:@"请输入出库编码"];return;
    }
    for (int i=1; i<self.tankInputArray.count; i+=2) {
        if (![self.tankInputArray[i] isKindOfClass:[NSDictionary class]]) {
            [IBTLoadingView showTextOnly:@"请选择油罐"];return;
        }
    }
    //判断损耗升数（负数）且绝对值大于发油升数的千分之三
    double lossNumber = [self.userInputArray[0][8 + self.numberValue] doubleValue];//损耗升数
    double delivery = [self.userInputArray[0][7 + self.numberValue] doubleValue];//发油升数
    __weak typeof(self) weakSelf = self;
    if (lossNumber < 0) {
        lossNumber = fabs(lossNumber);
         NSString *remark = @"该单损耗超过千分之三!";
        if (lossNumber > delivery * 3/1000) {
            //添加到备注信息
            if ([self.userInputArray[0][10 + self.numberValue] isEqualToString:@""]) {
                self.userInputArray[0][10 + self.numberValue] = remark;
            }else {
                NSString *string = self.userInputArray[0][10 + self.numberValue];
                if (![string containsString:remark]) {//包含就不追加
                    self.userInputArray[0][10 + self.numberValue] = [NSString stringWithFormat:@"%@,%@",string,remark];
                }
            }
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"该单损耗超过千分之三，确认继续吗？" preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf dismissViewControllerAnimated:YES completion:nil];return;
            }]];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                 [weakSelf callReceived:^(NSString *uuidString) {
                     block(uuidString);
                 } isPushDetails:boolValue];
            }]];
            [self presentViewController:alertVC animated:YES completion:nil];
        }else
        {
            //修改后不满足该单损耗超过千分之三
            NSString *string = self.userInputArray[0][10 + self.numberValue];
            if (![string containsString:remark]) {
                self.userInputArray[0][10] = [NSString stringWithFormat:@"%@",string];
            }
        }
    }else {
        
        [weakSelf callReceived:^(NSString *uuidString) {
            block(uuidString);
        } isPushDetails:boolValue];
    }
}


#pragma mark -调用保存收油单接口
- (void)callReceived:(void(^)(NSString *uuidString))block isPushDetails:(BOOL)boolValue
{
    for (NSInteger i=0; i<[self.userInputArray[1] count]; i++) {
        if ([self.userInputArray[1][i] length] == 0) {
            [IBTLoadingView showTextOnly:[self returnPromptInformation:i]];return;
        }
    }
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    ReceiveBill *orderBill = [[ReceiveBill alloc]init];
    //业主公司
    UCN *org = [[UCN alloc]init];
    org.code = user.orgCode;
    org.name = user.orgName;
    org.uuid = user.orguuid;
    orderBill.org = org;
    //油站经营类型
    orderBill.operatingType = self.recordSelectGasStation[@"operatingType"];
    //状态
    orderBill.state = @"initial";
    //油站
    UCN *store = [[UCN alloc]init];
    store.name = self.recordSelectGasStation[@"name"];
    store.code = self.recordSelectGasStation[@"code"];
    store.uuid = self.recordSelectGasStation[@"uuid"];
    orderBill.store = store;
    //配油单编号
    orderBill.pickingBillNumber = self.recordSelectOrder[@"billnumber"];
    //订油单编号
    orderBill.orderBillNumber = self.imageAndTitleArray[0][0][@"billnumber"];
    //供应商
    orderBill.provider = self.recordSelectOrder[@"provider"];
    //配送单计量数
    orderBill.billMeasure = self.imageAndTitleArray[0][0][@"orderBillDtl"][@"quantity"];
    //发油商
    UCN *fueler = [[UCN alloc]init];
    fueler.name = self.recordSelectOrder[@"fueler"][@"name"];
    fueler.code = self.recordSelectOrder[@"fueler"][@"code"];
    fueler.uuid = self.recordSelectOrder[@"fueler"][@"uuid"];
    orderBill.fueler = fueler;
    //油仓
    UCN *depot = [[UCN alloc]init];
    depot.name = self.recordSelectOrder[@"depot"][@"name"];
    depot.code = self.recordSelectOrder[@"depot"][@"code"];
    depot.uuid = self.recordSelectOrder[@"depot"][@"uuid"];
    orderBill.depot = depot;
    //油品信息
    UCN *oilType = [[UCN alloc]init];
    oilType.uuid = self.imageAndTitleArray[0][0][@"item"][@"uuid"];
    oilType.name = self.imageAndTitleArray[0][0][@"item"][@"name"];
    oilType.code = self.imageAndTitleArray[0][0][@"item"][@"code"];
    orderBill.item = oilType;
    //车牌号
    orderBill.truckNo = self.userInputArray[0][0 + self.numberValue]?self.userInputArray[0][0 + self.numberValue]:nil;
    //司机
    orderBill.carter = self.userInputArray[0][1 + self.numberValue]?self.userInputArray[0][1 + self.numberValue]:nil;
    //出库编码
    orderBill.envOutCode = self.userInputArray[0][9 + self.numberValue]?self.userInputArray[0][9 + self.numberValue]:nil;
    //油罐信息
    __weak typeof(self) weakSelf = self;
    NSMutableArray *tanksArray = [NSMutableArray array];
    for (int i=ONE;i<self.tankInputArray.count;i+=2) {
        NSDictionary *dict = self.tankInputArray[i];
        ReceiveTankDtl *details = [[ReceiveTankDtl alloc]init];
        //油罐
        UCN *tank = [[UCN alloc]init];
        tank.name = dict[@"name"];
        tank.code = dict[@"code"];
        tank.uuid = dict[@"uuid"];
        details.tank = tank;
        //用户录入油罐信息
        NSArray *inputArray = self.userInputArray[i];
        //计量信息
        GasMeasureValue *measureInformation;//声明
        for (int i=0; i<inputArray.count; i++) {
            if ([inputArray[i] length] == 0) {
                [IBTLoadingView showTextOnly:[NSString stringWithFormat:@"%@%@",dict[@"name"],[self returnPromptInformation:i]]];
                return;
            }
            NSString *string = inputArray[i];
            switch (i) {
                case 0://收油前油量
                {
                    GasMeasureValue *measureInformation = [[GasMeasureValue alloc]init];
                    measureInformation.capacity = [NSNumber numberWithDouble:[string doubleValue]];
                    details.measureBeforeUnload = measureInformation;
                }
                    break;
                case 1://收油后油量
                {
                    GasMeasureValue *measureInformation = [[GasMeasureValue alloc]init];
                    measureInformation.capacity = [NSNumber numberWithDouble:[string doubleValue]];
                    details.measureAfterUnload = measureInformation;
                }
                    break;
                case 2://期间销售
                {
                    GasMeasureValue *measureInformation = [[GasMeasureValue alloc]init];
                    measureInformation.capacity = [NSNumber numberWithDouble:[string doubleValue]];
                    details.measureOnSale = measureInformation;
                }
                    break;
                case 3://实测密度
                case 4://实际收油（升）
                case 5://实际收油（公斤）
                {
                    //3.4.5共用一个对象
                    if (!measureInformation) {
                        measureInformation = [[GasMeasureValue alloc]init];
                    }
                    if (i == 3) {
                        measureInformation.density = [NSNumber numberWithDouble:[string doubleValue]];
                        details.measureCalc = measureInformation;
                    }
                    if (i == 4) {
                        if ([string doubleValue] <= 0) {
                            [IBTLoadingView showTextOnly:@"实际收油不能小于等于0升"];return;
                        }
                        measureInformation.capacity = [NSNumber numberWithDouble:[string doubleValue]];
                        details.measureBill = measureInformation;
                    }
                    if (i == 5) {
                        if ([string doubleValue] <= 0) {
                            [IBTLoadingView showTextOnly:@"实际收油量不能小于等于0公斤"];return;
                        }
                        measureInformation.quality = [NSNumber numberWithDouble:[string doubleValue]];
                        details.measureRealDelivery = measureInformation;
                    }
                }
                    break;
                default:
                    break;
            }
        }
        [tanksArray addObject:details];
    }
    //发油公斤数
    orderBill.realMeasure = self.userInputArray[0][5 + self.numberValue];
    orderBill.tankDtls = (NSArray<ReceiveTankDtl> *)tanksArray;
    //要求到油时间
    orderBill.receiveTime = self.recordSelectOrder[@"receiveTime"];
    //实际到油时间
    orderBill.realReceiveTime = self.userInputArray[0][2 + self.numberValue];
    //收油营业日期
    orderBill.receiveBusinessDate = [NSString stringWithFormat:@"%@ 00:00:00",self.userInputArray[0][3 + self.numberValue]];
    //班次号
    orderBill.serviceNumber = self.userInputArray[0][4 + self.numberValue];
    //发油密度
    orderBill.pickFuelDensity = [NSNumber numberWithDouble:[self.userInputArray[0][6 + self.numberValue] doubleValue]];
    //发油升数
    orderBill.pickFuelDensityCapacity = [NSNumber numberWithDouble:[self.userInputArray[0][7 + self.numberValue] doubleValue]];
    //损耗升数
    orderBill.wasterCapacity = [NSNumber numberWithDouble:[self.userInputArray[0][8 + self.numberValue] doubleValue]];
    //备注
    orderBill.remark = self.userInputArray[0][10 + self.numberValue];
    NSString *urlString = [NSString stringWithFormat:@"%@/receiveBill/save?operId=%@&operName=%@&time=%@",HTTP_REST_API_BASE_URL,user.f_user_uuid,user.f_user_name,[GTOCommonTools GetCurrenttime]];
    NSString *string = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",[orderBill toDictionary]);
    [IBTLoadingView showProgressLabel:@"保存中..."];
    [HttpRequestManager requestNetworkwithURL:string withRequestType:ZERO withParameter:[orderBill toDictionary] withSuccess:^(id returnValue) {
        
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            if (!boolValue) {
                block(returnValue[@"data"][@"uuid"]);return;
            }
            [IBTLoadingView hideHUDWithText:@"保存成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                SeeObtainViewController *orderBill = [weakSelf.storyboard instantiateViewControllerWithIdentifier:@"SeeObtainViewController"];
                orderBill.orderUUIDString = returnValue[@"data"][@"uuid"];
                orderBill.storeDict = weakSelf.recordSelectGasStation;//油站
                orderBill.isReturnRootVC = YES;
                [weakSelf PushViewController:orderBill animated:YES];
            });
            
        } else {
            [IBTLoadingView hideHUDWithText:returnValue[@"message"]];
        }
        
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:@"保存失败"];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}


#pragma mark -返回提示信息
- (NSString *)returnPromptInformation:(NSInteger)index
{
    switch (index) {
        case 0://收油前油量
        {
            return @"请输入收油前油量";
        }
            break;
        case 1://收油后油量
        {
            return @"请输入收油后油量";
        }
            break;
        case 2://期间销售
        {
            return @"请输入期间销售";
        }
            break;
        case 3://实测密度
        {
            return @"请输入实测密度";
        }
            break;
            
        default:
            break;
    }
    return nil;
}



#pragma mark -提交收油单
- (void)commitRecevieOrder
{
    __weak typeof(self) weakSelf = self;
    ShowAlertView(@"提示", @"确定提交该收油单吗？", @[@"取消",@"确定"], UIAlertControllerStyleAlert, ^(NSInteger index) {
        if (index == ZERO) {
            return;
        }
        [weakSelf saveReceiveOrder:^(NSString *uuidString) {
            RsOperateInfo *user = [[RsOperateInfo alloc]init];
            user.operName = [ICRUserUtil sharedInstance].f_user_name;
            user.operId = [ICRUserUtil sharedInstance].f_user_uuid;
            user.enterprise = [ICRUserUtil sharedInstance].f_enterprise_uuid;
            user.time = [GTOCommonTools GetCurrenttime];
            [IBTLoadingView showProgressLabel:@"提交中..."];
            [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/receiveBill/submit/%@",HTTP_REST_API_BASE_URL,uuidString] withRequestType:ZERO withParameter:[user 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(), ^{
                        SeeObtainViewController *orderBill = [weakSelf.storyboard instantiateViewControllerWithIdentifier:@"SeeObtainViewController"];
                        orderBill.orderUUIDString = uuidString;
                        orderBill.isReturnRootVC = YES;
                        orderBill.storeDict = weakSelf.recordSelectGasStation;
                        [weakSelf PushViewController:orderBill animated:YES];
                    });
                } else {
                    [IBTLoadingView hideHUDWithText:returnValue[@"message"]];
                }
                
            } withFailed:^(NSError *failed) {
                [IBTLoadingView hideHUDWithText:@"提交失败"];
                [IBTLoadingView showTextOnly:failed.localizedDescription];
            }];
        } isPushDetails:NO];
    });
}


#pragma mark -到油时间选择
- (void)detailsTimeButtonClick:(UIButton *)btn
{
    __weak typeof(self) weakSelf = self;
    DetailTimeViewController *dateView = [[DetailTimeViewController alloc]init];
    dateView.defaultTime = [GTOCommonTools dateWithString:[btn currentTitle]];
    //实际收油时间
    if (btn.tag == 3 + self.numberValue) {
        dateView.indexStyle = 1;
    }
    [dateView setReturnSelectDate:^(NSString *dateString) {
        weakSelf.userInputArray[0][btn.tag] = dateString;
        [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];
    
    
    
}


@end
