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

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


#define COUNT 11

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



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

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

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

/**
 *  收油单详情
 */
@property (nonatomic,strong) ReceiveBill *orderDetails;

/**
 *  配油单详情
 */
@property (nonatomic,strong) PickingBill *orderBill;

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

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

/**
 *  当前收油单状态
 */
@property (nonatomic,assign) BOOL orderStateBoolValue;

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

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


@end

@implementation SeeObtainViewController


- (NSMutableArray *)imageAndTitleArray
{
    if (!_imageAndTitleArray) {
        _imageAndTitleArray = [NSMutableArray array];
        for (int i=0; i<2; i++) {
            NSMutableArray *array = [NSMutableArray array];
            [_imageAndTitleArray addObject:array];
        }
        [_imageAndTitleArray[0] addObject:@""];//配油单
        //送货人信息
        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[1] addObject:dict];
        }
        //油罐详情
//        _imageAndTitleArray[2] = self.oilDatasArray[0];
    }
    return _imageAndTitleArray;
}


- (NSMutableArray *)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<2; i++) {
            [_controlZoomArray addObject:@"1"];
        }
        //@"1",表示打开   @"0",表示关闭
    }
    return _controlZoomArray;
}


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


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

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

- (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;
}

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

#pragma mark -UI
- (void)uiConfigAction
{
    self.tankNumber = ONE;
    self.title = @"收油单详情";
    self.seeObtainTableView.delegate = self;
    self.seeObtainTableView.dataSource = self;
    self.seeObtainTableView.tableFooterView = [UIView new];
}

#pragma mark -获取选择油站下油罐信息
- (void)getUserTankDatas:(NSDictionary *)dict
{
    WS(weakSelf);
    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.orderBill.item.uuid];
    condtion.pageSize = 999;
    condtion.pageNumber = 0;
    condtion.conditions = (NSArray<QueryCondition> *)@[query,typeQuery];
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/mdata/gasTank/queryDefinition",HTTP_REST_API_BASE_URL] withRequestType:ZERO withParameter:[condtion toDictionary] withSuccess:^(id returnValue) {
        
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            weakSelf.tankResult = [[QueryResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
        } else {
            [IBTLoadingView showTextOnly:returnValue[@"message"]];
        }
        
    } withFailed:^(NSError *failed) {
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}

