//
//  SalesInputViewController.m
//  vanke
//
//  Created by Z on 16/4/15.
//  Copyright © 2016年 gomore. All rights reserved.
//

#import "SalesInputViewController.h"
#import "SalesInputTopView.h"
#import "SalesInputTableViewCell.h"
#import "VankeAppBoard_iPhone.h"
#import "HistoryViewController.h"
#import "ChooseShopViewController.h"
#import "VankeUserLoginAPI.h"
#import "ICRHTTPController.h"
#import "MyToolBar.h"
#import "SalesInputTotalVIew.h"
#import "ICRAppMacro.h"
#import "LoginShopsInstance.h"
#import "PaymentTypeModel.h"
#import "SalesInputCommitView.h"
#import "ChooseProjectTableViewController.h"

#define kCellCount 20
#define kCellID @"SalesInputTableViewCell.h"
@interface SalesInputViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SalesInputTopView *topView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) UIImage *navigationbarColorImage;
@property (nonatomic, strong) SalesInputTotalVIew *totalView;
@property (nonatomic, strong) NSString *selectDate;
@property (nonatomic, strong) NSMutableDictionary *cellDataDic;
@property (nonatomic, strong) NSMutableArray *arrPaymentType;
@property (nonatomic, strong) SalesInputCommitView *submitView;
@property (nonatomic, copy) NSString *todayTotalAmount;

@end

@implementation SalesInputViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.cellDataDic = [NSMutableDictionary dictionary];
    self.view.backgroundColor = [UIColor whiteColor];
    if ([LoginShopsInstance shareInstance].arrShops.count > 0) {
        self.shop = [LoginShopsInstance shareInstance].arrShops[0];
        
    }
    
    [self setUpNavigationBar];
    [self setUpTopView];
    [self setUpTableView];
    [self setUpTotalView];
    [self setUpCommitView];
    [self setUpData];
    // Do any additional setup after loading the view.
}

- (void)setUpCommitView {
    self.submitView = [self viewWithNibName:@"SalesInputCommitView"];
    self.submitView.frame = CGRectMake(0, SCREEN_HEIGHT - 70 - 64, SCREEN_WIDTH, 70 + 64);
    [self.submitView.buttonCommit addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.submitView];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[VankeAppBoard_iPhone sharedInstance] hideMenu];
    
    if([LoginShopsInstance shareInstance].arrShops.count == 1){
        self.topView.buttonName.userInteractionEnabled = NO;
    }
    
    if (self.shop == nil) {
        [self.topView setShopName:@""];
    }else{
        [self.topView setShopName:[NSString stringWithFormat:@"%@【%@】", self.shop.name, self.shop.code]];
    }
    
    [self getTodayTotalAmount];


}

ON_WILL_APPEAR( signal )
{
    [[VankeAppBoard_iPhone sharedInstance] hideMenu];
}

- (void)setUpTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 125, SCREEN_WIDTH, SCREEN_HEIGHT - self.topView.bottom - 70) style:UITableViewStylePlain];
    self.tableView.contentInset = UIEdgeInsetsMake(179, 0, 0, 0);

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"SalesInputTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kCellID];
    [self.view addSubview:self.tableView];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SalesInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID forIndexPath:indexPath];
    cell.paymentType.text = [self.arrPaymentType[indexPath.row] name];
    [cell cellWithArray:[self getCellDataArrWithIndexPath:indexPath]];
    
    WS(weakSelf)
    cell.updateCellData = ^(NSArray *dataArr){
        [weakSelf.cellDataDic setObject:dataArr forKey:indexPath];
        [weakSelf countTotalMonney];
    };
    

    return cell;
}

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

- (void)setUpNavigationBar {
    self.navigationItem.title = @"销售录入";
    
    self.navigationController.navigationBar.backgroundImage = [UIImage imageWithColor:[UIColor colorWithRed:0.953 green:0.439 blue:0.063 alpha:1.000]];
    
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"历史" style:UIBarButtonItemStyleDone target:self action:@selector(goToHistory)];
    rightBtn.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}


- (void)setUpTopView {
    SalesInputTopView *topView = [self viewWithNibName:@"SalesInputTopView"];
    topView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 125 + 64);
    self.topView = topView;
    topView.textfieldDate.inputView = self.datePicker;
    topView.textfieldDate.delegate = self;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    NSString *strTime = [df stringFromDate:[NSDate date]];
    topView.textfieldDate.text = strTime;

    
    topView.nameTapActionBlock = ^{
        [self chooseShopAction];
    };
    
    [self.view addSubview:topView];
    
    
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self getTodayTotalAmount];

}

- (void)setUpTotalView {
    self.totalView = [self viewWithNibName:@"SalesInputTotalView"];
    self.totalView.frame = CGRectMake(0, -179, SCREEN_WIDTH, 179);
    [self.tableView addSubview:self.totalView];
}


- (void)pickerDoneAction {
    [self.view endEditing:YES];
}


- (void)chooseShopAction {
    ChooseShopViewController *chooseVC = [[ChooseShopViewController alloc] init];

    chooseVC.chooseBlock = ^(VankeShopModel *shop){
        self.shop = shop;
        [self.topView setShopName:shop.name];
        [self setUpData];
        [self getTodayTotalAmount];
    };
    
    [self.navigationController pushViewController:chooseVC animated:YES];
}


