//
//  NewReceiveViewController.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/10/13.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "NewReceiveViewController.h"
#import "ReceiveProductViewController.h"
#import "TransferPdtDetail.h"
#import "NewReceiveProductViewController.h"
#import "ReceiveViewController.h"
#define BottomHeight                                50
#define LeftMargin                                  15
#define LeftWidth                                   100
#define LeftHeight                                  30
#define TopMargin                                   15
typedef enum : NSUInteger {
    SaveTag = 20000,
    ReceiveTag,
    AbortTag
    
} BtnTag;
@interface NewReceiveViewController ()<UIAlertViewDelegate>
{
    UIScrollView *_scrollView;
    UIView *_transportView;
    UIView *_bottomView;
    UIButton *_firstBtn;
    UIButton *_secondBtn;
    ReceiveProductViewController *_pvc;
    id uuidObject;
    id billNumberObject;
    NSNumber *versionObject;
}
@property (nonatomic,strong)UILabel *billNumberLabel;
@property (nonatomic,strong)UILabel *purchaseLabel;
@property (nonatomic,strong)UILabel *stateLabel;
@property (nonatomic,strong)UILabel *warehouseLabel;
@property (nonatomic,strong)UILabel *rwarehouseLabel;
@property (nonatomic,strong)UILabel *carnumberLabel;
@property (nonatomic,strong)UILabel *carhoneLabel;
@property (nonatomic,strong)UILabel *createOperLabel;
@property (nonatomic,strong)UILabel *noteLabel;
@property (nonatomic,strong)NSMutableArray *defalutState;
@property (nonatomic,strong)NSString *state;
@end

@implementation NewReceiveViewController
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)init{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editReceiveProduct:) name:KNOTIFICATION_EditReceiveProduct object:nil];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    uuidObject = [NSNull null];
    billNumberObject = [NSNull null];
    versionObject = [NSNumber numberWithInteger:0];
    [self bulifLayout];
    [self getDataFromServer];
}
- (void)getDataFromServer{
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message  = data[@"message"] ;
            if (success == 1) {
                NSDictionary *dictData = data[@"data"];
                
                Transfer *transfer = [[Transfer alloc]init];
                [transfer setValuesForKeysWithDictionary:dictData];
                
                NSMutableArray *productArr = [NSMutableArray array];
                for (NSDictionary *billDict in transfer.pdtDetails) {
                    TransferPdtDetail *billProbuct = [TransferPdtDetail new];
                    [billProbuct setValuesForKeysWithDictionary:billDict];
                    [productArr addObject:billProbuct];
                    if ([self.transfer.state isEqualToString:TRANSFER_STATE_RECEIVED] || [billProbuct.rctBaseQty floatValue] > 0 ||  [billProbuct.rctQty floatValue] > 0) {
                        [self.defalutState addObject:@"YES"];
                    }else{
                        [self.defalutState addObject:@"NO"];

                    }
                }
                transfer.pdtDetails = productArr;
                self.transfer = transfer;
                [strongSelf fetchtTransportDetail];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"     无记录     "];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController] getTransferResultWithTransferUuid:self.transfer.uuid success:succ failure:fail];
}
- (void)fetchtTransportDetail{
    self.billNumberLabel.text = [IBTCommon checkString:self.transfer.billnumber];
    if ([self.transfer.state isEqualToString:TRANSFER_STATE_UNRECEIVED]) {
        self.stateLabel.textColor = [UIColor redColor];
        self.stateLabel.text = @"待收货";
    }else if ([self.transfer.state isEqualToString:TRANSFER_STATE_RECEIVED]) {
        self.stateLabel.textColor = [UIColor greenColor];
        self.stateLabel.text = @"已收货";
    }else if ([self.transfer.state isEqualToString:TRANSFER_STATE_ABORTED]) {
        self.stateLabel.textColor = [UIColor grayColor];
        self.stateLabel.text = @"已作废";
    }
    self.purchaseLabel.text = [NSString stringWithFormat:@"转运单%@",self.transfer.billnumber];
    self.warehouseLabel.text = [IBTCommon checkString:self.transfer.warehouseName];
    self.rwarehouseLabel.text = [IBTCommon checkString:self.transfer.rwarehouseName];
    self.carnumberLabel.text = [IBTCommon checkString:self.transfer.carnumber];
    self.carhoneLabel.text = [IBTCommon checkString:self.transfer.carphone];
    self.noteLabel.text = [NSString stringWithFormat:@"%@",self.transfer.note?self.transfer.note:@"无"];
    self.createOperLabel.text = [NSString stringWithFormat:@"%@%@",[IBTCommon checkString:self.transfer.create_operName],self.transfer.create_time.length > 10 ? [self.transfer.create_time substringToIndex:10] : self.transfer.create_time];
    [self setNoteHeight];
    
    _pvc.productArr = [NSMutableArray arrayWithArray:self.transfer.pdtDetails];
    _pvc.defaultState = self.defalutState;
    [_pvc.tableView reloadData];

}
- (void)setNoteHeight
{
    CGFloat height =  [self.noteLabel calculateHeight];
    
    CGRect noteFrame = self.noteLabel.frame;
    noteFrame.size.height = height;
    self.noteLabel.frame = noteFrame;
    
    CGFloat totalHeight = height + LeftHeight*9;
    //    CGRect purchaseFrame = _purchaseView.frame;
    //    purchaseFrame.size.height = totalHeight;
    //    _purchaseView.frame = purchaseFrame;
    //
    //
    //    CGRect bottomFrame = _bottomView.frame;
    //    bottomFrame.origin.y = CGRectGetMaxY(_purchaseView.frame) + TopMargin;
    //    _bottomView.frame = bottomFrame;
    
    _scrollView.contentSize = CGSizeMake(ScreenSize.width, totalHeight + CGRectGetHeight(_bottomView.frame) + TopMargin*2);
}

