//
//  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"
#import "NSDate+FormatterAdditions.h"
#import "CalculateHelper.h"
#import "AttachmentModel.h"
#import "GalleryViewController.h"
#define kCellCount 20
#define kCellID @"SalesInputTableViewCell.h"
#define kPicCellId @"SaleInputPictureTableViewCell.h"
#define kAutoValue(value) (float)value / 375 * self.view.frame.size.width
static NSInteger const MaxPicNum = 5;

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

@end

@implementation SalesInputViewController

//顶部高度
static NSInteger const TOP_HEIGHT = 145;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.arrOnlineUuids = [self.model.attachments mutableCopy];
    self.cellDataDic = [NSMutableDictionary dictionary];
    self.view.backgroundColor = [UIColor whiteColor];
    self.isReadOnly = [self.model.state isEqualToString:@"approved"];
    [self setUpNavigationBar];
    [self setUpTopView];
    [self setUpTableView];
    [self setUpTotalView];
    [self setUpCommitView];
    
    switch (self.type) {
        case SalesInputViewControllerTypeInput: {
            self.navigationItem.title = @"销售录入";
            UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"历史查询" style:UIBarButtonItemStyleDone target:self action:@selector(goToHistory)];
            rightBtn.tintColor = [UIColor whiteColor];
            self.navigationItem.rightBarButtonItem = rightBtn;
            [self setUpData];
            [self.submitView.buttonCommit addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
            break;
        }
        case SalesInputViewControllerTypeAudit: {
            self.navigationItem.title = @"销售录入审批";
            [self.submitView.buttonCommit addTarget:self action:@selector(audit) forControlEvents:UIControlEventTouchUpInside];
            [self.submitView.buttonCommit setTitle:@"审批通过" forState:UIControlStateNormal];
            [self configWithAuditModel];
            [self httpGetAttachments];

            break;
        }
            
    }
}

- (void)configWithAuditModel{
    [self.topView setShopName:[NSString stringWithFormat:@"%@", self.model.shopName]];
    self.topView.textfieldDate.enabled = NO;
    self.topView.textfieldDate.text = self.model.salesDate;
    self.totalView.textFieldBillCount.text = [NSString stringWithFormat:@"%.0f",self.model.transactions];
    self.totalView.labelTotal.text = [NSString stringWithFormat:@"%.0f",self.model.amount];
    for (SalesInputLines *line in self.model.lines) {
        PaymentTypeModel *payType = [[PaymentTypeModel alloc] init];
        payType.name = line.payment;
        [self.arrPaymentType addObject:payType];
    }
    
    if (self.isReadOnly) {
        [self.submitView.buttonCommit setTitle:@"已审核" forState:UIControlStateNormal];
        [self.submitView.buttonCommit setBackgroundColor:[UIColor darkGrayColor]];
        self.submitView.buttonCommit.enabled = NO;
        self.totalView.textFieldBillCount.userInteractionEnabled = NO;
        
    }
    [self.tableView reloadData];
}

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


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getTodayTotalAmount];
    [[VankeAppBoard_iPhone sharedInstance] hideMenu];
    
    switch (self.type) {
        case SalesInputViewControllerTypeInput: {
            if (self.shop == nil) {
                [self.topView setShopName:@"请选择商铺"];
            }else{
                [self.topView setShopName:[NSString stringWithFormat:@"%@", self.shop.name]];
            }
            break;
        }
        case SalesInputViewControllerTypeAudit: {
            [self.tableView reloadData];
            break;
        }
    }
}

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

- (void)setUpTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, TOP_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - self.topView.bottom - 70) style:UITableViewStylePlain];
    if (self.type == SalesInputViewControllerTypeAudit) {
        self.tableView.top = TOP_HEIGHT - 45;
        [self.topView hideBottom];
    }
    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];
        };
        cell.userInteractionEnabled = !self.isReadOnly;
        return cell;
        
    }else{
        SaleInputPictureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kPicCellId forIndexPath:indexPath];
        cell.userInteractionEnabled = !self.isReadOnly;
        [cell setUpCellWithPictureArr:self.arrPics indexPath:indexPath];
        cell.addPicBlock = ^(NSInteger tag){
            [self pushImagePickerController];
        };
        
        cell.seePicBlock = ^(NSInteger tag){
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"SalesInPut" bundle:nil];
            GalleryViewController *galleryVC = [storyBoard instantiateViewControllerWithIdentifier:@"GalleryViewController"];
            galleryVC.arrData = self.arrPics;
            galleryVC.page = tag;
            galleryVC.type = GalleryTypeAudit;
            galleryVC.arrOnlineUuids = self.arrOnlineUuids;
            [self.navigationController pushViewController:galleryVC animated:YES];
        };
        
        WS(weakSelf);
        cell.deleteBolock = ^(NSInteger tag){
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确认删除这张图片？" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf.arrPics removeObjectAtIndex:tag];
                if (tag < weakSelf.arrOnlineUuids.count) {
                    [weakSelf.arrOnlineUuids removeObjectAtIndex:tag];
                }
                [weakSelf.tableView reloadData];
                
            }];
            [alertVC addAction:action];
            
            UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
            [alertVC addAction:actionCancel];
            [weakSelf.navigationController presentViewController:alertVC animated:YES completion:nil];
        };
        
        return cell;
    }
    
}

