//
//  ICRSystemViewController.m
//  Cruiser
//
//  Created by Xummer on 3/24/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRSystemViewController.h"
#import "ICRSystemHeaderView.h"
#import "ICRModifyPwdViewController.h"
#import "ICRConfigurationViewController.h"
#import "ICRHelpAndFeedBackViewController.h"
#import "ICRAboutViewController.h"
#import "ICRAppMacro.h"
#import "AppDelegate.h"
#import "GEToast.h"
#import "VankeVersionAPI.h"
#import "VankeCommonModel.h"

#define TAG_ACTION_SHEET_EXIT 0

@interface ICRSystemViewController ()

@property (strong, nonatomic) IBTTableViewInfo *m_tableViewInfo;
@property (weak, nonatomic) ICRSystemHeaderView *m_tableHeader;
@property (strong, nonatomic) NSString *upgradeUrl;
@end

@implementation ICRSystemViewController

DEF_NOTIFICATION( SUCC_LOGOUT )

#pragma mark - Life Cycle

ON_CREATE_VIEWS( signal )
{
    self.navigationBarShown = YES;
    self.navigationBarTitle = @"我";
    self.navigationBarLeft  = nil;
    
    UIColor *color = [UIColor colorWithR:63 g:134 b:244 a:1];
    if ( IOS7_OR_LATER ) {
        self.navigationController.navigationBar.barTintColor = color;
    } else {
        self.navigationController.navigationBar.tintColor = color;
    }
}

ON_WILL_APPEAR( signal )
{
    self.navigationBarShown = YES;
}

ON_DID_APPEAR( signal )
{
    [self initTableViewInfo];
}

