//
//  CartItemCell.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 14-7-9.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "ModelItemCell.h"
#import "iSalesNetwork.h"
#import "EditModelPriceViewController.h"
#import "RAUtils.h"
#import "BundleModelViewController.h"


#define NUMBERS @"0123456789\n"
@implementation ModelItemCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void) init_Stepper:(int) step max:(int) max min:(int)min value:(int)value
{
    
//    [self.stepper becomeFirstResponder];
    if(self.stepper!=nil)
    {
        if(min<=0)
            min=1;
        if(step<=0)
            step=1;
        self.stepper.minimumValue= min;
        
        
        
        self.stepper.stepValue= step;
        
        self.stepper.value= value;
        
        self.pre_val = value;
        
        [self.stepper addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
        self.totalchange=0;
        
    }
}
- (IBAction)setpperChanged:(UIStepper *)sender {
    
    DebugLog(@"setpperChanged");
    
    int val_change=(int)sender.value-self.pre_val;
    
        _totalchange=_totalchange+val_change;
    
    
//    
//    if(val_change==(int)sender.stepValue)
//    {
//        
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            
//            NSDictionary* cart_json = [iSalesNetwork cart_incresement:self.cart_id increse:true];
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                
//                
//                if([[cart_json valueForKey:@"result"] intValue]==2)
//                {
//                    if(self.onReturnQTY)
//                        self.onReturnQTY(sender.value,cart_json);
////                    
////                    if (self.delegate && [self.delegate respondsToSelector:@selector(returnQTY:)]) {
////                        [self.delegate returnQTY:sender.value ];
//                   // }
//                }
//                else
//                {
//                    UIViewController* vc=[RAUtils getViewController :self];
//                    [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Change Model Count" controller:vc] ;
//                }
//                
//                
//
//                
//            });
//        });
//        //increse;
//    }
//    else if(val_change==-(int)sender.stepValue)
//    {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            
//            NSDictionary* cart_json = [iSalesNetwork cart_incresement:self.cart_id increse:false];
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                
//                
//                
//                if([[cart_json valueForKey:@"result"] intValue]==2)
//                {
//                    if(self.onReturnQTY)
//                        self.onReturnQTY(sender.value,cart_json);
//                }
//                else
//                {
//                    UIViewController* vc=[RAUtils getViewController :self];
//                    [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Change Model Count" controller:vc] ;
//                }
//
//                
//            });
//        });
//        
//    }
//    else
//    {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            
//            NSDictionary* cart_json = [iSalesNetwork cart_setQTY:self.cart_id value:sender.value];
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                if([[cart_json valueForKey:@"result"] intValue]==2)
//                {
//                    if(self.onReturnQTY)
//                        self.onReturnQTY(sender.value,cart_json);
////                    if (self.delegate && [self.delegate respondsToSelector:@selector(returnQTY:)]) {
////                        [self.delegate returnQTY:sender.value ];
////                    }
//                }
//                else
//                {
//                    UIViewController* vc=[RAUtils getViewController :self];
//                    [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Change Model Count" controller:vc] ;
//                }
//                
//
//                
//            });
//        });
//        
//        //setvalue;
//    }
    self.pre_val = (int)sender.value;
    
    
    [self cancel_setQTY];
    [self performSelector:@selector(delayRun) withObject:nil afterDelay:0.8];
    
}

-(void) cancel_setQTY
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayRun) object:nil];
}
-(void) delayRun
{
//    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(calculate) object:nil];
//    // 启动
//    [thread start];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
                NSDictionary* cart_json = [iSalesNetwork cart_setQTY:self.cart_id value:self.pre_val];
    
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.totalchange=0;
                    if([[cart_json valueForKey:@"result"] intValue]==2)
                    {
                        if(self.onReturnQTY)
                            self.onReturnQTY(self.pre_val,cart_json);
    //                    if (self.delegate && [self.delegate respondsToSelector:@selector(returnQTY:)]) {
    //                        [self.delegate returnQTY:sender.value ];
    //                    }
                    }
                    else
                    {
                        UIViewController* vc=[RAUtils getViewController :self];
                        [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Change Model Count" controller:vc] ;
                    }
                    
    
                    
                });
            });
    
    
}

