//
//  KWMProductDetailView.m
//  iCemarose
//
//  Created by HouWeiBin on 2017/1/11.
//  Copyright © 2017年 kollway. All rights reserved.
//

#import "KWMFirstDetailView.h"
#import "KWMImageUtil.h"
#import "KWMStringUtil.h"
#import "KWMPageControl.h"
//#import "YYWebImage/YYWebImage.h"
#import <SDCycleScrollView/SDCycleScrollView.h>

@interface KWMFirstDetailView ()<SDCycleScrollViewDelegate>

@property(nonatomic,weak) IBOutlet UIView *vView;

@property(nonatomic,weak) IBOutlet SDCycleScrollView *imageScrollView;

@property(nonatomic,weak) IBOutlet UIButton *btnBrand;

@property(nonatomic,weak) IBOutlet UILabel *lbName;

@property(nonatomic,weak) IBOutlet UILabel *lbPrice;

@property(nonatomic,weak) IBOutlet UILabel *lbOldPrice;

@property(nonatomic,weak) IBOutlet UILabel *lbVariant;

@property(nonatomic,weak) IBOutlet UIView *freeShipping;

//单位label
@property(nonatomic,weak) IBOutlet UILabel *lbUnit;

//@property(nonatomic,weak) IBOutlet KWMPageControl *pageControl;

@property (weak, nonatomic) IBOutlet UIView *sizeGuideView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sizeGuideViewHeightConstraint;

@property (nonatomic) BUYProduct *product;

@property (nonatomic) NSMutableArray *imageArr;

//@property (nonatomic) NSTimer *timer;

//@property (nonatomic) BOOL isFirstScroll;

@property (nonatomic) BOOL isShowCNY;

- (IBAction)onClickSizeBtn:(id)sender;

- (IBAction)onClickBlandBtn:(id)sender;

//- (IBAction)onClickBuyNow:(id)sender;

//- (IBAction)onClickAddToShopCart:(id)sender;

@end

@implementation KWMFirstDetailView

//- (id)init{
//    if (self=[super init]){
//        [self addView];
//    }
//    return self;
//}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self addView];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self =[super initWithFrame:frame]) {
        [self addView];
    }
    return self;
}

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

-(void) addView{
    [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
                                  owner:self
                                options:nil];
    NSLog(@"KWMProductDetailView%f%f",self.frame.size.width,self.frame.size.height);
    self.vView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [self addSubview:self.vView];
    self.imageScrollView.autoScroll = false;
    self.imageScrollView.pageDotImage = [UIImage imageNamed:@"ic_page_1"];
    self.imageScrollView.currentPageDotImage = [UIImage imageNamed:@"ic_page_2"];
    self.imageScrollView.delegate = self;
    self.imageScrollView.backgroundColor = [UIColor whiteColor];
}

//-(void) addTimer{
//    if ([self.timer isValid]) {
//        return;
//    }
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(doTimer) userInfo:nil repeats:YES];
//    [self.timer setFireDate:[NSDate new]];//开启
//}

//-(void) removeTimer{
//    //结束
//    if ([self.timer isValid]) {
//        [self.timer invalidate];
//        self.timer = nil;
//    }
//}
//
////开始计时
//-(void) doTimer{
//    if (self.isFirstScroll) {
//        self.isFirstScroll = NO;
//        return;
//    }
//    NSInteger currentIndex = self.pageControl.currentPage;
//    currentIndex ++;
//    currentIndex = currentIndex % self.pageControl.numberOfPages;
////    [self.imageScrollView setContentOffset:CGPointMake(UI_SCREEN_WIDTH * currentIndex, 0) animated:YES];
//    self.pageControl.currentPage = currentIndex;
//}

-(void)setData:(BUYProduct *)product{
    if(product == nil){
        return;
    }
    self.isShowCNY = YES;
//    self.isFirstScroll = YES;
//    [self removeTimer];
    self.product = product;
//    [self.imageScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
//    for (UIView *subview in self.imageScrollView.subviews) {
//        [subview removeFromSuperview];
//    }
    [self initImage:product];
    [self initView:product];
    //[self addTimer];
}

-(void)initImage:(BUYProduct *)product{
    if(product == nil){
        return;
    }
//    [self.imageScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
//    NSInteger imageCount = product.imagesArray == nil? 0:product.imagesArray.count;
//    self.imageArr = [NSMutableArray array];
    self.imageArr = [NSMutableArray arrayWithArray:[KWMImageUtil getProductImageUrls:self.product ImageSize:BigImage]];
    self.imageScrollView.imageURLStringsGroup = self.imageArr;
    
//    CGFloat w = UI_SCREEN_WIDTH;
//    CGFloat h = UI_SCREEN_WIDTH;
//    for( int i =0;i < imageCount;i++){
//        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*w, 0, w, h)];
//        imageView.tag = i;
//        imageView.contentMode = UIViewContentModeScaleAspectFit;
//        imageView.clipsToBounds = YES;
//        NSString *imageUrl = [KWMImageUtil getProductImageUrlByPosition:self.product ImageSize:BigImage Position:i];
//        [self.imageArr addObject:imageUrl];
//        NSURL *imageURL = [NSURL URLWithString:imageUrl];
//        UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickImage:)];
//        imageView.userInteractionEnabled = YES;
//        [imageView addGestureRecognizer:imageTap];
//        if(i + 1 == imageCount){
//            [imageView yy_setImageWithURL:imageURL placeholder:nil options:YYWebImageOptionProgressive completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
//                if(image && !error){
//                    [self performSelector:@selector(addTimer) withObject:nil afterDelay:0.5f];
//                }
//            }];
//        }else{
//             [imageView yy_setImageWithURL:imageURL options:YYWebImageOptionProgressive];
//        }
//        
//        [self.imageScrollView addSubview:imageView];
//    }
//    self.pageControl.numberOfPages = imageCount;
//    self.pageControl.currentPage = 0;
//    self.pageControl.defaultImage = [UIImage imageNamed:@"ic_page_1"];
//    self.pageControl.currentImage = [UIImage imageNamed:@"ic_page_2"];
//    self.imageScrollView.contentSize = CGSizeMake(w*imageCount,0);
//    self.imageScrollView.pagingEnabled = YES;
}