#pragma mark -通过UUID获取收油单详情
- (void)getOrderBillDetails
{
    WS(weakSelf);
    [IBTLoadingView showProgressLabel:@"加载中..."];
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/receiveBill/get/%@",HTTP_REST_API_BASE_URL,self.orderUUIDString] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
        
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            weakSelf.orderDetails = [[ReceiveBill alloc]initWithDictionary:returnValue[@"data"] error:nil];
            //保存收油单状态
            if ([weakSelf.orderDetails.state isEqualToString:@"submit"] || [weakSelf.orderDetails.state isEqualToString:@"canceled"] || [weakSelf.orderDetails.state isEqualToString:@"accomplished"] | [weakSelf.orderDetails.state isEqualToString:@"delete"] | [weakSelf.orderDetails.state isEqualToString:@"cancel"]) {
                weakSelf.orderStateBoolValue = YES;
            }
            //加入数据源
            weakSelf.userInputArray[ONE][ZERO] = weakSelf.orderDetails.truckNo?weakSelf.orderDetails.truckNo:@"";//车牌号
            weakSelf.userInputArray[ONE][ONE] = weakSelf.orderDetails.carter?weakSelf.orderDetails.carter:@"";//司机
            weakSelf.userInputArray[ONE][2] = weakSelf.orderDetails.realReceiveTime?weakSelf.orderDetails.realReceiveTime:@"请选择";//实际到油时间
            weakSelf.userInputArray[ONE][3] = weakSelf.orderDetails.receiveBusinessDate?[[weakSelf.orderDetails.receiveBusinessDate componentsSeparatedByString:@" "] firstObject]:@"请选择";//到油营业时间
            weakSelf.userInputArray[ONE][4] = weakSelf.orderDetails.serviceNumber;//班次号
            weakSelf.userInputArray[ONE][5] = [NSString stringWithFormat:@"%.6lf",[weakSelf.orderDetails.realMeasure doubleValue]];//发油公斤数
            weakSelf.userInputArray[ONE][6] = [NSString stringWithFormat:@"%.6lf",[weakSelf.orderDetails.pickFuelDensity doubleValue]];//发油密度
            weakSelf.userInputArray[ONE][7] = [NSString stringWithFormat:@"%.6lf",[weakSelf.orderDetails.pickFuelDensityCapacity doubleValue]];//发油升数
            weakSelf.userInputArray[ONE][8] = [NSString stringWithFormat:@"%.6lf",[weakSelf.orderDetails.wasterCapacity doubleValue]];//损耗升数
            weakSelf.userInputArray[ONE][9] = weakSelf.orderDetails.envOutCode?weakSelf.orderDetails.envOutCode:@"";//出库编码;
            weakSelf.userInputArray[ONE][10] = weakSelf.orderDetails.remark?weakSelf.orderDetails.remark:@"";//备注;
            //默认数据源个数
            for (int i=0; i<weakSelf.orderDetails.tankDtls.count; i++) {
                NSInteger index = weakSelf.orderStateBoolValue?1:2;//区分收油单状态
                for (int i=0; i<index; i++) {
                    [weakSelf.userInputArray addObject:[NSMutableArray array]];
                }
                for (int i=0; i<6; i++) {
                    [weakSelf.userInputArray[weakSelf.userInputArray.count-2] addObject:@""];
                }
                if (weakSelf.orderStateBoolValue) {//区分收油单状态
                    [weakSelf.imageAndTitleArray addObject:weakSelf.oilDatasArray[0]];
                } else {
                    [weakSelf.imageAndTitleArray addObjectsFromArray:weakSelf.oilDatasArray];
                }
                [weakSelf.controlZoomArray addObjectsFromArray:@[@"1",@"1"]];//油罐和删除分区，默认一次加两个
                [weakSelf.tankInputArray addObject:@""];
            }
            //油罐信息
            [weakSelf.orderDetails.tankDtls enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
               
                NSInteger index = weakSelf.orderStateBoolValue?idx+2:idx*2+2;
                ReceiveTankDtl *details = (ReceiveTankDtl *)obj;
                weakSelf.tankInputArray[index] = [details.tank toDictionary];
                weakSelf.userInputArray[index][0] = [NSString stringWithFormat:@"%.6lf",[details.measureBeforeUnload.capacity doubleValue]];
                weakSelf.userInputArray[index][1] = [NSString stringWithFormat:@"%.6lf",[details.measureAfterUnload.capacity doubleValue]];
                weakSelf.userInputArray[index][2] = [NSString stringWithFormat:@"%.6lf",[details.measureOnSale.capacity doubleValue]];
                weakSelf.userInputArray[index][3] = [NSString stringWithFormat:@"%.6lf",[details.measureRealDelivery.density doubleValue]];
                weakSelf.userInputArray[index][4] = [NSString stringWithFormat:@"%.6lf",[details.measureRealDelivery.capacity doubleValue]];
                weakSelf.userInputArray[index][5] = [NSString stringWithFormat:@"%.6lf",[details.measureRealDelivery.quality doubleValue]];
            }];
            [weakSelf OilOrderDetailsHeaderAndFootView];
            [weakSelf getDistributionOrderDetails:returnValue[@"data"][@"pickingBillNumber"] completeBlock:^(PickingBill *orderBill) {
                weakSelf.userInputArray[ZERO][ZERO] = orderBill?orderBill:@"";
                [weakSelf.seeObtainTableView reloadData];
            }];
            
        } else {
            [IBTLoadingView showTextOnly:returnValue[@"message"]];
        }
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
    
}

