//
//  NewPurchaseViewController.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/8/21.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "NewPurchaseViewController.h"
#import "SeePurchaseNoticeViewController.h"
#import "TopPurchaseView.h"
#import "ProductBillViewController.h"
#import "PurchaseBillProduct.h"
#import "PurchaseViewController.h"
#import "ShopDetaileViewController.h"
#import "PurchaseBillProduct.h"
#import "GXFPopView.h"
#import "NoticeProduct.h"
#import "BottomPurchaseView.h"
#import "NewCostViewController.h"
#import "FeeAcountDetail.h"
#define TopHeight 328
#define BottomHeight 300
#define SpaceHeight 20
#define BottomViewHeight 60
typedef enum : NSUInteger {
    SaveTag = 8000,
    CommitTag,
} BtnTag;

@interface NewPurchaseViewController ()<TopPurchaseViewDelegate,UIAlertViewDelegate>
{
    UIScrollView *_scrollView;
    TopPurchaseView *_purchaseView;
    UIView *_bottomView;
    ProductBillViewController *_pvc ;
    BottomPurchaseView *_aBottomView;
    id uuidObject;
    id billNumberObject;
    NSNumber *versionObject;
}
@property (nonatomic,strong)NSString *state;
@property (nonatomic,strong)GXFPopView *popView;





@end

@implementation NewPurchaseViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        //监听值的改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setProductTotalPrice:) name:SetProductTotalPrice object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addPurchaseProduct:) name:KNOTIFICATION_AddPurchaseProduct object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addTransportCost:) name:KNOTIFICATION_AddTransportCost object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //布局
    [self bulidLayout];
    //数据默认值
    uuidObject = [NSNull null];
    billNumberObject = [NSNull null];
    versionObject = [NSNumber numberWithInteger:0];
    if (self.purchaseBill) {
        [self getDataFromServer];
    }
    if (self.purchaseNotice) {
        _purchaseView.noticeUuid = self.purchaseNotice.uuid;
        _purchaseView.noticeNumber = self.purchaseNotice.billnumber;
        //转换
        NSMutableArray *arr = [self coverPurchaseBillProduct:self.purchaseNotice.products];
        _aBottomView.productVC.productArr = arr;
    }
}
- (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"];
                PurchaseBill *bill = [[PurchaseBill alloc]init];
                [bill setValuesForKeysWithDictionary:dictData];
                self.purchaseBill = bill;
                [strongSelf prepareDataInCell];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"     无记录     "];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController] getPurchaseResultWithPurchaseUuid:self.purchaseBill.uuid success:succ failure:fail];
}
//赋值
- (void)prepareDataInCell{
    _purchaseView.bill = self.purchaseBill;
   
    
    NSMutableArray *arr = [NSMutableArray array];
    for (NSDictionary *productDict in self.purchaseBill.products) {
        PurchaseBillProduct *billProduct = [[PurchaseBillProduct alloc]init];
        [billProduct setValuesForKeysWithDictionary:productDict];
        [arr addObject:billProduct];
    }
    _aBottomView.productVC.productArr = arr;
   [_aBottomView.productVC.tableView reloadData];
}

- (void)addTransportCost:(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) {
            [_aBottomView refreshCost:fee indexPath:indexPath];
        }
    };
    nvc.deleteTransportCost = ^(FeeAcountDetail *fee,NSIndexPath *indexPath){
        if (fee) {
            [_aBottomView refreshDelCost:fee indexPath:indexPath];
        }
    };
    [self PushViewController:nvc animated:YES];
    
}


#pragma mark - 布局
- (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];

    _purchaseView = [[TopPurchaseView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, TopHeight)];
    _purchaseView.delegate = self;
    [_scrollView addSubview:_purchaseView];
    
//    _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_purchaseView.frame) + 20, ScreenSize.width,BottomHeight)];
//    _bottomView.backgroundColor = [UIColor whiteColor];
//    [_scrollView addSubview:_bottomView];
//    
//    _pvc = [[ProductBillViewController alloc]init];
//    _pvc.viewFrame = _bottomView.bounds;
//    [_bottomView addSubview:_pvc.view];
    _aBottomView = [[BottomPurchaseView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_purchaseView.frame) + 20, ScreenSize.width,BottomHeight) withHidden:NO];
    _aBottomView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_aBottomView];
    
}

