//
//  ViewController.m
//  FunCell123 PlatFormSDK
//
//  Created by soko on 3/13/2014.
//  Copyright (c) 2014 funcell123.com. All rights reserved.
//
//http://58.218.147.147:8082

#define UI_SCREEN_WIDTH                     [[UIScreen mainScreen] bounds].size.width
#define UI_SCREEN_HEIGHT                    [[UIScreen mainScreen] bounds].size.height
#define IMAGERESOURCEPATH               [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"GameImages"]
#define BUTTONWIDTH                 150
#define BUTTONHEIGHT                40


#import "ViewController.h"
//#import "PlatformInterface_IOS.h"
#import "PlatformInterface.h"


@interface ViewController ()

@end

@implementation ViewController


- (BOOL)prefersStatusBarHidden{
    return YES;
}

static ViewController* shareView = nil;
//当前实例系统
+(ViewController*) shareInstace
{
    @synchronized(self){
        if( shareView == nil)
        {
            shareView = [[self alloc] init];
        }
    }
    return  shareView;
}


- (void)viewDidLoad
{
    NSLog(@"ViewController viewDidLoad");
    [self InitSystem];
    CPlatformInterface::SetAreaInfo("12", "11");
    CPlatformInterface::SetRoleInfo("test", "123456");
}

- (void)viewDidUnload
{
}

//初始化回调的ＳＤＫ系统
-(void)InitSystem
{
    NSLog(@"ViewController InitSystem");
    //设置当前的实例
    shareView =self;
    //-DEMO-----
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    bgloginImageView = [[UIImageView alloc] init];
    [bgloginImageView setUserInteractionEnabled:YES];
    
    [bgloginImageView setFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    [[self view] addSubview:bgloginImageView];
    [bgloginImageView setHidden:NO];
    
    
    
    pploginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [pploginButton setFrame:CGRectMake(0, 0, 150, 40)];
    [pploginButton addTarget:self action:@selector(loginPressDown) forControlEvents:UIControlEventTouchUpInside];
    [pploginButton setImage:[UIImage imageWithContentsOfFile:[IMAGERESOURCEPATH stringByAppendingPathComponent:@"button.png"]]
                   forState:UIControlStateNormal];
    [bgloginImageView addSubview:pploginButton];
    
    
    UIView *view = [[UIView alloc] init];
    [view setTag:11];
    [view setFrame:CGRectMake(0, 0, 100, 100)];
    [self.view addSubview:view];
    [view release];
    
    
    //    ppmb = [PPMBProgressHUD showHUDAddedTo:view animated:YES];
    //    ppmb = [[PPMBProgressHUD alloc] init];
    //    [view addSubview:ppmb];
    //    [ppmb release];
    
    
    
    NSArray *array = [NSArray arrayWithObjects:@"正式",@"测试",@"自定义", nil];
    changeAddressButton = [[UISegmentedControl alloc] initWithItems:array];
    [changeAddressButton setSelectedSegmentIndex:0];
    [changeAddressButton addTarget:self action:@selector(changeAddressButtonPressDown)
                  forControlEvents:UIControlEventValueChanged];
    [changeAddressButton setFrame:CGRectMake(10, 10, 150, 30)];
    //    [bgloginImageView addSubview:changeAddressButton];
    
    
    //    customAddresTextField = [[UITextField alloc] init];
    //    [customAddresTextField setFrame:CGRectMake(10, 50, 250, 35)];
    //    [customAddresTextField setText:@"http://"];
    //    [customAddresTextField setDelegate:self];
    //    [customAddresTextField addTarget:self action:@selector(textFieldDidChange)
    //                    forControlEvents:UIControlEventEditingChanged];
    //    [customAddresTextField setBorderStyle:UITextBorderStyleLine];
    //    [bgloginImageView addSubview:customAddresTextField];
    //    [customAddresTextField setHidden:YES];
    
    UILabel *loginLabel = [[UILabel alloc] init];
    [loginLabel setBackgroundColor:[UIColor clearColor]];
    [loginLabel setText:@"登 录"];
    [loginLabel setFrame:CGRectMake(0, 0, BUTTONWIDTH, BUTTONHEIGHT)];
    [loginLabel setTextAlignment:NSTextAlignmentCenter];
    [pploginButton addSubview:loginLabel];
    [loginLabel release];
    
    
    bgGanmeCenterImageView = [[UIImageView alloc] init];
    [bgGanmeCenterImageView setUserInteractionEnabled:YES];
    [bgGanmeCenterImageView setFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    [[self view] addSubview:bgGanmeCenterImageView];
    [bgGanmeCenterImageView setHidden:YES];

    
    //NOTE 显示状态
    _showLabelForPropView = [[UILabel alloc] initWithFrame:CGRectMake(0, 290, 200, 40)];
    [bgGanmeCenterImageView addSubview:_showLabelForPropView];
    _showLabelForPropView.font = [UIFont systemFontOfSize:10];
    _showLabelForPropView.backgroundColor = [UIColor clearColor];
    
    
    _showLabelForBgloginImageView = [[UILabel alloc] initWithFrame:CGRectMake(0, 290, 200, 40)];
    [bgloginImageView addSubview:_showLabelForBgloginImageView];
    _showLabelForBgloginImageView.font = [UIFont systemFontOfSize:10];
    _showLabelForBgloginImageView.backgroundColor = [UIColor clearColor];
    
    
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        [pploginButton setCenter:CGPointMake(UI_SCREEN_WIDTH / 2, UI_SCREEN_HEIGHT / 2 + 30)];
        [bgloginImageView setImage:[UIImage imageWithContentsOfFile:[IMAGERESOURCEPATH stringByAppendingPathComponent:@"Login.png"]]];
        [bgGanmeCenterImageView setImage:[UIImage imageWithContentsOfFile:[IMAGERESOURCEPATH stringByAppendingPathComponent:@"bg.png"]]];
    }else{
        [pploginButton setFrame:CGRectMake(UI_SCREEN_HEIGHT / 2 - BUTTONWIDTH / 2, UI_SCREEN_WIDTH / 2 + 10, 150, 40)];
        [bgloginImageView setImage:[UIImage imageWithContentsOfFile:[IMAGERESOURCEPATH stringByAppendingPathComponent:@"Login_iPad.png"]]];
        [bgGanmeCenterImageView setImage:[UIImage imageWithContentsOfFile:[IMAGERESOURCEPATH stringByAppendingPathComponent:@"bg.png"]]];
    }
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)[[UIApplication sharedApplication] statusBarOrientation];
    [self willRotateToInterfaceOrientation:interfaceOrientation duration:NSTimeIntervalSince1970];
    
    //--------DEMO-------
}

