//
//  TransportPurchaseViewController.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/9/6.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "TransportPurchaseViewController.h"
#import "TransportPurchaseCell.h"
#import "QueryOrder.h"
#import "TransportPdtDetail.h"
#import "MJRefresh.h"
#import "ProductStockModel.h"
#define TopMargin 50
#define TableHeight 50
NSInteger purchaseStockCheckNumber = 0;
@interface TransportPurchaseViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
{
    BOOL _isRefresh;
    BOOL _isLoadMore;
    NSInteger _currentPage;
    id billNumberObject;
}
/**
 *  选中的商品
 */
@property (nonatomic,strong)NSMutableArray *indexArr;
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UITextField *selectTextFiled;
@property (nonatomic,strong)NSString *contentStr;
@end

@implementation TransportPurchaseViewController

- (instancetype)init{
    self = [super init];
    if (self) {

    }
    return self;
}
- (void)dealloc{
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择采购单";
    [self initData];
    [self bulidLayout];
    [self createRefresh];
    [self getData];
}
- (void)initData{
    self.dataArr = [NSMutableArray array];
    self.indexArr = [NSMutableArray array];
}


- (void)getData{
    [ICRUserUtil sharedInstance].needFresh = NO;
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf fetchtPuchaseList:data];
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    
    NSMutableArray *orderArr =[NSMutableArray array];
    if (orderArr.count == 0) {
        QueryOrder *order = [QueryOrder new];
        order.field = @"billNumber";
        order.direction = @"desc";
        [orderArr addObject:[order dictForCommit]];
    }
    billNumberObject = [NSNull null];
    if (self.contentStr.length > 0) {
        billNumberObject = self.contentStr;
    }
    NSDictionary *dict;
    
    if (self.isTransportIn) {
        dict = @{
          @"state":PURCHASE_STATE_RECEIVED,
          @"queryOrders":orderArr,
          @"userUuid":userUtil.userId,
          @"billNumberProductLike":billNumberObject,
          @"fetchParts":@"products",
          @"isProductCenter":@(1),
          @"pageNumber":@(_currentPage),
          @"pageSize":@(20)};
    }else{
        dict = @{
                 @"state":[NSNull null],
                 @"stateNotIn":@[PURCHASE_STATE_ABORTED,PURCHASE_STATE_REJECTED],
                 @"queryOrders":orderArr,
                 @"userUuid":userUtil.userId,
                 @"billNumberProductLike":billNumberObject,
                 @"fetchParts":@"products",
                 @"pageNumber":@(_currentPage),
                 @"pageSize":@(20)};
    }
    [[ICRHTTPController sharedController] queryPurchaseWithData:dict success:succ failure:fail];
}
- (void)fetchtPuchaseList:(id)data{
    if (data) {
        NSInteger success = [data[@"success"] integerValue];
        NSString *message  = data[@"message"] ;
        if (success == 1) {
            if (_currentPage == 0) {
                if (self.dataArr.count > 0) {
                    [self.dataArr removeAllObjects];
                }
            }
            NSArray *recodesArr = data[ @"data" ][ @"records" ];
            for (NSDictionary *purchaseBillDict in recodesArr) {
                PurchaseBill *purchaseBill = [[PurchaseBill alloc]init];
                [purchaseBill setValuesForKeysWithDictionary:purchaseBillDict];
                purchaseBill.products = [self coverTransportDetProduct:purchaseBillDict[@"products"] purchaseBill:purchaseBill];
                
                //*******筛选掉已经选择过的商品******
                //获取缓存的商品数据
                NSMutableArray *arr = [self.dicProduct objectForKey:purchaseBill.billNumber];
                if (arr.count == purchaseBill.products.count) {
                    CLog(@"采购单中的商品已经全部选择过了,不显示这个采购单");
                }else{
                    
                    NSMutableArray *tempProduct = purchaseBill.products.mutableCopy;
                    for (TransportPdtDetail *pdt in arr) {
                        for (TransportPdtDetail *onlinePdt in purchaseBill.products) {
                            if ([pdt.productCode isEqualToString:onlinePdt.productCode]) {
                                [tempProduct removeObject:onlinePdt];
                            }
                        }
                    }
                    purchaseBill.products = tempProduct.mutableCopy;
                    [self.dataArr addObject:purchaseBill];
                }
            }

            NSDictionary *pageDict = data[ @"data" ][ @"paging" ];
            NSInteger pageCount = [pageDict[@"pageCount"] integerValue];
            [self.tableView reloadData];
            [self endRefreshing];
            if (pageCount <= _currentPage) {
                [self.tableView.footer noticeNoMoreData];
            }
            if (_currentPage == 0 && self.dataArr.count > 0) {
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            }
        }else{
            [IBTLoadingView showTips:message];
        }
        
    }
    else{
        [IBTLoadingView showTips:@"      无记录      "];
    }
}
- (NSMutableArray *)coverTransportDetProduct:(NSArray *)arr purchaseBill:(PurchaseBill *)purchaseBill{
    NSMutableArray *transArr = [NSMutableArray array];
    for (NSDictionary *arrDict in arr) {
        TransportPdtDetail *detail = [TransportPdtDetail new];
        [detail setValuesForKeysWithDictionary:arrDict];
        detail.purchasebillnumber = purchaseBill.billNumber;
        detail.productUuid = arrDict[@"product_uuid"];
        detail.productCode = arrDict[@"product_code"];
        detail.productName = arrDict[@"product_name"];
        detail.price = arrDict[@"basePrice"];
        detail.packprice = arrDict[@"price"];
        detail.transferBaseQty = arrDict[@"shippedBaseQty"];
        detail.transferQty = arrDict[@"shippedQty"];
        detail.note = arrDict[@"remark"] != [NSNull null] ? arrDict[@"remark"] : @"无";
        
        
        [transArr addObject:detail];
    }
    return transArr;
}
- (void)checkWithBillNumber{
    if (self.indexArr.count > 0) {
        [self.indexArr removeAllObjects];
    }
    [self.selectTextFiled resignFirstResponder];
    if (self.selectTextFiled.text.length > 0) {
        self.contentStr = self.selectTextFiled.text;
    }else{
        self.contentStr = @"";
    }
    [self getData];

}

