//
//  KWMSelectSizeViewController.m
//  iCemarose
//
//  Created by HouWeiBin on 16/9/1.
//  Copyright © 2016年 kollway. All rights reserved.
//

#import "KWMSelectSizeVC.h"
#import "KWMSizeCell.h"
#import "KWMUserModel.h"
#import "KWMImageUtil.h"
#import "KWMBeforePayVC.h"
#import "KWMStringUtil.h"
#import "KWMLoginVC.h"
#import "KWMLoadingView.h"
#import "UIColor+SAMAdditions.h"
#import "BUYProductVariant+Currency.h"
#import "KWMCurrencyUtil.h"

@interface KWMSelectSizeVC ()

@end

@implementation KWMSelectSizeVC{
    NSMutableArray *shopCartList;
    BUYProductVariant *remindVariant;
    BUYProductVariant *defalutSize;
    NSInteger defalutCount;
    KWMLoadingView *loadingView;
    UIView *vLoadingContainer;
}

+(NSString *)kwmTag{
    return @"KWMSelectSizeVC";
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.btnBackground.hidden = YES;
    [self startPageAnim];
}

-(void)startPageAnim{
    
    // 透明度动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    // 设定动画选项
    animation.duration = 1; // 持续时间
    animation.repeatCount = 1; // 重复次数
    
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    
    animation.fromValue = [NSNumber numberWithFloat:0.0]; // 起始透明度
    animation.toValue = [NSNumber numberWithFloat:1.0]; // 终止透明度
    
    [self.btnBackground.layer addAnimation:animation forKey:@"trans-anim"];
    self.btnBackground.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initContentHeight];
    self.cvSize.delegate = self;
    [self.cvSize registerNib:[UINib nibWithNibName:@"KWMSizeCell" bundle:nil] forCellWithReuseIdentifier:@"KWMSizeCell"];
    [self refreshView:YES];
    if(self.product!=nil){
        [self requestAdminProduct:self.product.identifier];
    }
    self.vShopCar.hidden = self.isShopcart;
    self.btnComplete.hidden = !self.isShopcart;
    self.vShopCar.layer.cornerRadius = 1; //圆角(圆形)
    self.vShopCar.layer.borderColor  = [UIColor sam_colorWithHex:@"494949"].CGColor; //要设置的颜色
    self.vShopCar.layer.borderWidth = 1; //要设置的描边宽
    
    CGFloat screenWidth =  UIScreen.mainScreen.bounds.size.width;

    self.vRemindMarginLeft.constant = -screenWidth;
}

//初始化佈局高度
-(void)initContentHeight{
    if(self.product != nil && self.product.variantsArray!=nil){
        NSInteger cellCount =  self.product.variantsArray.count;
        if(cellCount <=0){
            return;
        }
        NSInteger cellWidth = (UI_SCREEN_WIDTH - (30 + 30) - (10*3)) / 3;
        NSInteger cellHeight = cellWidth * 0.4;
        NSInteger lineCount = (cellCount +2) / 3;
        self.vContentHeight.constant = 220 + lineCount * cellHeight + 10 *(lineCount - 1);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)setShopCartModel:(KWMShopCartModel *)shopCartModel{
    _shopCartModel = shopCartModel;
    if (shopCartModel != nil) {
        NSArray<BUYProductVariant *> *sizeArray = self.product.variantsArray;
        for (int i = 0; i < sizeArray.count; ++i) {
            BUYProductVariant *productSize = [sizeArray objectAtIndex:i];
            if ([shopCartModel.size isEqualToString:productSize.title]) {
                self.selectSize = productSize;
                self.count = shopCartModel.quantity;
                defalutSize = productSize;
                defalutCount = shopCartModel.quantity;
            }
        }
    }
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(self.product != nil && self.product.variantsArray!=nil){
        return self.product.variantsArray.count;
    }else{
        return 0;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *indentifier = @"KWMSizeCell";
    KWMSizeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:indentifier forIndexPath:indexPath];
    if(self.product!=nil){
        NSArray<BUYProductVariant *> *sizeArray = self.product.variantsArray;
        if(sizeArray!=nil && sizeArray.count > 0){
            
            BUYProductVariant *productSize = [sizeArray objectAtIndex:indexPath.row];
            KWMVariants *adminVariant = [self checkAdminVariants:self.adminVariants targetVariant:productSize];
            
            BOOL isSelect = self.selectSize && productSize.identifier.integerValue == self.selectSize.identifier.integerValue;
            BOOL isRemind = remindVariant && productSize.identifier.integerValue == remindVariant.identifier.integerValue;
            [cell setData:productSize adminVariant:adminVariant isSelect:isSelect isRemind:isRemind];
        }
    }
    cell.delegate = self;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //返回每个item的大小
    NSInteger width = (UI_SCREEN_WIDTH - (30 + 30) - (10*3)) / 3;
    NSInteger height = width * 0.4;
    return (CGSize){width,height};
}

-(CGFloat )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;{
    if(self.product!=nil){
        return self.product.variantsArray.count;
    }else{
        return 0;
    }
}

-(void)onClickBg:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)initModelByPrudct{
    
    _shopCartModel = [[KWMShopCartModel alloc] init];
    
    _shopCartModel.name = _product.title;
    _shopCartModel.brand = _product.vendor;
    
    NSString *imageUrl = [KWMImageUtil getProductImageUrl:_product ImageSize:NormalImage];
    
    _shopCartModel.imageStr = imageUrl;
    _shopCartModel.shopCartDict = _product.JSONDictionary;
}

