没更改

//

//  ShopCartViewController.m

//  MBuyGo

//

//  Created by fangqingmei on 15/10/9.

//  Copyright (c) 2015年 m6go.com. All rights reserved.

//

 

#import "ShopCartViewController.h"

#import "MLGHTTPRequestOperationManager.h"

#import "MLGSettlementViewController.h"

#import "MLGHomePageDoubleGoodsCell.h"

#import "CheckShoppingCartRequest.h"

#import "ShopCartProtocolDelegate.h"

#import "ShopCartTableHeaderView.h"

#import "MLGShopCarTableViewCell.h"

#import "SCExchangeShopViewController.h"

#import "GoodsDetailSourceMark.h"

#import "SCMerchantListModel.h"

#import "NSObject+MJKeyValue.h"

#import "ShopCartNoDataView.h"

#import "BottomAccountView.h"

#import "ShopRecommendGoodsModel.h"

#import "ShopCartModel.h"

#import "MerchantView.h"

#import "SCMerchantModel.h"

#import "SCDecreaseRuleModel.h"

#import "ProductTableViewCell.h"

#import "ActivityTypeView.h"

#import "GCDQueue.h"

#import "ShopCart.h"

#import "Masonry.h"

#import "Utility.h"

#import "ShopCartDef.h"

#import "ActivityModel.h"

#import "MLGLoadFailureView.h"

#import "MLGProgressView.h"

#import "InvalidModel.h"

 

@interface ShopCartViewController ()<UIGestureRecognizerDelegate,MLGHomePageDoubleGoodsCellDelegate,ShopCartProtocolDelegate,ShopCartProductCellDelegate>

@property (nonatomic, strong) UITableView               *firstGradeTableView;      ///<显示购物车商品的TableView

@property (nonatomic, strong) ShopCartTableHeaderView   *tableHeaderView;          ///<购物车头视图(登录提示语和button)

@property (nonatomic, strong) MLGLoadFailureView        *loadFailureView;          ///< 加载失败视图

 

@property (nonatomic, strong) NSMutableArray *shopRecommendGoodsModelArray;

@property (nonatomic, strong) NSMutableArray *moreGoodsArray;

@property (nonatomic, strong) NSMutableArray *activityArray;

@property (nonatomic, strong) NSMutableArray *editProductArray;

//换购模块的数据源数组

@property (nonatomic, strong) NSMutableArray *activitySelectGoodsArray;

 

@property (nonatomic, assign) NSInteger              start;                   ///< 起始位置

@property (nonatomic, assign) NSInteger              rows;                    ///< 加载数量

 

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, assign) NSInteger proAppearNum;

 

@property (nonatomic, assign) BOOL isEmptyData;

@property (nonatomic, assign) BOOL isHaveInvalidGoods;                       ///< 是否有失效商品

@property (nonatomic, assign) BOOL isSelectMerchatView;

@property (nonatomic, assign) BOOL isEdit;

@property (nonatomic, assign) BOOL isAllSelect;

@property (nonatomic, assign) BOOL isHaveRecommendData;

@property (nonatomic, assign) BOOL isRequestMainGoods;

@property (nonatomic, assign) BOOL isModifi;                                ///< 编辑状态下是否有改动

@property (nonatomic, assign) BOOL isSync;                                  ///< 是否同步数据

 

 

@property (nonatomic, strong) MerchantView *merchantView;

@property (nonatomic, strong) BottomAccountView *bottomAccountView;        ///< 底部结算view

@property (nonatomic, strong) ProductTableViewCell *proCell;

 

@property (nonatomic, strong) ShopCartModel *shopCartmodel;

@property (nonatomic, strong) ShopCartModel *payModel;

 

@end

 

@implementation ShopCartViewController

 

#pragma mark - 购物车显示2套UI

//- (void)setShopCartVCPushFromType:(ShopCartVCPushFromType)shopCartVCPushFromType

//{

//    _shopCartVCPushFromType = shopCartVCPushFromType;

//    switch (shopCartVCPushFromType) {

//        case ShopCartVCPushFromProductDetail:

//            [self hideTabBar:YES];

//            break;

//        case ShopCartVCPushFromClickedTabBar:

//            [self showTabBar:YES];

//            break;

//        default:

//            break;

//    }

//}

 

- (void)showTabBar:(BOOL)animated

{

    self.titleBar.leftBtn.hidden = YES;

    self.bottomAccountView.frame = CGRectMake(0, ScreenHeight-50 - 49, ScreenWidth, 50);

    self.firstGradeTableView.frame = CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-50-44);

    self.firstGradeTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

    

    [APPDELEGATE.tabBarViewController showTabBar:animated];

}

 

- (void)hideTabBar:(BOOL)animated

{

    self.titleBar.leftBtn.hidden = NO;

    self.bottomAccountView.frame = CGRectMake(0, ScreenHeight-50, ScreenWidth, 50);

    self.firstGradeTableView.frame = CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-50);

    self.firstGradeTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

    [APPDELEGATE.tabBarViewController hideTabBar:animated];

}

#pragma mark -重置结算view和firstGradeTableView的frame

- (void)resetBottomHidden:(BOOL)isHidden {

    self.bottomAccountView.frame = isHidden?CGRectMake(0, -ScreenHeight, ScreenWidth, 0):CGRectMake(0, ScreenHeight-50, ScreenWidth, 50);

    //    if(self.shopCartVCPushFromType == ShopCartVCPushFromProductDetail){

    //        self.bottomAccountView.frame = CGRectMake(0, ScreenHeight-50, ScreenWidth, 50);

    //    }

    

    self.firstGradeTableView.frame =  isHidden?CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-50):CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-50-44);

    if(self.shopCartVCPushFromType == ShopCartVCPushFromProductDetail && isHidden){

        self.firstGradeTableView.frame = CGRectMake(0, 64, ScreenWidth, ScreenHeight-64);

    }

}

 

- (void)leftBtnClicked:(UIButton *)sender {

    [APPDELEGATE.navigationController popViewControllerAnimated:YES];

}

 

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    

    self.titleBar.rightBtn.selected = NO;

    [self reloadDataSetTip];

    self.isSync = YES;

    [self readyForCarDataFromHttp];

    self.start = 0;

    [self prepareShopRecommendGoodsRequestData];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshShopCartData:) name:@"tongzhi" object:nil];

}

 

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:YES];

    [MLGProgressView hide];

    [APPDELEGATE.tabBarViewController showTabBar:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];

}

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    self.shopRecommendGoodsModelArray = [NSMutableArray arrayWithCapacity:0];

    self.moreGoodsArray = [NSMutableArray arrayWithCapacity:0];

    self.activityArray = [NSMutableArray arrayWithCapacity:0];

    self.editProductArray = [NSMutableArray arrayWithCapacity:0];

    self.activitySelectGoodsArray = [NSMutableArray arrayWithCapacity:0];

    self.view.backgroundColor = [UIColor whiteColor];

    

    [self.titleBar setTitleStr:@"购物车"];

    

    [self createEditBtn];

    [self createLoadFailureView];

    [self createContent];

    [self.bottomAccountView resetEmptyView];

    self.start = 0;  // 加载 起始

    self.rows  = 50; // 加载条数

}

 