#pragma mark - 布局
- (void)bulidLayout
{
    self.selectTextFiled = [[UITextField alloc] initWithFrame:CGRectMake(20,5,ScreenSize.width - 100,TopMargin -10)];
    self.selectTextFiled.textAlignment = NSTextAlignmentLeft;
    self.selectTextFiled.background = [UIImage imageNamed:@"textFiled"];
    self.selectTextFiled.delegate = self;
    self.selectTextFiled.placeholder = @"类似采购和商品单号";
    self.selectTextFiled.font = GXF_FIFTEENTEN_SIZE;
    [self.view addSubview:self.selectTextFiled];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(self.selectTextFiled.right + 5, 10, 60, TopMargin - 20);
    [btn setTitle:@"开始查询" forState:UIControlStateNormal];
    btn.titleLabel.font = FontSize(13);
    btn.layer.cornerRadius = 5;
    btn.layer.masksToBounds = YES;
    btn.backgroundColor = GXF_NAVIGAYION_COLOR;
    [btn addTarget:self action:@selector(checkWithBillNumber) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    
    UIImageView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 35, 40)];
    leftView.image = [UIImage imageNamed:@"search"];
    self.selectTextFiled.leftView = leftView;
    self.selectTextFiled.leftViewMode = UITextFieldViewModeAlways;
    
    UIButton *rightView = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightView setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
    rightView.frame = CGRectMake(0, 0, 35, 40);
    [rightView addTarget:self action:@selector(deleteTextFieldStr) forControlEvents:UIControlEventTouchUpInside];
    self.selectTextFiled.rightView = rightView;
    self.selectTextFiled.rightViewMode = UITextFieldViewModeAlways;
    
    
    self.tableView = [[UITableView alloc]initWithFrame:(CGRectMake(0, TopMargin,ScreenSize.width, ScreenSize.height - 64 - TopMargin)) style:(UITableViewStylePlain)];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureClick)];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)createRefresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_isRefresh) {
            return ;
        }
        _isRefresh = YES;
        _currentPage = 0;
        [self getData];
    }];
    self.tableView.header.lastUpdatedTimeKey = TransportUpdateDate;
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (_isLoadMore) {
            return ;
        }
        _isLoadMore = YES;
        _currentPage ++;
        [self getData];
    } ];
}
#pragma mark - 结束刷新
- (void)endRefreshing{
    _isLoadMore = NO;
    _isRefresh = NO;
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
}
- (void)deleteTextFieldStr{
    self.selectTextFiled.text = @"";
}
#pragma mark - 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"TransPortPurchase";
    TransportPurchaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[TransportPurchaseCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if(self.dataArr.count > 0){
        PurchaseBill *bill = _dataArr[indexPath.row];
        [cell setPurchaseBill:bill selectArr:self.indexArr];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //44+38+10 + count* 44
    PurchaseBill *bill = _dataArr[indexPath.row];
    return 102 + bill.products.count * 44;
}
#pragma mark - 按钮确定
- (void)sureClick{
    
    
//    NSMutableDictionary *dicProduct = [NSMutableDictionary dictionary];
    //把选中的商品和采购单对应,根据单号存储对应的商品
    for (PurchaseBill *bill in self.dataArr) {
        for (TransportPdtDetail *detail in bill.products) {
            detail.purchasebillnumber = bill.billNumber;
            if ([self.indexArr containsObject:detail]) {
                NSMutableArray *arrProduct = [self.dicProduct objectForKey:bill.billNumber];
                if (!arrProduct) {
                    arrProduct = [NSMutableArray array];
                    [self.dicProduct setObject:arrProduct forKey:bill.billNumber];
                }
                
                [arrProduct addObject:detail];
            }
        }
    }
    
    NSArray *array = self.dicProduct.allKeys;
    if (array.count == 0) {
        ShowMessage(@"请选择商品!");
        return;
    }
    __weak TransportPurchaseViewController *weakSelf = self;
    //判断数量问题
    [self stockValidWithDic:self.dicProduct billNumbers:array complete:^{
            [weakSelf PopViewControllerAnimated:YES];
            if (weakSelf.indexArr.count > 0) {
                NSMutableArray*arr = [NSMutableArray array];
                for (TransportPdtDetail *detail in weakSelf.indexArr) {
                    detail.purchasePdtDetail = detail.uuid;
                    detail.uuid = nil;
                    [arr addObject:detail];
                }
                
                if (weakSelf.getProchaseProduct) {
                    weakSelf.getProchaseProduct(arr);
                }
                
                for (PurchaseBill *bill in self.dataArr) {
                    if ([array containsObject:bill.billNumber]) {
                        if (weakSelf.blockFirstWarehouse) {
                            weakSelf.blockFirstWarehouse(@[bill]);
                        }
                        break;
                    }
                }
            }
    }];
    
    
    
    

}

- (void)stockValidWithDic:(NSMutableDictionary *)dic billNumbers:(NSArray *)billNumbers complete:(void (^)(void))complete {
    
    NSString *billNum = billNumbers[purchaseStockCheckNumber];
    NSMutableArray *arrProducts = [dic objectForKey:billNum];
    __weak TransportPurchaseViewController *weakSelf = self;
    [HTTP purchaseStockWithPurchaseUuid:billNum success:^(id succ) {
        if (![succ[@"data"] isKindOfClass:[NSArray class]]) {
            NSString *msg = [NSString stringWithFormat:@"该批次<%@>在总部系统的库存不足!", billNum];
            ShowMessage(msg);
            return ;
        }
        
        for (NSDictionary *dict in succ[@"data"]) {
            ProductStockModel *model = [ProductStockModel new];
            [model setValuesForKeysWithDictionary:dict];
            for (TransportPdtDetail *detail in arrProducts) {
                if ([detail.productCode isEqualToString:model.productCode]) {
                    
                    if (detail.baseQty.floatValue > model.qty.floatValue) {
                        CLog(@"库存不足");
                        purchaseStockCheckNumber = 0;
                        NSString *msg = [NSString stringWithFormat:@"该批次<%@>的商品%@在总部系统的库存不足!", billNum, detail.productName];
                        ShowMessage(msg);
                        return ;
                    }
                }
            }
        }
        
        purchaseStockCheckNumber += 1;
        if (purchaseStockCheckNumber == billNumbers.count) {
            purchaseStockCheckNumber = 0;
            complete();
        }else{
            [weakSelf stockValidWithDic:dic billNumbers:billNumbers complete:complete];
        }

    } failure:^(id fail) {
        purchaseStockCheckNumber = 0;
    }];
}

- (NSMutableDictionary *)dicProduct {
    if (!_dicProduct) {
        _dicProduct = [NSMutableDictionary dictionary];
    }
    return _dicProduct;
}


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