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

#import "DetailHeaderCell.h"
#import "iSalesNetwork.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "ContactListViewController.h"
#import "RAUtils.h"
#import "OrderListViewController.h"


#import "ImageScrollerViewController.h"
#import "CartUtils.h"


@implementation DetailHeaderCell
@synthesize celldelegate;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    
//    self.selector_imageView.layer.borderColor = [UIColorFromRGB(0x996633) CGColor];
//    self.selector_imageView.layer.borderWidth = 1;
    return self;
}

- (void)awakeFromNib
{
    
//    self.selector_imageView.layer.borderColor = [UIColorFromRGB(0x996633) CGColor];
//    self.selector_imageView.layer.borderWidth = 1;
    
    
    
    self.selector_Button.layer.borderWidth = 0.5;
    self.selector_Button.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.selector_Button.layer.cornerRadius = 0;
    
    
    [self.descriptionRTLabel setLineBreakMode: RTTextLineBreakModeWordWrapping];
    [self.descriptionRTLabel setTextAlignment:RTTextAlignmentCenter];
    [self.descriptionRTLabel setFont:[UIFont systemFontOfSize:22]];
//    self.label_net_err.layer.borderColor = [UIColor darkGrayColor].CGColor;
//    self.label_net_err.layer.borderWidth = 2.0;
//    self.label_net_err.layer.cornerRadius=15;
//    self.label_net_err.layer.masksToBounds=true;
    // Initialization code
}
- (IBAction)add_toPortfolio:(id)sender {
    
    //    int count=[self.quantity_text.text intValue];
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    
    if (appDelegate.user && appDelegate.user_type == USER_ROLE_CUSTOMER) {
        [[NSNotificationCenter defaultCenter] postNotificationName:No_Rights_Notification object:nil];
        return;
    }
    
    
    MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
    if(appDelegate.bLogin==false)
    {
        UIViewController *vc= [RAUtils getViewController:self];
        LoginViewController * loginvc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
        //        loginvc.delegate = self;
        //    loginvc.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态，自己看看是哪种
        
        loginvc.returnValue = ^(bool blogin){
            
            
            //            UIApplication * app = [UIApplication sharedApplication];
            //            AppDelegate *appDelegate = (AppDelegate *)[app delegate];
            
            
            
            
            if(blogin)
            {
                
                if(self.set_update_data)
                    self.set_update_data(true);
                
                [main_vc checklogin:true];
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* return_json = [iSalesNetwork add_toPortfolio:self.product_id ];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if([[return_json valueForKey:@"result"] intValue]==2)
                        {
                            
                            // DebugLog(@"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                            [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
                            if(self.WatchlistBlock!=nil)
                            {
                                UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                                
                                
                                CGRect iv_rect = CGRectMake(self.btnaddPortfolio.center.x-50, self.btnaddPortfolio.center.y-50, 100, 100);
                                UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                                iv.image = img;
                                //                        [self.contentView addSubview:iv];
                                self.PortfolioBlock(iv);
                                
                            }
                        }
                        else
                        {
                            [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add to portfolio" controller:vc] ;
                        }
                        
                        
                        
                    });
                });
                
                
            }
            
            //            self.offset = 0;
            //            [self.content_data removeAllObjects];
            //            [self loadpage];
            //
            //            [[self navigationController] setNavigationBarHidden:YES animated:NO];
            
        };
        
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
        
        
        
        
        
        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
        
        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
        [vc presentViewController:navi animated:YES completion:^{
            
            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
            
            DebugLog(@"LoginViewController present.........");
            
            //   self.btop = false;
            //  <#code#>
        }];
    }
    else
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSDictionary* return_json = [iSalesNetwork add_toPortfolio:self.product_id ];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if([[return_json valueForKey:@"result"] intValue]==2)
                {
                    [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
                    if(self.WatchlistBlock!=nil)
                    {
                        UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                        
                        
                        CGRect iv_rect = CGRectMake(self.btnaddPortfolio.center.x-50, self.btnaddPortfolio.center.y-50, 100, 100);
                        UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                        iv.image = img;
                        //                        [self.contentView addSubview:iv];
                        self.PortfolioBlock(iv);
                        
                    }
                }
                else
                {
                    UIViewController *vc= [RAUtils getViewController:self];
                    [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add to portfolio" controller:vc] ;
                }
                
                
                
            });
        });
    }
}

