//
//  ProductDetailsViewController.m
//  Lighting
//
//  Created by 曹云霄 on 16/5/4.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "ProductDetailsViewController.h"
#import "ProductDetailsTableViewCell.h"
#import "ProductDetailsHeaderView.h"
#import "goodsDetailsSectionview.h"
#import "goodsDetailsTableViewCell.h"
#import "FullScreenViewController.h"

@interface ProductDetailsViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic,strong) ProductDetailsHeaderView *headerView;

/**
 *  商品详情数据
 */
@property (nonatomic,strong )TOGoodsEntity *entity;

/**
 *  图文详情数据源
 */
@property (nonatomic,strong) NSMutableArray *goodsDetailsArray;

/**
 *  商品小图数据源
 */
@property (nonatomic,strong) NSMutableArray *imagesArray;

/**
 *  点击小图的下标 默认0
 */
@property (nonatomic,assign) NSInteger imageIndex;

@end

@implementation ProductDetailsViewController


/**
 *  初始化图文详情
 */
- (NSMutableArray *)goodsDetailsArray
{
    if (_goodsDetailsArray == nil) {
        _goodsDetailsArray = [NSMutableArray array];
    }
    return _goodsDetailsArray;
}

/**
 *  商品小图数据源
 */
- (NSMutableArray *)imagesArray
{
    if (_imagesArray == nil) {
        _imagesArray = [NSMutableArray array];
    }
    return _imagesArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self getGoodsListDetails];
    
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.imageIndex = 0;
    self.productDetilsTableview.dataSource = self;
    self.productDetilsTableview.delegate = self;
    [self.productDetilsTableview registerNib:[UINib nibWithNibName:@"goodsDetailsTableViewCell" bundle:nil] forCellReuseIdentifier:@"goodsdetailscell"];
    [self CreateHeaderView];
}


#pragma mark -获取商品详情
- (void)getGoodsListDetails

{
    [self CreateMBProgressHUDLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@%@",ServerAddress,@"/goods/getGoods/",_goodsID];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:url WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
           self.entity = [[TOGoodsEntity alloc]initWithDictionary:returnValue[@"data"] error:nil];
            [self HeaderViewAssignment];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
    }];
}


