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

#import "ShoppingViewController.h"
#import "ShoppingTableViewCell.h"
#import "AppDelegate.h"
#import "GenerateOrdersViewController.h"
#import "ShopcarModel.h"
#import "AddressModel.h"
#import "ProductDetailsViewController.h"

@interface ShoppingViewController ()<UITableViewDelegate,UITableViewDataSource,ChangeGoodsNumberDelegate,UITextFieldDelegate>

/**
 *  购物车数据源
 */
@property (nonatomic,strong) NSMutableArray *shopResponseArray;

/**
 *  折扣比例输入
 */
@property (nonatomic,strong) UITextField *textField;


@end

@implementation ShoppingViewController


/**
 *  数据源
 */
- (NSMutableArray *)shopResponseArray
{
    if (_shopResponseArray == nil) {
        _shopResponseArray = [NSMutableArray array];
    }
    return _shopResponseArray;
}

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

#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    [self.shopResponseArray removeAllObjects];
    [self initializeState];
    [self queryShoppingCarNumber];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

#pragma mark -初始化状态
- (void)initializeState
{
    [self.settlementButton setTitle:@"去结算(0)" forState:UIControlStateNormal];
    self.allSelectedButton.selected = NO;
    self.totalpriceLabe.text = nil;
    self.discountTextField.text = nil;
}

#pragma mark - UI
- (void)uiConfigAction
{
    self.settlementButton.layer.masksToBounds = YES;
    self.settlementButton.layer.cornerRadius = kCornerRadius;
    self.view.backgroundColor = RGB(238, 238, 238,1);
    self.discountTextField.delegate = self;
}

#pragma mark -获取数据
- (void)loadWebDataSource
{
    WS(weakSelf);
    if (self.pullPageIndex == ONE) {
        [self.shopResponseArray removeAllObjects];
    }
    [self getShoppingCardataCompleted:^(ShopCartResponse *result) {
        if (weakSelf.pullPageIndex >= result.totalpages) {
            [weakSelf endRefresh:EndRefreshNotData];
        }else {
            [weakSelf endRefresh:EndRefreshDefault];
        }
    }];
}


#pragma mark -获取购物车商品
- (void)getShoppingCardataCompleted:(void(^)(ShopCartResponse *result))completed
{
    //判断是否需要请求数据-通过当前客户ID
    if (![Shoppersmanager manager].currentCustomer) {
        return;
    }
    ShopCartFilter *shopcarNumber = [[ShopCartFilter alloc]init];
    shopcarNumber.consumerId = [Customermanager manager].model.consumer.fid;
    DataPage *Newpage = [[DataPage alloc]init];
    Newpage.page = ONE;
    Newpage.rows = 99999;
    shopcarNumber.dp = Newpage;
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(SHOPPINGBAG) withRequestType:ZERO withParameter:shopcarNumber withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            ShopCartResponse *shopcar = [[ShopCartResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            completed(shopcar);
            for (TOShopcartEntity *objc in shopcar.shopcart) {
                ShopcarModel *model = [[ShopcarModel alloc]initWithDictionary:[objc toDictionary] error:nil];
                [weakSelf.shopResponseArray addObject:model];
            }
            [weakSelf initializeState];
            [weakSelf.tableView reloadData];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    } withFailureBlock:^(NSError *error) {
        [weakSelf endRefresh:EndRefreshDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark -<UITextFieldDelegate>
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (![textField isEqual:self.discountTextField]) {
        return YES;
    }
    if (self.shopResponseArray.count == 0) {
        [XBLoadingView showHUDViewWithText:@"请先添加商品到购物车"];return NO;
    }
    NSMutableArray *array = [NSMutableArray array];
    for (ShopcarModel *model in self.shopResponseArray) {
        if (model.isSelected) {
            [array addObject:model];
        }
    }
    if (array.count == 0) {
        [XBLoadingView showHUDViewWithText:@"没有选中任何商品"];return NO;
    }
    [self inputDiscountNumber];
    return NO;
}

#pragma mark - 输入折扣金额
- (void)inputDiscountNumber
{
    WS(weakSelf);
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入折扣比例(%)" preferredStyle:UIAlertControllerStyleAlert];
    [alertControl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        weakSelf.textField.text = nil;
         [weakSelf textFieldEndEditing];
    }]];
    [alertControl addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        weakSelf.textField = textField;
        textField.placeholder = @"请输入";
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.delegate = self;
    }];
    [alertControl addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf textFieldEndEditing];
    }]];
    [self presentViewController:alertControl animated:YES completion:nil];
}