-(void)initView:(BUYProduct *)product{
    if(product == nil){
        return;
    }
    [self.btnBrand setTitle:product.vendor forState:UIControlStateNormal];
    self.lbName.text = product.title;
    BUYProductVariant *productVariant= product.variants.firstObject;
//    self.lbPrice.text = [KWMStringUtil price:productVariant.price];
    self.lbPrice.text = productVariant.price.priceValueFormatted;
    if (productVariant.compareAtPrice) {
//        NSString *priceString = [NSString stringWithFormat:@"¥%@",[KWMStringUtil price:productVariant.compareAtPrice]];
        NSString *priceString = productVariant.compareAtPrice.priceValueFormatted;
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:priceString attributes:attribtDic];
        self.lbOldPrice.attributedText = attribtStr;
    }else{
        self.lbOldPrice.hidden = YES;
    }
    
    UITapGestureRecognizer *priceTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickPrice:)];
    UITapGestureRecognizer *priceTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickPrice:)];
    UITapGestureRecognizer *priceTap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickPrice:)];
    [self.lbUnit addGestureRecognizer:priceTap1];
    [self.lbPrice addGestureRecognizer:priceTap2];
    [self.lbOldPrice addGestureRecognizer:priceTap3];
    self.lbUnit.userInteractionEnabled = YES;
    self.lbPrice.userInteractionEnabled = YES;
    self.lbOldPrice.userInteractionEnabled = YES;
    self.freeShipping.hidden = [product.tags containsObject:@"not-return"];
}

//-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    NSInteger index = fabs(scrollView.contentOffset.x)/scrollView.frame.size.width;
//    [self.pageControl setCurrentPage:index];
//}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    [self.delegate kwm_onClickImage:self.imageArr currentIndex:index];
}

//-(void)onClickImage:(UITapGestureRecognizer *)tapGesture{
//    if(self.delegate!=nil){
//        UIView *view = [tapGesture view];
//        [self.delegate kwm_onClickImage:self.imageArr currentIndex:view.tag];
//    }
//}

-(void)onClickPrice:(UITapGestureRecognizer *)tapGesture{
    if(self.product == nil){
        return;
    }
    self.isShowCNY = !self.isShowCNY;
    BUYProductVariant *productVariant= self.product.variants.firstObject;
    if(self.isShowCNY){
        self.lbUnit.text = @"¥";
        self.lbPrice.text = [KWMStringUtil price:productVariant.price];
        if (productVariant.compareAtPrice) {
            NSString *priceString = [NSString stringWithFormat:@"¥%@",[KWMStringUtil price:productVariant.compareAtPrice]];
            NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
            NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:priceString attributes:attribtDic];
            self.lbOldPrice.attributedText = attribtStr;
        }
    }else{
        self.lbUnit.text = @"€";
        self.lbPrice.text = productVariant.price.stringValue;
        if (productVariant.compareAtPrice) {
            NSString *priceString = [NSString stringWithFormat:@"€%@",productVariant.compareAtPrice.stringValue];
            NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
            NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:priceString attributes:attribtDic];
            self.lbOldPrice.attributedText = attribtStr;
        }
    }
}


-(void)onClickSizeBtn:(id)sender{
    if(self.delegate){
        [self.delegate kwm_onClickSizeBtn];
    }
}

- (IBAction)sizeGuideAction:(id)sender {
    [self.delegate kwm_sizeGuide];
}


-(void)onClickBlandBtn:(id)sender{
    if(self.delegate){
        [self.delegate kwm_goToBrandVC];
    }
}


-(void)setSelect:(BUYProductVariant *)variant color:(KWMColor *)color count:(NSInteger)count{
    _variant = variant;
    _color = color;
    _count = count;
    if(!variant){
        self.lbVariant.text = @"选择尺码/颜色";
    }else{
        NSString *colorString = color?[NSString stringWithFormat:@"%@ /",color.title]:@"";
        self.lbVariant.text =  [NSString stringWithFormat:@"已选择 %@ %@ / %ld",colorString,variant.title,count];
    }
}

- (void)setSizeGuideHidden:(BOOL)sizeGuideHidden {
    self.sizeGuideView.hidden = sizeGuideHidden;
    self.sizeGuideViewHeightConstraint.constant = sizeGuideHidden ? 0 : 50;
}

@end