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

#import "GenerateOrdersViewController.h"
#import "GenerateOrdersTableViewCell.h"
#import "GenerateOrdersModifyTableViewCell.h"
#import "PersonInformationTableViewCell.h"
#import "CommodityListTableViewCell.h"
#import "AllpriceTableViewCell.h"
#import "AddaddressViewController.h"
#import "ModifyShippingAddressView.h"
#import "AppDelegate.h"
#import "OrderdetailsViewController.h"
#import "AddressViewController.h"
#import "AddressModel.h"
@interface GenerateOrdersViewController ()<UITableViewDelegate,UITableViewDataSource,delecteDelegate>

/**
 *  增加或者修改地址
 */
@property (nonatomic,strong) ModifyShippingAddressView *addressView;



/**
 *  数据源
 */
@property (nonatomic,strong) NSMutableArray *datasArray;


@property (nonatomic,strong) UIView *Tabbarview;
@end

@implementation GenerateOrdersViewController

/**
 *  初始化数据源
 */
- (NSMutableArray *)datasArray
{
    if (_datasArray == nil) {
        
        _datasArray = [NSMutableArray array];
        for (int i=0; i<3; i++) {
            NSMutableArray *arr = [NSMutableArray array];
            [_datasArray addObject:arr];
        }
        //加入客户信息model
        Customermanager *customerModel = [Customermanager manager];
        [[_datasArray firstObject] addObject:customerModel];
        
        AddressModel *model = [[AddressModel alloc]init];
        model.name = @"地址占位";
        //地址占位
        [[_datasArray objectAtIndex_opple:1] addObject:model];
        
        //加入商品信息
        [_datasArray replaceObjectAtIndex:2 withObject:_settlementGoodsdatas];
    }
    
    return _datasArray;
}



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

#pragma mark -UI
- (void)uiConfigAction
{
    self.generateOrderTableview.dataSource = self;
    self.generateOrderTableview.delegate = self;
    self.generateOrderTableview.tableFooterView = [UIView new];
    self.backShoppingbagsButton.layer.masksToBounds = YES;
    self.backShoppingbagsButton.layer.cornerRadius = kCornerRadius;
    self.createOrderButton.layer.masksToBounds = YES;
    self.createOrderButton.layer.cornerRadius = kCornerRadius;
}


#pragma mark -获得地址信息
- (void)getAddressDatasRequest
{
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@%@",ServerAddress,@"/shippingAddress/listAddress/",[Customermanager manager].customerID] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
         
            RsShippingAddrEntity *address = [[RsShippingAddrEntity alloc]initWithDictionary:returnValue[@"data"] error:nil];
            
            for (NSInteger i=address.list.count-1; i>=0; i--) {
                
                TOShippingAddrEntity *model = [address.list objectAtIndex_opple:i];
                //自定义model
                AddressModel *Newmodel = [[AddressModel alloc]init];
                Newmodel.fid = model.fid;
                Newmodel.createDate = model.createDate;
                Newmodel.sysOrgCode = model.sysOrgCode;
                Newmodel.name = model.name;
                Newmodel.miblephone = model.miblephone;
                Newmodel.province = model.province;
                Newmodel.city = model.city;
                Newmodel.country = model.country;
                Newmodel.consumerId = model.consumerId;
                Newmodel.address = model.address;
                
                [[self.datasArray objectAtIndex_opple:1]insertObject:Newmodel atIndex:0];
            }
            
            //地址数组
            NSArray *addressArray = [self.datasArray objectAtIndex_opple:1];
            //增加cell
            NSMutableArray *addCellArray = [NSMutableArray array];
            for (int i=0; i<addressArray.count-1; i++) {
                NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:1];
                [addCellArray addObject:indexpath];
            }
            [self.generateOrderTableview insertRowsAtIndexPaths:addCellArray withRowAnimation:UITableViewRowAnimationBottom];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        NSLog(@"%@",error);
        [self RemoveMBProgressHUDLoding];
    }];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        PersonInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"secondcell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section == 1)
    {
        NSArray *Addressarr = [self.datasArray objectAtIndex_opple:indexPath.section];
        if (indexPath.row == Addressarr.count-1) {
            
            GenerateOrdersModifyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Modifycell" forIndexPath:indexPath];
            //增加地址或者修改
            [cell.addAddressButton addTarget:self action:@selector(AddAddressButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [cell.changeButton addTarget:self action:@selector(ChangeButtonClick) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = kTCColor(242, 242, 242);
            return cell;
        }
        GenerateOrdersTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"consigneecell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = kTCColor(242, 242, 242);
        cell.indexNumber = indexPath.row;
        //回调
        [cell setBlockSeletced:^(NSInteger index) {
            
            [self SetCustomerButtonClick:index];
        }];
        cell.NewModel = [self.datasArray objectAtIndex_opple:indexPath.section][indexPath.row];
        return cell;
    }
    else if (indexPath.section == 2)
    {

        NSArray *Addressarr = [self.datasArray objectAtIndex_opple:indexPath.section];
        if (indexPath.row == Addressarr.count-1) {
            
            AllpriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sixthcell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.goodsAllprice = [self.datasArray objectAtIndex_opple:indexPath.section];
            return cell;
        }
        CommodityListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fourthcell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = [self.datasArray objectAtIndex_opple:indexPath.section][indexPath.row];
        return cell;
    }
    return nil;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = [self.datasArray objectAtIndex_opple:section];
    return arr.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            return 140;
        }
            break;
        case 1:
        {
            return 56;
        }
            break;
        case 2:
        {
            NSArray *arr = [self.datasArray objectAtIndex_opple:indexPath.section];
            if (indexPath.row == arr.count-1) {
                
                return 50;
            }
            return 80;
        }
            break;
            
        default:
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        {
            return 0;
        }
            break;
        case 1:
        {
            return 5;
        }
            break;
        case 2:
        {
            return 44;
        }
            break;
            
        default:
            break;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 1:
        {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 5)];
            imageView.image = TCImage(@"lineNew");
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
            [view addSubview:imageView];
            return view;
        }
            break;
        case 2:
        {
            UILabel *titleLabe = [[UILabel alloc]initWithFrame:CGRectMake(50, 0, 100, 44)];
            titleLabe.text = @"购物袋清单";
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
            [view addSubview:titleLabe];
            
            //横线
            UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 43, ScreenWidth, 1)];
            lineView.backgroundColor = kTCColor(242, 242, 242);
            [view addSubview:lineView];
            return view;
        }
            break;
            
        default:
            break;
    }
    return nil;
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datasArray.count;
}




