//
//  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"
#import "SaleInputPictureTableViewCell.h"
#import "TZImagePickerController.h"
#import "UIImage+Helper.h"
#define kCellCount 20
#define kCellID @"SalesInputTableViewCell.h"
#define kPicCellId @"SaleInputPictureTableViewCell.h"

#define kAutoValue(value) (float)value / 375 * self.view.frame.size.width
/**
 *  colors
 */
#define kSysWhite  [UIColor whiteColor]
//红 #ED1B23
#define kMainRedColor [UIColor colorWithRed:0.929 green:0.106 blue:0.137 alpha:1.000];
//蓝 #478FF1
#define kMainBlueColor [UIColor colorWithRed:0.278 green:0.561 blue:0.945 alpha:1.000];
//橙 #EA6402
#define kMainOrangeColor [UIColor colorWithRed:0.918 green:0.392 blue:0.008 alpha:1.000];
//紫 #5435AD
#define kMainPurpleColor [UIColor colorWithRed:0.329 green:0.208 blue:0.678 alpha:1.000];
#define kTabbarColor [UIColor colorWithWhite:0.973 alpha:1.000];

@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;
@property (nonatomic, strong) NSMutableArray *arrPics;
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@end

@implementation SalesInputViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.cellDataDic = [NSMutableDictionary dictionary];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [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.tableView registerNib:[UINib nibWithNibName:@"SaleInputPictureTableViewCell" bundle:nil] forCellReuseIdentifier:kPicCellId];
    [self.view addSubview:self.tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.arrPaymentType.count;
    }else{
        return self.arrPics.count % 2 != 0 ? self.arrPics.count / 2 + 1: self.arrPics.count / 2; //有奇数个元素
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [self viewWithNibName:@"SaleInputPictureCellHeader"];
    return view;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGFLOAT_MIN;
    }else{
        return 50;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        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;
        
    }else{
        SaleInputPictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kPicCellId forIndexPath:indexPath];
        [cell setUpCellWithPictureArr:self.arrPics indexPath:indexPath];
        cell.addPicBlock = ^(NSInteger tag){
            [self pushImagePickerController];
        };
        
        cell.seePicBlock = ^(NSInteger tag){
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_arrPics index:tag];
            imagePickerVc.allowPickingOriginalPhoto = NO;
            imagePickerVc.isSelectOriginalPhoto = NO;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                _selectedAssets = [NSMutableArray arrayWithArray:assets];
                _arrPics = [NSMutableArray arrayWithArray:photos];
                [self.tableView reloadData];
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        };
        return cell;
    }
    
}

#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 delegate:nil];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    imagePickerVc.navigationBar.barTintColor = kMainOrangeColor;
    imagePickerVc.oKButtonTitleColorNormal = kMainOrangeColor;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        _selectedAssets = [NSMutableArray arrayWithArray:assets];
        _arrPics = [NSMutableArray arrayWithArray:photos];
        [_arrPics addObject:[UIImage imageNamed:@"add-photo_icon"]];
        [self.tableView reloadData];
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 50;
    }else{
        return kAutoValue(150);
    }
}

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

    WS(weakSelf)
    topView.nameTapActionBlock = ^{
        [weakSelf chooseShopAction];
    };
    
    [self.view addSubview:topView];
    
    
    
}

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

}

- (void)setUpTotalView {
    self.totalView = [self viewWithNibName:@"SalesInputTotalView"];
    self.tableView.tableHeaderView = 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.cellDataDic removeAllObjects];
        self.arrPics = nil;
        [self.selectedAssets removeAllObjects];
        [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.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;
    history.historyBlock = ^(){
        [self.arrPics removeAllObjects];
        [self.selectedAssets removeAllObjects];
        [self.cellDataDic removeAllObjects];
        [self.tableView reloadData];
    };
    [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) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择店铺！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        
    }else{
        
        [self httpPostAttachments];

    }
}

- (void)httpPostAttachments {
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    NSString *string = [NSString stringWithFormat:@"attachment/upload_by_file?entity_type=%@&entity_uuid=%@",@"salesInput",@"860576037625827160708160529115460847"];
    WS(weakSelf);
    [httpCtrl POST:string pictures:self.arrPics param:nil complete:^(id responseObject, NSError *error) {
        NSMutableArray *arrUuid = [NSMutableArray array];
        for (NSDictionary *data in responseObject[@"data"]) {
            [arrUuid addObject:data[@"uuid"]];
        }
        NSString *entityUuid = responseObject[@"data"][0][@"entityUuid"];
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        NSDictionary *params = [weakSelf getParamsAttachmentUuid:entityUuid pictureUuids:arrUuid];
        
        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 *)getParamsAttachmentUuid:(NSString *)attachmentUuid pictureUuids:(NSMutableArray *)pictures {
    
    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,
                                   @"attachments" : pictures ? pictures : [NSNull null],
                                   @"attachmentUuid" : attachmentUuid ? attachmentUuid : [NSNull null],
                                   @"lines" : lines};
    
    return myDictionary;
}

- (NSMutableArray *)arrPics {
    if (!_arrPics) {
        _arrPics = [NSMutableArray array];
        [_arrPics addObject:[UIImage imageNamed:@"add-photo_icon"]];
    }
    return _arrPics;
}

/** 添加选择的照片 */
- (void)addPic:(UIImage *)image {
    [self.arrPics insertObject:image atIndex:self.arrPics.count - 1];
}

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