- (IBAction)add_toWatchList:(id)sender {
    
    //    int count=[self.quantity_text.text intValue];
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
    if(appDelegate.bLogin==false)
    {
        UIViewController *vc= [RAUtils getViewController:self];
        LoginViewController * loginvc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
        //        loginvc.delegate = self;
        //    loginvc.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态，自己看看是哪种
        
        loginvc.returnValue = ^(bool blogin){
            
            
            //            UIApplication * app = [UIApplication sharedApplication];
            //            AppDelegate *appDelegate = (AppDelegate *)[app delegate];
            
            
            
            
            if(blogin)
            {
                
                if(self.set_update_data)
                    self.set_update_data(true);
                
                [main_vc checklogin:true];
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* return_json = [iSalesNetwork add_toWatchList:self.product_id ];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if([[return_json valueForKey:@"result"] intValue]==2)
                        {
                            
                           // DebugLog(@"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                            [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
                            if(self.WatchlistBlock!=nil)
                            {
                                UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                                
                                
                                CGRect iv_rect = CGRectMake(self.btnaddWish.center.x-50, self.btnaddWish.center.y-50, 100, 100);
                                UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                                iv.image = img;
                                //                        [self.contentView addSubview:iv];
                                self.WatchlistBlock(iv);
                                
                            }
                        }
                        else
                        {
                            [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add Wish List" controller:vc] ;
                        }
                        
                        
                        
                    });
                });
                
                
            }
            
            //            self.offset = 0;
            //            [self.content_data removeAllObjects];
            //            [self loadpage];
            //
            //            [[self navigationController] setNavigationBarHidden:YES animated:NO];
            
        };
        
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
        
        
        
        
        
        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
        
        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
        [vc presentViewController:navi animated:YES completion:^{
            
            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
            
            DebugLog(@"LoginViewController present.........");
            
            //   self.btop = false;
            //  <#code#>
        }];
    }
    else
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSDictionary* return_json = [iSalesNetwork add_toWatchList:self.product_id ];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if([[return_json valueForKey:@"result"] intValue]==2)
                {
                    [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
                    if(self.WatchlistBlock!=nil)
                    {
                        UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                        
                        
                        CGRect iv_rect = CGRectMake(self.btnaddWish.center.x-50, self.btnaddWish.center.y-50, 100, 100);
                        UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                        iv.image = img;
                        //                        [self.contentView addSubview:iv];
                        self.WatchlistBlock(iv);
                        
                    }
                }
                else
                {
                    UIViewController *vc= [RAUtils getViewController:self];
                    [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add Wish List" controller:vc] ;
                }
                
                
                
            });
        });
    }
}

