//
//  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"

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

@property (nonatomic,strong) ProductDetailsHeaderView *headerView;

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

@end

@implementation ProductDetailsViewController

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

#pragma mark -UI
- (void)uiConfigAction
{
    self.productDetilsTableview.dataSource = self;
    self.productDetilsTableview.delegate = self;
    [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];
            [self.productDetilsTableview reloadData];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
        
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
        NSLog(@"%@",error);
    }];
}


#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.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.series;
    self.headerView.nameLabe.text = self.entity.name;
    self.headerView.brandName.text = self.entity.brandId;
    self.headerView.dorpPriceLabe.text = [self.entity.tagPrice stringValue];
    [self.headerView.goodsImageview sd_setImageWithURL:[NSURL URLWithString:self.entity.pictures] placeholderImage:TCImage(@"140046029-MX260-D112-03-星冠-5700K（4）")];
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ProductDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productDetailscell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.datas = self.entity;
    return cell;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 170;
}


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

- (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:@"%d",goodsNumber];
            
        }
            break;
        case 101://增加
        {
            if (goodsNumber >= [self.entity.number integerValue]) {
                
                //不能大于库存
                [self ErrorMBProgressView:@"超过库存"];
                return;
            }
            goodsNumber ++;
            self.headerView.goodsNumber.text = [NSString stringWithFormat:@"%d",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:@"%d",[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)addGoodsShoppingbags
{
    //判断是否有当前客户
    if (![Shoppersmanager manager].currentCustomer) {
        
        [self ErrorMBProgressView:@"必须设置当前客户"];
        return;
    }
    [self CreateMBProgressHUDLoding];
    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) {
    
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            [self SuccessMBProgressView:@"加入购物车成功"];
            //刷新购物车
            [[NSNotificationCenter defaultCenter]postNotificationName:@"GOODSNUMBER" object:returnValue[@"data"]];
            
        }else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
       
        [self RemoveMBProgressHUDLoding];
    }];
}



#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