#pragma mark - 添加刷新方法

- (void)loadShops {

    __weak typeof(UIScrollView *) weakScrollView = self.firstGradeTableView;

    __weak typeof(self) weakSelf = self;

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC);

    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

        if(!self.isEditState){

            //请求购物车数据

            self.isSync = YES;

            [weakSelf readyForCarDataFromHttp];

            

            self.start = 0;

            //请求商品推荐数据

            [weakSelf prepareShopRecommendGoodsRequestData];

        }

        [weakScrollView finishLoading];

    });

}

#pragma mark 创建加载失败的视图

- (void)createLoadFailureView {

    WS(weakSelf)

    self.loadFailureView = [MLGLoadFailureView loadFailureViewWithRetryBlock:^{

        self.titleBar.rightBtn.selected = NO;

        [self reloadDataSetTip];

        self.isSync = YES;

        [self readyForCarDataFromHttp];

        self.start = 0;

        [self prepareShopRecommendGoodsRequestData];

    }];

    self.loadFailureView.hidden = YES;

    self.loadFailureView.backgroundColor = [UIColor clearColor];

    [self.view addSubview:self.loadFailureView];

    

    [self.loadFailureView mas_makeConstraints:^(MASConstraintMaker *make){

        make.center.equalTo(weakSelf.view);

        make.size.mas_equalTo(CGSizeMake(200, 230));

    }];

}

 

- (void)loadFailure {

    dispatch_async(dispatch_get_main_queue(), ^{

        self.loadFailureView.hidden = NO;

        [self hideContentView:YES];

    });

}

 

- (void)loadSuccess {

    dispatch_async(dispatch_get_main_queue(), ^{

        self.loadFailureView.hidden = YES;

        [self hideContentView:NO];

    });

}

 

- (void)refreshShopCartData:(NSNotification *)notification {

    self.titleBar.rightBtn.selected = NO;

    [self reloadDataSetTip];

    [self.bottomAccountView resetEmptyView];

    self.isSync = YES;

    [self readyForCarDataFromHttp];

    self.start = 0;

    [self prepareShopRecommendGoodsRequestData];

}

 

- (void)hideContentView:(BOOL)hide {

    self.firstGradeTableView.hidden = hide;

    self.bottomAccountView.hidden = hide;

}

 

#pragma mark 结算

- (void)buyAction:(UIButton*)sender {

    __weak typeof(self) weakSelf = self;

    NSMutableArray *selectGoodsArray = [NSMutableArray arrayWithCapacity:0];

    for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++) {

        NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

        //解档

        ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        if (shopCart.isSelected.integerValue==1) {

            [selectGoodsArray addObject:shopCart];

        }

    }

    

    if(selectGoodsArray.count < 1) {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"您未选购商品" message:nil delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

        [alertView show];

        return;

    }

    if(![NetworkCheck isConnect])

        return;

    sender.enabled = NO;

    NSString *auth = [Utility getUserAuth];

    NSNumber *userId = [Utility getUserID];

    

    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];

    NSMutableArray *productArray = [NSMutableArray arrayWithCapacity:0];

    NSMutableArray *selectedActivityArray = [NSMutableArray arrayWithCapacity:0];

    

    

    [MLGProgressView show];

    for (int i = 0; i < selectGoodsArray.count; i++) {

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

        

        ShopCart *shopCart = selectGoodsArray[i];

        

        [dict setValue:shopCart.goodsId forKey:@"goodsId"];

        [dict setValue:shopCart.goodsCount forKey:@"goodsCount"];

        [dict setValue:shopCart.goodsSkuId forKey:@"goodsSkuId"];

        [dict setValue:shopCart.salesId forKey:@"salesId"];

        [dict setValue:shopCart.goodsSourceType forKey:@"goodsSourceType"];

        [dict setValue:shopCart.pageSourceMark forKey:@"pageSourceMark"];

        

        [productArray addObject:dict];

    }

    for(int i = 0; i<weakSelf.activitySelectGoodsArray.count;i++) {

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

        SCActivityGoodsModel *acModel = weakSelf.activitySelectGoodsArray[i];

        if(acModel.aIsSelected == 1){

            [dict setValue:@(acModel.aGoodsId) forKey:@"goodsId"];

            [dict setValue:@(acModel.aGoodsSkuId) forKey:@"goodsSkuId"];

            [selectedActivityArray addObject:dict];

        }

    }

    

    [params setObject:userId forKey:@"userId"];

    [params setObject:auth forKey:@"auth"];

    [params setObject:productArray forKey:@"products"];

    [params setObject:selectedActivityArray forKey:@"selectedActivityGoods"];

    

    NSString *shopCartStr = [Configuration sharedConfiguration].shoppingCartBuyAction_url;

    

    MLGHTTPRequestOperationManager *manager = [[MLGHTTPRequestOperationManager alloc] init];

    [manager POST:shopCartStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

        

        [MLGProgressView hide];

        sender.enabled = YES;

        NSDictionary *msgDict = responseObject[@"msg"];

        NSString *code = [responseObject objectForKey:@"code"];

        

        

        if (code.integerValue == 200) {

            weakSelf.payModel = [ShopCartModel objectWithKeyValues:msgDict];

            

            if(weakSelf.payModel.canBuyType==0){

                

                MLGSettlementViewController *setVC = [[MLGSettlementViewController alloc] initSelectedGoodsArray:selectGoodsArray exchangedGoodsArray:weakSelf.activitySelectGoodsArray isBuyNowGoods:NO isCycle:NO];

                

                [weakSelf.navigationController pushViewController:setVC animated:YES];

            }else{

                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:weakSelf.payModel.showAlertText message:nil delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

                [alertView show];

                

            }

            

        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        sender.enabled = YES;

        

        [MLGProgressView hide];

    }];

}

 

#pragma mark 创建购物车显示的列表视图和结算视图