#pragma mark - Private Method
- (void)initTableViewInfo {
    CGRect bounds = self.view.bounds;
    bounds.origin.y = 64;
    self.m_tableViewInfo = [[IBTTableViewInfo alloc] initWithFrame:bounds style:UITableViewStyleGrouped];
    
    IBTTableView *tableV = [_m_tableViewInfo getTableView];
    tableV.backgroundColor = [UIColor colorWithW:246 a:1];
    [self.view addSubview:tableV];
    
    // Header
    ICRSystemHeaderView *tableHeader = [[ICRSystemHeaderView alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = 0,
        .size.width = tableV.width,
        .size.height = 150
    }];
    tableV.tableHeaderView = tableHeader;
    self.m_tableHeader = tableHeader;
    
    [tableHeader updateWithUserUtil];
    
    // Footer
    UIButton *btn = nil;
    UIView *tableFooter =
    [tableV buttonViewWithTitle:[IBTCommon localizableString:@"Logout"]
                          color:ICR_ORANGE_BTN_COLOR
                         topGap:25
                        pointer:&btn
                         target:self
                         action:@selector(onLogout:)];
    [btn.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    tableV.tableFooterView = tableFooter;
    
    IBTTableViewSectionInfo *secInfo;
    IBTTableViewCellInfo *cellInfo;
    
    UIColor *titleColor = [UIColor colorWithW:109 a:1];
    CGFloat fCellHeight = IBT_DEFAULT_CELL_HEIGHT;
    
    secInfo = [IBTTableViewSectionInfo sectionInfoDefaut];
    // Change Password
    cellInfo =
    [IBTTableViewCellInfo normalCellForSel:@selector(onChangePassword:) target:self
                                     title:[IBTCommon localizableString:@"Change Password"]
                                rightValue:nil
                             accessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    
    // Setting
//    cellInfo =
//    [IBTTableViewCellInfo normalCellForSel:@selector(onShowSettingView:) target:self
//                                     title:[IBTCommon localizableString:@"Setting"]
//                                rightValue:nil
//                             accessoryType:UITableViewCellAccessoryDisclosureIndicator];
//    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
//    cellInfo.fCellHeight = fCellHeight;
//    [secInfo addCell:cellInfo];
    
    // Help & Feedback
    cellInfo =
    [IBTTableViewCellInfo normalCellForSel:@selector(onShowHelpAndFeedBackView:) target:self
                                     title:[IBTCommon localizableString:@"Help & Feedback"]
                                rightValue:nil
                             accessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    
    // About
    cellInfo =
    [IBTTableViewCellInfo normalCellForSel:@selector(onShowAboutView:) target:self
                                     title:[IBTCommon localizableString:@"About"]
                                rightValue:nil
                             accessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    
    // 检查版本更新
    cellInfo =
    [IBTTableViewCellInfo normalCellForSel:@selector(onCheckNewVersion:) target:self
                                     title:@"检查版本更新"
                                rightValue:nil
                             accessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey];
    cellInfo.fCellHeight = fCellHeight;
    [secInfo addCell:cellInfo];
    
    [self.m_tableViewInfo addSection:secInfo];
}

#pragma mark - Actions
- (void)onLogout:(__unused id)sender {
//    ICRAppViewControllerManager *mgr =
//    [ICRAppViewControllerManager getAppViewControllerManager];
//    [mgr doLogout];
    [self confirmToLogout];
}

- (void)onChangePassword:(__unused id)sender {
//    ICRModifyPwdViewController *modifyPWDVC = [[ICRModifyPwdViewController alloc] init];
//    [self PushViewController:modifyPWDVC animated:YES];
    ICRModifyPwdViewController *board = [ICRModifyPwdViewController board];
    [self.stack pushBoard:board animated:YES];
}

- (void)onShowSettingView:(__unused id)sender {
//    ICRConfigurationViewController *configurationVC = [[ICRConfigurationViewController alloc] init];
//    [self PushViewController:configurationVC animated:YES];
    
    ICRConfigurationViewController *board = [ICRConfigurationViewController board];
    [self.stack pushBoard:board animated:YES];
}


- (void)onShowHelpAndFeedBackView:(__unused id)sender {
//    ICRHelpAndFeedBackViewController *helpAndFeedVC = [[ICRHelpAndFeedBackViewController alloc] init];
//    [self PushViewController:helpAndFeedVC animated:YES];
    
    ICRHelpAndFeedBackViewController *board = [ICRHelpAndFeedBackViewController board];
    [self.stack pushBoard:board animated:YES];
}

- (void)onShowAboutView:(__unused id)sender {
//    ICRAboutViewController *aboutVC = [[ICRAboutViewController alloc] init];
//    [self PushViewController:aboutVC animated:YES];
    
    ICRAboutViewController *board = [ICRAboutViewController board];
    [self.stack pushBoard:board animated:YES];
}

- (void) onCheckNewVersion: (__unused id)sender {
    [self checkNewVersion];
}

-(void) confirmToLogout {
    UIActionSheet *as=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出登录" otherButtonTitles:@"退出应用", nil ];
    as.tag = TAG_ACTION_SHEET_EXIT;
    [as showInView:self.view];
}

-(void) doLogout {
    // 删除当前用户
    VankeCommonModel *userModel = [VankeCommonModel sharedInstance];
    [userModel removeLoginInfo];
    [self postNotification:self.SUCC_LOGOUT];
}

- (void)exitApplication {
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    
    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
    //exit(0);
}

#pragma mark ----------ActionSheet 按钮点击-------------
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == TAG_ACTION_SHEET_EXIT) {
        if (buttonIndex == 0) {
            [self doLogout];
        } else if (buttonIndex == 1) {
            [self exitApplication];
        }
    }
}

-(void) checkNewVersion {
    [VankeVersionAPI cancel];
    
    VankeVersionAPI *api = [VankeVersionAPI api];
    
    @weakify(api);
    @weakify(self);
    
    api.whenSucceed = ^{
        @normalize(api);
        @normalize(self);
        
        if (api.succeed) {
            [GEToast hideProgress];
            
            if (nil == api.serverResp) {
                api.failed = YES;
            } else {
                VersionResponse *resp = (VersionResponse*) api.serverResp;
                [self performSelector:@selector(tryToUpdate:) withObject:resp];
            }
        }
    };
    
    api.whenFailed = ^{
        [GEToast hideProgress];
        [GEToast showWithText:@"当前已经是最新版本了" bottomOffset:45.0f duration:1.0f];
    };
    
    [GEToast showProgress:self.view];
    [api send];
}

-(void) tryToUpdate: (VersionResponse*) resp {
    VersionNumber *newVersion = [resp newVersion];
    if (nil == newVersion) {
        [GEToast showWithText:@"当前已经是最新版本了" bottomOffset:45.0f duration:1.0f];
    } else {
        INFO(@"发现新版本: %@", [newVersion toString]);
        self.upgradeUrl = resp.data.url;
        NSString *msg = [NSString stringWithFormat:@"发现新版本: %@, 请前往下载!", [newVersion toString]];
        if ([resp isForceUpdate]) {
            UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"新版本告知" message: msg delegate:self cancelButtonTitle:nil otherButtonTitles: @"去下载", nil];
            alertV.tag = 1001;
            [alertV show];
        } else {
            UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"新版本告知" message: msg delegate:self cancelButtonTitle:@"下次再说"otherButtonTitles: @"去下载", nil];
            alertV.tag = 1002;
            [alertV show];
        }
    }
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1001) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.upgradeUrl]];
    } else if (alertView.tag == 1002) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.upgradeUrl]];
        } else {
            // TODO
        }
    }
}

@end
