//
//  ShoppingView.m
//  Lighting
//
//  Created by mac on 16/5/23.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "ShoppingView.h"

@interface ShoppingView ()
{
    NSMutableArray * textArray;
}

@end

@implementation ShoppingView

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initdata];
    [self initView];
    // Do any additional setup after loading the view.
}
-(void)initdata
{
    self.isAllSelected=NO;
    self.nameDataArray=[[NSMutableArray alloc]initWithObjects:@"图片",@"产品信息",@"吊牌价",@"数量", nil];
    self.productModelArray=[[NSMutableArray alloc]init];
    self.AddArray=[[NSMutableArray alloc]init];
    textArray=[[NSMutableArray alloc]initWithObjects:@"1",@"1",@"1",@"1",@"1", nil];
    self.selectTagArray=[[NSMutableArray alloc]init];
}
-(void)initView
{
    self.subView=[[UIView alloc]initWithFrame:CGRectMake(100, 50, ScreenWidth-250, ScreenHeight-200)];
    self.subView.backgroundColor=[UIColor whiteColor];
    [self.view  addSubview:self.subView];
    
    //点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(DismissScreenView:)];
    tap.delegate = self;
    tap.cancelsTouchesInView = NO;
    [[UIApplication sharedApplication].keyWindow addGestureRecognizer:tap];
    [self initSubViews];
}
-(void)initSubViews
{
    self.headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.subView.frame.size.width, 50)];
    self.headerView.backgroundColor=RGB(225, 225, 225, 1);
    [self.subView addSubview:self.headerView];
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(20, 10, 30, 30);
    [btn setBackgroundImage:[UIImage imageNamed:@"addshopping"] forState:UIControlStateNormal];
    [self.headerView addSubview:btn];
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(65, 10, 150, 30)];
    lable.text=@"待添加至购物袋";
    [self.headerView addSubview:lable];
    
    self.toolView=[[UIView alloc]initWithFrame:CGRectMake(0,50, self.subView.frame.size.width, 50)];
     self.toolView.backgroundColor=[UIColor grayColor];
    [self.subView addSubview:self.toolView];
    for (int i=0; i<self.nameDataArray.count; i++) {
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        switch (i) {
            case 0:
                btn.frame=CGRectMake(self.subView.frame.size.width/8*(i+1)-10, 10, self.subView.frame.size.width/9, 30);
                break;
            case 1:
                btn.frame=CGRectMake(self.subView.frame.size.width/9*(i+3)-70, 10, self.subView.frame.size.width/9, 30);
                break;
            case 2:
                 btn.frame=CGRectMake(self.subView.frame.size.width/7*(i+2)+25, 10, self.subView.frame.size.width/9, 30);
                break;
                
            case 3:
                 btn.frame=CGRectMake(self.subView.frame.size.width/9*(i+4)+20, 10, self.subView.frame.size.width/9, 30);
                break;
            default:
                break;
        }
       
        [btn setTitle:[self.nameDataArray objectAtIndex:i] forState:UIControlStateNormal];
        [self.toolView addSubview:btn];
    }
    self.shoppingTableView=[[UITableView alloc]initWithFrame:CGRectMake( 0,100, self.subView.frame.size.width, self.subView.frame.size.height-200)];
    self.shoppingTableView.delegate=self;
    self.shoppingTableView.dataSource=self;
     self.shoppingTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.subView addSubview:self.shoppingTableView];
    
    self.footView=[[UIView alloc]initWithFrame:CGRectMake(0, self.subView.frame.size.height-100, self.subView.frame.size.width, 100)];
    [self.subView addSubview:self.footView];
   self.allSelectBtn=[[UIButton alloc]initWithFrame:CGRectMake(20, 35, 30, 30)];
    [self.allSelectBtn addTarget:self action:@selector(allSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self.allSelectBtn setBackgroundImage:[UIImage imageNamed:@"box-副本"] forState:UIControlStateNormal];
    [self.footView addSubview:self.allSelectBtn];
    UILabel *allLable=[[UILabel alloc]initWithFrame:CGRectMake(70, 35, 50, 50)];
    allLable.text=@"全选";
    [self.footView addSubview:allLable];
    UIButton * delegateBtn=[[UIButton alloc]initWithFrame:CGRectMake(150, 35, 30, 30)];
    [delegateBtn setBackgroundImage:[UIImage imageNamed:@"Trash"] forState:UIControlStateNormal];
    [delegateBtn addTarget:self action:@selector(delegateProduct:) forControlEvents:UIControlEventTouchUpInside];
    [self.footView addSubview:delegateBtn];
    UILabel *delegatelable=[[UILabel alloc]initWithFrame:CGRectMake(210, 35, 50, 50)];
    delegatelable.text=@"删除";
     [self.footView addSubview:delegatelable];
//    UILabel *totalAmountName=[[UILabel alloc]initWithFrame:CGRectMake(self.footView.frame.size.width-320, 25, 75, 50)];
//    totalAmountName.text=@"合计金额";
//    [self.footView addSubview:totalAmountName];
//      UILabel *totalAmountNum=[[UILabel alloc]initWithFrame:CGRectMake(self.footView.frame.size.width-240, 25, 75, 50)];
//   totalAmountNum.text=@"$5500";
//    totalAmountNum.textColor=[UIColor redColor];
//    [self.footView addSubview:totalAmountNum];
    self.confirmAddBtn=[[UIButton alloc]initWithFrame:CGRectMake(self.footView.frame.size.width-150, 15, 130, 60)];
    [self.confirmAddBtn setTitle:@"确认添加（0）" forState:UIControlStateNormal];
    [self.confirmAddBtn addTarget:self action:@selector(addProducts:) forControlEvents:UIControlEventTouchUpInside];
    [self.confirmAddBtn setBackgroundColor:RGB(78, 172, 217, 1)];
    [self.footView addSubview:self.confirmAddBtn];
    
}
//全选
-(void)allSelected:(UIButton*)sender
{
    if (!self.isAllSelected) {
        [sender setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];
        [self.shoppingTableView reloadData];
        for (int i=0; i<self.productModelArray.count; i++) {
            if (![self.selectTagArray containsObject:[NSString stringWithFormat:@"%d",i]]) {
                [self.selectTagArray addObject:[NSString stringWithFormat:@"%d",i]];
                [self.AddArray addObject:[self.productModelArray objectAtIndex:i]];
            }
            
        }
        [self.confirmAddBtn setTitle:[NSString stringWithFormat:@"确认添加（%lu）",(unsigned long)self.selectTagArray.count] forState:UIControlStateNormal];
        self.isAllSelected=YES;
    }else
    {
       [sender setBackgroundImage:[UIImage imageNamed:@"box-副本"] forState:UIControlStateNormal];
        [self.shoppingTableView reloadData];
        [self.selectTagArray removeAllObjects];
        [self.AddArray removeAllObjects];
         [self.confirmAddBtn setTitle:[NSString stringWithFormat:@"确认添加（0）"] forState:UIControlStateNormal];
        self.isAllSelected=NO;
    }
    
}
//删除
-(void)delegateProduct:(UIButton *)sender
{
    self.selectTagArray=[self sequenceProductList:self.selectTagArray];
    if (self.isAllSelected) {
        [self.productModelArray  removeAllObjects];
        [self.AddArray removeAllObjects];
        [self.confirmAddBtn setTitle:[NSString stringWithFormat:@"确认添加（0）"] forState:UIControlStateNormal];
        [ self.allSelectBtn setBackgroundImage:[UIImage imageNamed:@"box-副本"] forState:UIControlStateNormal];
        self.isAllSelected=NO;
    }else
    {
        for (int i=0; i<self.selectTagArray.count; i++) {
            NSString *str=[self.selectTagArray objectAtIndex:i];
            [self.AddArray removeObject:[self.productModelArray objectAtIndex:i]];
            [self.productModelArray removeObjectAtIndex:[str integerValue]];
            [self.selectTagArray removeObject:str];
           
        }
        [self.confirmAddBtn setTitle:[NSString stringWithFormat:@"确认添加（%lu）",(unsigned long)self.selectTagArray.count] forState:UIControlStateNormal];
    }
    [self.shoppingTableView reloadData];
}
//选择
-(void)selfctAtIndexpath:(CustomShopingSeclectButton *)sender
{
    if ([self.selectTagArray containsObject:[NSString stringWithFormat:@"%ld",(long)sender.tag]]) {
        [sender setBackgroundImage:[UIImage imageNamed:@"box-副本"] forState:UIControlStateNormal];
        [self.selectTagArray removeObject:[NSString stringWithFormat:@"%ld",(long)sender.tag]];
        [self.AddArray removeObjectAtIndex:sender.tag];
        if (self.isAllSelected) {
            [ self.allSelectBtn setBackgroundImage:[UIImage imageNamed:@"box-副本"] forState:UIControlStateNormal];
            self.isAllSelected=NO;
        }
        
    }else
    {
        [sender setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];
         [self.selectTagArray addObject:[NSString stringWithFormat:@"%ld",(long)sender.tag]];
        [self.AddArray addObject:[self.productModelArray objectAtIndex:sender.tag]];
        if (!self.isAllSelected&&self.selectTagArray.count==self.self.productModelArray.count ) {
            [ self.allSelectBtn setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];
            self.isAllSelected=YES;
        }
        
    }
   [self.confirmAddBtn setTitle:[NSString stringWithFormat:@"确认添加（%lu）",(unsigned long)self.selectTagArray.count] forState:UIControlStateNormal];
   
}
//第一种排序  倒序排列