- (void)createContent {

    self.firstGradeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.titleBar.bottom, ScreenWidth, ScreenHeight-self.titleBar.bottom-50) style:UITableViewStyleGrouped];

    

    self.firstGradeTableView.delegate = self;

    self.firstGradeTableView.dataSource = self;

    self.firstGradeTableView.showsHorizontalScrollIndicator = NO;

    self.firstGradeTableView.showsVerticalScrollIndicator = NO;

    self.firstGradeTableView.tableFooterView = [[UIView alloc] init];

    [self.firstGradeTableView addFooterTarget:self action:@selector(loadMoreShops)];

    [self.view addSubview:self.firstGradeTableView];

    //下拉刷新 同步购物车

    __weak typeof(self) weakSelf = self;

    [self.firstGradeTableView addPullToRefreshWithPullText:PullText pullTextColor:[UIColor blackColor] pullTextFont:DefaultTextFont refreshingText:RefreshingText refreshingTextColor:[UIColor blueColor] refreshingTextFont:DefaultTextFont1 action:^{

        [weakSelf loadShops];

    }];

    

    self.bottomAccountView = [[BottomAccountView alloc] initWithFrame:CGRectMake(0, ScreenHeight-50-49, ScreenWidth, bottom_height)];

    self.bottomAccountView.selectedBlock = ^(UIButton*sender){

        //tag=100 左边的全选button

        if(sender.tag == 100){

            if(weakSelf.isEditState){//编辑状态

                weakSelf.count = 0;

                for(SCMerchantModel *merchantModel in weakSelf.shopCartmodel.merchantModule){

                    for(SCDecreaseRuleModel *decreaseModel in merchantModel.goodsGroupingModule){

                        for(SCProductModel *productModel in decreaseModel.goodsList){

                            if(sender.selected){

                                weakSelf.count++;

                            }else{

                                weakSelf.count = 0;

                            }

                            productModel.isSelected = sender.selected;

                            [weakSelf.firstGradeTableView reloadData];

                            if(weakSelf.count == 0){

                                [weakSelf.editProductArray removeAllObjects];

                            }else{

                                

                                [weakSelf shopCartEditProductModel:productModel];

                                

                            }

                        }

                    }

                }

                

                [weakSelf resetBottomViewWithIsAllSelected:YES Count:weakSelf.count];

                

            }else{//非编辑状态

                //全选   全不选

                for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++)

                {

                    NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

                    //解档

                    ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

                    

                    shopCart.isSelected = @(sender.selected);

                    

                    data = [NSKeyedArchiver archivedDataWithRootObject:shopCart];

                    [APPDELEGATE.arrayShopCartPostParam replaceObjectAtIndex:i withObject:data];

                }

                weakSelf.isSync = NO;

                [weakSelf readyForCarDataFromHttp];

            }

            

        } else {//右边的结算button

            //编辑状态下删除

            if(weakSelf.isEditState){

                if(weakSelf.count == 0){

                    return;

                }

                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"确定删除这%@种商品吗",@(weakSelf.count)] delegate:weakSelf cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

                [alert show];

                

            }else{

                //非编辑状态下结算

                APPDELEGATE.loginVC.shouldBackVCType = 2;

                if (![Utility getAuth]) {

                    [APPDELEGATE goToCheckLogin];

                    

                    return;

                }

                [weakSelf buyAction:sender];

            }

        }

    };

    [self.view addSubview:self.bottomAccountView];

    

}

 

- (void)loadMoreShops

{

    

    [self.firstGradeTableView footerEndRefreshing];

    

}

#pragma mark=========创建“编辑按钮”==========

 

- (void)createEditBtn

{

    [self.titleBar.rightBtn setFrame:CGRectMake(ScreenWidth-60,IOS7?27:7, 60, 30)];

    [self.titleBar.rightBtn setBackgroundImage:nil forState:UIControlStateNormal];

    [self.titleBar.rightBtn setTitle:@"编辑" forState:UIControlStateNormal];

    [self.titleBar.rightBtn setTitle:@"完成" forState:UIControlStateSelected];

    [self.titleBar.rightBtn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];

    [self.titleBar.rightBtn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateSelected];

    self.titleBar.rightBtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];

}

 

#pragma mark=================购物车数据请求===================

 

- (void)readyForCarDataFromHttp

{

    self.isRequestMainGoods = NO;

    self.isEdit = NO;

    

    self.titleBar.rightBtn.hidden = YES;

    

    // 断网

    if(![NetworkCheck isConnect]){

        [self loadFailure];

        return;

    }

    

    //购物车为空

    if(APPDELEGATE.arrayShopCartPostParam.count == 0){

        self.isEmptyData = YES;

        

        self.titleBar.rightBtn.hidden = YES;

        self.firstGradeTableView.tableHeaderView = [[ShopCartTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1)];

        self.tableHeaderView = nil;

        [self.bottomAccountView resetEmptyView];

        [self resetBottomHidden:YES];

        [self loadSuccess];

        [self.firstGradeTableView reloadData];

        [self reloadDataSetTip];

        [APPDELEGATE.tabBarViewController setItemTip:@"" withIndex:3];

        if (![Utility getAuth]) {

            return;

        }

    }

    

    self.titleBar.rightBtn.hidden = NO;

    self.titleBar.rightBtn.selected = NO;

    

    

    NSString *auth = @"";

    NSNumber *userId = [Utility getUserID];

    auth = [Utility getUserAuth];

    

    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];

    NSMutableArray *productArray = [NSMutableArray arrayWithCapacity:0];

    NSMutableArray *selectedActivityArray = [NSMutableArray arrayWithCapacity:0];

    

    [MLGProgressView show];

    

    //遍历普通商品

    for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++) {

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

        

        NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

        //解档

        ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        

        [dict setValue:shopCart.goodsId forKey:@"goodsId"];

        [dict setValue:shopCart.goodsCount forKey:@"goodsCount"];

        [dict setValue:shopCart.goodsSkuId forKey:@"goodsSkuId"];

        [dict setValue:shopCart.salesId forKey:@"salesId"];

        [dict setValue:shopCart.goodsSourceType forKey:@"goodsSourceType"];

        [dict setValue:shopCart.operationTime forKey:@"operationTime"];

        [dict setValue:shopCart.isSelected forKey:@"isSelected"];

        [dict setValue:shopCart.pageSourceMark forKey:@"pageSourceMark"];

        

        [productArray addObject:dict];

    }

    //遍历失效商品

    for(int i = 0;i< APPDELEGATE.arrayInvalidParam.count;i++){

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

        

        NSData *data = APPDELEGATE.arrayInvalidParam[i];

        //解档

        ShopCart *invalidModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        

        [dict setValue:invalidModel.goodsId forKey:@"goodsId"];

        [dict setValue:invalidModel.goodsCount forKey:@"goodsCount"];

        [dict setValue:invalidModel.goodsSkuId forKey:@"goodsSkuId"];

        [dict setValue:@(0) forKey:@"salesId"];

        [dict setValue:invalidModel.goodsSourceType forKey:@"goodsSourceType"];

        [dict setValue:@"" forKey:@"operationTime"];

        [dict setValue:@(0) forKey:@"isSelected"];

        [dict setValue:@"" forKey:@"pageSourceMark"];

        

        [productArray addObject:dict];

        

    }

    //遍历换购商品

    for(int i = 0; i< APPDELEGATE.arrayActivityParam.count; i++){

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

        NSData *data = APPDELEGATE.arrayActivityParam[i];

        ActivityModel *acModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        

        [dict setValue:acModel.goodsId forKey:@"goodsId"];

        [dict setValue:acModel.goodsSkuId forKey:@"goodsSkuId"];

        [selectedActivityArray addObject:dict];

        

    }

    

    [params setObject:userId forKey:@"userId"];

    [params setObject:auth forKey:@"auth"];

    [params setObject:[NSNumber numberWithBool:self.isSync] forKey:@"IsSync"];//是否同步

    [params setObject:productArray forKey:@"products"];

    [params setObject:selectedActivityArray forKey:@"selectedActivityGoods"];

    NSString *shopCartStr = [Configuration sharedConfiguration].iPadcheckShoppingCart_url;

    

    TICK

    MLGHTTPRequestOperationManager *manager = [[MLGHTTPRequestOperationManager alloc] init];

    WS(weakSelf)

    [manager POST:shopCartStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

        TOCK

        [MLGProgressView hide];

        NSDictionary *msgDict = responseObject[@"msg"];

        NSString *code = [responseObject objectForKey:@"code"];

        

        NSLog(@"购物车数据:%@",responseObject);

        if (code.integerValue == 200) {

            self.shopCartmodel = [ShopCartModel objectWithKeyValues:msgDict];

            

            //同步得到的数据插入本地数据库

            [self updateGoodSourceType];

            //购物车为空

            if(APPDELEGATE.arrayShopCartPostParam.count == 0&&APPDELEGATE.arrayInvalidParam.count==0){

                self.isEmptyData = YES;

                

                self.titleBar.rightBtn.hidden = YES;

                self.firstGradeTableView.tableHeaderView = [[ShopCartTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1)];

                self.tableHeaderView = nil;

                [self.bottomAccountView resetEmptyView];

                [self resetBottomHidden:YES];

                [self loadSuccess];

                [self.firstGradeTableView reloadData];

                [self reloadDataSetTip];

                [APPDELEGATE.tabBarViewController setItemTip:@"" withIndex:3];

                return;

            }

            [self resetBottomHidden:NO];

            

            if(self.shopCartmodel.ifShowAlert == 1) {

                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:self.shopCartmodel.showAlertText message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

                [alertView show];

            }

            

            if(self.shopCartmodel.invalidProductList.count!=0){

                self.isHaveInvalidGoods = YES;

            }

            else{

                self.isHaveInvalidGoods = NO;

            }

            

            [self.activitySelectGoodsArray removeAllObjects];

            

            //更新本地换购商品的数据

            NSInteger num = 0;

            for(SCActivityGoodsModel *acModel in self.shopCartmodel.activityGoodsList){

                if(acModel.aIsSelected == 1){

                    num++;

                    [self.activitySelectGoodsArray addObject:acModel];

                }

            }

            

            [APPDELEGATE.arrayActivityParam removeAllObjects];

            

            for(SCActivityGoodsModel *model in self.activitySelectGoodsArray){

                ActivityModel *activityModel = [[ActivityModel alloc] init];

                activityModel.goodsId = @(model.aGoodsId);

                activityModel.goodsSkuId = @(model.aGoodsSkuId);

                activityModel.type = @(model.aType);

                NSData *data = [NSKeyedArchiver archivedDataWithRootObject:activityModel];

                [APPDELEGATE.arrayActivityParam addObject:data];

            }

            

            self.isEmptyData = NO;

            if (![Utility getAuth]){

                self.firstGradeTableView.tableHeaderView = [[ShopCartTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, scHeaderView_height)];

                //                self.tableHeaderView = nil;

            } else {

                if([self.shopCartmodel.firstOrderPrompt isEqualToString:@""]){

                    self.firstGradeTableView.tableHeaderView = [[ShopCartTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1)];

                    self.tableHeaderView = nil;

                }else{

                    self.firstGradeTableView.tableHeaderView = [[ShopCartTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, scHeaderView_height)];

                    

                    self.tableHeaderView = self.firstGradeTableView.tableHeaderView;

                    self.tableHeaderView.title = self.shopCartmodel.firstOrderPrompt;

                }

            }

            

            self.isEdit = NO;

            [self.firstGradeTableView reloadData];

            self.isRequestMainGoods = YES;

            self.bottomAccountView.shopCartModel = self.shopCartmodel;

            [self reloadDataSetTip];

            [self loadSuccess];

            

        }else{

            [self loadFailure];

        }

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self loadFailure];

        

        [MLGProgressView hide];

        

    }];

}

 