- (UIDatePicker *)datePicker {
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] init];
        _datePicker.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
        _datePicker.date = [NSDate date];

        _datePicker.datePickerMode = UIDatePickerModeDate;
         [_datePicker addTarget:self action:@selector(oneDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged]; // 添加监听器
        
    }
    return _datePicker;
}

- (void)getTodayTotalAmount {
    if (self.shop == nil) {
        
    }else{
        
        [self.cellDataDic removeAllObjects];
        [self.tableView reloadData];
        WS(weakSelf)

        NSDictionary *params = @{@"shopCodeEquals" : self.shop.code,
                                 @"beginDateEquals" : self.topView.textfieldDate.text,
                                 @"endDateEquals" : self.topView.textfieldDate.text,
                                 @"pageNumber" : @0,
                                 @"pageSize" : @0};
        
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        [httpCtrl getUrl:@"salesinput/query" params:params success:^(id data) {
            if ([data[@"data"][@"records"] count] > 0) {
                
                NSNumber *amount =  data[@"data"][@"records"][0][@"amount"];
                NSString *amountStr = [NSString stringWithFormat:@"%.0f", [amount floatValue]];
                weakSelf.todayTotalAmount = amountStr;
                weakSelf.totalView.labelTotalAmount.text = amountStr;
                
                

            }else{
                weakSelf.todayTotalAmount = @"0";
                weakSelf.totalView.labelTotalAmount.text = @"0";
            }
            [weakSelf countTotalMonney];
            NSLog(@"d");
        } failure:^(id data) {
            
        }];
        
        
    }
}


#pragma mark - 实现oneDatePicker的监听方法
- (void)oneDatePickerValueChanged:(UIDatePicker *) sender {
    NSDate *date = sender.date;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    NSString *strTime = [df stringFromDate:date];
    
    self.topView.textfieldDate.text = strTime;
    NSLog(@"%@", strTime);
}

- (void)countTotalMonney {
    CGFloat count = 0;
    for (NSIndexPath *obj in self.cellDataDic.allKeys) {
        NSArray *array = [self.cellDataDic objectForKey:obj];
        CGFloat monney = [array[0] floatValue];
        count = count + monney;
    }
    self.totalView.labelTotal.text = [NSString stringWithFormat:@"%.0f",count];

    self.totalView.labelTotalAmount.text = [NSString stringWithFormat:@"%.0f", count + [self.todayTotalAmount floatValue]];
    
}




- (id)viewWithNibName:(NSString *)viewName {
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:viewName owner:nil options:nil];
    return [nibView objectAtIndex:0];
}


- (NSArray *)getCellDataArrWithIndexPath:(NSIndexPath *)indextPath {
    
    //利用字典key的唯一性，保存每个cell上的数据
    if (![self.cellDataDic objectForKey:indextPath]) {
        [self.cellDataDic setObject:@[@"0",@"0"] forKey:indextPath];
    }
    return [self.cellDataDic objectForKey:indextPath];
}

- (void)goToHistory {
    HistoryViewController *history = [[HistoryViewController alloc] init];
    history.shop = self.shop; 
    [self.navigationController pushViewController:history animated:YES];
}

- (void)setUpData {
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];

    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd"];
    
    self.arrPaymentType = [NSMutableArray array];
    WS(weakSelf)
    [httpCtrl getUrl:@"payment/getall" params:nil success:^(id data) {
        NSDictionary *dic = data;
        for (NSDictionary *obj in dic[@"data"]) {
            PaymentTypeModel *model = [PaymentTypeModel modelWithDic:obj];
            [weakSelf.arrPaymentType addObject:model];
        }
        [weakSelf.tableView reloadData];
        
    } failure:^(id data) {
        
    }];
    
}

- (void)submit {
    if (self.shop == nil) {
        
    }else{
        
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        NSDictionary *params = [self getParams];
        
        NSString *url = [NSString stringWithFormat:@"salesinput/submit?time=%@&operId=%@&operName=%@",[[NSDate date] httpParameterString], [[[VankeCommonModel sharedInstance] getLoginInfo] user_uuid], [[[VankeCommonModel sharedInstance] getLoginInfo] user_name]];
        NSString *utf8String = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        WS(weakSelf)
        [httpCtrl postUrl:utf8String params:params success:^(id data) {
            
            [weakSelf goToHistory];
            
        } failure:^(id data) {
            
        }];
    }
    
    
}

- (NSDictionary *)getParams {
    
    NSMutableArray *lines = [NSMutableArray array];
    for (int i = 0; i < self.arrPaymentType.count; i++) {
        
        NSString *bill = [self.cellDataDic objectForKey:[NSIndexPath indexPathForRow:i inSection:0]][1];
        NSString *amount = [self.cellDataDic objectForKey:[NSIndexPath indexPathForRow:i inSection:0]][0];
        PaymentTypeModel *model = self.arrPaymentType[i];
        NSDictionary *pay =  @{@"payment" : model.name,
                               @"sortNumber" : model.sortNumber,
                               @"transactions" : [NSNumber numberWithFloat: [bill floatValue]],
                               @"amount" : [NSNumber numberWithFloat: [amount floatValue]]};
        [lines addObject:pay];
        
    }
    
 
    NSDictionary *myDictionary = @{@"projectId" : self.authorizedOrg.code,
                                   @"shopCode" : self.shop.code,
                                   @"shopName" : self.shop.name,
                                   @"salesDate" : self.topView.textfieldDate.text,
                                   @"lines" : lines};
    
    return myDictionary;
}

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