- (IBAction)add_toCart:(id)sender {
    
    UIViewController *vc= [RAUtils getViewController:self];
    [CartUtils add_to_cart:vc selectorholder:self selector:@selector(addtocart)];
    return;
    
    
    int count=[self.quantity_text.text intValue];
    
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
    if(appDelegate.bLogin==false)
    {
        UIViewController *vc= [RAUtils getViewController:self];
        LoginViewController * loginvc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
        //        loginvc.delegate = self;
        //    loginvc.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态，自己看看是哪种
        
        loginvc.returnValue = ^(bool blogin){
            
            
            //            UIApplication * app = [UIApplication sharedApplication];
            //            AppDelegate *appDelegate = (AppDelegate *)[app delegate];
            
            
            
            
            if(blogin)
            {
                if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE*/ true)
                {
                    if(self.set_update_data)
                        self.set_update_data(true);
                    [main_vc checklogin:false];
                    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"Do you want to add to pending a order or a new order", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil),NSLocalizedString(@"Add to new order", nil), nil];
                    
                    
                    
                    // alert.
                    [alert show];
                }
                else
                {
                    [main_vc checklogin:true];
                    
                    int c=[self.count_Label.text intValue];
                    DebugLog(@"count label : %@ , convert:%d", self.count_Label.text ,c);
                    
                    NSString* ct=[self.count_Label.text stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                    
                    
                    
                    if(c<count)
                    {
                        
                        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Availability %@",ct ] message:NSLocalizedString(@"Confirm add to cart. ", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Confirm", nil), nil];
                        
                        // alert.
                        
                        alert.tag = 1234;
                        [alert show];
                    }
                    else
                    {
                        if(appDelegate.order_code==nil)
                            [ self neworder];
                        else
                            [self addtocart:count];
                    }
                    
                    
                }
            }
            
            //            self.offset = 0;
            //            [self.content_data removeAllObjects];
            //            [self loadpage];
            //
            //            [[self navigationController] setNavigationBarHidden:YES animated:NO];
            
        };
        
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
        
        
        
        
        
        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
        
        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
        [vc presentViewController:navi animated:YES completion:^{
            
            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
            
            DebugLog(@"LoginViewController present.........");
            
            //   self.btop = false;
            //  <#code#>
        }];
    }
    else
    {
        
        
        if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE&&/*appDelegate.contact_id==nil&&*/appDelegate.order_code==nil)
        {
            [main_vc checklogin:false];
            
            if(appDelegate.can_create_order)
            {
                NSString* msg =@"";
                if(appDelegate.contact_id.length>0)
                {
                    msg = [msg stringByAppendingString:@"\n\nCustomer:"];
                    msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
                    
                }
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil),NSLocalizedString(@"Add to new order", nil), nil];
            
            // alert.
            [alert show];
            }
            else
            {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"Do you want to add to a pending order?", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil), nil];
                
                // alert.
                [alert show];
            }
        }
        else
        {
            
//            if ([self.priceLabel.text isEqualToString:@"No Price."])
//            {
////                UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @"Model No Price" message:@"Cannot add model without price." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
////
////                
////                
////                [alert show];
//                
//                
//                
//                [RAUtils alert_view:@"Cannot add model without price." title:@"Model No Price."];
//            }
//            else
            {
                
                int c=[self.count_Label.text intValue];
                DebugLog(@"count label : %@ , convert:%d", self.count_Label.text ,c);
                
                NSString* ct=[self.count_Label.text stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                
                
                
                if(c<count)
                {
                    
                    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Availability %@",ct ] message:NSLocalizedString(@"Confirm add to cart. ", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Confirm", nil), nil];
                    
                    // alert.
                    
                    alert.tag = 1234;
                    [alert show];
                }
                else
                {
                    if(appDelegate.order_code==nil)
                        [ self neworder];
                    else
                        [self addtocart:count];
                }
            }
            
        }
    }
    
    
    
    
    
    
    
    
}
-(void) addtocart
{
    int count=[self.quantity_text.text intValue];
    
    [self addtocart:count];
}
-(void)Hide_selector:(bool) bhide
{
    self.selector_Button.hidden=bhide;
    self.selector_dorpdown.hidden=bhide;
    self.selector_imageView.hidden=bhide;
    
}
-(void) addtocart:(int) count
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    if(self.cqty>0)
    {
        
        
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"QTY: %d of this model already in cart. Continue ?",self.cqty] message:nil preferredStyle:UIAlertControllerStyleAlert];
        //block代码块取代了delegate
        
        
        
        UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            
            int c=self.cqty+count;
            
            int m=c%self.step;
            if(m!=0&&appDelegate.alert_sold_in_quantities)
            {
                
                
                
                UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"Sold in quantities of %d, Are you sure?",self.step] message:nil preferredStyle:UIAlertControllerStyleAlert];
                //block代码块取代了delegate
                
                
                
                UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                    
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        
                        NSDictionary* return_json = [iSalesNetwork add_toCart:self.product_id count:count];
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            
                            
                            if([[return_json valueForKey:@"result"] intValue]==2)
                            {
                                
                                //    NSString* order_code = [return_json valueForKey:@"order_code"];
                                AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
                                
                                
                                if(self.shopCartBlock!=nil)
                                {
                                    UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                                    
                                    
                                    CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
                                    UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                                    iv.image = img;
                                    //                        [self.contentView addSubview:iv];
                                    self.shopCartBlock(iv);
                                    
                                    self.cqty +=count;
                                    if(self.set_cqty)
                                        self.set_cqty(self.cqty);
                                    
                                }
                                
                                
                            }
                            else
                            {
                                UIViewController *vc= [RAUtils getViewController:self];
                                [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:vc] ;
                            }
                            
                            
                            
                            
                        });
                    });
                    
                    
                }];
                
                UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    DebugLog(@"No");
                }];
                [alertControl addAction:actionOne];
                
                [alertControl addAction:alertthree];
                
                //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
                
                UIViewController *vc= [RAUtils getViewController:self];
                [vc presentViewController:alertControl animated:YES completion:nil];
                
                
                
            }
            else
            {
                            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                                NSDictionary* return_json = [iSalesNetwork add_toCart:self.product_id count:count];
                
                                dispatch_async(dispatch_get_main_queue(), ^{
                
                
                
                                    if([[return_json valueForKey:@"result"] intValue]==2)
                                    {
                
                                        //    NSString* order_code = [return_json valueForKey:@"order_code"];
                                            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                        [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
                
                
                                            if(self.shopCartBlock!=nil)
                                            {
                                                UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                
                
                                                CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
                                                UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                                                iv.image = img;
                                                //                        [self.contentView addSubview:iv];
                                                self.shopCartBlock(iv);
                
                                                self.cqty +=count;
                                                if(self.set_cqty)
                                                    self.set_cqty(self.cqty);
                
                                            }
                                            
                                        
                                    }
                                    else
                                    {
                                        UIViewController *vc= [RAUtils getViewController:self];
                                        [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:vc] ;
                                    }
                                    
                                    
                                    
                                    
                                });
                            });

            }
            
            