//为了防止最新的GoodSourceType与加入购物车时不一致从而导致商品无法删除无法编辑等问题

- (void)updateGoodSourceType

{

    [APPDELEGATE.arrayShopCartPostParam removeAllObjects];

    

    for(SCMerchantModel *merchantModel in self.shopCartmodel.merchantModule){

        for(SCDecreaseRuleModel *decreaseModel in merchantModel.goodsGroupingModule){

            for(SCProductModel *productModel in decreaseModel.goodsList){

                ShopCart *cart = [[ShopCart alloc] init];

                cart.salesId            = @(productModel.salesId);

                cart.goodsId            = @(productModel.goodsId);

                cart.goodsSkuId = @(productModel.goodsSkuId);

                cart.goodsCount         = @(productModel.goodsCount);

                cart.goodsSourceType    = @(productModel.serviceGoodsSourceType);

                cart.operationTime = productModel.operationTime;

                cart.pageSourceMark = productModel.pageSourceMark;

                cart.isSelected = @(productModel.isSelected);

                

                //归档

                NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cart];

                [APPDELEGATE.arrayShopCartPostParam addObject:data];

            }

        }

    }

    

    [APPDELEGATE.arrayInvalidParam removeAllObjects];

    

    for(SCInvalidProductModel *model in self.shopCartmodel.invalidProductList){

        InvalidModel *invalidModel = [[InvalidModel alloc] init];

        invalidModel.goodsId = @(model.invalidGoodsId);

        invalidModel.goodsSkuId = @(model.invalidGoodsSkuId);

        invalidModel.goodsCount = @(model.invalidGoodsCount);

        invalidModel.goodsSourceType = @(model.goodsSourceType);

        ShopCart *cart = [[ShopCart alloc] init];

        cart.goodsId = invalidModel.goodsId;

        cart.goodsSkuId = invalidModel.goodsSkuId;

        cart.goodsCount = invalidModel.goodsCount;

        cart.goodsSourceType = invalidModel.goodsSourceType;

        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cart];

        [APPDELEGATE.arrayInvalidParam addObject:data];

    }

}

 

 

#pragma mark==================商品推荐部分===================

- (void)prepareShopRecommendGoodsRequestData {

    if(self.moreGoodsArray.count != 0){

        self.isHaveRecommendData = YES;

        [self.firstGradeTableView setFooterHidden:NO];

        

    }else{

        self.isHaveRecommendData = NO;

        [self.firstGradeTableView setFooterHidden:YES];

    }

    

    

    NSString *idStr = @"";

    for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++) {

        NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

        //解档

        ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        if(![idStr isEqualToString:@""])

            idStr = [idStr stringByAppendingString:[NSString stringWithFormat:@",%@",shopCart.goodsId]];

        else

            idStr = [idStr stringByAppendingString:shopCart.goodsId.stringValue];

    }

    

    NSString *urlStr = [Configuration sharedConfiguration].shopRecommendGoods_231_url;

    NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];

    [postDic setObject:[Utility getUserID] forKey:@"userId"];

    [postDic setObject:[NSNumber numberWithInteger:self.start] forKey:@"start"];

    [postDic setObject:[NSNumber numberWithInteger:self.rows]  forKey:@"rows"];

    [postDic setObject:idStr forKey:@"goodsId"];

    

    MLGHTTPRequestOperationManager *manager = [[MLGHTTPRequestOperationManager alloc] init];

    [manager POST:urlStr parameters:postDic success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"ShopRecommendGoodsResponseObject=%@",responseObject);

        NSDictionary *msgDict = responseObject[@"msg"];

        NSString *code = [responseObject objectForKey:@"code"];

        if (code.integerValue == 200) {

            [self.shopRecommendGoodsModelArray removeAllObjects];

            self.shopRecommendGoodsModelArray = [ShopRecommendGoodsModel  objectArrayWithKeyValuesArray:msgDict[@"goodsList"]];

            [GCDQueue executeInMainQueue:^{

                if (self.start == 0 && self.shopRecommendGoodsModelArray.count <=50) {

                    [self.moreGoodsArray removeAllObjects];

                    [self.moreGoodsArray addObjectsFromArray:self.shopRecommendGoodsModelArray];

                    [self.firstGradeTableView setFooterHidden:NO];

                    self.firstGradeTableView.footerPullToRefreshText = @"本次探险结束!";

                }

                if(self.moreGoodsArray.count != 0){

                    self.isHaveRecommendData = YES;

                    [self.firstGradeTableView setFooterHidden:NO];

                    

                    if(self.isEmptyData){

                        [self.firstGradeTableView reloadData];

                    }else if (self.isRequestMainGoods){

                        [self.firstGradeTableView reloadData];

                    }

                    

                }else{

                    self.isHaveRecommendData = NO;

                    [self.firstGradeTableView setFooterHidden:YES];

                }

            }];

        } else if (code.integerValue == 411) { // 如果验签失败, 再获一次token

            [APPDELEGATE fetchAccessTokenRequest];

        } else {

        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        

    }];

}

 