#pragma mark -获取配油单详情
- (void)getDistributionOrderDetails:(NSString *)uuidString completeBlock:(void(^)(PickingBill *orderBill))block
{
    __weak typeof(self) weakSelf = self;
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/pickingBill/getByBillNumber/%@",HTTP_REST_API_BASE_URL,uuidString] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
        
        [IBTLoadingView hideHUDWithText:nil];
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            PickingBill *bill = [[PickingBill alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.orderBill = bill;
            [weakSelf getUserTankDatas:weakSelf.storeDict];
            block(bill);
        } else {
            [IBTLoadingView hideHUDWithText:nil];
        }
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}


#pragma mark -设置headerView、FootView(已提交、未提交)
- (void)OilOrderDetailsHeaderAndFootView
{
    SeeObtainHeaderView *headerView = [SeeObtainHeaderView initialize];
    headerView.frame = CGRectMake(0, 0, ScreenSize.width, 170);
    UIView *view = [[UIView alloc]initWithFrame:headerView.frame];
    [view addSubview:headerView];
    headerView.model = self.orderDetails;
    self.seeObtainTableView.tableHeaderView = view;
    //保存、提交
    __weak typeof(self) weakSelf = self;
    if (![self.orderDetails.state isEqualToString:@"canceled"] && ![self.orderDetails.state isEqualToString:@"accomplished"] && ![self.orderDetails.state isEqualToString:@"submit"] && ![self.orderDetails.state isEqualToString:@"delete"] && ![self.orderDetails.state isEqualToString:@"cancel"]) {
        SaveCommitView *commitView = [SaveCommitView initializeTwo];
        
        commitView.frame = CGRectMake(0,ScreenSize.height-164, ScreenSize.width,100);
        [commitView setCommitButtonBlock:^{//提交
            [weakSelf commitRecevieOrder];
        }];
        [commitView setSaveButtonBlock:^{//保存
            [weakSelf saveReceiveOrder:^(NSString *uuidString) {
            } isPushDetails:YES];
        }];
        [commitView setDelectButtonBlock:^{//删除
            [weakSelf deleteOrder];
        }];
        [commitView setInvalidButtonBlock:^{//作废暂时隐藏
//            [weakSelf invalidOrder];
        }];
        [self.view addSubview:commitView];
    } else {
        self.seeObtainTableView.frame = CGRectMake(0, 0, ScreenSize.width, ScreenSize.height-64);
    }
    //尾视图
    if ([self.orderDetails.state isEqualToString:@"initial"]) {
        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.seeObtainTableView.tableFooterView = footerView;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        
        if (indexPath.row == 2 || indexPath.row == 3) {//实际到油时间/到油营业时间
            SelectTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelectTimeCell" forIndexPath:indexPath];
            [cell.selecteArriveTimeButton addTarget:self action:@selector(detailsTimeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            cell.selecteArriveTimeButton.tag = indexPath.row;
            [cell.selecteArriveTimeButton setTitle:self.userInputArray[indexPath.section][indexPath.row] forState:UIControlStateNormal];
            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.enabled = !self.orderStateBoolValue;
            return cell;
        }
        if (indexPath.row == 5) {//发油公斤数
            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.userInputTextField.tag = indexPath.row;
            cell.userInputTextField.text = [NSString stringWithFormat:@"%.6lf",[self.userInputArray[indexPath.section][indexPath.row] doubleValue]];
            cell.headerView.image = TCImage([[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"image"]);
            cell.userInputTextField.enabled = !self.orderStateBoolValue;
            return cell;
        }
        if (indexPath.row == 6) {//发油密度
            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.userInputTextField addTarget:self action:@selector(firstTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
            cell.userInputTextField.tag = indexPath.row;
            cell.userInputTextField.text = [NSString stringWithFormat:@"%.6lf",[self.userInputArray[indexPath.section][indexPath.row] doubleValue]];
            cell.headerView.image = TCImage([[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"image"]);
            cell.userInputTextField.enabled = !self.orderStateBoolValue;
            return cell;
        }
        if (indexPath.row == 7) {//发油升数
            OilNumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OilNumberTableViewCell" forIndexPath:indexPath];
            cell.oilNumberLabel.text = [NSString stringWithFormat:@"%.6lf",[self.userInputArray[indexPath.section][indexPath.row] doubleValue]];
            return cell;
        }
        if (indexPath.row == 8) {//损耗升数
            LossNumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LossNumberTableViewCell" forIndexPath:indexPath];
            cell.lossNumberLabel.text = [NSString stringWithFormat:@"%.6lf",[self.userInputArray[indexPath.section][indexPath.row] doubleValue]];
            return cell;
        }
        if (indexPath.row == 9) {//出库编码
            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) {//备注
            NoteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoteTableViewCell" forIndexPath:indexPath];
            [cell.userInputTextField addTarget:self action:@selector(firstTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
            cell.userInputTextField.tag = indexPath.row;
            cell.userInputTextField.enabled = !self.orderStateBoolValue;
            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.titleLabe.text = [[[self.imageAndTitleArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"];
        cell.userInputTextField.tag = indexPath.row;
        [cell.userInputTextField addTarget:self action:@selector(firstTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
        cell.userInputTextField.text = self.userInputArray[indexPath.section][indexPath.row];
        cell.userInputTextField.enabled = !self.orderStateBoolValue;
        if (indexPath.row == 4) {//班次号
            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;
    }
    if (indexPath.section == 0) {
        
        OilOrderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OilOrderDetailTableViewCell" forIndexPath:indexPath];
        cell.model = [self.userInputArray[indexPath.section][indexPath.row] isKindOfClass:[NSString class]]?nil:self.userInputArray[indexPath.section][indexPath.row];
        return cell;
    } else {
        
        NSString *string = [self.userInputArray[indexPath.section][indexPath.row] isEqualToString:@""]?@"0":self.userInputArray[indexPath.section][indexPath.row];
        if (indexPath.row == 4) {
            ThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ThirdTableViewCell" forIndexPath:indexPath];
            cell.userInputTextField.text = string;
            return cell;
            
        } else if (indexPath.row == 5) {
            FourthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FourthTableViewCell" forIndexPath:indexPath];
            cell.userInputTextField.text = string;
            return cell;
        }
        SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondTableViewCell" forIndexPath:indexPath];
        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"];
        cell.userInputTextField.text = self.userInputArray[indexPath.section][indexPath.row]?self.userInputArray[indexPath.section][indexPath.row]:@"请输入";
        cell.userInputTextField.enabled = !self.orderStateBoolValue;
        cell.userInputTextField.tag = indexPath.row;
        [cell.userInputTextField addTarget:self action:@selector(secondTableViewCellInputString:) forControlEvents:UIControlEventEditingChanged];
        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) {
        SourceOrderSectionView *sectionView = [SourceOrderSectionView initializenThird];
        sectionView.zoomButton.tag = section;
        sectionView.oilOrderNumber.enabled = !self.orderStateBoolValue;
//        sectionView.arrowImageView.hidden = self.orderStateBoolValue;//区分收油单状态
        sectionView.arrowImageView.hidden = YES;//区分收油单状态
        sectionView.zoomButton.selected = ![[self.controlZoomArray objectAtIndex:section] boolValue];
        [sectionView.zoomButton addTarget:self action:@selector(zoomSectionAction:) forControlEvents:UIControlEventTouchUpInside];
        [sectionView.oilOrderNumber addTarget:self action:@selector(selectOrderButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
        [sectionView.oilOrderNumber setTitle:self.orderBill.billnumber forState:UIControlStateNormal];
        return sectionView;
    }
    if (section == 1) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 10)];
        view.backgroundColor = RGBA(238, 238, 238, 1);
        return view;
    }
    if (!self.orderStateBoolValue) {
        //删除
        if (section%2 != 0 && section > 2) {
            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 = self.orderStateBoolValue?[SourceOrderSectionView initializenTwo]:[SourceOrderSectionView initializeOne];
    sectionView.zoomButton.tag = section+1;
    sectionView.selectetankButton.tag = section;
    sectionView.selectetankButtonTwo.enabled = !self.orderStateBoolValue;//区分收油单状态
    [sectionView.selectetankButton addTarget:self action:@selector(selectetankButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [sectionView.zoomButton addTarget:self action:@selector(zoomSectionAction:) forControlEvents:UIControlEventTouchUpInside];
    id objc = self.tankInputArray[section];
    [self.orderStateBoolValue?sectionView.selectetankButtonTwo:sectionView.selectetankButton setTitle:[objc isKindOfClass:[NSDictionary class]]?objc[@"name"]:@"请选择" forState:UIControlStateNormal];
    sectionView.zoomButton.selected = ![[self.controlZoomArray objectAtIndex:section] boolValue];
    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 54;
    }
    if (section == 1) {
        return 10;
    }
    if (!self.orderStateBoolValue) {
        if (section%2 != 0 && section > 2) {
            return 44;
        }
    }
    return 54;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 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<index; i++) {
        [self.controlZoomArray addObject:@"1"];
    }
    //油罐信息
    for (int i=0; i<2; i++) {
        [self.userInputArray addObject:[NSMutableArray array]];
        //油罐编号
        [self.tankInputArray addObject:@""];
    }
    //油罐信息占位
    for (int i=0; i<6; i++) {
        [_userInputArray[index] addObject:@""];
    }
    [self.seeObtainTableView beginUpdates];
    [self.seeObtainTableView insertSections:indexset withRowAnimation:UITableViewRowAnimationFade];
    [self.seeObtainTableView endUpdates];
    self.tankNumber ++;
}

#pragma mark -取消section的停留
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.seeObtainTableView)
    {
        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
{
    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.userInputArray removeObjectAtIndex:index];
        [weakSelf.userInputArray removeObjectAtIndex:index-1];
        [weakSelf.tankInputArray removeObjectAtIndex:index];
        [weakSelf.tankInputArray removeObjectAtIndex:index-1];
        NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc]init];
        [indexSet addIndex:index];
        [indexSet addIndex:index-1];
        [weakSelf.seeObtainTableView beginUpdates];
        [weakSelf.seeObtainTableView deleteSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
        [weakSelf.seeObtainTableView endUpdates];
        self.tankNumber --;
    }]];
    [self presentViewController:alertView animated:YES completion:nil];
}

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

#pragma mark -选择配油单
- (void)selectOrderButtonClickAction:(UIButton *)button
{
    __weak typeof(self) weakSelf = self;
    SelectOrderViewController *selectOrder = [self.storyboard instantiateViewControllerWithIdentifier:@"SelectOrderViewController"];
    [selectOrder setCompleteSelectBlock:^(NSDictionary * dict) {
        
        [weakSelf getDistributionOrderDetails:dict[@"billnumber"] completeBlock:^(PickingBill *orderBill) {
           self.userInputArray[0][0] = orderBill?orderBill:@"";
            [self.seeObtainTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        }];
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    BaseNavigationViewController *nav = [[BaseNavigationViewController alloc]initWithRootViewController:selectOrder];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark -油罐选择
-  (void)selectetankButtonClickAction:(UIButton *)btn
{
    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=2; 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)secondTableViewCellInputString:(UITextField *)textField
{
    if (![self isPureInt:textField.text]) {
        textField.text = nil;
        return;
    }
    NSLog(@"%@--%ld",textField.text,textField.tag);
    self.userInputArray[self.userInputArray.count-2][textField.tag] = textField.text;
    //实际收油
    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 *addingRelsult = [GTOCommonTools calculateTwoStringAddingOneString:[subtractingResult stringValue] stringTwo:array[2]];
        array[array.count-2] = [NSString stringWithFormat:@"%.6lf",[addingRelsult doubleValue]];
        //实际收油（公斤）
        array[array.count-1] = [NSString stringWithFormat:@"%.6lf",[array[array.count-2] doubleValue] * [array[3] doubleValue]];
        
        [self.seeObtainTableView beginUpdates];
        [self.seeObtainTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:self.userInputArray.count-2],[NSIndexPath indexPathForRow:5 inSection:self.userInputArray.count-2]] withRowAnimation:UITableViewRowAnimationFade];
        [self.seeObtainTableView endUpdates];
    }
}

#pragma mark -监听车牌号、司机姓名录入
- (void)firstTableViewCellInputString:(UITextField *)textField
{
    //过滤车牌号输入、司机姓名输入、备注输入
    if (!(textField.tag == 0 || textField.tag == 1 || textField.tag == 9 || textField.tag == 4 || textField.tag == 10)) {
        if (![self isPureInt:textField.text]) {
            textField.text = nil;
            return;
        }
    }
    NSLog(@"%@--%ld",textField.text,textField.tag);
    NSInteger index = textField.tag;
    self.userInputArray[ONE][index] = textField.text;
    NSMutableArray *array = [NSMutableArray arrayWithObjects:self.userInputArray[ONE][5],self.userInputArray[ONE][6], nil];
    if ([array containsObject:@""]) {//判断发油公斤数和发油密度是否为空
        self.userInputArray[ONE][7] = @"";
    }else
    {
        double result = [array[0] doubleValue]/[array[1] doubleValue];
        self.userInputArray[ONE][7] = [NSString stringWithFormat:@"%.6lf",result];
    }
    [self.seeObtainTableView beginUpdates];
    [self.seeObtainTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:7 inSection:ONE],[NSIndexPath indexPathForRow:8 inSection:ONE]] withRowAnimation:UITableViewRowAnimationNone];
    [self.seeObtainTableView 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;
    for (int i=2; i<self.userInputArray.count; i+=2) {
        NSArray *array = self.userInputArray[i];
        receivedNumber += [array[5] doubleValue];
    }
    //损耗升数
    NSString *string = [NSString stringWithFormat:@"%.6lf",receivedNumber - [self.userInputArray[ONE][7] doubleValue]];
    if ([string isEqualToString:@"0.000000"]) {
        return;
    }
    self.userInputArray[ONE][8] = string;
    [self.seeObtainTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:8 inSection:ONE]] withRowAnimation:UITableViewRowAnimationNone];
    [self.seeObtainTableView endUpdates];
}


#pragma mark -保存收油单
- (void)saveReceiveOrder:(void(^)(NSString *uuidString))block isPushDetails:(BOOL)boolValue
{
    //判空
    if (!self.orderBill) {
        [IBTLoadingView showTextOnly:@"请添加配油单"];return;
    }
    if (!self.storeDict) {
        [IBTLoadingView showTextOnly:@"请选择油站"];return;
    }
    if (!self.userInputArray[ONE][5]) {
        [IBTLoadingView showTextOnly:@"请输入发油公斤数"];return;
    }
    if (!self.userInputArray[ONE][6]) {
        [IBTLoadingView showTextOnly:@"请输入发油密度"];return;
    }
    if ([self.userInputArray[ONE][2] isEqualToString:@"请选择"]) {
        [IBTLoadingView showTextOnly:@"请选择实际到油时间"];return;
    }
    if ([self.userInputArray[ONE][3] isEqualToString:@"请选择"]) {
        [IBTLoadingView showTextOnly:@"请选择到油营业日期"];return;
    }
    if ([self.userInputArray[ONE][4] isEqualToString:@""]) {
        [IBTLoadingView showTextOnly:@"请输入班次号"];return;
    }
    if ([self.userInputArray[ONE][9] isEqualToString:@""]) {
        [IBTLoadingView showTextOnly:@"请输入出库编码"];return;
    }
    for (int i=2; i<self.tankInputArray.count-1; i+=2) {
        if (![self.tankInputArray[i] isKindOfClass:[NSDictionary class]]) {
            [IBTLoadingView showTextOnly:@"请选择油罐"];return;
        }
    }
    if (self.userInputArray.count <= 2) {
        [IBTLoadingView showTextOnly:@"请添加油罐"];return;
    }
    for (NSInteger i=0; i<[self.userInputArray[2] count]; i++) {
        if ([self.userInputArray[2][i] length] == 0) {
            [IBTLoadingView showTextOnly:[self returnPromptInformation:i]];return;
        }
    }
    //判断损耗升数（负数）且绝对值大于发油升数的千分之三
    double lossNumber = [self.userInputArray[ONE][8] doubleValue];//损耗升数
    double delivery = [self.userInputArray[ONE][7] doubleValue];//发油升数
    __weak typeof(self) weakSelf = self;
    if (lossNumber < 0) {
        lossNumber = fabs(lossNumber);
        NSString *remark = @"该单损耗超过千分之三!";
        if (lossNumber > delivery * 3/1000) {
            //添加到备注信息
            if ([self.userInputArray[ONE][10] isEqualToString:@""]) {
                self.userInputArray[ONE][10] = remark;
            }else {
                NSString *string = self.userInputArray[ONE][10];
                if (![string containsString:remark]) {//包含就不追加
                    self.userInputArray[ONE][10] = [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 callReceivedAPI:^(NSString *uuidString) {
                    block(uuidString);
                } isPushDetails:boolValue];
            }]];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
        else{
            //修改后不满足该单损耗超过千分之三
            NSString *string = self.userInputArray[ONE][10];
            if (![string containsString:remark]) {
                self.userInputArray[ONE][10] = [NSString stringWithFormat:@"%@",string];
            }
        }
    }else {
        [weakSelf callReceivedAPI:^(NSString *uuidString) {
            block(uuidString);
        } isPushDetails:boolValue];
    }
}


#pragma mark -调用保存收油单接口
- (void)callReceivedAPI:(void(^)(NSString *uuidString))bolck isPushDetails:(BOOL)boolValue
{
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    //收油单UUID
    self.orderDetails.uuid = self.orderUUIDString;
    //企业验证码
    self.orderDetails.enterprise = user.f_enterprise_uuid;
    //油站
    UCN *store = [[UCN alloc]init];
    store.name = self.storeDict[@"name"];
    store.code = self.storeDict[@"code"];
    store.uuid = self.storeDict[@"uuid"];
    //车牌号
    self.orderDetails.truckNo = self.userInputArray[1][0]?self.userInputArray[1][0]:nil;
    //司机
    self.orderDetails.carter = self.userInputArray[1][1]?self.userInputArray[1][1]:nil;
    //油罐信息
    __weak typeof(self) weakSelf = self;
    NSMutableArray *tanksArray = [NSMutableArray array];
    for (int i=2;i<self.tankInputArray.count-1;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://实际收油（公斤）
                {
                    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;
                    }
                }
                default:
                    break;
            }
        }
        details.uuid = [self.orderDetails.tankDtls[i/2-1] uuid];//油罐ID
        [tanksArray addObject:details];
    }
    //发油公斤数
    self.orderDetails.realMeasure = self.userInputArray[ONE][5];
    self.orderDetails.tankDtls = (NSArray<ReceiveTankDtl> *)tanksArray;
    //要求到油时间
    self.orderDetails.receiveTime = self.orderBill.receiveTime;
    //实际到油时间
    self.orderDetails.realReceiveTime = self.userInputArray[ONE][2];
    //到油营业时间
    self.orderDetails.receiveBusinessDate = [NSString stringWithFormat:@"%@ 00:00:00",self.userInputArray[ONE][3]];
    //班次号
    self.orderDetails.serviceNumber = self.userInputArray[ONE][4];
    //发油密度
    self.orderDetails.pickFuelDensity = [NSNumber numberWithDouble:[self.userInputArray[ONE][6] doubleValue]];
    //发油升数
    self.orderDetails.pickFuelDensityCapacity = [NSNumber numberWithDouble:[self.userInputArray[ONE][7] doubleValue]];
    //损耗升数
    self.orderDetails.wasterCapacity = [NSNumber numberWithDouble:[self.userInputArray[ONE][8] doubleValue]];
    //出库编码
    self.orderDetails.envOutCode = self.userInputArray[ONE][9];
    //备注
    self.orderDetails.remark = self.userInputArray[ONE][10];
    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];
    [IBTLoadingView showProgressLabel:@"保存中..."];
    [HttpRequestManager requestNetworkwithURL:string withRequestType:ZERO withParameter:[self.orderDetails toDictionary] withSuccess:^(id returnValue) {
        
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            if (!boolValue) {
                [IBTLoadingView hideHUDWithText:nil];
                bolck(returnValue[@"data"][@"uuid"]);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)commitRecevieOrder
{
    __weak typeof(self) weakSelf = self;
    [self showAlertViewController:@"确定提交该收油单吗？" withCompleted:^{
        [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.storeDict;//油站
                        [weakSelf PushViewController:orderBill animated:YES];
                    });
                    
                } else {
                    [IBTLoadingView hideHUDWithText:returnValue[@"message"]];
                    [weakSelf saveOrderSuccess:uuidString];
                }
                
            } withFailed:^(NSError *failed) {
                [IBTLoadingView showTextOnly:failed.localizedDescription];
            }];
            
        } isPushDetails:NO];
    }];

}

#pragma mark -保存收油单成功
- (void)saveOrderSuccess:(NSString *)uuidString
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        SeeObtainViewController *orderBill = [self.storyboard instantiateViewControllerWithIdentifier:@"SeeObtainViewController"];
        orderBill.orderUUIDString = uuidString;
        orderBill.storeDict = self.storeDict;//油站
        orderBill.isReturnRootVC = YES;
        [self PushViewController:orderBill animated:YES];
    });
}


#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)invalidOrder
{
    __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:@"%@/receiveBill/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(), ^{
                    [weakSelf PopToRootViewControllerAnimated:YES];
                });
            } else {
                [IBTLoadingView hideHUDWithText:@"作废失败"];
            }
            
        } withFailed:^(NSError *failed) {
            [IBTLoadingView hideHUDWithText:@"作废失败"];
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    }];
}

#pragma mark -删除收油单
- (void)deleteOrder
{
    __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:@"%@/receiveBill/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.orderStateBoolValue) {
                            [weakSelf PopToRootViewControllerAnimated:YES];
                        } else {
                            [weakSelf returnUUIDsingAfterDeleteOrCancel:YES];
                            [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 -到油时间选择
- (void)detailsTimeButtonClick:(UIButton *)btn
{
    __weak typeof(self) weakSelf = self;
    DetailTimeViewController *dateView = [[DetailTimeViewController alloc]init];
    dateView.defaultTime = [GTOCommonTools dateWithString:[btn currentTitle]];
    //实际收油时间
    if (btn.tag == 3) {
        dateView.indexStyle = 1;
    }
    [dateView setReturnSelectDate:^(NSString *dateString) {
        weakSelf.userInputArray[ONE][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