//            
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                
//                NSDictionary* return_json = [iSalesNetwork add_toCart:self.product_id count:count];
//                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    
//                    
//                    
//                    if([[return_json valueForKey:@"result"] intValue]==2)
//                    {
//
//                        //    NSString* order_code = [return_json valueForKey:@"order_code"];
//                            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
////                            appDelegate.order_code = order_code;
////                            
////                        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
////                        appDelegate.order_code = order_code;
//                        [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
//                        
//                            
//                            if(self.shopCartBlock!=nil)
//                            {
//                                UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
//                                
//                                
//                                CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
//                                UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
//                                iv.image = img;
//                                //                        [self.contentView addSubview:iv];
//                                self.shopCartBlock(iv);
//                                
//                                self.cqty +=count;
//                                if(self.set_cqty)
//                                    self.set_cqty(self.cqty);
//                                
//                            }
//                            
//                        
//                    }
//                    else
//                    {
//                        UIViewController *vc= [RAUtils getViewController:self];
//                        [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:vc] ;
//                    }
//                    
//                    
//                    
//                    
//                });
//            });
//            
            
        }];
        
        UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            DebugLog(@"No");
        }];
        [alertControl addAction:actionOne];
        
        [alertControl addAction:alertthree];
        
        //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
        
        UIViewController *vc= [RAUtils getViewController:self];
        [vc presentViewController:alertControl animated:YES completion:nil];
        
        
    }
    else
    {
        
        int c=self.cqty+count;
        
        int m=c%self.step;
        if(m!=0&&appDelegate.alert_sold_in_quantities)
        {
            
            
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"Sold in quantities of %d, Are you sure?",self.step] message:nil preferredStyle:UIAlertControllerStyleAlert];
            //block代码块取代了delegate
            
            
            
            UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* return_json = [iSalesNetwork add_toCart:self.product_id count:count];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        
                        
                        if([[return_json valueForKey:@"result"] intValue]==2)
                        {
                            
                            //    NSString* order_code = [return_json valueForKey:@"order_code"];
                            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                            //                            appDelegate.order_code = order_code;
                            //
                            //                        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                            //                        appDelegate.order_code = order_code;
                            [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
                            
                            
                            if(self.shopCartBlock!=nil)
                            {
                                UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                                
                                
                                CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
                                UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                                iv.image = img;
                                //                        [self.contentView addSubview:iv];
                                self.shopCartBlock(iv);
                                
                                self.cqty +=count;
                                if(self.set_cqty)
                                    self.set_cqty(self.cqty);
                                
                            }
                            
                            
                        }
                        else
                        {
                            UIViewController *vc= [RAUtils getViewController:self];
                            [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:vc] ;
                        }
                        
                        
                        
                        
                    });
                });
                
                
            }];
            
            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                DebugLog(@"No");
            }];
            [alertControl addAction:actionOne];
            
            [alertControl addAction:alertthree];
            
            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
            
            UIViewController *vc= [RAUtils getViewController:self];
            [vc presentViewController:alertControl animated:YES completion:nil];
            
            
            
        }
        else
        {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                NSDictionary* return_json = [iSalesNetwork add_toCart:self.product_id count:count];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    
                    
                    if([[return_json valueForKey:@"result"] intValue]==2)
                    {
                        
                        //    NSString* order_code = [return_json valueForKey:@"order_code"];
                        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                        //                            appDelegate.order_code = order_code;
                        //
                        //                        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                        //                        appDelegate.order_code = order_code;
                        [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
                        
                        
                        if(self.shopCartBlock!=nil)
                        {
                            UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                            
                            
                            CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
                            UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                            iv.image = img;
                            //                        [self.contentView addSubview:iv];
                            self.shopCartBlock(iv);
                            
                            self.cqty +=count;
                            if(self.set_cqty)
                                self.set_cqty(self.cqty);
                            
                        }
                        
                        
                    }
                    else
                    {
                        UIViewController *vc= [RAUtils getViewController:self];
                        [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:vc] ;
                    }
                    
                    
                    
                    
                });
            });
            
        }
        
        
        //
        //            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //
        //                NSDictionary* return_json = [iSalesNetwork add_toCart:self.product_id count:count];
        //
        //                dispatch_async(dispatch_get_main_queue(), ^{
        //
        //
        //
        //                    if([[return_json valueForKey:@"result"] intValue]==2)
        //                    {
        //
        //                        //    NSString* order_code = [return_json valueForKey:@"order_code"];
        //                            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        ////                            appDelegate.order_code = order_code;
        ////
        ////                        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        ////                        appDelegate.order_code = order_code;
        //                        [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
        //
        //
        //                            if(self.shopCartBlock!=nil)
        //                            {
        //                                UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
        //
        //
        //                                CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
        //                                UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
        //                                iv.image = img;
        //                                //                        [self.contentView addSubview:iv];
        //                                self.shopCartBlock(iv);
        //
        //                                self.cqty +=count;
        //                                if(self.set_cqty)
        //                                    self.set_cqty(self.cqty);
        //
        //                            }
        //
        //
        //                    }
        //                    else
        //                    {
        //                        UIViewController *vc= [RAUtils getViewController:self];
        //                        [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:vc] ;
        //                    }
        //
        //
        //
        //
        //                });
        //            });
        //
        
    }
    
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