// 商品推荐的Item的点击事件

- (void)clickHomePageDoubleGood:(MLGHomePageDoubleGoodsCell *)cell and:(NSInteger)index {

    ShopRecommendGoodsModel *dataModel = [cell.infoArray objectAtIndex:index];

    [[MLGGotoVCManager sharedInstance] gotoProductDetailVCWithGoodId:[NSNumber numberWithInteger:dataModel.goodsId] andStockId:[NSNumber numberWithInteger:0] andGoodsSourceType:[NSNumber numberWithInteger:0] andSalesId:[NSNumber numberWithInteger:0] andPageSourceMark:App_Cart_GuessYouLike  isFilterSkuStock:[NSNumber numberWithInteger:1]];

}

 

- (void)setShopRecommendGoodsModelArray:(NSMutableArray *)shopRecommendGoodsModelArray {

    _shopRecommendGoodsModelArray = shopRecommendGoodsModelArray;

    if (shopRecommendGoodsModelArray.count == 0) return;

}

 

- (NSInteger)getNumberOfRows {

    if (self.moreGoodsArray.count > 0) {

        NSInteger totalCount = self.moreGoodsArray.count;

        NSInteger rowcount   = (totalCount - 1)/2 + 1;

        return rowcount;

    }

    return 0;

}

 

 

#pragma mark==================tableViewDelegate===================

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    NSInteger num=0;

    if(self.isEmptyData && self.isHaveRecommendData)

        return 2;

    else if (self.isEmptyData && !self.isHaveRecommendData)

        return 1;

    else{

        if(self.shopCartmodel.activityGoodsList.count!=0)

            num++;

        if(self.shopCartmodel.invalidProductList.count!=0)

            num++;

        if(self.isEditState || !self.isHaveRecommendData){

            

            return self.shopCartmodel.merchantModule.count+num;

            

        }else

            

            return self.shopCartmodel.merchantModule.count+num+1;

    }

    

}

 

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{

    __weak typeof(self) weakSelf = self;

    if (section == tableView.numberOfSections-1 && !self.isEditState && self.isHaveRecommendData){//如果是最后一个section,且非编辑状态,切含有推荐商品

        UILabel *sectionView = [[UILabel alloc] init];

        sectionView.backgroundColor = [UIColor whiteColor];

        if(self.isEmptyData){ //如果购物车数据为空,则显示“看看热卖”,否则显示“你可能还想要"

            

            sectionView.text = @"看看热卖";

            

        }else

        {

            sectionView.text = @"你可能还想要";

        }

        

        sectionView.textAlignment = NSTextAlignmentCenter;

        return sectionView;

    }else{

        if(self.isEmptyData){//购物车为空显示去逛逛

            if (![Utility getAuth]) {

                self.firstGradeTableView.tableHeaderView = [[ShopCartTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, scHeaderView_height)];

                

                self.tableHeaderView = self.firstGradeTableView.tableHeaderView;

            }

            

            ShopCartNoDataView *empatyView = [[ShopCartNoDataView alloc] init];

            //empatyView.clickedGoAroundButtonFromType = _shopCartVCPushFromType ;

            return empatyView;

        }else{

            if(self.shopCartmodel.merchantModule.count!=0){

                if(section<self.shopCartmodel.merchantModule.count){

                    self.merchantView = [[MerchantView alloc] init];

                    self.merchantView.merchantModel = self.shopCartmodel.merchantModule[section];

                    SCMerchantModel *merchantModel = self.shopCartmodel.merchantModule[section];

                    

                    self.merchantView.nextBtnSelectBlock = ^(UIButton *sender){

                        if(!weakSelf.isEdit){

                            [[MLGGotoVCManager sharedInstance] gotoHTML5VCWithURLString:merchantModel.gatherGoodsUrl andNavTitle:@"凑单"];

                        }

                    };

                    //全选一组

                    self.merchantView.chooseBtnSelectBlock = ^(UIButton *sender){

                        for(SCDecreaseRuleModel *decreaseModel in merchantModel.goodsGroupingModule){

                            

                            if(weakSelf.isEditState){

                                

                                if(sender.selected){

                                    weakSelf.count = weakSelf.count+decreaseModel.goodsList.count;

                                    for(SCProductModel *productModel in decreaseModel.goodsList){

                                        if(productModel.isSelected==1)

                                            

                                            weakSelf.count--;

                                    }

                                    

                                }

                                

                                else

                                    weakSelf.count = weakSelf.count-decreaseModel.goodsList.count;

                                for(SCProductModel *productModel in decreaseModel.goodsList){

                                    productModel.isSelected = sender.selected;

                                    if(weakSelf.count == 0){

                                        [weakSelf.editProductArray removeAllObjects];

                                    }else{

                                        [weakSelf shopCartEditProductModel:productModel];

                                    }

                                    [weakSelf.firstGradeTableView reloadData];

                                }

                                

                                [weakSelf resetBottomViewWithIsAllSelected:[weakSelf panEditStateIsAllSelected] Count:weakSelf.count];

                            }else{

                                for(SCProductModel *productModel in decreaseModel.goodsList){

                                    productModel.isSelected = sender.selected;

                                    

                                    for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++)

                                    {

                                        NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

                                        //解档

                                        ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

                                        if (shopCart.goodsId.intValue == productModel.goodsId && shopCart.goodsSkuId.intValue == productModel.goodsSkuId && shopCart.goodsSourceType.intValue == productModel.serviceGoodsSourceType) {

                                            

                                            shopCart.salesId = @(productModel.salesId);

                                            shopCart.goodsId = @(productModel.goodsId);

                                            shopCart.goodsSkuId = @(productModel.goodsSkuId);

                                            shopCart.goodsCount = @(productModel.goodsCount);

                                            shopCart.goodsSourceType = @(productModel.serviceGoodsSourceType);

                                            shopCart.isSelected = @(productModel.isSelected);

                                            

                                            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:shopCart];

                                            [APPDELEGATE.arrayShopCartPostParam replaceObjectAtIndex:i withObject:data];

                                        }

                                    }

                                    

                                }

                                

                            }

                            

                        }

                        if(!weakSelf.isEditState){

                            weakSelf.isSync = NO;

                            [weakSelf readyForCarDataFromHttp];

                        }

                    };

                    

                    self.isSelectMerchatView = YES;

                    for(SCDecreaseRuleModel *decreaseModel in merchantModel.goodsGroupingModule){

                        for(SCProductModel *productModel in decreaseModel.goodsList){

                            

                            if(productModel.isSelected==0){

                                self.isSelectMerchatView = NO;

                            }

                        }

                    }

                    [self.merchantView setChooseBtnState:self.isSelectMerchatView];

                    

                    return self.merchantView;

                }

            }

            if(self.shopCartmodel.invalidProductList.count!=0){

                if(section == self.shopCartmodel.merchantModule.count){

                    return [[UIView alloc] init];

                }

            }

            if(self.shopCartmodel.activityGoodsList.count!=0){

                if(section == self.shopCartmodel.merchantModule.count + self.isHaveInvalidGoods?1:0){

                    ActivityTypeView *activityView = [[ActivityTypeView alloc] init];

                    [activityView activityView];

                    activityView.ExchangeShopBlock = ^(UIButton *sender){

                        if(!weakSelf.isEdit){

                            SCExchangeShopViewController *vc = [[SCExchangeShopViewController alloc] initWithDataArray:self.shopCartmodel.activityGoodsList];

                            [APPDELEGATE.navigationController pushViewController:vc animated:YES];

                        }

                    };

                    

                    return activityView;

                }

            }

            

        }

        

    }

    return [[UIView alloc]init];

}

 

 

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