-(NSMutableArray *)sequenceProductList:(NSMutableArray*)productList
{
    //    数组排序
    NSComparator cmptr = ^(id obj1, id obj2){
        if ([obj1   integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] > [obj2  integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
    
    if ( productList.count>0) {
        productList=[NSMutableArray arrayWithArray:[productList sortedArrayUsingComparator:cmptr] ];
    }
    
    return productList;
}
//加入购物车
-(void)addProducts:(UIButton *)sender
{
    //加入购物车
        //判断是否有当前客户
        if (![Shoppersmanager manager].currentCustomer) {
            
            [self ErrorMBProgressView:@"必须设置当前客户"];
            return;
        }
    SaveShoppingCartRequest *shopCar = [[SaveShoppingCartRequest alloc]init];
    shopCar.consumerId = [Customermanager manager].model.fid;
    shopCar.goodsId =@"";
    shopCar.count = @"";
    for (int i=0; i<self.shoppingTableView.visibleCells.count; i++) {
        ShoppingCell *cell=[self.shoppingTableView.visibleCells objectAtIndex:i];
        if ( [self.selectTagArray containsObject:[NSString stringWithFormat:@"%ld",(long)cell.selectedButton.tag]] ) {
            TOGoodsEntity *model=cell.customGoods.tOGoodsEntity;
            if (![shopCar.count isEqualToString:@""]&&![shopCar.goodsId isEqualToString:@""]) {
                shopCar.goodsId=[NSString stringWithFormat:@"%@,%@",shopCar.goodsId,model.fid];
                shopCar.count=[NSString stringWithFormat:@"%@,%d",shopCar.count,cell.value];
            }

            if ([shopCar.goodsId isEqualToString:@""]) {
                shopCar.goodsId=model.fid;
            }
            if ([shopCar.count isEqualToString:@""]) {
                shopCar.count=[NSString stringWithFormat:@"%d",cell.value];
            }
            
        }
        
    }
    [self addGoodsShoppingbags:shopCar complate:^{
        NSLog(@"加入购物车完成");
     
    }];

}
#pragma mark -添加至购物车
- (void)addGoodsShoppingbags:(SaveShoppingCartRequest *)shopCar complate:(void(^)())response
{
    
      [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(ADDSHOPPINGBAG) WithRequestType:0 WithParameter:shopCar WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            response();
              [self SuccessMBProgressView:@"添加购物车成功"];
            
        }else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        [self ErrorMBProgressView:@"加入购物车失败"];
    }];
}


#pragma mark - 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.productModelArray.count;

    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        return 100;
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"ChooseTansferCell";
    ShoppingCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[ShoppingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
     TOGoodsEntity *model=[self.productModelArray objectAtIndex:indexPath.row];
    cell.customGoods.tOGoodsEntity=model;
    cell.selectedButton.tag=indexPath.row;
    cell.selectedButton.customIndexPath=indexPath;
    [cell.selectedButton addTarget:self action:@selector(selfctAtIndexpath:) forControlEvents:UIControlEventTouchUpInside];
   
    NSArray *imageArray = [[[self.productModelArray objectAtIndex_opple:indexPath.row] pictures] componentsSeparatedByString:@","];
    [cell.goodsImageView sd_setImageWithURL:[NSURL URLWithString:[imageArray firstObject]] placeholderImage:REPLACEIMAGE];
    
    cell.goodsInformationLabe.text=[NSString stringWithFormat:@"%@\n%@\n%@ ",model.name,model.code,model.size];
    cell.tagsPriceLabe.text = [NSString stringWithFormat:@"￥%@",model.tagPrice];

    if (self.isAllSelected) {
        [cell.selectedButton setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];
    }else
    {
        [cell.selectedButton setBackgroundImage:[UIImage imageNamed:@"box-副本"] forState:UIControlStateNormal];
    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}

-(void)DismissScreenView:(UITapGestureRecognizer*)sender{
    CGPoint point = [sender locationInView:self.view];
    if (point.x<100 || point.x >ScreenWidth-150||point.y<50||point.y>ScreenHeight-150) {
        
        if (self) {
            if ([self.delegate respondsToSelector:@selector(restShoppingBtnImage)]) {
                [self.delegate restShoppingBtnImage];
            }
            [self.view removeFromSuperview];
        }
    }
}

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