- (void)setProductTotalPrice:(NSNotification *)fication{
    //计算总金额
    //其他费用 + 商品总金额
    float otherPrice = [_purchaseView.otherPriceFiled.text floatValue];
    NSMutableArray *purchaseProduct = _aBottomView.productVC.productArr;
    float totalPrice = 0;
    for (PurchaseBillProduct *billProduct in purchaseProduct) {
        totalPrice += [billProduct.total floatValue];
    }
    _purchaseView.purchasePriceLabel.text = [NSString stringWithFormat:@"%.2f",totalPrice + otherPrice];
    _purchaseView.chargePurchase = [NSNumber numberWithFloat:otherPrice];
    _purchaseView.total = [NSNumber numberWithFloat:totalPrice+otherPrice];
}
- (void)addPurchaseProduct:(NSNotification *)fication{
    
    PurchaseBillProduct *billProduct = [[fication userInfo] objectForKey:@"purchaseBillProduct"];
    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){
            if (Detail.IsDeleted) {
                [_aBottomView.productVC.productArr removeObjectAtIndex:indexTag];
            }else{
                PurchaseBillProduct *billProduct = [self coverPurchaseProduct:Detail];
                [_aBottomView.productVC.productArr replaceObjectAtIndex:indexTag withObject:billProduct];
            }
            [_aBottomView.productVC.tableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:SetProductTotalPrice object:nil];
        };
        svc.shopDetail=shopDetail;
    }else{
        // 回调
        svc.navTitle = @"添加商品";
        svc.choseShopDetail = ^(ShopDetail *shopDetail){
            PurchaseBillProduct *billProduct = [self coverPurchaseProduct:shopDetail];
            [_aBottomView.productVC.productArr addObject:billProduct];
            [_aBottomView.productVC.tableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:SetProductTotalPrice object:nil];
        };
    }
   
    svc.title = [IBTCommon localizableString:@"AddShopDetail"];
    [self PushViewController:svc animated:YES];
}


