//
//	 ______    ______    ______
//	/\  __ \  /\  ___\  /\  ___\
// //	\ \  __<  \ \  __\_ \ \  __\_
//	 \ \_____\ \ \_____\ \ \_____\
// //	  \/_____/  \/_____/  \/_____/
//
//	Powered by BeeFramework
//
//
//  VankeStatementDetailListBoard_iPhone.m
//  vanke
//
//  Created by xiaomi on 15/11/16.
//  Copyright © 2015年 gomore. All rights reserved.
//

#import "VankeStatementDetailListBoard_iPhone.h"
#import "PullLoader.h"
#import "FootLoader.h"
#import "VankeUtil.h"
#import "GEToast.h"
#import "SRMonthPicker.h"
#import "NoDataCell_iPhoneCell.h"
#import "VankeStatementRejectModel.h"
#import "VankeStatementConfirmModel.h"
#import "VankeStatementSubjectListModel.h"
#import "VankeStatementDetailListCell_iPhone.h"
#import "VankeStatementDetailMonthCell_iPhone.h"

#pragma mark -

@interface VankeStatementDetailListBoard_iPhone ()
{
    //<#@private var#>
    VankeStatementConfirmModel *confirmModel;
    VankeStatementRejectModel *rejectModel;
}
@end

@implementation VankeStatementDetailListBoard_iPhone

SUPPORT_AUTOMATIC_LAYOUT( YES )
SUPPORT_RESOURCE_LOADING( YES )

@synthesize data = _data;
@synthesize settleEquals = _settleEquals;
@synthesize contractEquals = _contractEquals;

DEF_NOTIFICATION( STATE_CHANGED )

DEF_MODEL( VankeStatementListModel, model )
DEF_OUTLET( BeeUIScrollView,     list )
DEF_OUTLET( VankeStateDetailOperCell_iPhone, operBar )
DEF_OUTLET( VankeStatementDetailMonthCell_iPhone, settlementBar)
DEF_OUTLET( BeeUIImageView, imgState)

- (void)load
{
    self.model = [VankeStatementSubjectListModel modelWithObserver:self];
    confirmModel = [VankeStatementConfirmModel modelWithObserver:self];
    rejectModel = [VankeStatementRejectModel modelWithObserver:self];
}

- (void)unload
{
    self.model = nil;
    confirmModel = nil;
    rejectModel = nil;
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationBarShown = YES;
    self.allowedSwipeToBack = YES;
    self.title = _data.shopName;
//    self.operBar.hidden = ![_data unconfirmed];
    self.operBar.hidden = YES;
    [self initListAndModel];
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
    CGRect statusFrame = [[UIApplication sharedApplication] statusBarFrame];
    if (statusFrame.size.height == 40.0f) {
        self.operBar.top -= 20.0f;
    }
}

ON_WILL_APPEAR( signal )
{
    self.navigationBarShown = YES;
    if ( NO == self.model.loaded )
    {
        [self.model firstPage];
    }
    
    UIColor *color = [VankeUtil rgbStringToColor: @"144,76,245"];
    if ( IOS7_OR_LATER ) {
        self.navigationController.navigationBar.barTintColor = color;
    } else {
        self.navigationController.navigationBar.tintColor = color;
    }
    
    [BeeUIRouter sharedInstance].view.pannable = YES;
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
    [BeeUIRouter sharedInstance].view.pannable = NO;
}

ON_DID_DISAPPEAR( signal )
{
}

#pragma mark model

ON_SIGNAL3( VankeStatementSubjectListModel, RELOADING, signal )
{
    [GEToast showProgress:self.view];
    self.list.headerLoading = YES;
    self.list.footerLoading = YES;
}

ON_SIGNAL3( VankeStatementSubjectListModel, RELOADED, signal )
{
    [GEToast hideProgress];
    self.list.headerLoading = NO;
    self.list.footerLoading = NO;
    self.list.footerMore = self.model.more;
    [self.list reloadData];
    
    StatementSubjectListResponseData *respData = _model.lastResp.data;
    if (nil != respData && respData.items.count > 0) {
        self.title = respData.shopName;
        $(self.settlementBar).DATA(respData);
        $(self.imgState).DATA([NSString stringWithFormat:@"%@_big.png", respData.state]);
        // self.operBar.hidden = ![respData unconfirmed];
        self.operBar.hidden = YES;
    } else {
        if (nil == respData) {
            respData = [[StatementSubjectListResponseData alloc] init];
        }
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMM"];
        respData.settle = [dateFormatter stringFromDate:_model.settle];
        respData.amount = [NSNumber numberWithDouble:.0f];
        $(self.settlementBar).DATA(respData);
        $(self.imgState).DATA(nil);
        self.operBar.hidden = YES;
    }
}

ON_SIGNAL3( VankeStatementConfirmModel, RELOADING, signal ) {
    [GEToast showProgress:self.view];
}

