//
//  KWMShopCartVC.m
//  iCemarose
//
//  Created by 陈荣科 on 16/8/24.
//  Copyright © 2016年 kollway. All rights reserved.
//

#import "KWMShopCartVC.h"
#import "KWMSelectSizeVC.h"
#import "KWMShopCarCell.h"
#import "KWMBeforePayVC.h"
#import "KWMUserModel.h"
#import "KWMLoginVC.h"
#import "KWMShopCartData.h"
//#import "KWMNewVC.h"
#import "KWMCategoryVC.h"
#import "KWMStringUtil.h"
#import "KWMShoppingCart.h"
#import "KWMRecommendView.h"
#import "KWMPPCacheUtil.h"

@interface KWMShopCartVC ()<UIAlertViewDelegate,KWMRecommendDelegate>
@property (nonatomic, weak) IBOutlet KWMRecommendView *newestRecommendView;
@property (nonatomic, weak) IBOutlet KWMRecommendView *mainRecommendView;
@property (nonatomic) NSMutableArray *shopCartList;
@property (nonatomic, strong) NSMutableArray *soldout;
@end

@implementation KWMShopCartVC{
    KWMShopCartModel *_removeModel;
    KWMShopCartModel *_changeModel;
}

+(NSString *)kwmTag{
    return @"KWMShopCartVC";
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"购物车";
//    self.vBackground.hidden = NO;
    _shopCartList = (NSMutableArray *)[[KWMShoppingCart sharedInstance] items];
    if (_shopCartList.count == 0) {
        self.vBackground.hidden = NO;
    }else{
        self.vBackground.hidden = YES;
    }
    self.btnRandom.layer.borderWidth = 0.5;
    self.btnRandom.layer.borderColor = [UIColor colorWithRed:78.0/255 green:78.0/255 blue:78.0/255 alpha:1.0].CGColor;
    
    [self setTotalPrice];
    
    [self checkInStockAndRefresh];
    self.newestRecommendView.title = @"最新单品";
    self.mainRecommendView.title = @"主推单品";
    self.newestRecommendView.delegate = self;
    self.mainRecommendView.delegate = self;
}

- (void) checkInStockAndRefresh {
    __weak typeof(self) this = self;
    [self showLoading];
    [[KWMShoppingCart sharedInstance] setSync:YES];
    [[KWMShoppingCart sharedInstance] allItemsWithCallback:^(NSError *error, KWMCartResult *cart) {
        [this refresh];
        [[KWMShoppingCart sharedInstance] setSync:NO];
        NSArray *ids = [cart.items rx_mapWithBlock:^id(KWMShopCartModel *each) {
            return each.product_id;
        }];
        if (ids && ids.count > 0) {
            [this.api getAdminProductsById:ids success:^(NSURLSessionDataTask *task, KWMProductResult *result) {
                [this hideLoading];
                [this checkInStockWithItems:cart.items products:result.products];
            } failure:nil];
//            [this.client getProductsByIds:ids completion:^(NSArray<BUYProduct *> * _Nullable products, NSError * _Nullable error) {
//                [this hideLoading];
////                [this refresh];
//                [this checkInStockWithItems:cart.items products:products];
//            }];
        }else{
            [this hideLoading];
            [this refresh];
        }
    }];
}

- (void) checkInStockWithItems:(NSArray<KWMShopCartModel *> *) items products:(NSArray<KWMProduct *> *) products {
    self.soldout = [NSMutableArray new];
    for (KWMShopCartModel *item in items) {
        NSInteger quantity = 0;
        if((quantity = [self checkInStockWithItem:item products:products]) < 0) {
            NSInteger has = item.quantity + quantity;
            if (has < 0) {
                has = 0;
            }
            item.quantity = has;
            [self.soldout addObject:item];
        }
    }
    if (self.soldout.count > 0) {
        [[[UIAlertView alloc] initWithTitle:nil message:@"订单中有售罄商品哦!!!" delegate:self cancelButtonTitle:@"直接删除" otherButtonTitles:@"加入愿望清单", nil] show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [[KWMShoppingCart sharedInstance] setSync:YES];
    NSArray *ids = [self.soldout rx_mapWithBlock:^id(KWMShopCartModel *each) {
        return each.identifier;
    }];
    NSArray *qus = [self.soldout rx_mapWithBlock:^(KWMShopCartModel *it){ return @(it.quantity); }];
    __weak typeof(self) this = self;
    [self showLoading];
    [[KWMShoppingCart sharedInstance] updateProductWithVariantIds:ids quantitties:qus callback:^(NSError *error, KWMCartResult *cart) {
        [[KWMShoppingCart sharedInstance] setSync:NO];
        [this hideLoading];
        [this refresh];
        if (buttonIndex == 1) {
            [this addSoldOutProductToWishlist];
        }
    }];
}

- (void) addSoldOutProductToWishlist {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        KWMUserModel *customer = [KWMUserModel shareUser];
        [self.soldout enumerateObjectsUsingBlock:^(KWMShopCartModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary * dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"];
            NSDictionary *parament = @{
                                         @"customer_id":dict[@"id"],
                                         @"customer_email":dict[@"email"],
                                         @"customer_name":dict[@"last_name"] ?: @"",
                                         @"product_title":obj.shopCartDict[@"product_title"],
                                         @"product_id":obj.product_id,
                                         @"variant_id":obj.identifier,
                                         @"variant_sku":obj.shopCartDict[@"sku"],
                                         @"variant_title":obj.size,
                                         @"product_handle":obj.shopCartDict[@"handle"],
                                         @"shop":Shopify_SHOP_DOMAIN
                                         };
//              [self.api saveWish:parament success:nil failure:nil];
            [self.api saveWish:parament success:^(NSURLSessionDataTask *task, KWMAdditionalListResult *result) { } failure:^(NSURLSessionDataTask *task, NSError *error) { }];
        }];
        self.soldout = nil;
    });
    
}