- (void)createBtnWithArr:(NSArray *)arr{
    CGFloat btnWidth = (ScreenSize.width - LeftMargin * (arr.count+1))/arr.count;
    for (NSInteger i = 0; i < arr.count; i++) {
        NSInteger btnTag = 0;
        if ([arr[i] isEqualToString:@"保存"]) {
            btnTag = SaveTag;
        }else if ([arr[i] isEqualToString:@"收货"]) {
            btnTag = ReceiveTag;
        }else if([arr[i] isEqualToString:@"作废"]){
            btnTag = AbortTag;
        }
        CGRect btnFrame = CGRectMake(LeftMargin + (LeftMargin + btnWidth)*i,  ScreenSize.height  - 64 - BottomHeight +5, btnWidth, 40);
        UIButton *perBtn = [IBTCustomButtom creatButtonWithFrame:btnFrame target:self sel:@selector(btnClick:) tag:btnTag image:nil title:arr[i] titleColor:[UIColor whiteColor] isCorner:YES corner:5 bgColor:GXF_COMMIT_COLOR];
        [self.view addSubview:perBtn];
    }
}
- (void)hiddenBottom{
    CGRect scrollViewFrame = _scrollView.frame;
    scrollViewFrame.size.height = ScreenSize.height - 64;
    _scrollView.frame = scrollViewFrame;
}