- (void)changeAddressButtonPressDown
{
    NSLog(@"changeAddressButtonPressDown");
}

#pragma mark ---------------------------------------------------- 登 录 -------------------------------------------------------

- (void)loginPressDown{
    //如果想屏蔽登陆界面关闭按钮请使用以下代码
    //    Class PPLoginViewImpl = NSClassFromString(@"PPLoginView");
    //    id activeInstance = [PPLoginViewImpl performSelector:@selector(sharedInstance)];
    //    for (int i = 0 ; i < [[activeInstance subviews] count]; i++) {
    //        UIView *mainView = [[activeInstance subviews] objectAtIndex:i];
    //        for (int i = 0 ; i < [[mainView subviews] count]; i++) {
    //            UIView *imageView = [[mainView subviews] objectAtIndex:i];
    //            for (int i = 0 ; i < [[imageView subviews] count]; i++) {
    //                UIView *buttonView = [[imageView subviews] objectAtIndex:i];
    //                if ([buttonView isKindOfClass:[UIButton class]]) {
    //                    if (buttonView.frame.size.height == 60 && buttonView.frame.size.width == 60) {
    //                        [buttonView setHidden:YES];
    //                    }
    //                }
    //            }
    //        }
    //    }
    
    CPlatformInterface::Login();
}


- (void)buy:(UIButton *)sender{
   // double prices[] = {1, 2, 3, 4};
    int index = (int)sender.tag;
    _name = [[NSString alloc] initWithFormat:@"%@",[arrayName objectAtIndex:index]];
    
    
    [self exchangeGoods:index];
}

static string m_paylist="";

