//
//	 ______    ______    ______
//	/\  __ \  /\  ___\  /\  ___\
// //	\ \  __<  \ \  __\_ \ \  __\_
//	 \ \_____\ \ \_____\ \ \_____\
// //	  \/_____/  \/_____/  \/_____/
//
//	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 "NoDataCell_iPhoneCell.h"
#import "VankeStatementRejectModel.h"
#import "VankeStatementConfirmModel.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 authorizedOrgUuidEquals = _authorizedOrgUuidEquals;

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

- (void)load
{
    self.model = [VankeStatementListModel 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 codeName];
    [self showOperButtons: [_data unconfirmed]];
    [self initListAndModel];
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    self.navigationBarShown = YES;
    //    [self.list reloadData];
    
    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( VankeStatementListModel, RELOADING, signal )
{
    [GEToast showProgress:self.view];
    self.list.headerLoading = YES;
    self.list.footerLoading = YES;
}

ON_SIGNAL3( VankeStatementListModel, RELOADED, signal )
{
    [GEToast hideProgress];
    self.list.headerLoading = NO;
    self.list.footerLoading = NO;
    self.list.footerMore = self.model.more;
    [self.list reloadData];
    $(self.settlementBar).DATA(_data);
    $(self.imgState).DATA([NSString stringWithFormat:@"%@_big.png", _data.state]);
    [self showOperButtons: [_data unconfirmed]];
}

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:50.0f duration:2.0f];
    } else {
        [GEToast showWithText:@"确认成功!" bottomOffset:50.0f duration:2.0f];
        [self.model firstPage];
    }
}

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

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

#pragma VankeStatementDetailMonthCell_iPhone

ON_SIGNAL3(VankeStatementDetailMonthCell_iPhone, pickerMask, signal) {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIDatePicker *picker = [[UIDatePicker alloc] init];
    [picker setDatePickerMode:UIDatePickerModeDate];
    [picker setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_Hans_CN"]];
    [alertController.view addSubview:picker];
    [alertController addAction:({
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            // 立即设置账期
            self.settleEquals = picker.date;
            self.model.settleEquals = 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(VankeStatementDetailListBoard_iPhone, btnReject, signal) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拒绝原因" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    alert.tag = ALERT_REJECT_TAG;
    [alert show];
}

ON_SIGNAL3(VankeStatementDetailListBoard_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: _data.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:_data.contract settle:settleStr message:msgField.text];
        }
    }
}

#pragma private methods

-(void) showOperButtons: (BOOL) show {
    NSArray *items = [[NSArray alloc] initWithObjects: $(@"bg1"),$(@"bg2"),$(@"btnReject"),$(@"btnConfirm"), nil];
    for (BeeUIQuery *qry in items) {
        if (show) {
            qry.SHOW();
        } else {
            qry.HIDE();
        }
    }
}

-(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 initCurrentData];
        self.list.total = _data.items.count;
        
        INFO(@"total = %d", _data.items.count);
        
        if (self.list.total <= 0) {
            self.list.total = 1;
            BeeUIScrollItem * item = self.list.items[0];
            
            item.size = CGSizeMake( self.list.width, 50);
            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 = [_data.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];
    };
    
    if (![VankeUtil isBlankString:_data.shopCode]) {
        _model.shopLike = _data.shopCode;
    }
    _model.projectsIn = [[NSArray alloc] initWithObjects:_authorizedOrgUuidEquals, nil];
    _model.settleEquals = _settleEquals;
}

-(void) initCurrentData {
    for (StatementShop *shop in _model.shops) {
        if (nil != _data && nil != _data.shopCode && [_data.shopCode eq:shop.shopCode]) {
            _data = shop;
            break;
        }
    }
}


@end