#pragma mark - 视图初始化
- (void)bulifLayout{
    self.defalutState = [NSMutableArray array];
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, ScreenSize.height - 64 - BottomHeight)];
    _scrollView.showsHorizontalScrollIndicator  = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.backgroundColor = XXFBgColor;
    [self.view addSubview:_scrollView];
    
    if ([self.transfer.state isEqualToString:TRANSFER_STATE_UNRECEIVED]) {
        if ([IBTCommon checkIsPermission:RECEIVE_ACTION_RECEIVE]) {
            [self createBtnWithArr:@[@"保存",@"收货"]];
        }else{
            [self hiddenBottom];
        }
    }else if ([self.transfer.state isEqualToString:TRANSFER_STATE_RECEIVED]) {
        if ([IBTCommon checkIsPermission:TRANSFER_ACTION_ABORT]) {
            [self createBtnWithArr:@[@"作废"]];
        }else{
            [self hiddenBottom];
        }
    }
    
    NSArray *leftArr = @[@"单号:",@"来源单据:",@"状态:",@"发货仓库:",@"收货仓库:",@"车辆:",@"司机电话:",@"创建:",@"备注"];
    
    _transportView= [[UIView alloc]initWithFrame:CGRectMake(0, TopMargin, ScreenSize.width, LeftHeight*leftArr.count +LeftMargin)];
    _transportView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_transportView];
    
    
    for (NSInteger i = 0 ; i < leftArr.count; i++) {
        UILabel *leftLabel = [[UILabel alloc]initWithFrame:CGRectMake(LeftMargin, 10 + LeftHeight *i, LeftWidth, LeftHeight)];
        leftLabel.font = GXF_SEVENTEENTH_SIZE;
        leftLabel.text = leftArr[i];
        leftLabel.textColor = GXF_DETAIL_COLOR;
        [_transportView addSubview:leftLabel];
        
        UILabel *rightLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(leftLabel.frame), 10 + LeftHeight *i, _transportView.frame.size.width - LeftMargin - LeftWidth, LeftHeight)];
        rightLabel.font = GXF_SEVENTEENTH_SIZE;
        rightLabel.textColor = GXF_DETAIL_COLOR;
        
        if (i == 0) {
            self.billNumberLabel = rightLabel;
        }else if (i == 1) {
            self.purchaseLabel = rightLabel;
        }else if(i == 2){
            self.stateLabel = rightLabel;
        }else if(i == 3){
            self.warehouseLabel = rightLabel;
        }else if(i == 4){
            self.rwarehouseLabel = rightLabel;
        }else if(i == 5){
            self.carnumberLabel = rightLabel;
        }else if(i == 6){
            self.carhoneLabel = rightLabel;
        }else if(i == 7){
            self.createOperLabel = rightLabel;
        }else if(i == leftArr.count - 1){
            rightLabel.numberOfLines = 0;
            self.noteLabel = rightLabel;
        }
        [_transportView addSubview:rightLabel];
    }
    [self createBottomView];
}
- (void)createBottomView{
    _bottomView= [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_transportView.frame) + TopMargin, ScreenSize.width, 300)];
    _bottomView.backgroundColor = [UIColor whiteColor];
    
    [_scrollView addSubview:_bottomView];

    _pvc = [[ReceiveProductViewController alloc]init];
    _pvc.viewFrame = _bottomView.bounds;
    _pvc.isHiddenAdd = YES;
    _pvc.isHiddenEdit = self.isNotShowEdit;
    [_bottomView addSubview:_pvc.view];
}


- (void)editReceiveProduct:(NSNotification *)fination{
    
    NewReceiveProductViewController *nvc = [NewReceiveProductViewController new];
    NSInteger indexTag = [[[fination userInfo] objectForKey:@"indexPath"] integerValue];
    TransferPdtDetail *transferPdtDetail = [[fination userInfo] objectForKey:@"transferPdtDetail"];
    
    if (transferPdtDetail) {
        nvc.navTitle = @"商品明细";
        nvc.indexTag = indexTag;
        nvc.noticeProduct = transferPdtDetail;
    }
    nvc.editReceiveProduct = ^(TransferPdtDetail *transferPdtDetail,NSInteger indexTag){
        if (transferPdtDetail) {
            [_pvc.productArr replaceObjectAtIndex:indexTag withObject:transferPdtDetail];
            [_pvc.defaultState replaceObjectAtIndex:indexTag withObject:@"YES"];
            [_pvc.tableView reloadData];
        }
    };
   
    [self PushViewController:nvc animated:YES];
    
}





- (void)btnClick:(UIButton *)btn{
    switch (btn.tag) {
        case SaveTag:
        {
            if ([self checkReceive]) {
                self.state = RECEIVE_STATE_SAVE;
                [self getDataFromServer:RECEIVE_STATE_SAVE msg:@"正在保存..."];
            }
        }
            break;
        case ReceiveTag:{
            if ([self checkReceive]) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"收货后不能重复收货，请确认是否要收货？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                alertView.delegate = self;
                alertView.tag = ReceiveTag;
                [alertView show];
            }
        }
            break;
        case AbortTag:
        {
            CLog(@"作废");
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确认作废" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            alertView.delegate = self;
            alertView.tag = AbortTag;
            [alertView show];
        }
            break;
        default:
            break;
    }
}