-(void)setPayList:(NSString*)paylist
{
    NSLog(@"viewcontroller serpaylist");
    m_paylist.assign([paylist UTF8String]);
}

- (void)exchangeGoods:(int)index
{
    if (m_paylist.length() < 1)
    {
        CPlatformInterface::GetPayList();
        //[CFunCellPlatfom showAlert:@"正在请求资源，请稍候。。。。。"];
        return ;
    }
    
    string paylist = m_paylist;//CPlatformInterface::GetPayList(); //不强制更新，如果调用getpaylist(true) 表示强制更新列表
    NSString * outJson = [NSString stringWithFormat:@"%s",paylist.c_str()];
    NSData* jsdata = [outJson dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsdata options:NSJSONReadingMutableLeaves error:&error];
    //NSDictionary *dic = [outJson JSONValue];
    
    NSEnumerator * enumeratorValue = [dic objectEnumerator];
    //检查是否有过期的物品
    for( NSDictionary * object in enumeratorValue)
    {
        int64_t overtime = [[object objectForKey:@"end_date"] longLongValue];
        int64_t over = overtime - (int64_t)(time(0));
        
        if ( overtime != 0 && over < 1)
        {
            CPlatformInterface::GetPayList();//强更新
            [self showPayview];
            //结束
            break;
        }
    }
    
    if ( [dic count] > index)
    {
        int sortNo = -1;
        
        NSEnumerator * enumValue = [dic objectEnumerator];
        
        for( NSDictionary * object in enumValue)
        {
            sortNo = sortNo + 1;
            if ( sortNo != index) continue;
            NSString * item = [object objectForKey:@"item"];
            NSString * type = [object objectForKey:@"category"];
            NSString * itemName=[object objectForKey:@"name"];
            
            float  price = [[object objectForKey:@"price"] floatValue];
            int64_t overtime = [[object objectForKey:@"end_date"] longLongValue];
            
            if ( overtime != 0)
            {
                int64_t over = overtime - (int64_t)(time(0)) + 300;//可以推后5分钟计算过期时间
                if ( over < 1 ) //如果过期这个就需要特殊处理， 如果要求还是以原价格购买，则购买，如果不让购买则给出相应的提示信息再进行
                {
                    UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                        message:@"物品已经过期了，不能再购买了，请重新打开一下支付界面！"
                                                                       delegate:nil
                                                              cancelButtonTitle:NSLocalizedString(@"确定",nil)
                                                              otherButtonTitles:nil];
                    
                    [alerView show];
                    [alerView release];
                    
                    //刷新支付界面
                    return ;
                }
            }
            
            //打折价格检查
            float tmp = [[object objectForKey:@"discount_price"] floatValue];
            if (tmp != 0)
            {
                price = tmp;
            }
            CPlatformInterface::Pay([item UTF8String], [itemName UTF8String], [ type UTF8String], 1, price, "RMB");
            
            //结束
            break;
        }
    }
    else{
        
    }
}

- (void) LogOff
{
    NSLog(@"注销的回调");
    NSLog(@"注销的回调");
    _showLabelForPropView.text = @"注销的回调";
    _showLabelForBgloginImageView.text = @"注销的回调";
    _showLabelForPropView.text = @"注销的回调";
    _showLabelForBgloginImageView.text = @"注销的回调";
    [bgGanmeCenterImageView setHidden:YES];
    [bgloginImageView setHidden:NO];
}


- (void) doLoginSuccess
{
    if (propView != nil)
    {
        NSLog(@"doLoginSuccess removeview");
        [propView removeFromSuperview];
        propView = nil;
    }
    propView = [[UIView alloc] init];
    [propView setFrame:CGRectMake(0, 0, UI_SCREEN_HEIGHT, UI_SCREEN_WIDTH / 3 * 2)];
    [bgGanmeCenterImageView addSubview:propView];
    
    [bgloginImageView setHidden:YES];
    [bgGanmeCenterImageView setHidden:NO];
    
    NSLog(@"doLoginSuccess end");
    
    CPlatformInterface::SetRoleInfo("123", "11");
    CPlatformInterface::GetPayList();
}

//显示支付界面内容
-(void) showPayview
{
    CPlatformInterface::GetPayList();
}