{

    UIView *sectionFooderView = [[UIView alloc] init];

    sectionFooderView.backgroundColor = RGBCOLOR(235, 235, 235);

    return sectionFooderView;

}

 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    if(section == tableView.numberOfSections-1 && !self.isEditState && self.isHaveRecommendData)

        return 40;

    else{

        if(self.isEmptyData)

            return ScreenWidth*0.966;

        else{

            if(self.shopCartmodel.merchantModule.count!=0){

                if(section<self.shopCartmodel.merchantModule.count){

                    

                    return merchant_merchantView_height+activity_viewHeight;

                }

            }

            if(self.shopCartmodel.invalidProductList.count!=0){

                if(section == self.shopCartmodel.merchantModule.count){

                    return 0.1;

                }

            }

            if(self.shopCartmodel.activityGoodsList.count!=0){

                if(section == self.shopCartmodel.merchantModule.count + self.isHaveInvalidGoods?1:0){

                    return activity_viewHeight;

                }

            }

            return 0.1;

        }

    }

}

 

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

{

    return shopCart_fooderHeight;

}

 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    if(indexPath.section == tableView.numberOfSections-1 && !self.isEditState && self.isHaveRecommendData)

        return MLGLayoutHeight(215);

    else{

        if(self.shopCartmodel.merchantModule.count!=0){

            if(indexPath.section<self.shopCartmodel.merchantModule.count){

                MLGShopCarTableViewCell *cell = [[MLGShopCarTableViewCell alloc] initWithMerchantModel:self.shopCartmodel.merchantModule[indexPath.section]];

                NSLog(@"cellheight == %d",[cell getCellHeight]);

                return [cell getCellHeight];

            }

        }

        if(self.shopCartmodel.invalidProductList.count!=0){

            if(indexPath.section == self.shopCartmodel.merchantModule.count){

                MLGShopCarTableViewCell *cell = [[MLGShopCarTableViewCell alloc] initWithShopCartModel:self.shopCartmodel];

                NSLog(@"cellheight == %d",[cell getCellHeight]);

                return [cell getCellHeight];

            }

        }

        if(self.shopCartmodel.activityGoodsList.count!=0){

            if(indexPath.section == self.shopCartmodel.merchantModule.count + self.isHaveInvalidGoods?1:0){

                return product_viewHeight;

            }

        }

        return 0;

    }

    

}

 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    

    if(section == tableView.numberOfSections-1 && !self.isEditState && self.isHaveRecommendData)

        return [self getNumberOfRows];

    else{

        if(self.isEmptyData)

            return 0;

        else{

            if(self.shopCartmodel.merchantModule.count!=0){

                if(section<self.shopCartmodel.merchantModule.count){

                    return 1;

                }

            }

            if(self.shopCartmodel.invalidProductList.count!=0){

                if(section == self.shopCartmodel.merchantModule.count){

                    return 1;

                }

            }

            if(self.shopCartmodel.activityGoodsList.count!=0){

                if(section == self.shopCartmodel.merchantModule.count + self.isHaveInvalidGoods?1:0){

                    return self.activitySelectGoodsArray.count;

                }

            }

            return 0;

        }

    }

}

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    if(indexPath.section == tableView.numberOfSections - 1 && !self.isEditState && self.isHaveRecommendData){//推荐商品,暂时不做

        static NSString *cellID = @"ShopRecommendGoodsCell";

        

        MLGHomePageDoubleGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

        if (cell == nil) {

            cell = [[MLGHomePageDoubleGoodsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];

            cell.selectionStyle  = UITableViewCellSelectionStyleNone;

            

        }

        cell.delegate = self;

        cell.row = indexPath.row;

        cell.backgroundColor = [UIColor whiteColor];

        cell.separatorInset = UIEdgeInsetsMake(0, 750, 0, 0);

        

        NSInteger remainCount = [self.moreGoodsArray count] - indexPath.row * 2;

        if(remainCount > 0){

            if (remainCount > 2) {

                cell.infoArray = [self.moreGoodsArray subarrayWithRange:NSMakeRange(indexPath.row * 2, 2)];

            }else{

                cell.infoArray = [self.moreGoodsArray subarrayWithRange:NSMakeRange(indexPath.row * 2, remainCount)];

            }

        }

        [cell initFun];

        return cell;

        

    } else {

        if(self.shopCartmodel.merchantModule.count!=0){//商家对象集合个数

            if(indexPath.section<self.shopCartmodel.merchantModule.count){

                MLGShopCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];

                if(cell == nil){

                    cell = [[MLGShopCarTableViewCell alloc] initWithMerchantModel:self.shopCartmodel.merchantModule[indexPath.section]];

                    

                    [cell setTarget:self action:@selector(buttonClicked:)];

                    cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);

                    cell.backgroundColor = [UIColor redColor];

                }

                return cell;

            }

        }

        if(self.shopCartmodel.invalidProductList.count != 0){

            if(indexPath.section == self.shopCartmodel.merchantModule.count){

                

                MLGShopCarTableViewCell *cell = [[MLGShopCarTableViewCell alloc] initWithShopCartModel:self.shopCartmodel];

                

                [cell setTarget:self action:@selector(buttonClicked:)];

                cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);

                return cell;

            }

        }

        if(self.shopCartmodel.activityGoodsList.count!=0){

            if(indexPath.section == self.shopCartmodel.merchantModule.count + self.isHaveInvalidGoods?1:0){

                

                if(self.activitySelectGoodsArray.count != 0 && indexPath.row < self.activitySelectGoodsArray.count) {

                    SCActivityGoodsModel *acModel = self.activitySelectGoodsArray[indexPath.row];

                    

                    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];

                    if (cell == nil) {

                        cell = [[ProductTableViewCell alloc] init];

                    }

                    cell.selectionStyle = UITableViewCellSelectionStyleNone;

                    cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);

                    cell.activityModel = acModel;

                    return cell;

                } else {

                    SCActivityGoodsModel *activitymodel = self.shopCartmodel.activityGoodsList[0];

                    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];

                    if (cell == nil) {

                        cell = [[ProductTableViewCell alloc] init];

                        if(self.isEditState){

                        }

                        cell.selectionStyle = UITableViewCellSelectionStyleNone;

                        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);

                        cell.activityModel = activitymodel;

                        return cell;

                        

                    }

                }

            }

        }

    }

    return [[UITableViewCell alloc]init];

    

}

 