- (NSInteger) checkInStockWithItem:(KWMShopCartModel *) item products:(NSArray<KWMProduct *> *) products {
    for (KWMProduct *p in products) {
        if (item.product_id.integerValue == p.id.integerValue) {
            for (KWMVariants *v in p.variants) {
                if (item.identifier.integerValue == v.id.integerValue) {
                    return v.inventoryQuantity.integerValue - item.quantity;
                }
            }
        }
//        if (item.product_id.integerValue == p.identifier.integerValue) {
//            for (BUYProductVariant *v in p.variants) {
//                if ([item.size isEqualToString:v.title] && v.availableValue) {
//                    return YES;
//                }
//            }
//        }
    }
    return 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger count = self.shopCartList ? self.shopCartList.count : 0;
    self.vBackground.hidden = count != 0;
    return count;
}

#pragma  mark UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 184;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *indentifier = @"KWMShopCarCell";
    
    KWMShopCarCell *shopCartCell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    KWMShopCartModel *shopCartModel = [_shopCartList objectAtIndex:indexPath.row];
    if (!shopCartCell) {
        [tableView registerNib:[UINib nibWithNibName:indentifier bundle:nil] forCellReuseIdentifier:indentifier];
        shopCartCell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    }
    shopCartCell.shopCartModel = shopCartModel;
    shopCartCell.delegate = self;
    return shopCartCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    KWMShopCartModel *model = [_shopCartList objectAtIndex:indexPath.row];
    NSString *handle = model.shopCartDict[@"handle"];
    if (handle) {
        [self openURLWithString:[NSString stringWithFormat:@"https://cemarose.myshopify.com/products/%@",handle]];
    }
}