- (void)initBySelectSize{
    _shopCartModel.size = _selectSize.title;
//    _shopCartModel.price = _selectSize.price.integerValue;
    _shopCartModel.price = _selectSize.price;
    _shopCartModel.identifier = [NSString stringWithFormat:@"%@",_selectSize.identifier];
    _shopCartModel.quantity = _count;
}
/**
 *  点击加入购物车
 *
 *  @param sender <#sender description#>
 */
-(void)onClickComplete:(UIButton *)sender{
    if (self.selectSize == nil || self.count==0) {
        [self showToast:@"请选择您想要的规格"];
        return;
    }
    if (self.product && !self.product.JSONDictionary){
        [self showToast:@"该商品信息缺失"];
        return;
    }
    
    BOOL buyNow = sender.tag == 1;
    __weak id this = self;
    [self showLoading];
    if (self.delegate) {
        [self.delegate kwm_addShopWithVariantId:_selectSize.identifier quantity:_count variant:_selectSize buyNow:buyNow callback:^(BOOL success) {
            [self hideLoading];
            if(success) {
                [this dismissViewControllerAnimated:YES completion:nil];
            }
        }];
    }
//    KWMShopCartData *shopCartData = [[KWMShopCartData alloc] init];
//    if (_shopCartModel == nil) {
//        [self initModelByPrudct];
//        [self initBySelectSize];
//        [shopCartData inocreaseItem:_shopCartModel];
//    }else{
//        NSString *seletStr = [NSString stringWithFormat:@"%@",_selectSize.identifier];
//        _shopCartModel.quantity = _count;
//        //判断规格是否相同
//        if ([_shopCartModel.identifier isEqualToString:seletStr]) {
//            [self initBySelectSize];
//            [shopCartData changeNumberShopcart:_shopCartModel];
//        }else{
//            [shopCartData removeItem:_shopCartModel];
//            [self initBySelectSize];
//            //变为选择的规格
//            [shopCartData inocreaseItem:_shopCartModel];
//        }
//    }
//    self.btnComplete.userInteractionEnabled =NO;
//    if (_isShopcart) {
//        [self showToast:@"修改成功"];
//    }else{
//        [self showToast:@"加入成功"];
//    }
//    if (self.delegate != nil) {
//        [self.delegate kwm_addShopCartItem:_shopCartModel];
//    }
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self dismissViewControllerAnimated:YES completion:nil];
//    });
}

////点击了快速购买按钮
//-(void)onClickFastBuy:(id)sender{
//    
//    if (self.selectSize == nil || self.count == 0) {
//        [self showToast:@"请选择您想要的规格"];
//        return;
//    }
//    if (self.product && !self.product.JSONDictionary){
//        [self showToast:@"该商品信息缺失"];
//        return;
//    }
//    BUYCart *cart = [self.client.modelManager insertCartWithJSONDictionary:nil];
//    [cart setVariant:self.selectSize withTotalQuantity:self.count];
//    [self dismissViewControllerAnimated:YES completion:nil];
//    if(self.delegate != nil){
//        [self.delegate kwm_fastBuy:cart];
//    }
//}

-(void)initData{
    if(self.product == nil){
        return;
    }
    if(self.product.variantsArray!=nil && self.product.variantsArray.count>0){
        self.selectSize = [self.product.variantsArray objectAtIndex:0];
    }
    [self refreshView:NO];
}