#pragma mark -新增或者修改收货地址
- (void)CreateModifyShippingView:(AddressModel *)model Withindex:(NSInteger)cellindex
{
    
    AddressViewController *address = [[AddressViewController alloc]init];
    address.delegate = self;
    if (model != nil) {
        
        address.model = model;
        address.isChange = YES;
    }
    address.cellindex = cellindex;
    address.preferredContentSize = CGSizeMake(315, 320);
    address.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = address.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = address.view;
    [self presentViewController:address animated:YES completion:nil];
}




#pragma mark -生成订单
- (IBAction)CreateOrderButtonClick:(UIButton *)sender {
    
    
    OrderBill *order = [[OrderBill alloc]init];
    //分页
    DataPage *page = [[DataPage alloc]init];
    page.page = 0;
    order.datapage = page;
    
    //收货地址
    TOOrderEntity *orderReceiver = [[TOOrderEntity alloc]init];
    NSArray *Adressarr = [self.datasArray objectAtIndex_opple:1];
    for (int i=0; i<Adressarr.count; i++) {
        
        if ([[Adressarr objectAtIndex_opple:i] isKindOfClass:[AddressModel class]]) {
            
            AddressModel *model = [Adressarr objectAtIndex_opple:i];
            if (model.isSelected) {
                
                //收货人信息
                orderReceiver.receiverName = model.name;
                orderReceiver.receiverMobile = model.miblephone;
                orderReceiver.receiverAddress = model.address;
                order.order = orderReceiver;
                orderReceiver.guideId = [[Shoppersmanager manager] Shoppers].employee.fid;
                orderReceiver.consumerId = [[Customermanager manager] customerID];
                orderReceiver.orderState = @"001";
                //商品ID
                NSArray *goodArray = [self.datasArray lastObject];
                NSMutableArray *goodidArr = [NSMutableArray array];
                for (int i=0; i<goodArray.count-1; i++) {
                    ShopcarModel *model = [goodArray objectAtIndex_opple:i];
                    TOOrderdetailEntity *orderGoods = [[TOOrderdetailEntity alloc]init];
                    orderGoods.goodsId = model.fid;
                    orderGoods.goodsCover = model.goods.pictures;
                    orderGoods.goodsCode = model.goods.code;
                    orderGoods.goodsSpec = model.goods.spec;
                    orderGoods.goodsName = model.goods.name;
                    orderGoods.goodsBrand = model.goods.brandId;
                    orderGoods.goodsNum = model.goods.number;
                    orderGoods.goodsPrice = model.goods.costPrice;
                    orderGoods.remark = model.goods.spec;
                    orderGoods.goodsUnit = model.goods.unit;
                    
                    //总价
                    NSInteger allprice = [model.goods.number integerValue]*[model.goods.costPrice integerValue];
                    orderGoods.goodsTotalPrice = [NSNumber numberWithInteger:allprice];
                    orderReceiver.orderPrice = [NSNumber numberWithInteger:allprice];
                    [goodidArr addObject:orderGoods];
                }
                
                order.orderdetailList = (NSArray<TOOrderdetailEntity> *)goodidArr;
                [self CreateMBProgressHUDLoding];
                [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/order/save"] WithRequestType:0 WithParameter:order WithReturnValueBlock:^(id returnValue) {
                    [self RemoveMBProgressHUDLoding];
                    if ([returnValue[@"code"] isEqualToNumber:@0]) {
                        //商品购物车id
                        NSMutableArray *codeArrray = [NSMutableArray array];
                        for (ShopcarModel *model in _settlementGoodsdatas) {
                            [codeArrray addObject:model.fid?model.fid:@" "];
                        }
                        //调用删除购物车
                        if (self.DelecteSelectedGoods) {
                            self.DelecteSelectedGoods(codeArrray);
                        }
                        OrderdetailsViewController *orderDetails = [[self getStoryboardWithName] instantiateViewControllerWithIdentifier:@"orderdetails"];
                        orderDetails.orderCode = returnValue[@"data"];
                        orderDetails.sectionTitle = @[@"订单信息",@"客户信息",@"收货信息",@"商品清单"];
                        orderDetails.isShowattachment = NO;
                        orderDetails.isShowPayButton = YES;
                        [self.navigationController pushViewController:orderDetails animated:YES];
                        
                    }else
                    {
                        [self ErrorMBProgressView:returnValue[@"message"]];
                    }
                } WithErrorCodeBlock:^(id errorCodeValue) {
                    
                } WithFailureBlock:^(id error) {
                    [self RemoveMBProgressHUDLoding];
                }];
                return;
            }
            else if (i == Adressarr.count -1)
            {
               [self ErrorMBProgressView:@"未选中地址"];
            }
        }
    }
}