#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    NSInteger allowSelectNumber = MaxPicNum - (self.arrPics.count - 1);
    
    if (allowSelectNumber <= 0) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"最多只能选择%ld张图片",MaxPicNum] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:action];
        [self.navigationController presentViewController:alertVC animated:YES completion:nil];
        return;
    }
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:allowSelectNumber 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) {

        //把选择中的图片加入数组
        for (id obj in photos) {
            [self addPic:obj];
        }
        [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.navigationController.navigationBar.backgroundImage = [UIImage imageWithColor:[UIColor colorWithRed:0.918 green:0.392 blue:0.004 alpha:1.000]];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}


- (void)setUpTopView {
    SalesInputTopView *topView = [self viewWithNibName:@"SalesInputTopView"];
    topView.frame = CGRectMake(0, 0, SCREEN_WIDTH, TOP_HEIGHT + 64);
    if (self.type == SalesInputViewControllerTypeAudit) {
        topView.frame = CGRectMake(0, 0, SCREEN_WIDTH, TOP_HEIGHT + 64 - 45);
    }
    
    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 = ^{
        if (weakSelf.type == SalesInputViewControllerTypeInput) {
            [weakSelf chooseShopAction];
        }
    };
    [self.view addSubview:topView];
    if ([[VankeCommonModel sharedInstance] curUserIsTenant]) {
        self.shop = [LoginShopsInstance shareInstance].arrShops[0];
    }
    
}

- (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.projectId = self.authorizedOrg.code;
    
    if ([[VankeCommonModel sharedInstance] curUserIsTenant]) {
        return;
    }
    chooseVC.chooseBlock = ^(VankeShopModel *shop){
        self.shop = shop;
        [self.topView setShopName:shop.name];
        [self setUpData];
        [self.cellDataDic removeAllObjects];
        self.arrPics = nil;
        [self.selectedAssets removeAllObjects];
        self.totalView.textFieldBillCount.text = nil;
        [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;
            }else{
                weakSelf.todayTotalAmount = @"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 {
    NSDecimalNumber *count = [NSDecimalNumber decimalNumberWithString:@"0"];
    for (NSIndexPath *obj in self.cellDataDic.allKeys) {
        NSArray *array = [self.cellDataDic objectForKey:obj];
        count = [CalculateHelper calculateNum1:count num2:array[0] type:CalculateTypeAdd roundingType:NSRoundPlain cutLenth:2];
    }
    self.totalView.labelTotal.text = [count stringValue];

    self.topView.textFieldTotalAmount.text = [[CalculateHelper calculateNum1:count num2:self.todayTotalAmount type:CalculateTypeAdd roundingType:NSRoundPlain cutLenth:2] stringValue];
    
}

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


- (NSArray *)getCellDataArrWithIndexPath:(NSIndexPath *)indextPath {
    
    switch (self.type) {
        case SalesInputViewControllerTypeInput: {
            //利用字典key的唯一性，保存每个cell上的数据
            if (![self.cellDataDic objectForKey:indextPath]) {
                [self.cellDataDic setObject:@[@""] forKey:indextPath];
            }
            
            break;
        }
        case SalesInputViewControllerTypeAudit: {
            if (![self.cellDataDic objectForKey:indextPath]) {
                SalesInputLines *line = self.model.lines[indextPath.row];
                [self.cellDataDic setObject:@[[NSString stringWithFormat:@"%.0f",line.amount]] forKey:indextPath];
            }
            
            break;
        }
    }
     return [self.cellDataDic objectForKey:indextPath];
}

- (void)goToHistory {
    HistoryViewController *history = [[HistoryViewController alloc] init];
    history.projectid = self.authorizedOrg.code;
    history.shop = self.shop;
    WS(weakSelf);
    history.historyBlock = ^(){
        [weakSelf.arrPics removeAllObjects];
        [weakSelf.selectedAssets removeAllObjects];
        [weakSelf.cellDataDic removeAllObjects];
        weakSelf.totalView.textFieldBillCount.text = nil;
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:history animated:YES];
}

//获取支付方式
- (void)setUpData {
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];

    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd"];
    
    WS(weakSelf);
    [self.arrPaymentType removeAllObjects];
    [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)httpGetAttachments {
    NSString *url = @"attachment/get_urls_by_uuids";
    NSArray *attachmentUuids = self.model.attachments;
    __weak typeof(self)weakSelf = self;

    [[ICRHTTPController sharedController] postUrl:url params:attachmentUuids success:^(id data) {
        NSDictionary *dic = data;
        CLog(@"%@", dic.JSONString);

        for (NSDictionary *dict in data[@"data"]) {
            AttachmentModel *model = [[AttachmentModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",VANKE_SERVER_MEDIA_BASE_URL, model.fileUrl];
            [weakSelf addPic:imageUrl];
        }
        [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{
        NSString *info = [self noEmpty];
        WS(weakSelf);
        if (!info) {//没有空的，全部填写了，提交数据
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认提交？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *post = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf httpPostAttachments];
            }];
            [alert addAction:post];
            
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:cancel];
            [self.navigationController presentViewController:alert animated:YES completion:nil];

        }else{//存在未填写内容，提示用户
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:info preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *post = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:post];
            [self.navigationController presentViewController:alert animated:YES completion:nil];
        }
        
        
        
    }
}

/** 判断是否有空没填 */
- (NSString *)noEmpty {
    if (self.totalView.textFieldBillCount.text.length == 0) {
        return @"笔数不能为空，请修改后重试";
    }else{
        for (id key in self.cellDataDic.allKeys) {
            NSString *amount = [self.cellDataDic objectForKey:key][0];
            if (amount.length == 0) {
                return @"支付明细中不能为空，请修改后重试";
                break;
            }
        }
    }
    return nil;
}

- (void)httpPostAttachments {
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    NSString *string = [NSString stringWithFormat:@"attachment/upload_by_file?entity_type=%@&entity_uuid=%@",@"salesInput",[NSString stringWithFormat:@"%@%@",self.shop.code, self.topView.textfieldDate.text]];
    WS(weakSelf);
    NSMutableArray *pics = [self.arrPics mutableCopy];
    [pics removeLastObject];
    [httpCtrl POST:string pictures:pics param:nil complete:^(id responseObject, NSError *error) {
        NSMutableArray *arrUuid = [NSMutableArray array];
        for (NSDictionary *data in responseObject[@"data"]) {
            [arrUuid addObject:data[@"uuid"]];
        }
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        NSDictionary *params = [weakSelf getParamsAttachmentUuid:[NSString stringWithFormat:@"%@%@",weakSelf.shop.code, weakSelf.topView.textfieldDate.text] 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) {
            
            [hud hide:YES];
            MBProgressHUD *successHud = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
            [[UIApplication sharedApplication].keyWindow addSubview:successHud];
            successHud.mode = MBProgressHUDModeText;
            if ([data[@"message"] isEqualToString:@"ok"]) {
                successHud.labelText = @"提交成功！";
                weakSelf.arrPics = nil;
                [weakSelf.selectedAssets removeAllObjects];
                [weakSelf.cellDataDic removeAllObjects];
                [weakSelf.tableView reloadData];
                [weakSelf goToHistory];
            }else{
                successHud.labelText = @"提交失败，请重试！";
            }
            [successHud show:YES];
            [successHud hide:YES afterDelay:1];
        } failure:^(id data) {
            
        }];
        
    }];
}


- (NSDictionary *)getParamsAttachmentUuid:(NSString *)attachmentUuid pictureUuids:(NSMutableArray *)pictures {
    
    NSMutableArray *lines = [NSMutableArray array];
    for (int i = 0; i < self.arrPaymentType.count; i++) {
        NSString *amount = [self.cellDataDic objectForKey:[NSIndexPath indexPathForRow:i inSection:0]][0];
        NSString *filter = amount.length > 0 ? amount : @"0";
        PaymentTypeModel *model = self.arrPaymentType[i];
        NSDictionary *pay =  @{@"payment" : model.name,
                               @"sortNumber" : model.sortNumber,
                               @"transactions" : @"0",
                               @"amount" : [NSDecimalNumber decimalNumberWithString:filter]};
        [lines addObject:pay];
    }
 
    NSDictionary *myDictionary;
    NSString *transaction = self.totalView.textFieldBillCount.text;
    if (attachmentUuid) {
        myDictionary = @{@"projectId" : self.authorizedOrg.code,
                         @"shopCode" : self.shop.code,
                         @"shopName" : self.shop.name,
                         @"salesDate" : self.topView.textfieldDate.text,
                         @"attachments" : pictures,
                         @"transactions":transaction,
                         @"attachmentUuid" : attachmentUuid ? attachmentUuid : [NSNull null],
                         @"lines" : lines};

    }else{
        myDictionary = @{@"projectId" : self.authorizedOrg.code,
                         @"shopCode" : self.shop.code,
                         @"shopName" : self.shop.name,
                         @"salesDate" : self.topView.textfieldDate.text,
                         @"transactions":self.totalView.textFieldBillCount.text,
                         @"lines" : lines};
    }
    
    NSMutableDictionary *dic = [myDictionary mutableCopy];
    if (self.type == SalesInputViewControllerTypeAudit) {
        [dic setObject:self.model.uuid forKey:@"uuid"];
    }

    return dic;
}

/** 审批通过 */
- (void)audit {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确认审核通过？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //----------------------
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
        
        NSString *string = [NSString stringWithFormat:@"attachment/upload_by_file?entity_type=%@&entity_uuid=%@",@"salesInput",self.model.attachmentUuid];
        WS(weakSelf);
        
        NSMutableArray *postPic = [NSMutableArray array];
        for (id obj in self.arrPics) {
            if ([obj isKindOfClass:[UIImage class]]) {
                [postPic addObject:obj];
            }
        }
        [postPic removeLastObject];
        
        NSMutableArray *uuids = [self.arrOnlineUuids mutableCopy];
        [httpCtrl POST:string pictures:postPic param:nil complete:^(id responseObject, NSError *error) {
            for (NSDictionary *data in responseObject[@"data"]) {
                [uuids addObject:data[@"uuid"]];
            }
            NSString *url = [NSString stringWithFormat:@"salesinput/approve?time=%@&operId=%@&operName=%@",
                             [[NSDate date] httpParameterString],
                             [[[VankeCommonModel sharedInstance] getLoginInfo] user_uuid],
                             [[[VankeCommonModel sharedInstance] getLoginInfo] user_name]];
            NSString *utf8String = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSMutableArray *lines = [NSMutableArray array];
            for (int i = 0; i < self.model.lines.count; i++) {
                NSString *amount = [self.cellDataDic objectForKey:[NSIndexPath indexPathForRow:i inSection:0]][0];
                NSString *filter = amount.length > 0 ? amount : @"0";
                SalesInputLines *aLine = self.model.lines[i];
                NSDictionary *pay =  @{@"payment" : aLine.payment,
                                       @"sortNumber" : [NSNumber numberWithDouble:aLine.sortNumber],
                                       @"transactions" : @"0",
                                       @"amount" : [NSDecimalNumber decimalNumberWithString:filter]};
                [lines addObject:pay];
            }
            
            NSDictionary *myDictionary = @{@"projectId" : self.model.projectId,
                                           @"shopCode" : self.model.shopCode,
                                           @"shopName" : self.model.shopName,
                                           @"salesDate" : self.topView.textfieldDate.text,
                                           @"attachments" : uuids,
                                           @"transactions":self.totalView.textFieldBillCount.text,
                                           @"attachmentUuid" : self.model.attachmentUuid ? self.model.attachmentUuid : [NSNull null],
                                           @"lines" : lines,
                                           @"uuid":self.model.uuid};
            
            
            [httpCtrl postUrl:utf8String params:myDictionary success:^(id data) {
                [hud hide:YES];
                MBProgressHUD *successHud = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
                [[UIApplication sharedApplication].keyWindow addSubview:successHud];
                successHud.mode = MBProgressHUDModeText;
                if ([data[@"message"] isEqualToString:@"ok"]) {
                    successHud.labelText = @"审核成功！";
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else{
                    successHud.labelText = @"审核失败！";
                }
                [successHud show:YES];
                [successHud hide:YES afterDelay:1];
                
            } failure:^(id data) {
                
            }];
            
            
        }];
        
        //----------------------
    }];
    [alertVC addAction:action];
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    [alertVC addAction:actionCancel];
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];
    
    
}

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

- (NSMutableArray *)arrPaymentType {
    if (!_arrPaymentType) {
        _arrPaymentType = [NSMutableArray array];
    }
    return _arrPaymentType;
}

/** 添加选择的照片 */
- (void)addPic:(id)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