-(void)kwm_onClickSize:(BUYProductVariant *)productVariant adminVariant:(KWMVariants *)adminVariant setSelect:(BOOL)isSelect{
    if(self.selectSize == nil && isSelect){
        self.count = 1;
    }
    if(isSelect){
        self.selectSize = productVariant;
        self.selectAdminSize = adminVariant;
    }else{
        self.selectSize = nil;
    }
    if (defalutSize.identifier.integerValue == productVariant.identifier.integerValue) {
        self.count = defalutCount;
    }else{
        self.count = 1;
    }
    [self refreshInventory:adminVariant];
    [self.cvSize reloadData];
    [self refreshView:NO];
}

-(void)kwm_onClickRemind:(BUYProductVariant *)productVariant{
    self.vRemind.hidden = NO;
    self.vRemindMarginLeft.constant = 0;
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}

-(void)onClickAdd:(id)sender{
    if(self.selectSize == nil){
        [self showToast:@"请选择您想要的规格"];
    }
    if(self.selectAdminSize!=nil && self.selectAdminSize.inventoryQuantity!=nil){
        if(self.count + 1 > self.selectAdminSize.inventoryQuantity.integerValue){
            [self showToast:@"商品剩余数量不足"];
            return;
        }
    }
    
    self.count ++;
    [self refreshView:NO];
}

-(void)onClickReduce:(id)sender{
    if(self.selectSize == nil){
        [self showToast:@"请选择您想要的规格"];
        return;
    }
    if(self.count != 1){
        self.count --;
        [self refreshView:NO];
    }
}

-(void)onClickRemind:(id)sender{
        CGFloat screenWidth =  UIScreen.mainScreen.bounds.size.width;
        self.vRemindMarginLeft.constant = -screenWidth;
        self.vRemind.hidden = YES;
}

//更新庫存
-(void)refreshInventory:(KWMVariants *)adminVariant{
    if(adminVariant!=nil && adminVariant.inventoryQuantity!=nil && adminVariant.inventoryQuantity.integerValue<5){
        self.lbInventory.hidden = NO;
        self.lbInventory.text = [NSString stringWithFormat:@"(仅剩%@件)",adminVariant.inventoryQuantity.stringValue];
    }else{
        self.lbInventory.hidden = YES;
    }
}

-(KWMVariants *)checkAdminVariants:(NSArray<KWMVariants *> *)adminVariants targetVariant:(BUYProductVariant *)targetVariant{
    if(adminVariants!=nil && targetVariant!=nil){
        for(KWMVariants *variant in adminVariants){
            if(variant!=nil && variant.id!=nil
               && targetVariant.identifier!=nil
               && variant.id.integerValue ==  targetVariant.identifier.integerValue){
                return variant;
            }
        }
    }
    return nil;
}

//更新数量,总价,以及按钮状态
-(void)refreshView:(BOOL)isDefalut{
    if(self.selectSize != nil ){
        self.lbCount.text = [NSString stringWithFormat: @"%ld", (long)self.count];
        if (defalutSize.identifier.integerValue == self.selectSize.identifier.integerValue && isDefalut) {
            self.count = defalutCount;
        }
//        double price =  self.selectSize.price.doubleValue * self.count;
        NSDecimalNumber *totalPrice = [self.selectSize.priceValue decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithDecimal:@(self.count).decimalValue]];
//        self.lbPrice.text = [NSString stringWithFormat: @"¥ %@", [KWMStringUtil getEUR2CNYstring:@(price)]];
        self.lbPrice.text = [[KWMCurrencyUtil sharedInstance] priceFormatted:totalPrice];
    }else{
        self.lbCount.text = @"0";
        self.lbPrice.text = @"¥ 0.00";
        self.count = 0;
    }
}

-(void)requestAdminProduct:(NSNumber *)productId{
    if(productId == nil){
        return;
    }
    __weak KWMSelectSizeVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        //        [weakSelf hideLoading];
        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMProductResult *) = ^(NSURLSessionDataTask *task,KWMProductResult *result){
        //        [weakSelf hideLoading];
        if(result!=nil && result.product!=nil){
            KWMProduct* adminProduct = (KWMProduct *)result.product;
            if(adminProduct!=nil){
                NSArray<KWMVariants *> *adminVariants = adminProduct.variants;
                weakSelf.adminVariants = adminVariants;
                [weakSelf.cvSize reloadData];
                
                //如果已選中了某一項,更新標題
                KWMVariants* adminVariant = [self checkAdminVariants:adminVariants targetVariant:weakSelf.selectSize];
                self.selectAdminSize = adminVariant;
                [weakSelf refreshInventory:adminVariant];
            }
        }
    };
    [self.api getAdminProduct:nil productId:productId success:success failure:failure];
    //    [self showLoading];
}

@end