#pragma mark -返回购物车

- (IBAction)BackShoppingBagsButtonClick:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -设置为当前地址回调
- (void)SetCustomerButtonClick:(NSInteger)index;
{
    
    for (UITableViewCell *cell in self.generateOrderTableview.visibleCells) {
        
        if ([cell isKindOfClass:[GenerateOrdersTableViewCell class]]) {
            
           GenerateOrdersTableViewCell *Newcell = (GenerateOrdersTableViewCell *)cell;
           Newcell.isSelectedButton.selected = NO;
        }
    }
    for (id objc in [self.datasArray objectAtIndex_opple:1]) {
        
        if ([objc isKindOfClass:[AddressModel class]]) {
            
            AddressModel *model = (AddressModel *)objc;
            model.isSelected = NO;
        }
    }
    AddressModel *model = [[self.datasArray objectAtIndex_opple:1] objectAtIndex_opple:index];
    model.isSelected = YES;
}



#pragma mark -修改地址
- (void)ChangeButtonClick
{
    NSArray *arr = [self.datasArray objectAtIndex_opple:1];
    for (int i=0; i<arr.count; i++) {
        
        if ([[arr objectAtIndex_opple:i] isKindOfClass:[AddressModel class]]) {
            
            AddressModel *model = [arr objectAtIndex_opple:i];
            //判断是否为选中
            if (model.isSelected) {
                
                [self CreateModifyShippingView:[arr objectAtIndex_opple:i] Withindex:i];
            }
        }
    }
}


#pragma mark -新增地址
- (void)AddAddressButtonClick
{
    [self CreateModifyShippingView:nil Withindex:0];
}


#pragma mark -新增地址回调
- (void)addAddressCell:(AddressModel *)model
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [[self.datasArray objectAtIndex_opple:1]insertObject:model atIndex:0];
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:1];
    [self.generateOrderTableview insertRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationLeft];
}

#pragma mark -修改地址回调
- (void)ChangeAddresscell:(AddressModel *)model Withcellindex:(NSInteger)cellindex
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [[self.datasArray objectAtIndex_opple:1]replaceObjectAtIndex:cellindex withObject:model];
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:cellindex inSection:1];
    [self.generateOrderTableview reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationLeft];
}

#pragma mark -删除地址
- (void)delecteCell:(NSString *)addressid
{
    NSArray *arr = [self.datasArray objectAtIndex_opple:1];
    for (int i=0; i<arr.count; i++) {
        
        if ([[arr objectAtIndex_opple:i] isKindOfClass:[AddressModel class]]) {
            
            AddressModel *model = [arr objectAtIndex_opple:i];
            //判断是否为选中
            if ([model.fid isEqualToString:addressid]) {
                
                [[self.datasArray objectAtIndex_opple:1] removeObjectAtIndex:i];
                NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:1];
                [self.generateOrderTableview deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationLeft];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
    }
}

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