//解决当商品推荐为单数时点击空白处会崩溃bug

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

{

    if(indexPath.section == tableView.numberOfSections - 1 && !self.isEditState && self.isHaveRecommendData)

    {

        

    }else{

        if(!self.isEdit){

            SCActivityGoodsModel *activityModel = self.activitySelectGoodsArray[indexPath.row];

            [[MLGGotoVCManager sharedInstance] gotoProductDetailVCWithGoodId:@(activityModel.aGoodsId) andStockId:@(activityModel.aGoodsSkuId) andGoodsSourceType:@(0) andSalesId:@(0) andPageSourceMark:App_ShoppingCart isFilterSkuStock:[NSNumber numberWithInteger:0]];

        }

        

    }

}

 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{

    return NO;

}

 

#pragma mark --点击事件--

- (void)buttonClicked:(NSDictionary*)dict

{

    NSNumber *selectNum = dict[@"params"];

    for(UIView *view in self.firstGradeTableView.subviews){

        if([view isKindOfClass:[MerchantView class]]){

            self.merchantView = view;

            self.merchantView.chooseButton.selected = selectNum.boolValue;

        }

    }

    

}

#pragma  mark 右键  编辑/完成

- (void)rightBtnClick:(UIButton *)sender

{

    sender.selected = !sender.selected;

    self.isEdit = sender.selected;

    if(self.isEditState){

        [self.bottomAccountView resetStateWithIsAllSelected:NO andDeleteCount:0];

    }

    __weak typeof(self) weakSelf = self;

    if(self.isEditState){

        for(SCMerchantModel *merchantModel in weakSelf.shopCartmodel.merchantModule){

            for(SCDecreaseRuleModel *decreaseModel in merchantModel.goodsGroupingModule){

                for(SCProductModel *productModel in decreaseModel.goodsList){

                    productModel.isSelected = 0;

                    [weakSelf.firstGradeTableView reloadData];

                }

            }

        }

        [weakSelf.firstGradeTableView setFooterHidden:YES];

    }

    

    if(!sender.selected){

        self.isSync = NO;

        [self readyForCarDataFromHttp];

        self.start = 0;

        [self prepareShopRecommendGoodsRequestData];

    }

    self.count = 0;

}

 

#pragma mark 更改删除商品同步购物车的请求

- (void)modificatSyncShopCartData:(NSMutableArray *)products :(BOOL)isDelete

{

    //登录状态才去同步数据

    if ([Utility getAuth]) {

        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];

        NSMutableArray *productArray = [NSMutableArray arrayWithCapacity:0];

        

        for(ShopCart *model in products){

            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

            

            [dict setValue:model.goodsId forKey:@"goodsId"];

            [dict setValue:isDelete?[NSNumber numberWithInt:0]:model.goodsCount forKey:@"goodsCount"];

            [dict setValue:model.goodsSkuId forKey:@"goodsSkuId"];

            [dict setValue:model.goodsSourceType forKey:@"goodsSourceType"];

            [productArray addObject:dict];

        }

        

        

        

        NSNumber *userId = [Utility getUserID];

        [params setValue:userId forKey:@"userId"];

        [params setValue:productArray forKey:@"products"];

        

        NSString *urlStr = [Configuration sharedConfiguration].iPadShoppingCartChange_url;

        

        MLGHTTPRequestOperationManager *manager = [[MLGHTTPRequestOperationManager alloc] init];

        [manager POST:urlStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSLog(@"更改删除同步返回=%@",responseObject);

            NSDictionary *msgDict = responseObject[@"msg"];

            NSString *code = [responseObject objectForKey:@"code"];

            if (code.integerValue == 200) {

            } else if (code.integerValue == 411) { // 如果验签失败, 再获一次token

                [APPDELEGATE fetchAccessTokenRequest];

            } else {

            }

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            

        }];

        

    }

    

}

 

 

#pragma mark 左滑手势删除单个商品

- (void)shopCartDeleteWithProductModel:(id)model

{

    NSMutableArray *deleteArr = [NSMutableArray array];

    if([model isKindOfClass:[SCProductModel class]]){

        

        SCProductModel *productModel = model;

        

        for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++)

        {

            NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

            //解档

            ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

            

            if (shopCart.goodsId.integerValue == productModel.goodsId && shopCart.goodsSkuId.integerValue == productModel.goodsSkuId && shopCart.goodsSourceType.integerValue == productModel.serviceGoodsSourceType) {

                [APPDELEGATE.arrayShopCartPostParam removeObjectAtIndex:i];

                [deleteArr addObject:shopCart];

                [self modificatSyncShopCartData:deleteArr :YES];

                

            }

        }

    }

    else if ([model isKindOfClass:[SCInvalidProductModel class]]){

        SCInvalidProductModel *invalidproductModel = model;

        

        for (int i = 0; i < APPDELEGATE.arrayInvalidParam.count; i++)

        {

            NSData *data = APPDELEGATE.arrayInvalidParam[i];

            //解档

            ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

            if (shopCart.goodsId.integerValue == invalidproductModel.invalidGoodsId && shopCart.goodsSkuId.integerValue == invalidproductModel.invalidGoodsSkuId) {

                [APPDELEGATE.arrayInvalidParam removeObjectAtIndex:i];

                [deleteArr addObject:shopCart];

                [self modificatSyncShopCartData:deleteArr :YES];

                

            }

            

        }

        

        for(int i = 0; i < APPDELEGATE.arrayActivityParam.count; i++){

            NSData *data = APPDELEGATE.arrayActivityParam[i];

            ActivityModel *acModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];

            if(acModel.goodsId.integerValue == invalidproductModel.invalidGoodsId && acModel.goodsSkuId.integerValue == invalidproductModel.invalidGoodsSkuId){

                [APPDELEGATE.arrayActivityParam removeObjectAtIndex:i];

            }

        }

        

    }

#warning 同步接口通了之后打开

    self.isSync = NO;

    [self readyForCarDataFromHttp];

}

 

#pragma mark 清空失效商品

- (void)shopCartCleanInvalidProducts

