//
//  NewTransferViewController.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/9/28.
//  Copyright (c) 2015年 Xummer. All rights reserved.
// 新建转运单

#import "NewTransferViewController.h"
#import "TopTransferView.h"
#import "BottomTransferView.h"
#import "TransportPurchaseViewController.h"
#import "NewCostViewController.h"
#import "TransferPdtDetail.h"
#import "FeeAcountDetail.h"
#import "TransferViewController.h"
#import "ShopDetaileViewController.h"
#import "TransportPdtDetail.h"
#import "ChooseTransportViewController.h"
typedef enum : NSUInteger {
    SaveTag = 7000,
    CommitTag,
} BtnTag;

#define TopHeight 382
#define BottomHeight 300
#define SpaceHeight 20
#define BottomViewHeight 60
@interface NewTransferViewController ()<TopTransferViewDelegate,UIScrollViewDelegate,UIAlertViewDelegate>
{
    UIScrollView *_scrollView;
    TopTransferView *_sheetView;
    BottomTransferView *_bottomView;
    id uuidObject;
    id billNumberObject;
    NSNumber *versionObject;
}
@property (nonatomic,strong)NSString *state;
@end

@implementation NewTransferViewController
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)init{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(choseTransferPurchase) name:KNOTIFICATION_ChoseTransportPurchase object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addTransferCost:) name:KNOTIFICATION_AddTransportCost object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addPurchferProduct:) name:KNOTIFICATION_AddPurchaseProduct object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseTransportProduct) name:KNOTIFICATION_ChoseTransportProduct object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //布局
    [self bulidLayout];
    uuidObject = [NSNull null];
    billNumberObject = [NSNull null];
    versionObject = [NSNumber numberWithInteger:0];
    if (self.transfer) {
        [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];
                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
{
    _sheetView.transfer = self.transfer;
    [_bottomView refreshCost:self.transfer.accountDetails];
    [_bottomView refreshTranProduct:self.transfer.pdtDetails];
}

- (void)bulidLayout{
    self.view.backgroundColor  = XXFBgColor;
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0, ScreenSize.width, ScreenSize.height- 64 - BottomViewHeight )];
    _scrollView.showsHorizontalScrollIndicator  = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.contentSize = CGSizeMake(ScreenSize.width, TopHeight+ BottomHeight + SpaceHeight*2);
    [self.view addSubview:_scrollView];
    
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenSize.height - BottomViewHeight - 64, ScreenSize.width, BottomViewHeight)];
    UIButton *saveBtn =  [IBTCustomButtom creatButtonWithFrame:CGRectMake(15, 8, (ScreenSize.width - 15*3)/2, 44) target:self sel:@selector(btnClick:) tag:SaveTag image:nil title:@"保存" titleColor: [UIColor whiteColor] isCorner:YES corner:5 bgColor:GXF_SAVE_COLOR];
    [footView addSubview:saveBtn];
    
    UIButton *commitBtn = [IBTCustomButtom creatButtonWithFrame:CGRectMake(CGRectGetMaxX(saveBtn.frame) + 15, 8, (ScreenSize.width - 15*3)/2, 44) target:self sel:@selector(btnClick:) tag:CommitTag image:nil title:@"提交" titleColor: [UIColor whiteColor] isCorner:YES corner:5 bgColor:GXF_COMMIT_COLOR];
    [footView addSubview:commitBtn];
    
    [self.view addSubview:footView];
    
    _sheetView = [[TopTransferView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, TopHeight)];
    _sheetView.delegate = self;
    [_scrollView addSubview:_sheetView];
    
    _bottomView = [[BottomTransferView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_sheetView.frame) + 20, ScreenSize.width,BottomHeight) withHidden:NO];
    _bottomView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_bottomView];
}
- (void)btnClick:(UIButton *)btn{
    switch (btn.tag) {
        case SaveTag:
        {
            if ([self checkTransfer]) {
                self.state = TRANSFER_STATE_INITIAL;
                [self getDataFromServer:TRANSFER_STATE_INITIAL msg:@"正在保存..."];
            }
        }
            break;
        case CommitTag:{
            if ([self checkTransfer]) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确认提交" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                alertView.delegate = self;
                [alertView show];
            }
        }
            break;
        default:
            break;
    }
}
- (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:PURCHASE_STATE_INITIAL]) {//保存成功
                    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{//提交成功
                    TransferViewController *svc = [TransferViewController 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 _bottomView.productVC.transferProductArr) {
        [billProducts  addObject:[pdtDetail dictForCommit]];
    }
    NSMutableArray *costs = [NSMutableArray array];
    for (FeeAcountDetail *fee in _bottomView.costVC.costArr) {
        [costs  addObject:[fee dictForCommit]];
    }
//        self.state = state;
    
    NSDictionary *dict = @{@"uuid":uuidObject,
                           @"version":versionObject,
                           @"billnumber":billNumberObject,
                           @"enterprise":[ICRUserUtil sharedInstance].orgId,
                           @"state":state,
                           @"warehouseUuid":[IBTCommon checkString:_sheetView.warehouseUuid],
                           @"warehouseCode":[IBTCommon checkString:_sheetView.warehouseCode],
                           @"warehouseName":[IBTCommon checkString:_sheetView.warehouseName],
                           @"rwarehouseUuid":[IBTCommon checkString:_sheetView.rwarehouseUuid],
                           @"rwarehouseCode":[IBTCommon checkString:_sheetView.rwarehouseCode],
                           @"rwarehouseName":[IBTCommon checkString:_sheetView.rwarehouseName],
                           @"carnumber":[IBTCommon checkString:_sheetView.carnumber],
                           @"type":[IBTCommon checkString:_sheetView.type],
                           @"carphone":[IBTCommon checkString:_sheetView.carphone],
                           @"arriveDate":[IBTCommon checkString:_sheetView.arriveDate],
                           @"note":[IBTCommon checkString:_sheetView.note],
                           @"pdtDetails":billProducts,
                           @"accountDetails":costs
                           };
    [IBTLoadingView showProgressLabel:msg];
    [[ICRHTTPController sharedController] saveTransferWithData:dict success:succ failure:fail];
}



- (BOOL)checkTransfer{
    _sheetView.note = _sheetView.remarkTextView.text;
    _sheetView.carnumber = _sheetView.carTextFiled.text;
    _sheetView.carphone = _sheetView.phoneTextFiled.text;
    
    if (_sheetView.warehouseName.length == 0 ) {
        ShowMessage(@"发货仓库不能为空");
        return NO;
    }
    if (_sheetView.rwarehouseUuid.length == 0 ) {
        ShowMessage(@"收货仓库不能为空");
        return NO;
    }
    
    if (_sheetView.type.length == 0 ) {
        ShowMessage(@"运输类型不能为空");
        return NO;
    }
    if (_sheetView.carnumber.length == 0) {
        ShowMessage(@"车牌号不能为空");
        return NO;
    }
    if (_sheetView.carphone.length == 0) {
        ShowMessage(@"司机电话不能为空");
        return NO;
    }
    if (_bottomView.productVC.transferProductArr.count == 0) {
        ShowMessage(@"商品不能为空");
        return NO;
    }
    if (_bottomView.costVC.costArr.count == 0) {
        ShowMessage(@"费用不能为空");
        return NO;
    }
    for (TransferPdtDetail *billProduct in _bottomView.productVC.transferProductArr) {
        if ([billProduct.qty integerValue] <= 0 || [billProduct.baseQty integerValue] <= 0) {
            ShowMessage(@"有数量等于0的商品明细，请编辑后保存");
            return NO;
        }
        if ([billProduct.price floatValue] <=0 || [billProduct.packprice floatValue] <= 0) {
            ShowMessage(@"有价格未填写的商品明细，请编辑后保存");
            return NO;
        }
    }
    // 校验手机号码
    if (![RegexUtil isValidatePhone:_sheetView.carphone] || ![RegexUtil isValidatePhoneNew:_sheetView.carphone]){
        ShowMessage(@"手机号格式不正确");
        return NO;
    }

    return YES;
}

#pragma mark - 通知选择采购单
- (void)choseTransferPurchase{
    TransportPurchaseViewController *tpv = [TransportPurchaseViewController new];
    tpv.getProchaseProduct = ^(NSArray *products){
        if (products.count > 0) {
            NSMutableArray *arr = [self coverTransferProduct:products];
            [_bottomView reProduct:arr];
        }
    };
    [self PushViewController:tpv animated:YES];
}
#pragma mark - 通知选择发运单
- (void)chooseTransportProduct{
    ChooseTransportViewController *tpv = [ChooseTransportViewController new];
    tpv.getTransferProduct = ^(NSArray *products){
        if (products.count > 0) {
            NSMutableArray *arr = [self coverTransferFromTransportProduct:products];
            [_bottomView reProduct:arr];
        }
    };
    [self PushViewController:tpv animated:YES];
}
- (void)addTransferCost:(NSNotification *)fination{
    
    NewCostViewController *nvc = [NewCostViewController new];
    NSIndexPath *indexPath = [[fination userInfo] objectForKey:@"indexPath"];
    FeeAcountDetail *fee = [[fination userInfo] objectForKey:@"feeAccountDetail"];
    
    if (indexPath) {
        nvc.navTitle = @"编辑费用";
        nvc.indexPath = indexPath;
        nvc.accountDetail = fee;
    }else{
        nvc.navTitle = @"添加费用";
    }
    nvc.getTransportCost = ^(FeeAcountDetail *fee,NSIndexPath *indexPath){
        if (fee) {
            [_bottomView refreshCost:fee indexPath:indexPath];
        }
    };
    nvc.deleteTransportCost = ^(FeeAcountDetail *fee,NSIndexPath *indexPath){
        if (fee) {
            [_bottomView refreshDelCost:fee indexPath:indexPath];
        }
    };
    [self PushViewController:nvc animated:YES];
    
}
- (void)addPurchferProduct:(NSNotification *)fication{
    TransferPdtDetail *billProduct = [[fication userInfo] objectForKey:@"transferPdtDetail"];
    NSInteger indexTag = [[[fication userInfo] objectForKey:@"indexTag"] integerValue];
    
    ShopDetaileViewController *svc = [[ShopDetaileViewController alloc] init];
    if (billProduct) {
        svc.navTitle = @"编辑商品";
        ShopDetail *shopDetail=[self coverShopDetail:billProduct];
        shopDetail.IsXiuGai=YES;
        svc.choseShopDetail = ^(ShopDetail *Detail){
            TransferPdtDetail *tdetail = [self coverTransportPdtDetail:Detail];
            if (Detail.IsDeleted) {
                [_bottomView refreshDelProduct:tdetail tag:indexTag];
            }else{
                [_bottomView refreshEditProduct:tdetail tag:indexTag];
            }
        };
        svc.shopDetail=shopDetail;
    }else{
        svc.navTitle = @"添加商品";
        // 回调
        svc.choseShopDetail = ^(ShopDetail *shopDetail){
            TransferPdtDetail *tdetail = [self coverTransportPdtDetail:shopDetail];
            [_bottomView refreshProduct:tdetail];
        };
    }
    [self PushViewController:svc animated:YES];
}


- (TransferPdtDetail *)coverTransportPdtDetail:(ShopDetail *)shopDetail{
    TransferPdtDetail *billProduct = [[TransferPdtDetail alloc]init];
    billProduct.uuid = shopDetail.uuid;
    billProduct.productUuid = shopDetail.product_uuid;
    billProduct.productCode = shopDetail.product_code;
    billProduct.productName = shopDetail.merchandise;
    billProduct.qpc = [NSNumber numberWithFloat:[shopDetail.packageSpecification floatValue]];
    billProduct.unit = shopDetail.packageUnit;
    billProduct.qty = [NSNumber numberWithFloat:[shopDetail.packageQuantity floatValue]];
    billProduct.packprice = [NSNumber numberWithFloat:[shopDetail.packageUnitPrice floatValue]];
    billProduct.price = [NSNumber numberWithFloat:[shopDetail.foundationUnitPrice floatValue]];
    billProduct.baseQty = [NSNumber numberWithFloat:[shopDetail.foundationQuantity floatValue]];
    billProduct.total = [NSNumber numberWithFloat:[shopDetail.totalMoney floatValue]];
    billProduct.note = shopDetail.remark;
    billProduct.qpcStr = shopDetail.packageQpcStr ? shopDetail.packageQpcStr : @"无" ;
    billProduct.baseUnit = shopDetail.packageQpcUnit;
    billProduct.sourcetype = shopDetail.sourceType;
    billProduct.sourcebillnumber = shopDetail.sourceBillNumber;
    billProduct.sourcePdtDetail = shopDetail.sourceDetail;
    return billProduct;
}
- (ShopDetail *)coverShopDetail:(TransferPdtDetail *)billProduct{
    ShopDetail *shopDetail = [[ShopDetail alloc]init];
    shopDetail.uuid = billProduct.uuid;
    shopDetail.product_uuid = billProduct.productUuid;
    shopDetail.product_code = billProduct.productCode;
    shopDetail.merchandise  = billProduct.productName;
    shopDetail.packageSpecification  =  [billProduct.qpc stringValue];
    shopDetail.packageUnit = billProduct.unit;
    shopDetail.packageQuantity = [billProduct.qty stringValue];
    shopDetail.packageUnitPrice  = [billProduct.packprice stringValue];
    shopDetail.foundationUnitPrice= [billProduct.price stringValue];
    shopDetail.foundationQuantity= [billProduct.baseQty  stringValue];
    shopDetail.totalMoney= [billProduct.total stringValue];
    shopDetail.remark  = billProduct.note;
    shopDetail.packageQpcUnit = billProduct.baseUnit;
    shopDetail.packageQpcStr = billProduct.qpcStr;
    shopDetail.sourceBillNumber = billProduct.sourcebillnumber;
    shopDetail.sourceDetail = billProduct.sourcePdtDetail;
    shopDetail.sourceType = billProduct.sourcetype;
    return shopDetail;
    
}

- (NSMutableArray *)coverTransferProduct:(NSArray *)products{
    NSMutableArray *transferP = [NSMutableArray new];
    for (TransportPdtDetail *pdt in products) {
        TransferPdtDetail *ferPdt = [TransferPdtDetail new];
        ferPdt.uuid = pdt.uuid;
        ferPdt.productCode = pdt.productCode;
        ferPdt.productName = pdt.productName;
        ferPdt.productUuid = pdt.productUuid;
        ferPdt.sourcebillnumber = pdt.purchasebillnumber;
        ferPdt.sourcePdtDetail = pdt.purchasePdtDetail;
        ferPdt.sourcetype = @"purchase";
        ferPdt.qpc = pdt.qpc;
        ferPdt.qpcStr = pdt.qpcStr;
        ferPdt.unit = pdt.unit;
        ferPdt.qty = pdt.qty;
        ferPdt.price = pdt.price;
        ferPdt.baseQty = pdt.baseQty;
        ferPdt.packprice = pdt.packprice;
        ferPdt.baseUnit = pdt.baseUnit;
        ferPdt.total = pdt.total;
        ferPdt.note = pdt.note;
        [transferP addObject:ferPdt];
    }
    return transferP;
}
- (NSMutableArray *)coverTransferFromTransportProduct:(NSArray *)products{
    NSMutableArray *transferP = [NSMutableArray new];
    for (TransportPdtDetail *pdt in products) {
        TransferPdtDetail *ferPdt = [TransferPdtDetail new];
        ferPdt.uuid = pdt.uuid;
        ferPdt.productCode = pdt.productCode;
        ferPdt.productName = pdt.productName;
        ferPdt.productUuid = pdt.productUuid;
        ferPdt.sourcebillnumber = pdt.purchasebillnumber;
        ferPdt.sourcePdtDetail = pdt.purchasePdtDetail;
        ferPdt.sourcetype = @"transport";
        ferPdt.qpc = pdt.qpc;
        ferPdt.qpcStr = pdt.qpcStr;
        ferPdt.unit = pdt.unit;
        ferPdt.qty = pdt.qty;
        ferPdt.price = pdt.price;
        ferPdt.baseQty = pdt.baseQty;
        ferPdt.packprice = pdt.packprice;
        ferPdt.baseUnit = pdt.baseUnit;
        ferPdt.total = pdt.total;
        ferPdt.note = pdt.note;
        [transferP addObject:ferPdt];
    }
    return transferP;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //提交
        self.state = TRANSFER_STATE_UNRECEIVED;
        [self getDataFromServer:TRANSFER_STATE_UNRECEIVED msg:@"正在提交..."];
    }
}

#pragma mark - TopPurchaseViewDelegate

- (void)pushNextViewController:(id)vc{
    [self PushViewController:vc animated:YES];
}
#pragma mark - 协议方法
- (void)hiddenKeyBoard{
    [self keyboardHidden];
}
- (void)keyboardHidden{
    [_sheetView.phoneTextFiled resignFirstResponder];
    [_sheetView.carTextFiled resignFirstResponder];
    [_sheetView.remarkTextView resignFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if(self.transfer && [self.state isEqualToString:TRANSFER_STATE_INITIAL]){
        [ICRUserUtil sharedInstance].needFresh = YES;
    }
    if (_sheetView.startTimeView) {
        [_sheetView.startTimeView removeFromSuperview];
        _sheetView.startTimeView = nil;
    }
}

/*
#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