#pragma mark -头部视图
- (void)CreateHeaderView
{
    self.headerView = [[[NSBundle mainBundle] loadNibNamed:@"ProductDetailsHeaderView" owner:self options:nil] lastObject];
    self.headerView.goodsNumber.delegate = self;
    //增加，减少商品
    [self.headerView.reduceButton addTarget:self action:@selector(reduceGoodsButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.addButton addTarget:self action:@selector(reduceGoodsButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //放大
    [self.headerView.amplificationButton addTarget:self action:@selector(amplificationButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.productDetilsTableview.tableHeaderView = self.headerView;
    
    //添加至购物车
    [self.headerView.addGoodsShoppingbagsButton addTarget:self action:@selector(addGoodsShoppingbags:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark -header赋值
- (void)HeaderViewAssignment
{
    self.headerView.serialNumber.text = self.entity.code;
    self.headerView.nameLabe.text = self.entity.name;
    self.headerView.brandName.text = self.entity.company;
    self.headerView.dorpPriceLabe.text = [NSString stringWithFormat:@"￥%.2f",[self.entity.tagPrice floatValue]];
    self.imagesArray = [NSMutableArray arrayWithArray:[self.entity.pictures componentsSeparatedByString:@","]];
    [self.headerView.goodsImageview sd_setImageWithURL:[self.imagesArray firstObject] placeholderImage:REPLACEIMAGE];
    //商品小图
    self.imagesArray = [NSMutableArray arrayWithArray:[self.entity.pictures componentsSeparatedByString:@","]];
    for (int i=0; i<self.imagesArray.count; i++) {
        UIImageView *subImageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, i*100, 80, 60)];
        subImageview.tag = 100+i;
        subImageview.userInteractionEnabled = YES;
        [subImageview sd_setImageWithURL:[NSURL URLWithString:[self.imagesArray objectAtIndex_opple:i]] placeholderImage:REPLACEIMAGE];
        [subImageview addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(SubimageViewClickAction:)]];
        [self.headerView.goodsBrotherScrollview addSubview:subImageview];
    }
    self.headerView.goodsBrotherScrollview.contentSize = CGSizeMake(0, self.imagesArray.count*100);
    self.headerView.goodsBrotherScrollview.showsVerticalScrollIndicator = NO;
    self.headerView.goodsBrotherScrollview.pagingEnabled = YES;
    self.headerView.goodsBrotherScrollview.userInteractionEnabled = YES;
    
    //图文大图
    self.goodsDetailsArray = [NSMutableArray arrayWithArray:[self.entity.detailedIntro componentsSeparatedByString:@","]];
    [self.productDetilsTableview reloadData];
}

#pragma mark -小图点击手势、切换图片显示
- (void)SubimageViewClickAction:(UITapGestureRecognizer *)tap
{
    self.imageIndex = tap.view.tag-100;
    [self.headerView.goodsImageview sd_setImageWithURL:[self.imagesArray objectAtIndex_opple:tap.view.tag-100] placeholderImage:REPLACEIMAGE];
}



#pragma mark -图片放大点击
- (void)amplificationButtonClick
{
    FullScreenViewController *fullScreenVC = [[FullScreenViewController alloc]init];
    fullScreenVC.datasArray = self.imagesArray;
    fullScreenVC.isProductLibrary = YES;
    fullScreenVC.currentindex = self.imageIndex;
    [self presentViewController:fullScreenVC animated:YES completion:nil];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ProductDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productDetailscell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.datas = self.entity;
        return cell;
        
    }else if (indexPath.section == 1)
    {
        goodsDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"goodsdetailscell" forIndexPath:indexPath];
        [cell.detailsImageView sd_setImageWithURL:[NSURL URLWithString:[self.goodsDetailsArray objectAtIndex_opple:indexPath.row]] placeholderImage:REPLACEIMAGE];
        
        return cell;
    }
    return nil;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return self.goodsDetailsArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        return 170;
    }
    return ScreenWidth;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    goodsDetailsSectionview *sectionView = [[[NSBundle mainBundle] loadNibNamed:@"goodsDetailsSectionview" owner:self options:nil] firstObject];
    sectionView.goodSectionLabe.text = section?@"图文详情":@"商品参数";
    return sectionView;
}


#pragma mark -减少商品----增加商品
- (void)reduceGoodsButtonClick:(UIButton *)sender {
    
    NSInteger goodsNumber = [self.headerView.goodsNumber.text integerValue];
    switch (sender.tag) {
        case 100://减少
        {
            if (goodsNumber <= 1) {
                
                //不能小于1
                [self ErrorMBProgressView:@"不能小于1"];
                return;
            }
            goodsNumber --;
            self.headerView.goodsNumber.text = [NSString stringWithFormat:@"%ld",(long)goodsNumber];
        }
            break;
        case 101://增加
        {
            if (goodsNumber >= [self.entity.number integerValue]) {
                
                //不能大于库存
                [self ErrorMBProgressView:@"超过库存"];
                return;
            }
            goodsNumber ++;
            self.headerView.goodsNumber.text = [NSString stringWithFormat:@"%ld",(long)goodsNumber];
        }
            break;
            
        default:
            break;
    }
}





#pragma mark -UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"%@",textField.text);
    NSString *inputString = textField.text;
    if (![self isPureInt:inputString]) {
        
        [self ErrorMBProgressView:@"输入格式错误"];
        textField.text = @"1";
        return;
    }
    
    if ([inputString integerValue] > [self.entity.number integerValue]) {
        
        [self ErrorMBProgressView:@"超过库存数量"];
        textField.text = [NSString stringWithFormat:@"%ld",(long)[self.entity.number integerValue]];
        return;
    }
}

//
//@synthesize fid;
//@synthesize createName;
//@synthesize createBy;
//@synthesize createDate;
//@synthesize updateName;
//@synthesize updateBy;
//@synthesize updateDate;
//@synthesize sysOrgCode;
////@synthesize goodsId;
//@synthesize goodsCode;
//@synthesize goodsName;
//@synthesize goodsCover;
//@synthesize goodsSpec;
//@synthesize goodsBrand;
//@synthesize goodsSellerPrice;
//@synthesize goodsNum;
//@synthesize goodsPrice;
//@synthesize goodsTotalPrice;
//@synthesize consumerId;

#pragma mark -开发加入购物车动画
- (void)StartAddShoppingCarAnimationWithimage:(UIImage *)image withStartpoint:(CGPoint)point
{
    //起点
    CGPoint startPoint = point;
    //终点
    CGPoint endPoint = SHARED_APPDELEGATE.shoppingCarPoint;
    //控点
    CGPoint controlPoint = CGPointMake(endPoint.x, startPoint.x);
    
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 60, 42)];
    imageView.layer.position = point;
    imageView.tag = 100;
    imageView.image = image;
    
    [self.view.layer addSublayer:imageView.layer];
    
    //创建关键帧
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.delegate = self;
    //动画时间
    animation.duration = 1;
    
    //当动画完成，停留到结束位置
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    
    //当方法名字遇到create,new,copy,retain，都需要管理内存
    CGMutablePathRef path = CGPathCreateMutable();
    //设置起点
    CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
    CGPathAddQuadCurveToPoint(path, NULL, controlPoint.x, controlPoint.y, endPoint.x,endPoint.y);
    
    //设置动画路径
    animation.path = path;
    
    //执行动画
    [imageView.layer addAnimation:animation forKey:nil];
    
    //释放路径
    CGPathRelease(path);
}

#pragma mark -完成加入购物车动画完成后回调
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    NSLog(@"动画完成了");
   [[NSNotificationCenter defaultCenter]postNotificationName:@"ADDGOODSNUMBER" object:@([self.headerView.goodsNumber.text integerValue])];
}


#pragma mark -添加至购物车
- (void)addGoodsShoppingbags:(UIButton *)button
{
    //判断是否有当前客户
    if (![Shoppersmanager manager].currentCustomer) {
        
        [self ErrorMBProgressView:@"必须设置当前客户"];
        return;
    }
    [self StartAddShoppingCarAnimationWithimage:self.headerView.goodsImageview.image withStartpoint:[self.headerView convertPoint:[button center] toView:self.view.window]];
    SaveShoppingCartRequest *shopCar = [[SaveShoppingCartRequest alloc]init];
    shopCar.consumerId = [[Customermanager manager] customerID];
    shopCar.goodsId = _goodsID;
    shopCar.count = [self.headerView.goodsNumber.text intValue];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/shopcart/save"] WithRequestType:0 WithParameter:shopCar WithReturnValueBlock:^(id returnValue) {
    
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            NSLog(@"添加购物车成功");
        }else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
       
        [self ErrorMBProgressView:@"添加购物车失败"];
        
    }];
}



#pragma mark -判断是否为纯数字
- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}



- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


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