{

    NSMutableArray *deleteArr = [NSMutableArray array];

    for(SCInvalidProductModel *invalidproductModel in self.shopCartmodel.invalidProductList){

        

        for (int i = 0; i < APPDELEGATE.arrayInvalidParam.count; i++)

        {

            NSData *data = APPDELEGATE.arrayInvalidParam[i];

            //解档

            ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

            

            if (shopCart.goodsId.integerValue == invalidproductModel.invalidGoodsId && shopCart.goodsSkuId.integerValue == invalidproductModel.invalidGoodsSkuId) {

                [deleteArr addObject:shopCart];

                [APPDELEGATE.arrayInvalidParam removeObjectAtIndex:i];

            }

        }

        

        for(int i = 0; i < APPDELEGATE.arrayActivityParam.count; i++){

            NSData *data = APPDELEGATE.arrayActivityParam[i];

            ActivityModel *acModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];

            if(acModel.goodsId.integerValue == invalidproductModel.invalidGoodsId && acModel.goodsSkuId.integerValue == invalidproductModel.invalidGoodsSkuId){

                [APPDELEGATE.arrayActivityParam removeObjectAtIndex:i];

            }

        }

    }

#warning 接口通了 打开

    [self modificatSyncShopCartData:deleteArr :YES];

    self.isSync = NO;

    [self readyForCarDataFromHttp];

}

 

//勾选复选按钮时改变商品缓存是否选中状态

- (void)shopCartSelectedProductModel:(id)model

{

    if([model isKindOfClass:[SCProductModel class]]){

        SCProductModel *productModel = model;

        for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++) {

            NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

            //解档

            ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

            if (shopCart.goodsId.intValue == productModel.goodsId && shopCart.goodsSkuId.intValue == productModel.goodsSkuId && shopCart.goodsSourceType.intValue == productModel.serviceGoodsSourceType) {

                

                shopCart.isSelected = @(productModel.isSelected);

                

                NSData *data = [NSKeyedArchiver archivedDataWithRootObject:shopCart];

                [APPDELEGATE.arrayShopCartPostParam replaceObjectAtIndex:i withObject:data];

            }

        }

    }

    

    if(!self.isEdit){

        self.isSync = NO;

        [self readyForCarDataFromHttp];

    }

}

 

#pragma mark 编辑状态时所选择的商品

- (void)shopCartEditProductModel:(id)model {

    if([model isKindOfClass:[SCProductModel class]]){

        BOOL isExist = NO;

        SCProductModel *productModel = model;

        for (int i = 0; i < self.editProductArray.count; i++) {

            

            SCProductModel *proModel = self.editProductArray[i];

            

            if (productModel.goodsId == proModel.goodsId &&

                productModel.goodsSkuId == proModel.goodsSkuId && productModel.serviceGoodsSourceType == proModel.serviceGoodsSourceType

                ) {

                if(productModel.isSelected == 1){

                    if(proModel.isSelected==1) [self.editProductArray removeObject:proModel];

                    [self.editProductArray addObject:productModel];

                }else{

                    [self.editProductArray removeObject:productModel];

                }

                

                isExist = YES;

            }

        }

        if(!isExist){

            if(productModel.isSelected==1)

                [self.editProductArray addObject:productModel];

        }

    }

    

}

 

//方便外部判断主控制器是不是编辑状态

- (BOOL)isEditState

{

    return self.isEdit;

}

 

//重置购物车底部按钮状态以及删除数量

- (void)resetBottomViewWithIsAllSelected:(BOOL)isAllSelected Count:(NSInteger)count

{

    [self.firstGradeTableView reloadData];

    [self.bottomAccountView resetStateWithIsAllSelected:isAllSelected andDeleteCount:count];

}

 

//编辑时删除几项商品

- (NSInteger)addCountWithAdd:(BOOL)add

{

    if(add)

        self.count++;

    else

        self.count--;

    return self.count;

}

 

//判断有没有全选

- (BOOL)panEditStateIsAllSelected {

    BOOL isAllSelected = YES;

    for(SCMerchantModel *merchantModel in self.shopCartmodel.merchantModule){

        for(SCDecreaseRuleModel *decreaseModel in merchantModel.goodsGroupingModule){

            for(SCProductModel *productModel in decreaseModel.goodsList){

                if(productModel.isSelected==0){

                    isAllSelected = NO;

                }

            }

        }

    }

    return isAllSelected;

}

 

#pragma mark 编辑时确定删除提示

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    if(buttonIndex == 1){

        // 先批量删除本地的数据

        NSMutableArray *deleteArr = [NSMutableArray array];

        for(SCProductModel *productModel in self.editProductArray){

            for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++) {

                NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

                // 解档

                ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

                NSLog(@"%d %d %d %d %d %d",shopCart.goodsId.intValue,shopCart.goodsSkuId.intValue,shopCart.goodsSourceType.intValue,productModel.goodsId,productModel.goodsSkuId,productModel.serviceGoodsSourceType);

                if (shopCart.goodsId.intValue == productModel.goodsId && shopCart.goodsSkuId.intValue == productModel.goodsSkuId && shopCart.goodsSourceType.intValue == productModel.serviceGoodsSourceType) {

                    [APPDELEGATE.arrayShopCartPostParam removeObjectAtIndex:i];

                    [deleteArr addObject:shopCart];

                }

            }

        }

        self.titleBar.rightBtn.selected = NO;

        //判断是否需要同步

        [self modificatSyncShopCartData:deleteArr :YES];

        self.isSync = NO;

        [self readyForCarDataFromHttp];

        self.start = 0;

        [self prepareShopRecommendGoodsRequestData];

    }

}

 

#pragma mark 数量选择器点击事件

- (void)shopCartWithCountStepper:(NSInteger)count withCell:(ProductTableViewCell *)cell withGoodsSourceType:(NSNumber *)_goodsSourceType withIndexPath:(NSIndexPath *)path withGoodId:(NSNumber *)goodId withGoodStockId:(NSNumber *)goodStockId withGoodSourceType:(NSNumber *)goodSourceType

{

    if (self.isEdit) {

        self.isModifi = YES;

    }

    self.proCell = cell;

    float currentGoodsCount = cell.tfStepper.Current;

    

    for (int i = 0; i < APPDELEGATE.arrayShopCartPostParam.count; i++)

    {

        NSData *data = APPDELEGATE.arrayShopCartPostParam[i];

        //解档

        ShopCart *shopCart = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        if (shopCart.goodsId.integerValue == goodId.integerValue && shopCart.goodsSkuId.integerValue == goodStockId.integerValue && shopCart.goodsSourceType.integerValue == goodSourceType.integerValue)

        {

            shopCart.goodsCount = [NSNumber numberWithFloat:currentGoodsCount];

            //归档

            NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:shopCart];

            [APPDELEGATE.arrayShopCartPostParam replaceObjectAtIndex:i withObject:data1];

            

            //修改商品数量的时候同步

            NSArray *addProductArr = [NSArray arrayWithObject:shopCart];

            [self modificatSyncShopCartData:addProductArr :NO];

        }

    }

    

    if(!self.isEdit){

        self.isSync = NO;

        [self readyForCarDataFromHttp];

    }

}

 

#pragma mark-- 滚动代理,隐藏返回顶部按钮

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    _btnScrollTop.hidden = YES;

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

}

 

@end

 

posted @ 2015-12-10 20:52  Emyin  阅读(178)  评论(0编辑  收藏  举报