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

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


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


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

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

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

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

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

/**
 *  订单数组（油品、数量、到油时间）
 */
@property (nonatomic,strong) NSMutableArray *recordOrderArray;




@end

@implementation NewOrderViewController


- (NSMutableArray *)recordOrderArray
{
    if (!_recordOrderArray) {
        _recordOrderArray = [NSMutableArray array];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [_recordOrderArray addObject:dict];
    }
    return _recordOrderArray;
}

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


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


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

#pragma mark -获取油站列表、油品信息
- (void)getGasStationList
{
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    dispatch_queue_t queue = dispatch_queue_create("顺序执行", DISPATCH_QUEUE_SERIAL);
    dispatch_group_t group = dispatch_group_create();
    __weak typeof(self) weakSelf = self;
    //任务一->获取油站列表
    dispatch_group_async(group, queue, ^{
        dispatch_suspend(queue);
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/mdata/store/getsByUser/%@",HTTP_REST_API_BASE_URL,[ICRUserUtil sharedInstance].f_user_uuid] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
            dispatch_resume(queue);
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                weakSelf.oilListDatas = returnValue[@"data"];
                [weakSelf setupHeaderViewAndFooterView];
            }
        } withFailed:^(NSError *failed) {
            [IBTLoadingView hideHUDWithText:nil];
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    });
    //任务二->获得油品信息
    dispatch_group_async(group, queue, ^{
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,OILTYPE] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
            [IBTLoadingView hideHUDWithText:nil];
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                weakSelf.oilTypeListDatasArray = returnValue[@"data"];
            }
        } withFailed:^(NSError *failed) {
            
            [IBTLoadingView hideHUDWithText:nil];
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    });
}

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

#pragma mark -设置HeaderView、FooterView
- (void)setupHeaderViewAndFooterView
{
    //头视图
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 80)];
    imageView.image = TCImage(@"矩形-36");
    UIView *headerView = [[UIView alloc]initWithFrame:imageView.frame];
    [headerView addSubview:imageView];
    [self.OrderTableview setTableHeaderView:headerView];
    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];
    [headerView addSubview:self.locationButton];
    //保存、提交
    SaveCommitView *commitView = [SaveCommitView initializeOne];
    commitView.frame = CGRectMake(0,ScreenSize.height-164, ScreenSize.width,100);
    __weak typeof(self) weakSelf = self;
    [commitView setCommitButtonBlock:^{
        [weakSelf commitOilOrder];
    }];
    [commitView setSaveButtonBlock:^{
        [weakSelf saveOilOrder:^(NSDictionary *returnSaveuuid, OrderBill *order) {
        } isPushDetails:YES];
    }];
    [self.view addSubview:commitView];
    
    //需求改变，只能添加一种油品
//    //尾视图
//    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, 100)];
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//    [footerView addSubview:button];
//    button.layer.borderWidth = 1.0f;
//    button.layer.cornerRadius = TCcornerRadius;
//    button.layer.masksToBounds = YES;
//    button.layer.borderColor = RGBA(12, 96, 163, 1).CGColor;
//    [button setTitleColor:RGBA(12, 96, 163, 1) forState:UIControlStateNormal];
//    [button setTitle:@"添加" forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(addCellAction) forControlEvents:UIControlEventTouchUpInside];
//    [button mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(footerView.mas_left).mas_offset(60);
//        make.right.equalTo(footerView.mas_right).mas_offset(-60);
//        make.center.equalTo(footerView);
//        make.height.mas_equalTo(40);
//    }];
//    self.OrderTableview.tableFooterView = footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BookingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BookingTableViewCell" forIndexPath:indexPath];
    [cell.selectOilTypeButton setTitle:[self.recordOrderArray[indexPath.row] objectForKey:@"oilType"][@"name"]?[self.recordOrderArray[indexPath.row] objectForKey:@"oilType"][@"name"]:@"请选择" forState:UIControlStateNormal];
    [cell.arriveTimeButton setTitle:[self.recordOrderArray[indexPath.row] objectForKey:@"orderTime"]?[self.recordOrderArray[indexPath.row] objectForKey:@"orderTime"]:@"请选择" forState:UIControlStateNormal];
    cell.bookingNumberField.text = [self.recordOrderArray[indexPath.row] objectForKey:@"orderNumber"];
    cell.bookingNumberField.placeholder = @"请输入";
    cell.delectCellButton.tag = indexPath.row;
    [cell.delectCellButton addTarget:self action:@selector(delectCellButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.arriveTimeButton addTarget:self action:@selector(detailsTimeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.selectOilTypeButton addTarget:self action:@selector(selectOilTypeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.bookingNumberField.tag = indexPath.row;
    cell.selectOilTypeButton.tag = indexPath.row;
    cell.arriveTimeButton.tag = indexPath.row;
    [cell.bookingNumberField addTarget:self action:@selector(textFieldEndEditing:) forControlEvents:UIControlEventEditingChanged];
    return cell;
}

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

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


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


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


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

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

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

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

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

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

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


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



@end