- (void)dealByAction:(NSString *)action{
    //保存
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message = data[@"message"];
            if (success == 1) {
                [ICRUserUtil sharedInstance].needFresh = YES;
                [self PopViewControllerAnimated:YES];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"操作异常"];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController] abortTransferWithTransferUuid:self.transfer.uuid version:self.transfer.version success:succ failure:fail];
}


- (void)getDataFromServer:(NSString *)state msg:(NSString *)msg{
    //保存
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message = data[@"message"];
            if (success == 1) {
                //成功
                if ([state isEqualToString:RECEIVE_STATE_SAVE]) {//保存成功
                    NSString *uuidS = data[@"data"][@"uuid"];
                    NSString *billNumberS = data[@"data"][@"billNumber"];
                    NSNumber *versionN = data[@"data"][@"version"];
                    uuidObject = uuidS;
                    billNumberObject = billNumberS;
                    versionObject = versionN;
                    [IBTLoadingView showTips:[NSString stringWithFormat:@"当前单据%@已保存成功",billNumberS]];
                }else{//提交成功
                    ReceiveViewController *svc = [ReceiveViewController new];
                    svc.title = @"收货单列表";
                    [self PushViewController:svc animated:YES];
                }
            }else{
                [IBTLoadingView showTips:message];
            }
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    
    if(self.transfer.uuid.length > 0 && uuidObject == [NSNull null]){
        uuidObject = self.transfer.uuid;
    }
    if (self.transfer.billnumber > 0 && billNumberObject == [NSNull null]) {
        billNumberObject = self.transfer.billnumber;
    }
    if (self.transfer && [versionObject integerValue] == 0) {
        versionObject = self.transfer.version;
    }
    NSMutableArray *billProducts = [NSMutableArray array];
    for (TransferPdtDetail *pdtDetail in _pvc.productArr) {
        [billProducts  addObject:[pdtDetail dictForCommit]];
    }
    NSDictionary *dict = @{@"uuid":uuidObject,
                           @"version":versionObject,
                           @"billnumber":billNumberObject,
                           @"enterprise":[ICRUserUtil sharedInstance].orgId,
                           @"state":self.transfer.state,
                           @"warehouseUuid":[IBTCommon checkString:self.transfer. warehouseUuid],
                           @"warehouseCode":[IBTCommon checkString:self.transfer.warehouseCode],
                           @"warehouseName":[IBTCommon checkString:self.transfer.warehouseName],
                           @"rwarehouseUuid":[IBTCommon checkString:self.transfer.rwarehouseUuid],
                           @"rwarehouseCode":[IBTCommon checkString:self.transfer.rwarehouseCode],
                           @"rwarehouseName":[IBTCommon checkString:self.transfer.rwarehouseName],
                           @"carnumber":[IBTCommon checkString:self.transfer.carnumber],
                           @"type":[IBTCommon checkString:self.transfer.type],
                           @"carphone":[IBTCommon checkString:self.transfer.carphone],
                           @"note":[IBTCommon checkString:self.transfer.note],
                           @"pdtDetails":billProducts,
                           };
    [IBTLoadingView showProgressLabel:msg];
    if ([state isEqualToString:RECEIVE_STATE_SAVE]) {
        [[ICRHTTPController sharedController] saveReceiveWithData:dict success:succ failure:fail];
    }else{
        [[ICRHTTPController sharedController] saveReceiptAndReceiveWithData:dict success:succ failure:fail];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == AbortTag) {
        if (buttonIndex == 1) {
            [self dealByAction:TRANSFER_STATE_ABORTED];//作废
        }
    }else if(alertView.tag == ReceiveTag){
        if (buttonIndex == 1) {
            //提交
            self.state = RECEIVE_STATE_RECEIVE;
            [self getDataFromServer:RECEIVE_STATE_RECEIVE msg:@"收货中..."];
        }
    }
}

- (BOOL)checkReceive{
    for (NSString *isEdit in _pvc.defaultState) {
        if ([isEdit isEqualToString:@"NO"]) {
            ShowMessage(@"有商品行没有编辑过收货数量，请先编辑再收货");
            return NO;
        }
    }
    
    if (_pvc.productArr.count == 0) {
        ShowMessage(@"商品不能为空");
        return NO;
    }
    
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