- (void) showPayView:(const char *)payList
{
    NSLog(@"viewcontroller showpayview");
    string paylist = payList;
    NSString *outJson = [NSString stringWithFormat:@"%s",paylist.c_str()];
    NSData* jsdata = [outJson dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsdata options:NSJSONReadingMutableLeaves error:&error];
    //NSDictionary *dic = [outJson JSONValue];
    
    NSEnumerator * enumeratorValue = [dic objectEnumerator];
    
    arrayName = [[NSMutableArray alloc]  init];
    arrayPrice = [[NSMutableArray alloc]  init];
    
    int index = -1;
    for ( NSDictionary * object in enumeratorValue)
    {
        index += 1;
        [arrayName addObject:[object objectForKey:@"name"]];
        [arrayPrice addObject:[NSString stringWithFormat:@"%d", index]];
    }
    
    
    for (int i = 0; i < [arrayName count]; i++) {
        UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [buyButton setTag:i];
        [buyButton setTitle:@"购 买" forState:UIControlStateNormal];
        [buyButton addTarget:self action:@selector(buy:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *lbl = [[UILabel alloc] init];
        [lbl setTextColor:[UIColor whiteColor]];
        [lbl setText:[arrayName objectAtIndex:i]];
        [lbl setBackgroundColor:[UIColor clearColor]];
        [lbl setNumberOfLines:2];
        if (i % 2 == 0) {
            [lbl setFrame:CGRectMake(propView.frame.size.height / 2 - 100,  10 + i / 2 * 80, 100, 50)];
            [buyButton setFrame:CGRectMake(propView.frame.size.height / 2 - 100, 60 + i / 2 * 80, 100, 30)];
        }else{
            [lbl setFrame:CGRectMake(propView.frame.size.height / 2 + 100,  10 + i / 2 * 80, 100, 50)];
            [buyButton setFrame:CGRectMake(propView.frame.size.height / 2 + 100, 60 + i / 2 * 80, 100, 30)];
        }
        [bgGanmeCenterImageView addSubview:buyButton];
        [bgGanmeCenterImageView addSubview:lbl];
        [lbl release];
    }
}


-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                               duration:(NSTimeInterval)duration
{
    if ([[UIDevice currentDevice].systemVersion intValue] > 7)
        return;
    
	CGRect screenRect = [[UIScreen mainScreen] bounds];
	CGRect rect = CGRectZero;
    
    if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        [propView setFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT / 3 * 2)];
        [pploginButton setCenter:CGPointMake(UI_SCREEN_WIDTH / 2 , UI_SCREEN_HEIGHT / 2)];
        [changeAddressButton setCenter:CGPointMake(UI_SCREEN_WIDTH / 2 , UI_SCREEN_HEIGHT / 2 + 50)];
        [customAddresTextField setCenter:CGPointMake(UI_SCREEN_WIDTH / 2 , UI_SCREEN_HEIGHT / 2 - 90)];
        
        
		rect = screenRect;
	}
	else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
	{
        [propView setFrame:CGRectMake(0, 0, UI_SCREEN_HEIGHT, UI_SCREEN_WIDTH / 3 * 2)];
        [pploginButton setCenter:CGPointMake(UI_SCREEN_HEIGHT / 2, UI_SCREEN_WIDTH / 2 + 30)];
        [changeAddressButton setCenter:CGPointMake(UI_SCREEN_HEIGHT / 2, UI_SCREEN_WIDTH / 2 + 80)];
        [customAddresTextField setCenter:CGPointMake(UI_SCREEN_HEIGHT / 2, UI_SCREEN_WIDTH / 2 - 120)];
        
        
        rect.size = CGSizeMake( screenRect.size.height, screenRect.size.width );
    }
    bgloginImageView.frame = rect;
    bgGanmeCenterImageView.frame = rect;
}


#pragma mark      ---------------------ios supportedInterfaceOrientations -------------
//iOS 6.0旋屏开关
- (BOOL)shouldAutorotate
{
    return YES;
}


//iOS 6.0旋屏支持方向
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
    //return UIInterfaceOrientationMaskLandscape;
}


//iOS 6.0以下旋屏
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
        return YES;
    }
    return NO;
}

-(void) dealloc{
    [super dealloc];
}

@end