//点击随意逛逛
- (IBAction)onClickRandomBtn:(id)sender {
    NSLog(@"点击了随意逛逛");
//    KWMNewVC *newVC = (KWMNewVC *)[KWMBaseVC findControllerBy:[KWMNewVC kwmTag] fromStoryboard:@"Main"];
    self.hidesBottomBarWhenPushed = NO;
    KWMCategoryVC *vc = [KWMCategoryVC getNewInstance];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)onClickComplete:(id)sender{
    
    KWMUserModel *useModel = [KWMUserModel shareUser];
    if (useModel.status) {
        KWMBeforePayVC *beforePayVC = (KWMBeforePayVC *)[KWMBaseVC findControllerBy:[KWMBeforePayVC kwmTag] fromStoryboard:@"ShopCart"];
        beforePayVC.shopcartArray = self.shopCartList;
        [self.navigationController pushViewController:beforePayVC animated:YES];
    }else{
        //登录
        KWMLoginVC *loginVc = (KWMLoginVC *)[KWMBaseVC findControllerBy:[KWMLoginVC kwmTag] fromStoryboard:@"Login"];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark KWMRecommendDelegate
-(void)kwm_gotoRecommendPage:(KWMRecommendView *)recommendView{
    if(recommendView.tag == 1){
        [self openURLWithString:@"https://cemarose.myshopify.com/collections/new?title=最新单品"];
    }else{
        [self openURLWithString:@"https://cemarose.myshopify.com/collections/hot-sell-app?title=主推单品"];
    }
}

-(void)kwm_onClickProduct:(BUYProduct *)product{
    [self openURLWithString:[NSString stringWithFormat:@"https://cemarose.myshopify.com/products/%@",product.handle]];
}

- (void)kwm_onClickDelete:(KWMShopCartModel *)shopCartModel{
    self.vDelete.hidden = NO;
    self.vDelete.delegate = self;
    _removeModel = shopCartModel;
}

- (void)kwm_onClickEdit:(KWMShopCartModel *)shopCartModel{
    __block KWMShopCartVC *this = self;
    _changeModel = shopCartModel;
    [self showLoading];
    [self.client getProductById:shopCartModel.product_id completion:^(BUYProduct * _Nullable product, NSError * _Nullable error) {
        [this hideLoading];
        
        if(product){
            KWMVariantsVC  *variantsVC = (KWMVariantsVC *)[KWMVariantsVC findControllerBy:[KWMVariantsVC kwmTag] fromStoryboard:@"NewProduct"];
            variantsVC.product = product;
            variantsVC.delegate = self;
            variantsVC.shopCartModel = shopCartModel;
            CGSize size = [UIScreen mainScreen].bounds.size;
            [self showPresentation:variantsVC size:size tapOutsideClose:YES style:MZFormSheetPresentationTransitionStyleFade];
        }
        
        
//        this.definesPresentationContext = YES;
//        KWMSelectSizeVC *editVC = (KWMSelectSizeVC *)[KWMBaseVC findControllerBy:[KWMSelectSizeVC kwmTag] fromStoryboard:@"ShopCart"];
//        editVC.delegate = this;
//        editVC.isShopcart = YES;
//        editVC.product = product;
//        editVC.shopCartModel = shopCartModel;
//        
//        editVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
//        editVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
//        editVC.providesPresentationContextTransitionStyle = YES;
//        editVC.definesPresentationContext = YES;
//        [this presentViewController:editVC animated:YES completion:nil];
    }];
    
}

#pragma mark -- KWMSelectSizeVCDelegate

- (void)kwm_addShopWithVariantId:(NSNumber *)identifier quantity:(NSInteger)quantity variant:(BUYProductVariant *) variant buyNow:(BOOL)buyNow callback:(void (^)(BOOL))callback {
    __weak KWMShopCartVC *this = self;
    void(^success)(NSError*,KWMCartResult*) = ^(NSError *error,KWMCartResult *cart){
        [[KWMShoppingCart sharedInstance] setSync:NO];
        if (!error) {
            [this refresh];
            callback(YES);
        }else{
            [this showError:error];
            callback(NO);
        }
    };
    if (_changeModel.identifier.integerValue == identifier.integerValue) {
        [[KWMShoppingCart sharedInstance] setSync:YES];
        [[KWMShoppingCart sharedInstance] changeProductWithVariantId:identifier quantity:quantity callback:success];
    }else{
        NSNumber *oldId = @(_changeModel.identifier.integerValue);
//        KWMShopCartModel *model  = _changeModel;
        _changeModel = nil;
        NSArray<NSNumber *> *variantIds = @[oldId,identifier];
        NSArray<NSNumber *> *quantities = @[@0,@(quantity)];
        [[KWMShoppingCart sharedInstance] setSync:YES];
        [[KWMShoppingCart sharedInstance] updateProductWithVariantIds:variantIds quantitties:quantities callback:^(NSError *error, KWMCartResult *cart) {
//            if (!cart.items.firstObject.product_id) {
//                KWMShopCartModel *tmp = cart.items.firstObject;
//                tmp.imageStr = model.imageStr;
//                tmp.size = variant.title;
//                tmp.brand = model.brand;
//                tmp.name = model.name;
//                tmp.price = variant.price;
//                tmp.product_id = model.product_id;
//            }
            success(error,cart);
        }];
//        [[KWMShoppingCart sharedInstance] deleteProductWithVariantId:oldId callback:^(NSError *error, KWMCartResult *cart) {
//            [[KWMShoppingCart sharedInstance] increaseProductWithVariantId:identifier quantity:quantity callback:^(NSError *error, KWMCartResult *cart) {
//                if (!cart.items.lastObject.product_id) {
//                    KWMShopCartModel *tmp = cart.items.lastObject;
//                    tmp.imageStr = model.imageStr;
//                    tmp.size = variant.title;
//                    tmp.brand = model.brand;
//                    tmp.name = model.name;
//                    tmp.price = variant.price.floatValue;
//                    tmp.product_id = model.product_id;
//                }
//                success(error,cart);
//            }];
//        }];
    }
}

//- (void)kwm_addShopCartItem:(KWMShopCartModel *)shopCartModel{
//    
//    [_shopCartList removeAllObjects];
//    [_shopCartList addObjectsFromArray:[[KWMShopCartData alloc] getALLItems]];
//    [self.tbvCart reloadData];
//    [self setTotalPrice];
//}
//
//-(void)kwm_fastBuy:(BUYCart *)fastBuyCart{
//    
//}

-(void)kwm_deleteProduct{
//    BOOL isHas = NO;
//    for (KWMShopCartModel *item in _shopCartList) {
//        if ([item isEqual:_removeModel]) {
//            isHas = YES;
//            break;
//        }
//    }
//    if (isHas) {
//        [_shopCartList removeObjectIdenticalTo:_removeModel];
//    }
//    [self.tbvCart reloadData];
//    [self setTotalPrice];
//    [[KWMShopCartData alloc] removeItem:_removeModel];
    NSNumber *identifier = @(_removeModel.identifier.integerValue);
    __weak KWMShopCartVC *this = self;
    [self showLoading];
    [[KWMShoppingCart sharedInstance] deleteProductWithVariantId:identifier callback:^(NSError *error, KWMCartResult *cart) {
        [this hideLoading];
        [this refresh];
    }];
}

- (void)refresh {
    self.shopCartList = [[KWMShoppingCart sharedInstance] items];
    [self.tbvCart reloadData];
    [self setTotalPrice];
    if(! self.shopCartList || self.shopCartList.count == 0){
        //请求推荐商品数据
        [self requestProductWithHandle:@"new" tags:nil valueKeyPath:@"newestRecommendView"];
        [self requestProductWithHandle:@"hot-sell-app" tags:nil valueKeyPath:@"mainRecommendView"];
    }
//    [self.client getProductsByIds:[self.shopCartList rx_mapWithBlock:^id(KWMShopCartModel *each) {
//        return each.product_id;
//    }] completion:^(NSArray<BUYProduct *> * _Nullable products, NSError * _Nullable error) {
//        
//    }];
}

//计算总价格
- (void) setTotalPrice{
//    NSInteger price = 0;
    NSDecimalNumber *total = [NSDecimalNumber decimalNumberWithDecimal:@(0).decimalValue];
    for (KWMShopCartModel *model in _shopCartList) {
        if (model.line_price) {
//            price += model.line_price.priceValue.integerValue;
            total = [total decimalNumberByAdding:model.line_price.priceValue];
        }else{
//            price += [model.price.priceValue decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@(model.quantity).stringValue]].integerValue;
            total = [total decimalNumberByAdding:[model.price.priceValue decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@(model.quantity).stringValue]]];
        }
    }
//    _lbTotalPrice.text = [NSString stringWithFormat: @"¥%@",[KWMStringUtil getEUR2CNYstring:@(price)]];
    _lbTotalPrice.text = total.priceFormatted;
}

#pragma makr - api
- (void) requestProductWithHandle:(NSString *) handle tags:(NSArray *) tags valueKeyPath:(nonnull NSString *) valueKeyPath {
    NSDictionary *parameters = [KWMPPCacheUtil getProductCacheKeyDictionary:1 tags:tags handle:handle];
    BOOL useProductDataCache = [self useProductDataCache:parameters valueKeyPath:valueKeyPath page:1];
    __weak KWMShopCartVC *weakSelf = self;
    [self.client getCollectionByHandle:handle completion:^(BUYCollection * _Nullable collection, NSError * _Nullable error) {
        if (!error) {
            [weakSelf.client getProductsPage:1 inCollection:collection.identifier withTags:tags sortOrder:BUYCollectionSortCollectionDefault completion:^(NSArray<BUYProduct *> * _Nullable products, NSUInteger page, BOOL reachedEnd, NSError * _Nullable error) {
                if (!error) {
                    [KWMPPCacheUtil saveDataToCache:parameters urlKey:CACHE_KEY_SDK_getCollectionByHandle_getProductsPage products:products];
                    if(products){
                        if([valueKeyPath isEqualToString:@"newestRecommendView"]){
                            weakSelf.newestRecommendView.productArray = products;
                        }else{
                            weakSelf.mainRecommendView.productArray = products;
                        }
                    }
                }
            }];
        }
    }];
}

-(BOOL)useProductDataCache:(NSDictionary *)cacheKeyDictionary valueKeyPath:(NSString *)valueKeyPath page:(NSUInteger)page{
    if(!kIsNetwork || page == 1){
        NSArray *products = [KWMPPCacheUtil getProductDataByCache:cacheKeyDictionary urlKey:CACHE_KEY_SDK_getCollectionByHandle_getProductsPage];
        if(products && products.count > 0){
            if([valueKeyPath isEqualToString:@"newestRecommendView"]){
                self.newestRecommendView.productArray = products;
            }else{
                self.mainRecommendView.productArray = products;
            }
        }else{
            return false;
        }
    }
    return !kIsNetwork;
}


@end