- (IBAction)selectorOnClick:(id)sender {
    DebugLog(@"select click");
    [celldelegate SelectorClicked:(UIButton*) sender];
    //         [self performSegueWithIdentifier:@"selector_popover" sender:self];
    
}
#pragma mark -
#pragma mark Deck DataSource Protocol Methods

-(NSUInteger)numberOfPhotosInPhotoStackView:(PhotoStackView *)photoStack {
    return [self.photos count];
}

-(UIImage *)photoStackView:(PhotoStackView *)photoStack photoForIndex:(NSUInteger)index {
    
    
    if(self.photos.count==0)
        return nil;
    return [self.photos objectAtIndex:index];
}



#pragma mark -
#pragma mark Deck Delegate Protocol Methods

-(void)photoStackView:(PhotoStackView *)photoStackView willStartMovingPhotoAtIndex:(NSUInteger)index {
    // User started moving a photo
}

-(void)photoStackView:(PhotoStackView *)photoStackView willFlickAwayPhotoFromIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex {
    // User flicked the photo away, revealing the next one in the stack
}

-(void)photoStackView:(PhotoStackView *)photoStackView didRevealPhotoAtIndex:(NSUInteger)index {
    self.pageControl.currentPage = index;
}

-(void)photoStackView:(PhotoStackView *)photoStackView didSelectPhotoAtIndex:(NSUInteger)index {
    DebugLog(@"selected %lu", (unsigned long)index);
    
    
//    NSMutableArray *imgList = [NSMutableArray arrayWithCapacity:_data.count];
//    for (int i = 0; i < _data.count; i++) {
//        UIImage *imgMod = _data[i];
//        [imgList addObject:imgMod];
//    }
    
    // 调用展示窗口
    ImageScrollerViewController *imgShow = [[ImageScrollerViewController alloc] initWithSourceData:[self.photos mutableCopy] withIndex:index];
    
    UIViewController *vc= [RAUtils getViewController:self];
    [vc.navigationController pushViewController:imgShow animated:true];
   // UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:imgShow];
    
   // [self presentViewController:nav  animated:YES completion:nil];
//    UIDocumentInteractionController
//    UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url];
//    preview.delegate = self;
//    [preview presentPreviewAnimated:YES];
}