- (void)btnClick:(UIButton *)btn{
    switch (btn.tag) {
        case SaveTag:
        {
            if ([self checkPurchase]) {
                [self getDataFromServer:PURCHASE_STATE_INITIAL msg:@"正在保存..."];
            }
        }
            break;
        case CommitTag:{
            if ([self checkPurchase]) {
                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{//提交成功
                    if (self.purchaseNotice) {
                        [self PopViewControllerAnimated:YES];
                    }else{
                        PurchaseViewController *svc = [PurchaseViewController 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.purchaseBill.uuid.length > 0 && uuidObject == [NSNull null]){
        uuidObject = self.purchaseBill.uuid;
    }
    if (self.purchaseBill.billNumber > 0 && billNumberObject == [NSNull null]) {
        billNumberObject = self.purchaseBill.billNumber;
    }
    if (self.purchaseBill && [versionObject integerValue] == 0) {
        versionObject = self.purchaseBill.version;
    }
    if (_purchaseView.noticeUuid.length ==0 || _purchaseView.noticeNumber.length == 0) {
        if (self.purchaseBill && self.purchaseBill.noticeNumber && self.purchaseBill.noticeUuid) {
            _purchaseView.noticeUuid = self.purchaseBill.noticeUuid;
            _purchaseView.noticeNumber = self.purchaseBill.noticeNumber;
        }
    }
    NSMutableArray *billProducts = [NSMutableArray array];
    for (PurchaseBillProduct *billProduct in _aBottomView.productVC.productArr) {        [billProducts  addObject:[billProduct dictForCommit]];
    }
    self.state = state;
    
    NSMutableArray *costs = [NSMutableArray array];
    for (FeeAcountDetail *fee in _aBottomView.costVC.costArr) {
        [costs  addObject:[fee dictForCommit]];
    }
    NSDictionary *dict = @{@"uuid":uuidObject,
                           @"version":versionObject,
                           @"billnumber":billNumberObject,
                           @"state":state,
                           @"type":[IBTCommon checkString:_purchaseView.type],
                           @"noticeUuid":[IBTCommon checkString:_purchaseView.noticeUuid],
                           @"noticeNumber":[IBTCommon checkString:_purchaseView.noticeNumber],
                           @"vendor_uuid":[IBTCommon checkString:_purchaseView.vendor_uuid],
                           @"vendor_code":[IBTCommon checkString:_purchaseView.vendor_code],
                           @"vendor_name":[IBTCommon checkString:_purchaseView.vendor_name],
                           @"receiveWrh_uuid":[IBTCommon checkString:_purchaseView.receiveWrh_uuid],
                           @"receiveWrh_code":[IBTCommon checkString:_purchaseView.receiveWrh_code],
                           @"receiveWrh_name":[IBTCommon checkString:_purchaseView.receiveWrh_name],
                           @"total":_purchaseView.total,
                           @"charge":_purchaseView.chargePurchase,
                           @"remark":[IBTCommon checkString:_purchaseView.remark],
                           @"products":billProducts,
                           @"accountDetails":costs0};
    [IBTLoadingView showProgressLabel:msg];
    [[ICRHTTPController sharedController] savePurchaseWithData:dict success:succ failure:fail];
}
#pragma mark - checkNull
- (BOOL)checkPurchase{
    _purchaseView.remark = _purchaseView.remarkTextView.text;
    if (_purchaseView.type.length == 0 ) {
        ShowMessage(@"采购类型不能为空");
        return NO;
    }
    if (_purchaseView.vendor_uuid.length == 0 ) {
        ShowMessage(@"供应商不能为空");
        return NO;
    }
    if (_purchaseView.receiveWrh_uuid.length == 0 ) {
        ShowMessage(@"收货仓库不能为空");
        return NO;
    }
    if (_aBottomView.productVC.productArr.count == 0) {
        ShowMessage(@"采购商品不能为空");
        return NO;
    }
    if ([_purchaseView.total floatValue] < 0 || !_purchaseView.total) {
        ShowMessage(@"金额不能为空");
        return NO;
    }
    for (PurchaseBillProduct *billProduct in _aBottomView.productVC.productArr) {
        if ([billProduct.qty floatValue] <= 0 || [billProduct.baseQty floatValue] <= 0) {
            ShowMessage(@"有数量等于0的商品明细,请编辑后保存");
            return NO;
        }
        if ([billProduct.price floatValue] <=0 || [billProduct.basePrice floatValue] <= 0) {
            ShowMessage(@"有价格未填写的商品明细,请编辑后保存");
            return NO;
        }
    }

    return YES;
}


#pragma mark - TopPurchaseViewDelegate

- (void)pushNextViewController:(id)vc{
    [self PushViewController:vc animated:YES];
}
//两个类之间的转换
- (PurchaseBillProduct *)coverPurchaseProduct:(ShopDetail *)shopDetail{
    PurchaseBillProduct *billProduct = [[PurchaseBillProduct alloc]init];
    billProduct.uuid = shopDetail.uuid;
    billProduct.product_uuid = shopDetail.product_uuid;
    billProduct.product_code = shopDetail.product_code;
    billProduct.product_name = shopDetail.merchandise;
    billProduct.qpc = [NSNumber numberWithFloat:[shopDetail.packageSpecification floatValue]];
    billProduct.unit = shopDetail.packageUnit;
    billProduct.qty = [NSNumber numberWithFloat:[shopDetail.packageQuantity floatValue]];
    billProduct.price = [NSNumber numberWithFloat:[shopDetail.packageUnitPrice floatValue]];
    billProduct.baseQty = [NSNumber numberWithFloat:[shopDetail.foundationQuantity floatValue]];
    billProduct.basePrice = [NSNumber numberWithFloat:[shopDetail.foundationUnitPrice floatValue]];
    billProduct.total = [NSNumber numberWithFloat:[shopDetail.totalMoney floatValue]];
    billProduct.remark = shopDetail.remark;
    billProduct.qpcStr = shopDetail.packageQpcStr ? shopDetail.packageQpcStr : @"无";
    billProduct.baseUnit = shopDetail.packageQpcUnit;
    return billProduct;
}
- (ShopDetail *)coverShopDetail:(PurchaseBillProduct *)billProduct{
    ShopDetail *shopDetail = [[ShopDetail alloc]init];
    shopDetail.uuid = billProduct.uuid;
    shopDetail.product_uuid = billProduct.product_uuid;
    shopDetail.product_code = billProduct.product_code;
    shopDetail.merchandise  = billProduct.product_name;
    shopDetail.packageSpecification  =  [billProduct.qpc stringValue];
    shopDetail.packageUnit = billProduct.unit;
    shopDetail.packageQuantity = [billProduct.qty stringValue];
    shopDetail.packageUnitPrice  = billProduct.price;
    shopDetail.foundationQuantity= [billProduct.baseQty stringValue];
    shopDetail.foundationUnitPrice= billProduct.basePrice;
    shopDetail.totalMoney= billProduct.total;
    shopDetail.remark  = billProduct.remark;
    shopDetail.packageQpcStr = billProduct.qpcStr;
    shopDetail.packageQpcUnit = billProduct.baseUnit;
    return shopDetail;
}
- (NSMutableArray *)coverPurchaseBillProduct:(NSArray *)arr{
    NSMutableArray *billArr = [NSMutableArray array];
    for (NoticeProduct *product in arr) {
        PurchaseBillProduct *billProduct = [PurchaseBillProduct new];
//        billProduct.uuid = product.uuid;
        billProduct.product_name = product.productName;
        billProduct.product_uuid  = product.productUuid;
        billProduct.product_code = product.productCode;
        billProduct.baseUnit = product.baseUnit;
        billProduct.qpc = product.qpc;
        billProduct.unit = product.packUnit;
        billProduct.qty = [NSNumber numberWithFloat:0];
        billProduct.price = [NSNumber numberWithFloat:0];
        billProduct.baseQty = [NSNumber numberWithFloat:0];
        billProduct.basePrice = [NSNumber numberWithFloat:0];
        billProduct.total = [NSNumber numberWithFloat:0];
        billProduct.remark = @"";
        billProduct.qpcStr = [NSString stringWithFormat:@"1*%@",product.qpc];
        [billArr addObject:billProduct];
    }
    return billArr;
}

#pragma mark - 协议方法
- (void)hiddenKeyBoard{
    [self keyboardHidden];
}
- (void)keyboardHidden{
    [_purchaseView.otherPriceFiled resignFirstResponder];
    [_purchaseView.remarkTextView resignFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if(self.purchaseBill && [self.state isEqualToString:PURCHASE_STATE_INITIAL]){
        [ICRUserUtil sharedInstance].needFresh = YES;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self getDataFromServer:PURCHASE_STATE_SUBMITTED msg:@"正在提交..."];//提交
    }
}

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