ON_SIGNAL3( VankeStatementConfirmModel, RELOADED, signal ) {
    [GEToast hideProgress];
    
    if (![confirmModel isOk]) {
        NSString *msg = [NSString stringWithFormat:@"确认失败: %@", confirmModel.serverResp.message];
        [GEToast showWithText:msg bottomOffset:60.0f duration:2.0f];
    } else {
        [GEToast showWithText:@"确认成功!" bottomOffset:60.0f duration:2.0f];
        [self.model firstPage];
        [self postNotification:self.STATE_CHANGED];
    }
}

ON_SIGNAL3( VankeStatementRejectModel, RELOADING, signal ) {
    [GEToast showProgress:self.view];
}

ON_SIGNAL3( VankeStatementRejectModel, RELOADED, signal ) {
    [GEToast hideProgress];
    if (![rejectModel isOk]) {
        NSString *msg = [NSString stringWithFormat:@"拒绝失败: %@", rejectModel.serverResp.message];
        [GEToast showWithText:msg bottomOffset:60.0f duration:2.0f];
    } else {
        [GEToast showWithText:@"拒绝成功!" bottomOffset:60.0f duration:2.0f];
        [self.model firstPage];
        [self postNotification:self.STATE_CHANGED];
    }
}

#pragma VankeStatementDetailMonthCell_iPhone

-(SRMonthPicker*) buildMonthPicker {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_Hans_CN"];
    SRMonthPicker *picker = [[SRMonthPicker alloc] initWithDate: _settleEquals calendar: calendar];
    picker.yearFirst = YES;
    NSDate *today = [NSDate date];
    picker.maximumYear = today.year;
    picker.minimumYear = 2000;
    return picker;
}

ON_SIGNAL3(VankeStatementDetailMonthCell_iPhone, pickerMask, signal) {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    SRMonthPicker *picker = [self buildMonthPicker];
    [alertController.view addSubview:picker];
    [alertController addAction:({
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            // 立即设置账期
            self.settleEquals = picker.date;
            self.model.settle = self.settleEquals;
            [self.model firstPage];
        }];
        action;
    })];
    [alertController addAction:({
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        action;
    })];
    
    UIPopoverPresentationController *popoverController = alertController.popoverPresentationController;
    popoverController.sourceView = self.view;
    popoverController.sourceRect = [self.view bounds];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma VankeStatementDetailListBoard_iPhone

#define ALERT_REJECT_TAG 100

ON_SIGNAL3(VankeStateDetailOperCell_iPhone, btnReject, signal) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拒绝原因" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *textField = [alert textFieldAtIndex:0];
    textField.placeholder = @"请输入拒绝原因...";
//    textField.borderStyle=UITextBorderStyleRoundedRect;
    alert.tag = ALERT_REJECT_TAG;
    [alert show];
}

ON_SIGNAL3(VankeStateDetailOperCell_iPhone, btnConfirm, signal) {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"是否确认账单？" message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        INFO(@"正在确认账单。。。");
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMM"];
        NSString *settleStr = [dateFormatter stringFromDate:_settleEquals];
        [confirmModel confirm: _model.contract settle:settleStr];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:archiveAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == ALERT_REJECT_TAG) {
        if (buttonIndex == 1) {
            INFO(@"准备拒绝单据");
            UITextField * msgField = [alertView textFieldAtIndex:0];
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyyMM"];
            NSString *settleStr = [dateFormatter stringFromDate:_settleEquals];
            
            [rejectModel reject:_model.contract settle:settleStr message:msgField.text];
        }
    }
}

#pragma private methods

-(void) initListAndModel {
    self.list.headerClass = [PullLoader class];
    self.list.headerShown = YES;
    
    self.list.footerClass = [FootLoader class];
    self.list.footerShown = YES;
    
    self.list.lineCount = 1;
    self.list.animationDuration = 0.2f;
    self.list.baseInsets = bee.ui.config.baseInsets;
    
    self.list.whenReloading = ^
    {
        self.list.total = _model.items.count;
        
        INFO(@"total = %d", _model.items.count);
        
        if (self.list.total <= 0) {
            self.list.total = 1;
            BeeUIScrollItem * item = self.list.items[0];
            
            item.size = CGSizeMake( self.list.width, 200);
            item.order = 0;
            item.rule = BeeUIScrollLayoutRule_Fall;
            item.clazz = [NoDataCell_iPhoneCell class];
            item.data = @"没有数据，请稍后重试！";
        } else {
            for ( BeeUIScrollItem *item in self.list.items )
            {
                item.size = CGSizeMake( self.list.width / self.list.lineCount, 70 );
                item.order = 0;
                item.rule = BeeUIScrollLayoutRule_Fall;
                item.clazz = [VankeStatementDetailListCell_iPhone class];
                SubjectItem *subject = [_model.items safeObjectAtIndex:item.index];
                item.data = subject;
            }
        }
    };
    self.list.whenReloaded = ^
    {
    };
    
    self.list.whenAnimated = ^
    {
    };
    self.list.whenScrolling = ^
    {
    };
    self.list.whenStop = ^
    {
    };
    self.list.whenHeaderRefresh = ^
    {
        [self.model firstPage];
    };
    self.list.whenFooterRefresh = ^
    {
        [self.model nextPage];
    };

    _model.settle = _settleEquals;
    _model.contract = _contractEquals;
}

@end