#pragma mark - 结束编辑
- (void)textFieldEndEditing
{
    if ([BaseViewController isBlankString:self.textField.text]) {
        return;
    }
    Shoppersmanager *user = [Shoppersmanager manager];
    if ([self.textField.text integerValue] < [user.shoppers.lowestDiscount integerValue] && ![[self class] isBlankString:self.textField.text])
    {
        [XBLoadingView showHUDViewWithText:@"当前价格低于你的价格权限!"];
        self.textField.text = nil;
    }else {
        self.discountTextField.text = self.textField.text;
        [self unifiedChangeDiscount:self.textField.text];
    }
}

#pragma mark - 输入折扣比例
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return [self validateNumber:string];
}

#pragma mark - 判断输入是否有效<两位整数、第一位不能为0>
- (BOOL)validateNumber:(NSString*)number
{
    BOOL res = YES;
    if ([number isEqualToString:@""]) {
        return YES;
    }
    if (self.textField.text.length == 2) {
        return NO;
    }
    if([[self class] isBlankString:self.textField.text] && [number isEqualToString:@"0"])
    {
        if([number isEqualToString:@"0"]){
            return NO;
        }
    }
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

#pragma mark - 统一修改折扣率
- (void)unifiedChangeDiscount:(NSString *)discount
{
    WS(weakSelf);
    NSDecimalNumber *discountNumber = [NSDecimalNumber decimalNumberWithString:discount];
    NSDecimalNumber *number = [discountNumber decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"100"]];
    for (ShopcarModel *model in self.shopResponseArray) {
        if (model.isSelected) {
            NSNumber *constPrice = model.goods.tagPrice;
            model.costPrice = [number decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:[constPrice stringValue]]];
        }
    }
    //** boolValue为false表示修改失败 */
    [self modifyMultipleGoodsNnumberOrPrice:self.shopResponseArray completeModify:^(BOOL boolValue) {
        if (!boolValue) {
            for (ShopcarModel *model in weakSelf.shopResponseArray) {
                if (model.isSelected) {
                    model.costPrice = model.goods.tagPrice;
                    model.goodsNum = 1;
                }
            }
        }
        [weakSelf.tableView reloadData];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Shopping" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = [self.shopResponseArray objectAtIndex_opple:indexPath.row];
    cell.delegate = self;
    cell.cellindex = indexPath.row;
    //cell选中回调
    __weak typeof(cell) weakCell = cell;
    WS(weakSelf);
    [cell setReturnCellblock:^(NSInteger index) {
        [weakSelf setSelectedButton:index];
    }];
    //提示框回调
    [cell setPromptStringBlock:^(NSString *string) {
        [XBLoadingView showHUDViewWithText:string];
        [weakCell.clinchTextfield becomeFirstResponder];
    }];
    return  cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shopResponseArray.count;
}


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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductDetailsViewController *productDetails = [ProductDetailsViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    productDetails.goodsID = [[self.shopResponseArray objectAtIndex_opple:indexPath.row] goodsId];
    [self pushViewController:productDetails animated:YES];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -选中商品回调
- (void)setSelectedButton:(NSInteger)index;
{
    ShopcarModel *model = [self.shopResponseArray objectAtIndex_opple:index];
    model.isSelected = !model.isSelected;
    
    NSInteger goodsNumber = 0;
    for (ShopcarModel *model in self.shopResponseArray) {
        if (model.isSelected) {
            goodsNumber ++;
        }
    }
    if (goodsNumber == self.shopResponseArray.count) {
        self.allSelectedButton.selected = YES;
    }else
    {
        self.allSelectedButton.selected = NO;
    }
    [self CalculateSelectedGoodsAllprice];
    [self.settlementButton setTitle:[NSString stringWithFormat:@"去结算(%ld)",goodsNumber] forState:UIControlStateNormal];
}


#pragma mark -结算
- (IBAction)settlementButtonClick:(UIButton *)sender {
    
    NSMutableArray *array = [NSMutableArray array];
    for (ShopcarModel *model in self.shopResponseArray) {
        if (model.isSelected) {
            [array addObject:model];
        }
    }
    if (array.count == 0) {
        
        [XBLoadingView showHUDViewWithText:@"没有选中任何商品"];
        return;
    }
    //商品总信息占位
     ShopcarModel*zhanweiModel = [[ShopcarModel alloc]init];
    [array addObject:zhanweiModel];
    GenerateOrdersViewController *generateOrder = [GenerateOrdersViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    generateOrder.settlementGoodsdatas = array;
    //清除已经生成订单的商品
    [generateOrder setDelecteSelectedGoods:^(NSArray *goodsCode) {
        
        DeleteCartRequest *delecteGoods = [[DeleteCartRequest alloc]init];
        delecteGoods.cartIds = goodsCode;
        WS(weakSelf);
        [HTTP networkRequestWithURL:SERVERREQUESTURL(REMOVESHOPPINGBAG)  withRequestType:ZERO withParameter:delecteGoods withReturnValueBlock:^(id returnValue) {
            
            [XBLoadingView hideHUDViewWithDefault];
            if (RESULT(returnValue)) {
                [weakSelf queryShoppingCarNumber];
                //商品cell
                NSMutableArray *cellArray = [NSMutableArray array];
                //删除商品
                for (int i=0; i<weakSelf.shopResponseArray.count; i++) {
                    ShopcarModel *model = [weakSelf.shopResponseArray objectAtIndex_opple:i];
                    if ([goodsCode containsObject:model.fid]) {
                        [weakSelf.shopResponseArray removeObject:model];
                        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
                        [cellArray addObject:indexpath];
                    }
                }
                [weakSelf.tableView deleteRowsAtIndexPaths:cellArray withRowAnimation:UITableViewRowAnimationTop];
            }else
            {
                [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
            }
        } withFailureBlock:^(NSError *error) {
            [XBLoadingView hideHUDViewWithDefault];
            [XBLoadingView showHUDViewWithText:error.localizedDescription];
        }];
    }];
    [self pushViewController:generateOrder animated:YES];
}

#pragma mark -全选
- (IBAction)allSelectedButtonClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        //全部选中
        for (ShoppingTableViewCell *cell in self.tableView.visibleCells) {
            cell.selectedButton.selected = YES;
        }
        for (ShopcarModel *model in self.shopResponseArray) {
            model.isSelected = YES;
        }
        [self.settlementButton setTitle:[NSString stringWithFormat:@"去结算(%ld)",self.shopResponseArray.count] forState:UIControlStateNormal];
    }else
    {
        //取消全部选中
        for (ShoppingTableViewCell *cell in self.tableView.visibleCells) {
            cell.selectedButton.selected = NO;
        }
        for (ShopcarModel *model in self.shopResponseArray) {
            model.isSelected = NO;
        }
        [self.settlementButton setTitle:@"去结算(0)" forState:UIControlStateNormal];
    }
    //计算总金额
    [self CalculateSelectedGoodsAllprice];
}

#pragma mark -计算选中后的商品总金额
- (void)CalculateSelectedGoodsAllprice
{
    CGFloat allPrice = 0;
    for (ShopcarModel *model in self.shopResponseArray) {
        if (model.isSelected) {
            allPrice += ([model.costPrice floatValue]?[model.costPrice floatValue]:[model.goods.tagPrice floatValue]) * model.goodsNum;
        }
    }
    self.totalpriceLabe.text = [NSString stringWithFormat:@"￥%.2f",allPrice];
}


#pragma mark -删除选中商品
- (IBAction)delecteSelectedGoods:(UIButton *)sender {

    [XBLoadingView showHUDViewWithDefault];
    DeleteCartRequest *delecteGoods = [[DeleteCartRequest alloc]init];
    //code数组
    NSMutableArray *codeArr = [NSMutableArray array];
    //需要删除的cell数组indexpath
    NSMutableArray *delecteArray = [NSMutableArray array];
    //模型数组
    NSMutableArray *delectemodel = [NSMutableArray array];
    for (int i=0; i<self.shopResponseArray.count; i++) {
        ShopcarModel *model = [self.shopResponseArray objectAtIndex_opple:i];
        if (model.isSelected) {
            [codeArr addObject:model.fid];
            [delectemodel addObject:model];
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
            [delecteArray addObject:indexpath];
        }
    }
    //没有选中任何商品
    if (codeArr.count == 0) {
        [XBLoadingView hideHUDViewWithDefault];
        [XBLoadingView showHUDViewWithText:@"未选中商品"];
        return;
    }
    delecteGoods.cartIds = codeArr;
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(REMOVESHOPPINGBAG)  withRequestType:ZERO withParameter:delecteGoods withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            
            [weakSelf queryShoppingCarNumber];
            //删除商品
            for (ShopcarModel *model in delectemodel) {
                [weakSelf.shopResponseArray removeObject:model];
            }
            [weakSelf.tableView deleteRowsAtIndexPaths:delecteArray withRowAnimation:UITableViewRowAnimationLeft];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
            [XBLoadingView showHUDViewWithSuccessText:@"删除成功" completeBlock:nil];
            [weakSelf CalculateSelectedGoodsAllprice];
            weakSelf.allSelectedButton.selected = NO;
            [weakSelf.settlementButton setTitle:@"去结算(0)" forState:UIControlStateNormal];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 修改多个商品数量、价格
- (void)modifyMultipleGoodsNnumberOrPrice:(NSArray<ShopcarModel *> *)goodsArray completeModify:(void(^)(BOOL boolValue))finish
{
    WS(weakSelf);
    dispatch_group_t group = dispatch_group_create();
    static NSInteger number = ZERO;
    [XBLoadingView showHUDViewWithDefault];
    [goodsArray enumerateObjectsUsingBlock:^(ShopcarModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {

        dispatch_group_enter(group);
        NSString *urlString = [NSString stringWithFormat:SERVERREQUESTURL(CHANGESHOPPINGBAGNUMBERPRICE),model.fid,[model.costPrice stringValue],model.goodsId,model.goodsNum];
        [HTTP networkWithDictionaryRequestWithURL:urlString withRequestType:ZERO withParameter:nil withReturnValueBlock:^(id returnValue) {
            
            dispatch_group_leave(group);
            if (RESULT(returnValue)) {
                number ++;
            }
        } withFailureBlock:^(NSError *error) {
            dispatch_group_leave(group);
        }];
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        [XBLoadingView hideHUDViewWithDefault];
        if (number == goodsArray.count) {
            [weakSelf CalculateSelectedGoodsAllprice];
            [weakSelf queryShoppingCarNumber];
            finish(YES);
        }else {
            [XBLoadingView showHUDViewWithText:@"修改失败"];
            finish(NO);
        }
        number = ZERO;
    });
}

#pragma mark -修改单个商品数量、价格
- (void)changeGoodsNumber:(NSInteger)goodsNumber withcostPrice:(CGFloat)costprice withcellindex:(NSInteger)cellindex returnValue:(void (^)(id))result
{
    [XBLoadingView showHUDViewWithDefault];
    //保存商品数量
    ShopcarModel *model = [self.shopResponseArray objectAtIndex_opple:cellindex];
    model.goodsNum = goodsNumber;
    //保存成交价格
    model.costPrice = [NSNumber numberWithFloat:costprice];
    WS(weakSelf);
    NSString *urlString = [NSString stringWithFormat:SERVERREQUESTURL(CHANGESHOPPINGBAGNUMBERPRICE),model.fid,[model.costPrice stringValue],model.goodsId,model.goodsNum];
    [HTTP networkWithDictionaryRequestWithURL:urlString  withRequestType:ZERO withParameter:nil withReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        result(returnValue);//提供是否支持修改的参数
        if (RESULT(returnValue)) {
            [weakSelf CalculateSelectedGoodsAllprice];
            [weakSelf queryShoppingCarNumber];
        }else{
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}



@end