- (void)valueChanged:(UIStepper *)sender {
    
    
    
    self.editCount.text = [NSString stringWithFormat:@"%d",(int)sender.value ];
    
    [self set_Count:(int)sender.value ];
    
    
    //
    //    [celldelegate stepClicked:(int)sender.value];
    //    -(void) stepClicked:(int) value;
}
-(void) set_Count:(int) count
{
    
    self.stepper.value=count;
    if(self.enable_longpress)
    {
      //  [self addGestureRecognizer: [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longTap:)]];
    }
    
    double dprice=0;
    if(self.bundle_item!=nil)
    {
        int citem=0;
        
        int bcount=[[self.bundle_item valueForKey:@"count"] intValue];
        for(int bc=0;bc<bcount;bc++)
        {
            NSDictionary * bitem = [self.bundle_item objectForKey:[NSString stringWithFormat:@"item_%d",bc]];
            int modulus= [[bitem valueForKey:@"modulus"] intValue];
            citem+= modulus;
            double uprice= [[bitem valueForKey:@"unit_price"]doubleValue];
            dprice+= uprice*modulus;
            
        }
        if(citem==1)
                self.bundleLabel.text= [NSString stringWithFormat: @"%d bundle item with price of $ %.2f",citem,dprice ];
        else
            self.bundleLabel.text= [NSString stringWithFormat: @"%d bundle items with price of $ %.2f",citem,dprice ];
        self.bundleButton.hidden = NO;
        self.bundleLabel.hidden = NO;
    }
    else
    {
        self.bundleButton.hidden = YES;
        self.bundleLabel.hidden = YES;
    }
    
    //    self.labelUnitPrice.text =[NSString stringWithFormat:@"%.2f",self.unit_price];
    
    
    
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    NSString* price = [NSString stringWithFormat:@"%.2f",(self.unit_price* (1.0-self.discount/100.0)+dprice)*count ];
    if(appDelegate.can_see_price&&appDelegate.price_hidden==false)
    {
        
    }
    else
    {
        price=nil;
    }
    

    if(self.noprice&&self.unit_price==0.0)
        self.labelPrice.text =@"No Price";
    else
        self.labelPrice.text =price;
    
    self.editCount.text =[NSString stringWithFormat:@"%d",count];
}
- (void)awakeFromNib
{
    // Initialization code
    
    

}


//-(UIViewController*) getViewController
//{
//    for (UIView* next = [self superview]; next; next = next.superview) {
//        UIResponder* nextResponder = [next nextResponder];
//        if ([nextResponder isKindOfClass:[UIViewController class]]) {
//            return (UIViewController*)nextResponder;
//        }
//    }
//    return nil;
//    
//}

- (IBAction)OnClick_BundleDetail:(id)sender {
    
    UIViewController* vc=[RAUtils getViewController :self.bundleButton];
    
    
    BundleModelViewController * bundleVC =[ vc.storyboard instantiateViewControllerWithIdentifier:@"BundleModelViewController"];

    bundleVC.content_data = self.bundle_item;
    
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:bundleVC] ;
    
    
    
    
    
    
    navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
    [vc presentViewController:navi animated:YES completion:^{
        
        //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
        
        DebugLog(@"bundle present.........");
        
        //   self.btop = false;
        //  <#code#>
    }];
    

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}
#pragma mark textField delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    DebugLog(@"text:%@",textField.text);
    
    
  
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
    
    BOOL canChange = [string isEqualToString:filtered];
    
    
    
    
    return canChange;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    int qty = [textField.text intValue];
    
    if(qty==0)
        qty=self.stepper.minimumValue;
    
    
    
        
        int c=qty;
        
        int m=c%(int)(self.stepper.stepValue);
        if(m!=0&&appDelegate.alert_sold_in_quantities)
        {
            
            
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"Sold in quantities of %d, Are you sure?",(int)(self.stepper.stepValue)] message:nil preferredStyle:UIAlertControllerStyleAlert];
            //block代码块取代了delegate
            
            
            
            UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                [self set_Count:qty];
                
                
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* cart_json = [iSalesNetwork cart_setQTY:self.cart_id value:qty];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if([[cart_json valueForKey:@"result"] intValue]==2)
                        {
                            //                if (self.delegate && [self.delegate respondsToSelector:@selector(returnQTY:)]) {
                            //                    [self.delegate returnQTY:qty];
                            //                }
                            
                            if(self.onReturnQTY)
                                self.onReturnQTY(qty,cart_json);
                        }
                        else
                        {
                            UIViewController* vc=[RAUtils getViewController :self];
                            [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Change Model Count" controller:vc] ;
                        }
                        
                        
                        
                    });
                });

            }];
            
            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                DebugLog(@"No");
                textField.text = [NSString stringWithFormat:@"%d",self.pre_val];
            }];
            [alertControl addAction:actionOne];
            
            [alertControl addAction:alertthree];
            
            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
            
            UIViewController *vc= [RAUtils getViewController:self];
            [vc presentViewController:alertControl animated:YES completion:nil];
            
            
            
        }
        else
        {
            [self set_Count:qty];
            
            
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                NSDictionary* cart_json = [iSalesNetwork cart_setQTY:self.cart_id value:qty];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if([[cart_json valueForKey:@"result"] intValue]==2)
                    {
                        //                if (self.delegate && [self.delegate respondsToSelector:@selector(returnQTY:)]) {
                        //                    [self.delegate returnQTY:qty];
                        //                }
                        
                        if(self.onReturnQTY)
                            self.onReturnQTY(qty,cart_json);
                    }
                    else
                    {
                        UIViewController* vc=[RAUtils getViewController :self];
                        [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Change Model Count" controller:vc] ;
                    }
                    
                    
                    
                });
            });

        }
        
    
        
    
    
    
    

}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSString* text = textField.text;
    if(text.length==0)
        text=@"0";
    self.pre_val = [textField.text intValue];
    
   // self.last_edit = textField.text;
}

@end