-(void) neworder
{
    
    UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Create Order"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary* return_json = [iSalesNetwork new_Order];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
            
            
            if([[return_json valueForKey:@"result"] intValue]==2)
            {
                int result=[[return_json valueForKey:@"result"] intValue];
                if(result==2)
                {
                    //successed.
                    
                    NSString* order_code = [return_json valueForKey:@"orderCode"];
                    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                    appDelegate.order_code = order_code;
                    
                    int count=[self.quantity_text.text intValue];
                    [self addtocart:count];
                    
                    
                    //    [self ReloadData];
                    
                    
                    //                    if(self.shopCartBlock!=nil)
                    //                    {
                    //                        UIImage* img=[self photoStackView:self.photoStack photoForIndex:0];
                    //
                    //
                    //                        CGRect iv_rect = CGRectMake(self.btnaddCart.center.x-50, self.btnaddCart.center.y-50, 100, 100);
                    //                        UIImageView* iv = [[UIImageView alloc] initWithFrame:iv_rect];
                    //                        iv.image = img;
                    //                        //                        [self.contentView addSubview:iv];
                    //                        self.shopCartBlock(iv);
                    //
                    //                    }
                    
                }
            }
            else
            {
                UIViewController *vc= [RAUtils getViewController:self];
                [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:vc] ;
            }
            
            
            
            
        });
    });
}
#pragma mark - UIAlertViewDelegate
// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    if(alertView.tag==1234)//库存小于0
    {
        
        // availability warring;
        
        int count=[self.quantity_text.text intValue];
        if(buttonIndex!=alertView.cancelButtonIndex)
        {
            if(appDelegate.order_code==nil)
            {
                [self neworder];
            }
            else
            {
                [self addtocart:count];
            }
        }
        return;
    }
    //   int count=[self.quantity_text.text intValue];
    
    MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
    if(buttonIndex==alertView.cancelButtonIndex)
    {
        
        
        
    }
    else if(buttonIndex==1)
    {
        //open exist
        UIViewController *vc= [RAUtils getViewController:self];
        OrderListViewController* ovc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
        ovc.showNavibar = true;
        ovc.selectOrder = ^(NSMutableDictionary* order_detail){
            if(appDelegate.order_code==nil)
            {
                [self neworder];
            }
            else
            {
                if(self.set_update_data)
                    self.set_update_data(true);
                
                int model_count = [[order_detail valueForKey:@"model_count"] intValue];
                for(int i=0;i<model_count;i++)
                {
                    NSDictionary* item = [order_detail objectForKey:[NSString stringWithFormat:@"item_%d",i]];
                    NSString* product_id = [item valueForKey:@"product_id"];
                    if([product_id isEqualToString:self.product_id])
                    {
                        self.cqty = [[item valueForKey:@"QTY"]intValue];
                        if(self.set_cqty)
                            self.set_cqty(self.cqty);
                        break;
                    }
                    
                }
                int count=[self.quantity_text.text intValue];
                [self addtocart:count];
                [main_vc checklogin:true];
                
                
            }
            
        };
        ovc.init_style = OL_OPEN;
        ovc.onCancel = ^(){
            
            [main_vc checklogin:true];
            
        };
        
        [vc.navigationController pushViewController:ovc animated:true];
    }
    else
    {
        //create new;
        if(appDelegate.customerInfo==nil)// select contact if current contact not exist
        {
            UIViewController *vc= [RAUtils getViewController:self];
            
            ContactListViewController* cvc = [vc.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
            cvc.showNavibar = true;
            cvc.contact_type = @"Sales_Order_Customer";
            cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
                
                appDelegate.contact_id=[value valueForKey:@"customer_cid"];
                appDelegate.customerInfo = value;
                
                
                if(appDelegate.order_code==nil)
                    [self neworder];
                
                [main_vc checklogin:true];
                //            [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
                
                //
                //                if(self.returnValue)
                //                    self.returnValue(value);
            };
            
            cvc.onCancel = ^(){
                
                UIViewController *vc= [RAUtils getViewController:self];
                [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order" controller:vc];
                
            };
            cvc.onReset = ^(){
                [main_vc checklogin:true];
            };
            
            [vc.navigationController pushViewController:cvc animated:true];
        }
        else
        {
            [self neworder];
        }
        
        
    }
}

