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

#import "SeeRequestViewController.h"
#import "PriceNumberTypeTableViewCell.h"
#import "TotalPriceTableViewCell.h"
#import "BeginEndDateTableViewCell.h"
#include "OrderDetailsTableViewCell.h"
#import "wareHouseView.h"
#import "SaveCommitView.h"
#import "TimeSelectViewController.h"

@interface SeeRequestViewController ()<UITableViewDelegate,UITableViewDataSource>

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

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

/**
 *  是否可编辑(所有的控件)
 */
@property (nonatomic,assign) BOOL isEditing;

@end

@implementation SeeRequestViewController

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


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

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


#pragma mark -UI
- (void)uiConfigAction
{
    self.title = @"查看建仓申请详情";
    self.viewRequestTableView.dataSource = self;
    self.viewRequestTableView.delegate = self;
    self.viewRequestTableView.tableFooterView = [UIView new];
}


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


#pragma mark -设置tableHeaderView和提交、保存、删除、作废view
- (void)setuptableHeaderViewAndCommitSaveDeleteCancelView
{
    //TableviewHeader
    wareHouseView *headerView = [wareHouseView InitializeView];
    headerView.frame = CGRectMake(0, 0, ScreenSize.width, 80);
    UIView *loadHeaderView = [[UIView alloc]initWithFrame:headerView.frame];
    headerView.orderNumberLabe.text = self.orderDetails.billnumber;
    headerView.orderSateLabe.text = [GTOCommonTools returnOrderStateString:self.orderDetails.state];
    headerView.orderSateLabe.textColor = [GTOCommonTools returnOrderSateColor:self.orderDetails.state];
    [loadHeaderView addSubview:headerView];
    self.viewRequestTableView.tableHeaderView = loadHeaderView;
    //保存、提交
    __weak typeof(self) weakSelf = self;
    if (![self.orderDetails.state isEqualToString:@"canceled"] && ![self.orderDetails.state isEqualToString:@"accomplished"] && ![self.orderDetails.state isEqualToString:@"effectived"]){
        SaveCommitView *commitView = [self.orderDetails.state isEqualToString:@"submit"]?[SaveCommitView initializeThird]:[SaveCommitView initializeTwo];
        commitView.frame = CGRectMake(0,ScreenSize.height-164, ScreenSize.width,100);
        [commitView setCommitButtonBlock:^{//提交
            
        }];
        [commitView setSaveButtonBlock:^{//保存
            
        }];
        [commitView setDelectButtonBlock:^{//删除
            [weakSelf deleteOrder];
        }];
        [commitView setInvalidButtonBlock:^{//作废
            [weakSelf cancelOrder];
        }];
        [self.view addSubview:commitView];
    }else {
        self.viewRequestTableView.frame = CGRectMake(0, 0, ScreenSize.width, ScreenSize.height-64);
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            PriceNumberTypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PriceNumberTypeTableViewCell" forIndexPath:indexPath];
            cell.headerImageView.image = TCImage(@"12");
            cell.contentLabe.text = self.orderDetails.item.name;
            cell.titleLabe.text = @"油品";
            return cell;
        }
            break;
        case 1:
        {
            PriceNumberTypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PriceNumberTypeTableViewCell" forIndexPath:indexPath];
            cell.headerImageView.image = TCImage(@"P");
            cell.contentLabe.text = [NSString stringWithFormat:@"%@元/吨",[self.orderDetails.reqPrice stringValue]];
            cell.titleLabe.text = @"申请价格";
            return cell;
        }
            break;
        case 2:
        {
            PriceNumberTypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PriceNumberTypeTableViewCell" forIndexPath:indexPath];
            cell.headerImageView.image = TCImage(@"量");
            cell.contentLabe.text = [NSString stringWithFormat:@"%.6lf吨",[self.orderDetails.quantity doubleValue]];
            cell.titleLabe.text = @"申请数量";
            return cell;
        }
            break;
        case 3:
        {
            TotalPriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TotalPriceTableViewCell" forIndexPath:indexPath];
            cell.applyTotalPriceLabe.text = [NSString stringWithFormat:@"%.2f",[self.orderDetails.quantity floatValue]*[self.orderDetails.reqPrice floatValue]];
            return cell;
        }
            break;
        case 4:
        {
            BeginEndDateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BeginEndDateTableViewCell" forIndexPath:indexPath];
            NSArray *beginTime = [self.orderDetails.deliveryTime.beginDateTime componentsSeparatedByString:@" "];
            NSArray *endTime = [self.orderDetails.deliveryTime.endDateTime componentsSeparatedByString:@" "];
            [cell.beginDateButton setTitle:[beginTime firstObject] forState:UIControlStateNormal];
            [cell.endDateButton setTitle:[endTime firstObject] forState:UIControlStateNormal];
            cell.beginDateButton.enabled = self.isEditing;
            cell.endDateButton.enabled = self.isEditing;
            [cell.beginDateButton addTarget:self action:@selector(beginTimeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [cell.endDateButton addTarget:self action:@selector(endTimeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
            break;
        case 5:
        {
            OrderDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailsTableViewCell" forIndexPath:indexPath];
            cell.establishWarehouseUnitLabe.text = self.orderDetails.org.name;
            cell.establishName.text = self.orderDetails.createInfo.operator.operName;
            cell.establishDate.text = self.orderDetails.createInfo.time;
            if ([self.orderDetails.state isEqualToString:@"general"]) {
               cell.typeLabe.text = @"普通";
            }
            cell.distributionLabe.text = self.orderDetails.deliveryArea.name;
            return cell;
        }
            break;
            
        default:
            break;
    }
    return nil;
}

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

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




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

#pragma mark -删除建仓单
- (void)deleteOrder
{
    __weak typeof(self) weakSelf = self;
    [self userSureDeleteOrCancelOperation:@"删除" returnBlock:^{
        [IBTLoadingView showProgressLabel:@"删除中..."];
        //操作人
        RsOperateInfo *infomation = [[RsOperateInfo alloc]init];
        ICRUserUtil *user = [ICRUserUtil sharedInstance];
        infomation.operId = user.f_user_uuid;
        infomation.operName = user.f_user_name;
        infomation.enterprise = user.f_enterprise_uuid;
        infomation.time = [GTOCommonTools GetCurrenttime];
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/depotRequest/remove/%@",HTTP_REST_API_BASE_URL,self.orderUUID] withRequestType:ZERO withParameter:[infomation toDictionary] withSuccess:^(id returnValue) {
            
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                [IBTLoadingView hideHUDWithText:@"删除成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    weakSelf.boolValue?[weakSelf PopToRootViewControllerAnimated:YES]:[weakSelf PopViewControllerAnimated:YES];
                    [weakSelf returnUUIDsingAfterDeleteOrCancel:YES];
                });
                
            } else {
                [IBTLoadingView hideHUDWithText:nil];
                [IBTLoadingView showTextOnly:returnValue[@"message"]];
            }
            
        } withFailed:^(NSError *failed) {
            [IBTLoadingView hideHUDWithText:nil];
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    }];

}


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

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


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



#pragma mark -删除或者作废后返回此订单UUID
- (void)returnUUIDsingAfterDeleteOrCancel:(BOOL)isDelete
{
    if (self.deleteAndCancelOrderBillblock) {
        self.deleteAndCancelOrderBillblock(self.orderUUID,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];
}











@end