- (void)valueChanged:(UIStepper *)sender {
    
    
    
    self.quantity_text.text = [NSString stringWithFormat:@"%d",(int)sender.value ];
    
    [celldelegate stepClicked:(int)sender.value];
    //    -(void) stepClicked:(int) value;
}


#pragma mark -
#pragma mark Actions
-(void)ClearPhotos
{
    NSMutableArray *photosMutable = [self.photos mutableCopy];
    [photosMutable removeAllObjects];
    self.photos = photosMutable;
    [self.photoStack reloadData];
    


}
- (void)AddPhoto :(UIImage*)photo {
    
    NSMutableArray *photosMutable = [self.photos mutableCopy];
    [photosMutable addObject:photo];
    self.photos = photosMutable;
    [self.photoStack reloadData];
    self.pageControl.numberOfPages = [self.photos count];
    if(self.photos.count<2-1)//1 for qrcode;
        self.photoStack.showBorder=false;
    else
        self.photoStack.showBorder=true;
        
}



#pragma mark -
#pragma mark Setup
-(void)setup {
    
    
    
    self.stepper.minimumValue= self.step;
    
    
    
    self.stepper.stepValue= self.step;
    
    self.stepper.value= self.quantity;
    
    
    
    [self.stepper addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    
    if(true)//(self.photos==nil)
    {
        
        self.photos = [NSArray arrayWithObjects:
                       nil];
    }
    if(true)//(self.photoStack==nil)
    {
        //       if(self.photoStack!=nil)
        //           [self.photoStack removeFromSuperview];
        //  self.photoStack = [[PhotoStackView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
        //        self.photoStack.backgroundColor =[UIColor redColor];
        //    self.photoStack.center = CGPointMake(self.center.x, 220);
        self.photoStack.dataSource = self;
        self.photoStack.delegate = self;
        
        
        //    [self addSubview:self.photoStack];
        self.pageControl.numberOfPages = [self.photos count];
    }
}

- (IBAction)notifyMeButtonClicked:(UIButton *)sender {
    
    if (self.notifyMeBlock) {
        self.notifyMeBlock();
    }
    
}


@end
