//
//  OrderListViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 8/18/15.
//  Copyright (c) 2015 United Software Applications, Inc. All rights reserved.
//

#import "OrderListViewController.h"

#import "OrderListTableViewCell.h"
#import "iSalesNetwork.h"
#import "OrderDetailViewController.h"
#import "MainViewController.h"

#import "ContactListViewController.h"
#import "DefaultAppearance.h"
#import "DefaultTableHeaderView.h"
#import "SelectUploadOrderViewController.h"
#import "NotificationNameCenter.h"
#import "Singleton.h"


@interface OrderListViewController ()

@property (nonatomic,strong) NSOperationQueue *dataOperationQueue;

@property (nonatomic,strong) NSMutableArray *mergeList;

@property (nonatomic,assign) NSInteger orderType;///<sales order/shop order

@property (nonatomic,strong) NSMutableDictionary *sales_order_filter;
@property (nonatomic,strong) NSMutableDictionary *shop_order_filter;

@property (strong, nonatomic) IBOutlet UIBarButtonItem *mergeListButton;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *editOrderListButton;
@property (strong, nonatomic) IBOutlet UISegmentedControl *orderTypeSegmentControl;

@end

@implementation OrderListViewController

- (NSOperationQueue *)dataOperationQueue {
    if (!_dataOperationQueue) {
        _dataOperationQueue = [[NSOperationQueue alloc] init];
        _dataOperationQueue.maxConcurrentOperationCount = 1;
    }
    return _dataOperationQueue;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSMutableArray *)mergeList {
    if (!_mergeList) {
        _mergeList = [NSMutableArray array];
    }
    return _mergeList;
}

-(void) logout
{
        [self.mergeList removeAllObjects];
    self.offset = 0;
    [self.content_data removeAllObjects];
    [self.table_order reloadData];
    self.status_cadedate = nil;
}
-(void) reload_container_getdata:(bool) update_data
{
    [super reload_container_getdata:update_data];
    if(update_data)
    {
        //    self.offset = 0;
        //    [self.content_data removeAllObjects];
        self.reset_result=true;
        self.norefresh=true;
        [self loadpage];
    }
    else
    {
        [self.table_order reloadData];
    }
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    if(appDelegate.can_create_order)
    {
        
        
        [self.btn_newOrder setImage:[UIImage imageNamed:@"neworder"]];
        self.btn_newOrder.enabled = true;
    }
    else
    {
        [self.btn_newOrder setImage:nil];
        self.btn_newOrder.enabled = false;
    }
}
-(void) showHidePrice
{
    [self reload_container_getdata:false];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.loading_queue = dispatch_queue_create("orderlist_loading", NULL);
    
    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;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changePriceType:) name:Change_Price_Type_Notification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lockOrderListNotification:) name:Lock_Permission_Notification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lockOrderListNotification:) name:unLock_Permission_Notification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUserLogin:) name:User_LoginOK_Notification object:nil];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refresh_btn_click:)];
    //            tap.minimumPressDuration = 0.8; //定义按的时间
    [self.label_net_err addGestureRecognizer:tap];
    // Do any additional setup after loading the view.
    self.offset = 0;
    self.limit = 25;
    self.content_data = [[NSMutableArray alloc]init];
    // Customer Order Type 0 Shop Order/ 1 Sales Order
    self.orderType = self.orderTypeSegmentControl.selectedSegmentIndex;
    [Singleton sharedInstance].customer_order_type = self.orderType;
    
    
    UIRefreshControl *ref = [[UIRefreshControl alloc]init];
    ref.tag = 201 ;
    ref.attributedTitle = [[NSAttributedString alloc]initWithString:@"Pull to refresh"];
    ref.tintColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
    //    ref.hidden = true;
    [ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged];
    [self.table_order addSubview:ref];
    self.table_order.allowsMultipleSelectionDuringEditing = YES;
    
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//    NSString *documents = [paths objectAtIndex:0];
//    NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
    
    
    //    if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
    //
    //        DebugLog(@"文件已经存在了");
    //
    //    }
    //    else
    //    {
    //
    //
    //
    //        //        DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
    //
    //        NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
    //
    //        //        DebugLog(@"mainBundleFile==%@",mainBundleFile);
    //
    //        [[NSFileManager defaultManager] createFileAtPath:dist_path
    //
    //                                                contents:mainBundleFile
    //
    //                                              attributes:nil];
    //
    //    }
    
    [self loadfilter];
    
    
}
-(void) loadfilter
{
    
    if(self.status_cadedate!=nil)
        return;
    
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    
    if (appDelegate.user && appDelegate.user_type == USER_ROLE_CUSTOMER) {
        self.shop_order_filter = [Singleton sharedInstance].shop_order_status_filter;
        self.sales_order_filter = appDelegate.OrderFilter;
        if(self.init_style==OL_OPEN)
        {
            NSData *data=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]  pathForResource:@"status_filter_cadedate_open" ofType:@"json" ]];
            NSError *error=nil;
            self.status_cadedate = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error] mutableCopy];
            
        } else if (self.orderTypeSegmentControl.selectedSegmentIndex == 0) {
            self.status_cadedate = self.shop_order_filter;
        } else {
            self.status_cadedate = self.sales_order_filter;
        }
        return;
    }
    
    NSData* json =nil;
    if(self.init_style==OL_OPEN)
    {
        json=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]  pathForResource:@"status_filter_cadedate_open" ofType:@"json" ]];
        NSError *error=nil;
        self.status_cadedate = [[NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error] mutableCopy];
        
    }
    else
    {
        //        json=//[NSData dataWithContentsOfFile:dist_path];
        //    NSError *error=nil;
        self.status_cadedate = appDelegate.OrderFilter;//[[NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error] mutableCopy];
    }
}
- (IBAction)onCancel:(id)sender {
    if(self.onCancel)
        self.onCancel();
    [self.navigationController popViewControllerAnimated:false];
}
- (IBAction)onStatusFilterClick:(id)sender {
    if (self.table_order.isEditing || self.init_style == OL_OPEN) {
        return;
    }
    EnumSelectViewController* enumvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"EnumSelectorViewController"];
    enumvc.delegate = self;
    enumvc.max_select = 0;
    //enumvc.updatePosition = indexPath;
    //        if([[required lowercaseString] isEqualToString:@"true"])
    //        enumvc.canbeEmpty = false;
    //        else
    //        enumvc.canbeEmpty =true;
    enumvc.cadedate = self.status_cadedate ;
    enumvc.title = @"Order Status Selection";
    //       enumvc.value = [value_json mutableCopy];
    enumvc.single_select =false;
    
    [self.navigationController pushViewController:enumvc animated:true];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadfilter];
    
//    [self ReloadData]; // 保存新订单后返回没刷新
    
    //    UIApplication * app = [UIApplication sharedApplication];
    //    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    //    if(appDelegate.bLogin==false)
    //    {
    //        LoginViewController * loginvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
    ////        loginvc.delegate = self;
    //        //    loginvc.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态，自己看看是哪种
    //
    //        loginvc.returnValue = ^(bool blogin){
    //
    //
    //            UIApplication * app = [UIApplication sharedApplication];
    //            AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    //            MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
    //
    //            [main_vc checklogin:true];
    //
    ////            self.offset = 0;
    ////            [self.content_data removeAllObjects];
    ////            [self loadpage];
    //
    //            [[self navigationController] setNavigationBarHidden:!self.showNavibar animated:NO];
    //
    //        };
    //
    //        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
    //
    //
    //
    //
    //
    //        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
    //
    //        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
    //        [self presentViewController:navi animated:YES completion:^{
    //
    //            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
    //
    //            DebugLog(@"LoginViewController present.........");
    //
    //            //   self.btop = false;
    //            //  <#code#>
    //        }];
    //    }
    //    else
    //    {
    //
    //        if(!self.norefresh)//避免 多次刷新
    //        {
    //            self.norefresh = true;
    //            self.offset = 0;
    //            [self.content_data removeAllObjects];
    //            [self loadpage];
    //
    //        }
    //
    //    }
    [[self navigationController] setNavigationBarHidden:!self.showNavibar animated:NO];
    
    // 检查权限
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSMutableArray *items = [self.toolbarView.items mutableCopy];
    
    if(appDelegate.user && appDelegate.user_type == USER_ROLE_CUSTOMER) {
        
        
        // 合并订单的权限
        if ([Singleton sharedInstance].permissions_merge_order) { // 能够合并
            
            // 4 6 顺序不能换
            if (![items containsObject:self.editOrderListButton]) { // 没显示button
                [items insertObject:self.editOrderListButton atIndex:4];
            }
            
//            if (![items containsObject:self.mergeListButton]) { // 没显示button
//                [items insertObject:self.mergeListButton atIndex:6];
//            }

            self.toolbarView.items = items;
            
        } else { // 不能合并
//            if ([items containsObject:self.mergeListButton]) { // 显示button
//                [items removeObject:self.mergeListButton];
//            }
            if ([items containsObject:self.editOrderListButton]) { // 显示button
                [items removeObject:self.editOrderListButton];
            }
            
            self.toolbarView.items = items;
        }
        
        // Check For Saved Order 不能合并
        if(self.init_style==OL_OPEN || self.orderType == 1) {
//            if ([items containsObject:self.mergeListButton]) { // 显示button
//                [items removeObject:self.mergeListButton];
//            }
            if ([items containsObject:self.editOrderListButton]) { // 显示button
                [items removeObject:self.editOrderListButton];
            }
            
            self.toolbarView.items = items;

        }

    } else {
        
//        self.mergeListButton.hidden = YES;
//        if ([items containsObject:self.mergeListButton]) { // 显示button
//            [items removeObject:self.mergeListButton];
//        }
        if ([items containsObject:self.editOrderListButton]) { // 显示button
            [items removeObject:self.editOrderListButton];
        }
        
        self.toolbarView.items = items;
    }
    
    // 非Customer用户不用区分Sales Order 和 Shop Order
    if (appDelegate.user_type != USER_ROLE_CUSTOMER) {
        self.orderTypeSegmentControl.hidden = YES;
        CGFloat y = CGRectGetMinY(self.orderTypeSegmentControl.frame);
        CGFloat height = CGRectGetHeight(self.orderTypeSegmentControl.frame);
        CGRect frame = self.table_order.frame;
        if (frame.origin.y != y) {
            frame.origin.y = y;
            frame.size.height += height;
        }
        self.table_order.frame = frame;
    } else {
        self.orderTypeSegmentControl.hidden = NO;
        CGFloat y = CGRectGetMinY(self.orderTypeSegmentControl.frame);
        CGFloat height = CGRectGetHeight(self.orderTypeSegmentControl.frame);
        CGRect frame = self.table_order.frame;
        if (frame.origin.y == y) {
            frame.origin.y = y + height;
            frame.size.height -= height;
        }
        self.table_order.frame = frame;
    }
    
    // 显示Sales Order与否
    if (appDelegate.user && appDelegate.user_type == USER_ROLE_CUSTOMER) {
        if ([Singleton sharedInstance].global_lock || ![Singleton sharedInstance].customer_can_see_sales_Order) { // 是否解锁，是否有查看Sales Order权限
            if (self.orderTypeSegmentControl.numberOfSegments > 1) {
                [self.orderTypeSegmentControl removeSegmentAtIndex:1 animated:YES];
            }
        }
    }
    
}
- (IBAction)onNewOrderClicked:(id)sender {
    
    NSString* msg=@"Do you want to create a new order?";
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if(appDelegate.order_code.length==0)
    {
        
        if(appDelegate.contact_id.length>0)
        {
            msg = [msg stringByAppendingString:@"\n\nCustomer:"];
            msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
            
        }
    }
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Warning", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"NO", nil) otherButtonTitles:NSLocalizedString(@"YES", nil), nil];
    [alert show];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)manually_refresh
{
    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:201];
    if(self.isrefreshing)
    {
        [reF endRefreshing];
        return;
    }
    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"Refreshing"];
    if ([self respondsToSelector:@selector(ReloadData)])
        [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1];
    
}

-(void)ReloadData
{
    
    
    //    [self.content_data removeAllObjects];
    //    [self.table_order reloadData];
    
    
    // self.table_order.hidden = true;
    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:201];
    
    [reF endRefreshing];
    
    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"Pull to refresh"];
    
    self.keywords=self.searchbar.text;
    //    self.offset = 0;
    self.reset_result=true;
    //    [self.content_data removeAllObjects];
    //    [self.table_order reloadData];
    
    
    [self loadpage];
    
    //   [self loadpage];
    
}

- (void)operation_loadPage {

    if (self.dataOperationQueue.operationCount > 1) { // 队列后面还有操作
        return;
    }
    
//    dispatch_async(self.loading_queue, ^{
    
        dispatch_sync(dispatch_get_main_queue(), ^{
            if(self.reset_result)
            {
                self.offset = 0;
                [self.content_data removeAllObjects];
                [self.table_order reloadData];
            }
            
            //            NSMutableArray* arr_status = [[NSMutableArray alloc] init];
            
            NSMutableArray* arr_statusname = [[NSMutableArray alloc] init];
            int count = [[self.status_cadedate valueForKey:@"count"] intValue];
            for(int i=0;i<count;i++)
            {
                NSDictionary* val_json =[self.status_cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]];
                int check = [[val_json valueForKey:@"check"] intValue];
                if(check==1)
                {
                    //                    [arr_status addObject:[NSString stringWithFormat:@"%@",[val_json valueForKey:@"value_id"]]];
                    [arr_statusname addObject:[NSString stringWithFormat:@"%@",[val_json valueForKey:@"value"]]];
                    
                    // break;
                }
            }
            
            //            NSString * str_status = [arr_status componentsJoinedByString:@","];
            NSString * str_statusname = [arr_statusname componentsJoinedByString:@","];
            if(str_statusname.length==0)
                str_statusname = @"All";
            self.label_filter.text = str_statusname;
            if(self.offset==0)
            {
                self.table_order.hidden = true;
                
                self.mum.center = self.view.center;
                
                self.mum.hidden = false;
                [self.mum startAnimating];
            }
            self.label_net_err.hidden=true;
            
        });
//    });
//    dispatch_async(self.loading_queue, ^{
        if(self.isrefreshing)
            return;
        self.isrefreshing=true;
        
        
        
        
        
        
        
        
        
        NSMutableArray* arr_status = [[NSMutableArray alloc] init];
        
        //    NSMutableArray* arr_statusname = [[NSMutableArray alloc] init];
        int count = [[self.status_cadedate valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[self.status_cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                [arr_status addObject:[NSString stringWithFormat:@"%@",[val_json valueForKey:@"value_id"]]];
                //            [arr_statusname addObject:[NSString stringWithFormat:@"%@",[val_json valueForKey:@"value"]]];
                
                // break;
            }
        }
        
        NSString * str_status = [arr_status componentsJoinedByString:@","];
    
    BOOL isMerged = NO;
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (appDelegate.user_type == USER_ROLE_CUSTOMER) {
        if (self.orderType == 0) {
            isMerged = NO;
        } else {
            isMerged = YES;
        }
    }
    
    
        NSMutableDictionary* content=nil;
        content=[[iSalesNetwork request_OrderList:self.offset limit : self.limit keywords:self.keywords status:str_status customer:self.customer_id is_merged:isMerged] mutableCopy];
    
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            
            
            
            
            [self.mum stopAnimating];
            self.isrefreshing=false;
            if (self.dataOperationQueue.operationCount > 1) { // 队列后面还有操作
                return ;
            }
            int result=[[content valueForKey:@"result"] intValue];
            
            if(result==2||result==0)
            {
                
                
                int count = [[content valueForKey:@"count" ] intValue] ;
                
                
                self.time_zone = [content valueForKey:@"time_zone" ];
                self.offset += count;
                for(int i=0;i<count;i++)
                {
                    
                    NSDictionary* objmsg = [content objectForKey:[NSString stringWithFormat:@"item_%d",i]];
                    [self.content_data addObject:[NSMutableDictionary dictionaryWithDictionary:objmsg]];
                    
                }
                if(count<self.limit)
                {
                    
                    //                    int i =self.btnrefresh.state;
                    self.load_more_hint=@"All loaded";
                    //                    self.btnrefresh.titleLabel.text =NSLocalizedString(@"no_more", nil);
                    //                    [self.btnrefresh setTitle:@"No more" forState:UIControlStateNormal];
                }
                else
                {
                    self.load_more_hint=@"Load more...";
                    //                    self.btnrefresh.enabled = true;
                    //                    self.btnrefresh.titleLabel.text =NSLocalizedString(@"load_more",nil);
                    //                    [self.btnrefresh setTitle:@"Load more" forState:UIControlStateNormal];
                }
                
                
                self.table_order.hidden = false;
                self.reset_result=false;
                [self.table_order reloadData ];
            }
            else if(result==RESULT_NET_ERROR &&self.offset==0)
            {
                self.label_net_err.hidden=false;
                self.table_order.hidden = true;
            }
            else
            {
                [RAUtils message_alert:[content valueForKey:@"err_msg"]  title:@"Loading Order List" controller:self] ;
            }
            
            
            
            
            
            
            //            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            //            bool autologin =[defaults boolForKey:@"autologin"];
            //            if(!autologin)
            //            {
            //                TabBarController * viewController =[self.storyboard instantiateViewControllerWithIdentifier:@"LoginTabBar"];
            //                [self presentViewController:viewController animated:YES completion:^{
            //
            //                }];
            //            }
            
            
        });
        
        
//    });
}
-(void) loadpage
{
    __weak typeof(self) weakself = self;
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        
        if (weakself) {
            __strong typeof(weakself) strongself = weakself;
            [strongself operation_loadPage];
        }
        
    }];
    
    [self.dataOperationQueue addOperation:operation];
    
}

- (void)loadmore
{
    //    self.btnrefresh.enabled = NO;
    //    self.btnrefresh.titleLabel.text =NSLocalizedString(@"loading",nil);
    
    //    [self.btnrefresh setTitle:@"Loading..." forState:UIControlStateNormal];
    [self loadpage];
}
//-(void)changeCell
//{
////    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
////    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"refreshing"];
//    [self performSelector:@selector(loadmore) withObject:nil afterDelay:1];
//    DebugLog(@"refresh!!!!!!!!");
//
//}

-(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;
                    appDelegate.order_status = [[return_json valueForKey:@"orderStatus"] intValue];
                    MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
                    [main_vc reloadCart:true immediately:false];
                    [self ReloadData];
                    
                    
                    //     [self performSelector:@selector(loadpage) withObject:nil afterDelay:1];
                    //    [self loadpage];
                    
                    
                    //                    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
            {
                [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Create Order" controller:self] ;
            }
            
            
            
            
        });
    });
}
#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
{
    if(buttonIndex!=alertView.cancelButtonIndex)
    {
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        if(appDelegate.order_code && appDelegate.order_code.length>0)
        {
            appDelegate.order_code= nil;
            [appDelegate SetSo:nil];
            
            if (appDelegate.user_type == USER_ROLE_EMPLOYEE) {
                //     MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
                ContactListViewController* cvc = [self.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;
                    
                    self.norefresh = true;
                    [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 = ^(){
                    self.norefresh = true;
                    if(appDelegate.customerInfo==nil)
                    {
                        [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"" controller:self];
                    }
                    else
                    {
                        [self neworder];
                    }
                    //  [main_vc checklogin:true];
                };
                cvc.onReset = ^(){
                    //   [main_vc checklogin:true];
                };
                
                [self.navigationController pushViewController:cvc animated:true];
            }
            else if (appDelegate.user_type == USER_ROLE_CUSTOMER){
                [self neworder];
            }
            
        }
        else
        {
            //create new;
            
            if(appDelegate.customerInfo==nil)// select contact if current contact not exist
            {
                MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
                ContactListViewController* cvc = [self.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 = ^(){
                    
                    [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"" controller:self];
                    
                    
                    
                };
                cvc.onReset = ^(){
                    [main_vc checklogin:true];
                };
                
                [self.navigationController pushViewController:cvc animated:true];
            }
            else
            {
                [self neworder];
            }
        }
        
    }
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    return 66;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 0;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 0;
//}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//        UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 0.0001)];
//    return myView;
//
//}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    NSString* value =[DefaultAppearance get_noneappearance_value:@"DefaultTableHeaderView" valuename:@"title_text_color"];
    
    if(value==nil)
        value=@"";
    unsigned long color = strtoul([value UTF8String],0,16);
    
    DefaultTableHeaderView* myView = [[DefaultTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 0.0001)];
    //  myView.backgroundColor =  UIColorFromRGB(0x996633);
    myView.layer.shadowPath =[UIBezierPath bezierPathWithRect:myView.bounds].CGPath;
    myView.layer.shadowColor = [UIColor blackColor].CGColor;
    myView.layer.shadowOffset = CGSizeMake(0, 0);
    myView.layer.shadowOpacity = 0.5;
    myView.layer.shadowRadius = 2.0;
    
    
    UILabel *statuslabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 2, 130, 22)];
    statuslabel.textColor=UIColorFromRGB(color);
    statuslabel.backgroundColor = [UIColor clearColor];
    statuslabel.text=NSLocalizedString(@"Status", nil);
    [statuslabel sizeToFit];
    [myView addSubview:statuslabel];
    
    UILabel *solabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 21, 130, 22)];
    solabel.textColor=UIColorFromRGB(color);
    solabel.backgroundColor = [UIColor clearColor];
    solabel.text=NSLocalizedString(@"SO#", nil);
    [solabel sizeToFit];
    [myView addSubview:solabel];
    
    UILabel *userlabel = [[UILabel alloc] initWithFrame:CGRectMake(155, 2, 135, 22)];
    userlabel.textColor=UIColorFromRGB(color);
    userlabel.backgroundColor = [UIColor clearColor];
    userlabel.text=NSLocalizedString(@"Sales rep", nil);
    [userlabel sizeToFit];
    [myView addSubview:userlabel];
    
    UILabel *creatorlabel = [[UILabel alloc] initWithFrame:CGRectMake(155, 21, 135, 22)];
    creatorlabel.textColor=UIColorFromRGB(color);
    creatorlabel.backgroundColor = [UIColor clearColor];
    creatorlabel.text=NSLocalizedString(@"Create by", nil);
    [creatorlabel sizeToFit];
    [myView addSubview:creatorlabel];
    
    UILabel *contactlabel = [[UILabel alloc] initWithFrame:CGRectMake(300, 11, 150, 22)];
    
    contactlabel.textColor=UIColorFromRGB(color);
    contactlabel.backgroundColor = [UIColor clearColor];
    contactlabel.text=NSLocalizedString(@"Contact", nil);
    [contactlabel sizeToFit];
    [myView addSubview:contactlabel];
    
    //
    //    UILabel *modellabel = [[UILabel alloc] initWithFrame:CGRectMake(424, 11, 52, 22)];
    //    modellabel.textColor=[UIColor whiteColor];
    //    modellabel.backgroundColor = [UIColor clearColor];
    //    modellabel.text=NSLocalizedString(@"Model", nil);
    //    [modellabel sizeToFit];
    //    [myView addSubview:modellabel];
    
    //    UILabel *modellabel = [[UILabel alloc] initWithFrame:CGRectMake(self.table_order.frame.size.width-276, 2, 100, 22)];
    //    modellabel.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin;
    //    modellabel.textColor=[UIColor whiteColor];
    //    modellabel.backgroundColor = [UIColor clearColor];
    //    modellabel.text=NSLocalizedString(@"Items/QTY", nil);
    //    [modellabel sizeToFit];
    //    [myView addSubview:modellabel];
    
    UILabel *pricelabel = [[UILabel alloc] initWithFrame:CGRectMake(/*492*/self.table_order.frame.size.width-276, 11, 100, 22)];
    pricelabel.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin;
    pricelabel.textColor=UIColorFromRGB(color);
    pricelabel.backgroundColor = [UIColor clearColor];
    pricelabel.text=NSLocalizedString(@"Order Total", nil);
    [pricelabel sizeToFit];
    [myView addSubview:pricelabel];
    
    UILabel *timelabel = [[UILabel alloc] initWithFrame:CGRectMake(self.table_order.frame.size.width-163/*605*/,11, 148, 22)];
    timelabel.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin;
    timelabel.textColor=UIColorFromRGB(color);
    timelabel.backgroundColor = [UIColor clearColor];
    if(self.time_zone==nil)
        timelabel.text=@"Create time";
    else
        timelabel.text=[NSString stringWithFormat:@"Create time (%@)",self.time_zone];
    [timelabel sizeToFit];
    [myView addSubview:timelabel];
    
    myView.autoresizesSubviews=true;
    // [myView setAutoresizingMask:UIViewAutoresizingFlexibleWidth  | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin];
    
    
    
    
    //    modellabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    //    pricelabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    //    timelabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    myView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    //
    return myView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}
//
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    if(section==0)
//        return nil;
//    else
//        return @"detail section";
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // NSDictionary * item_json = [self.content_data objectForKey:@"items"];
    if( self.content_data.count==0)
        return 0;
    return self.content_data.count+1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    //    if(tableView==self.itemListTable)
    //    {
    
    //    if(indexPath.row>self.content_data.count)
    //    {
    //        int debug=true;
    //    }
    //   DebugLog(@"row %ld",(long)indexPath.row);
    if(indexPath.row==self.content_data.count)
    {
        UITableViewCell *moreCell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"mores"];
        UILabel *moreDataLabel=[[UILabel alloc] init];
        
        moreDataLabel.tag=200;
        moreDataLabel.text=self.load_more_hint;
        [moreDataLabel setFont:[UIFont systemFontOfSize:14.0f]];
        [moreDataLabel setTextAlignment:NSTextAlignmentCenter];
        moreDataLabel.frame=CGRectMake(0, 10, self.table_order.bounds.size.width, 20);
        [moreDataLabel setBackgroundColor:[UIColor clearColor]];
        //        [moreDataLabel addTarget:self action:@selector(changeCell) forControlEvents:UIControlEventValueChanged];
        
        [moreCell.contentView addSubview:moreDataLabel];
        if([self.load_more_hint isEqualToString:@"Load more..."])
            [self performSelector:@selector(loadmore) withObject:nil afterDelay:1];
        //        DebugLog(@"更多...");
        moreCell.backgroundColor = [UIColor whiteColor];
        return moreCell;
    }
    else
    {
        NSString *CellIdentifier = @"OrderListTableViewCell";
        OrderListTableViewCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        NSString* po= [self.content_data[indexPath.row] valueForKey:@"so#"];
        NSString* price= [self.content_data[indexPath.row] valueForKey:@"price"];
        if(appDelegate.can_see_price&&appDelegate.price_hidden==false)
        {
            
        }
        else
        {
            price=nil;
        }
        
        
        NSString* purchase_time= [self.content_data[indexPath.row] valueForKey:@"purchase_time"];
        NSString* status = [self.content_data[indexPath.row] valueForKey:@"order_status"] ;
        NSString* customer_name = [self.content_data[indexPath.row] valueForKey:@"customer_name"];
        NSString* model_count = [self.content_data[indexPath.row] valueForKey:@"model_count"];
        NSString* sales = [self.content_data[indexPath.row] valueForKey:@"sales_rep"];
        NSString* creator = [self.content_data[indexPath.row] valueForKey:@"create_by"];
        cell.label_so.text=po;
        cell.labelprice.text=price;
        cell.label_date.text=purchase_time;
        cell.label_contact.text=customer_name;
        cell.label_model.text = model_count;
        
        cell.label_sales.text = sales;
        cell.label_creator.text = creator;
        
        cell.label_status.text=status;
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
    }
    //    NSDictionary * item_json = [self.content_data objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
    //   NSDictionary * combine_json =[item_json objectForKey:@"combine"];
    
    //    cell.bundle_item=combine_json;
    //    NSString* img_url = [item_json valueForKey:@"img_url"];
    //    NSString* description = [item_json valueForKey:@"description"];
    //    //    NSString* identifier = [item_json valueForKey:@"identifier"];
    //    //    NSString* attribute = [item_json valueForKey:@"attribute"];
    //    NSString* currency = [item_json valueForKey:@"currency"];
    //    int count =[[item_json valueForKey:@"count"] intValue];
    //    double price =[[item_json valueForKey:@"price"] doubleValue];
    //    //    cell.labelAttribute.text = attribute;
    //    cell.labelCurrency.text = currency;
    //    cell.labelDescription.text = description;
    //    //   cell.labelIdentifier.text = identifier;
    //    cell.labelPrice.text = [NSString stringWithFormat:@"%.2f",price];
    //
    //
    //
    //    [cell set_Count:count];
    
    //    NSString* file_name=[img_url lastPathComponent];
    //    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
    //    if(img_data!=nil)
    //    {
    //
    //        UIImage * img =[UIImage imageWithData:img_data];
    //        [cell.btnImage setBackgroundImage:img forState:UIControlStateNormal];
    //    }
    //    else
    //    {
    //
    //        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //
    //            NSData*  downloadimg_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:img_url]];
    //
    //            dispatch_async(dispatch_get_main_queue(), ^{
    //
    //
    //
    //                if(downloadimg_data!=nil)
    //                {
    //                    [iSalesDB cache_img:downloadimg_data :file_name ];
    //
    //                    UIImage * img =[UIImage imageWithData:downloadimg_data];
    //                    [cell.btnImage setBackgroundImage:img forState:UIControlStateNormal];
    //                }
    //
    //            });
    //        });
    //
    //
    //    }
    
    //    }
    //    else
    //    {
    //        NSString *CellIdentifier = @"OrderInfoListItem";
    //        UITableViewCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    //        return cell;
    //    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.isEditing) { // 编辑模式下不响应
        return;
    }
    //
    if(indexPath.row==self.content_data.count)
        return;
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

    if(appDelegate.user_type==USER_ROLE_CUSTOMER) { // Customer
        if ([Singleton sharedInstance].global_lock) { // Order list 被锁
            [RAUtils message_alert:@"Permission Needed.\nGoto Menu -> Unlock" title:@"Warning" controller:self];
            return;
        }
    }
    
    NSString* orderid= [self.content_data[indexPath.row] valueForKey:@"order_id"];
    OrderDetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"OrderDetailViewController" ];
    
    //    int i =[[self.content_data[indexPath.row] valueForKey:@"order_code"];
    dvc.selectOrder=^(NSMutableDictionary* order_detail){
        
        [self.navigationController popViewControllerAnimated:false];
        if(self.selectOrder)
            self.selectOrder(order_detail);
        
        
        
    };
    NSString* order_code =[self.content_data[indexPath.row] valueForKey:@"order_code"];
    
    dvc.is_shoporder=(self.orderType == 0);
    dvc.order_code = order_code;
    dvc.order_status =[[self.content_data[indexPath.row] valueForKey:@"orderStatus"] intValue];
    //    bool temp_order = false ;
    //    NSString* order_status=[self.content_data[indexPath.row] valueForKey:@"order_status"];
    //    if([order_status isEqualToString:@"Saved"]||[order_status isEqualToString:@"Quoted"])
    //        temp_order=true;
    //
    //    dvc.isTempOrder = temp_order;
    
    //            dvc
    
    dvc.orderid=orderid;
    //    dvc.category_id=nil;
    //    dvc.ispush=true;
    //    [dvc reload];
    [self.navigationController pushViewController:dvc animated:true];
    
    
}


#pragma mark - searchBar delegate;
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.keywords=searchBar.text;
    //        self.offset = 0;
    //        [self.content_data removeAllObjects];
    self.reset_result=true;
    [self loadpage];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    if([searchText isEqualToString:@""] && !self.reset)
    {
        DebugLog(@"clear");
        self.reset=true;
        self.keywords=nil;
        
        //        self.offset = 0;
        //        [self.content_data removeAllObjects];
        self.reset_result=true;
        [self loadpage];
    }
    else
        self.reset = false;
}




#pragma mark 在滑动手势删除某一行的时候，显示出更多的按钮

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    // 添加一个删除按钮
    
    //    self.indexPath=indexPath;
    
    
    if(indexPath.row==self.content_data.count)
        return @[];
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    NSString* so= [self.content_data[indexPath.row] valueForKey:@"so#"];
    NSString* orderid= [self.content_data[indexPath.row] valueForKey:@"order_id"];
    NSString* order_status= [self.content_data[indexPath.row] valueForKey:@"order_status"];
    
    if(appDelegate.user_type==USER_ROLE_EMPLOYEE) {

        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            DebugLog(@"delete click");
            
            
            NSString * title =[NSString stringWithFormat:@"Are you sure to delete order SO#: %@",so];
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
            //block代码块取代了delegate
            
            
            //        [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            //            textField.text = self.save_name;
            //
            //
            //        }];
            
            UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                
                UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Delete Order"];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* return_json = [iSalesNetwork delete_Order:orderid];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                        
                        
                        if([[return_json valueForKey:@"result"] intValue]==2)
                        {
                            if([appDelegate.order_code isEqualToString: [self.content_data[indexPath.row] valueForKey:@"order_code"]])
                            {
                                appDelegate.order_code= nil;
                                [appDelegate SetSo:nil];
                                
                                
                            }
                            
                            [RAUtils message_alert:nil title:@"Order Delete" controller:self] ;
                            [self ReloadData];
                        }
                        else
                        {
                            [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Delete Order" controller:self] ;
                        }
                        
                        
                        
                        
                    });
                });
                
                
            }];
            
            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                DebugLog(@"Cancel");
            }];
            [alertControl addAction:actionOne];
            
            [alertControl addAction:alertthree];
            
            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
            
            
            [self presentViewController:alertControl animated:YES completion:nil];
            
            
            
            
            
            
            
        }];
        deleteRowAction.backgroundColor = UIColorFromRGB(0x336699);
        
        // 添加一个编辑按钮
        
        UITableViewRowAction *cancelAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Cancel Order"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            DebugLog(@"edit click");
            
            
            
            NSString * title =[NSString stringWithFormat:@"Are you sure to cancel order SO#: %@",so];
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            
            
            UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                
                UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Cancel Order"];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* return_json = [iSalesNetwork cancel_Order:orderid order_code:nil];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                        
                        
                        if([[return_json valueForKey:@"result"] intValue]==2)
                        {
                            if([appDelegate.order_code isEqualToString: [self.content_data[indexPath.row] valueForKey:@"order_code"]])
                            {
                                appDelegate.order_code= nil;
                                //appDelegate.user_type = 0;
                                appDelegate.customerInfo = nil;
                                appDelegate.contact_id = nil;
                                appDelegate.order_customer_id = nil;
                                [appDelegate SetSo:nil];
                                appDelegate.cart_count=0;
                                [appDelegate update_count_mark];
                                
                                
                            }
                            [RAUtils message_alert:nil title:@"Order Canceled" controller:self] ;
                            [self ReloadData];
                        }
                        else
                        {
                            [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Cancel Order" controller:self] ;
                        }
                        
                        
                        
                        
                    });
                });
                
                
            }];
            
            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                DebugLog(@"Cancel");
            }];
            [alertControl addAction:actionOne];
            
            [alertControl addAction:alertthree];
            
            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
            
            
            [self presentViewController:alertControl animated:YES completion:nil];
            
            
            
            //
            
        }];
        
        
        cancelAction.backgroundColor = UIColorFromRGB(0xff9933);
        
        
        
        
        
        
        
        
        
        if([order_status isEqualToString:@"Saved Order"]&&appDelegate.can_cancel_order)
            return @[cancelAction];
        
        else
        {
            if([order_status isEqualToString:@"Quote Saved"])
            {
                NSMutableArray* arr=[@[] mutableCopy];
                if(appDelegate.can_delete_order)
                    [arr addObject:deleteRowAction];
                if(appDelegate.can_cancel_order)
                    [arr addObject:cancelAction];
                return arr;
            }
        }
        
        
        
    } else if (appDelegate.user_type==USER_ROLE_CUSTOMER) {
        
//        UITableViewRowAction *add2MergeListAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Add To Combine List" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//            
//            NSString *orderCode = [NSString stringWithFormat:@"%@",[self.content_data[indexPath.row] valueForKey:@"order_code"]];
//            
//            
//            NSString *create_by = [self.content_data[indexPath.row] valueForKey:@"create_by"];
//            NSString *create_time = [self.content_data[indexPath.row] valueForKey:@"purchase_time"];
//            
//            __block BOOL contain = NO;
//            [self.mergeList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//               
//                NSString *so_id = [(NSDictionary *)obj objectForKey:@"so_id"];
//                if ([so_id isEqualToString:so]) {
//                    
//                    contain = YES;
//                    
//                    *stop = YES;
//                }
//                
//            }]; // 避免重复添加
//            
//            
//            if (!contain) {
//                
//                __block BOOL closeOrder = NO;
//                // 检查是否被自己打开
//                if ([orderCode isEqualToString:appDelegate.order_code]) {
//                    
//                    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:@"can not add to combine list because current order is opened. Do you want to close order and add to combine list?" preferredStyle:UIAlertControllerStyleAlert];
//                    
//                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                        
//                        closeOrder = NO;
//                        [alertVC dismissViewControllerAnimated:YES completion:nil];
//                        
//                    }];
//                    
//                    UIAlertAction *closeOrderAction = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                        
//                        
//                        [alertVC dismissViewControllerAnimated:YES completion:nil];
//                        // 关闭订单
//                        UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Release Order"];
//                        NSDictionary* order_json = [iSalesNetwork release_Order:orderCode];
//                        
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            
//                            [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
//                            if([[order_json valueForKey:@"result"] intValue]==2)
//                            {
//                                AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//
//                                [appDelegate closeOrder];
//                                closeOrder = YES;
//
//                                // 锁订单／检查是否被别人锁定
//                                NSDictionary *lock_dic = [iSalesNetwork lock_order:orderCode]; // 和open一样，只不过不用更新car count
//
//                                
//                                if ([[lock_dic objectForKey:@"result"] integerValue] == RESULT_TRUE) {
//                                    
//                                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//                                    
//                                    [dic setValue:orderid forKey:@"order_id"];
//                                    [dic setValue:so forKey:@"so_id"];
//                                    [dic setValue:create_by forKey:@"create_by"];
//                                    [dic setValue:create_time forKey:@"create_time"];
//                                    [dic setValue:[NSNumber numberWithInteger:0] forKey:@"check"]; // 合并到
//                                    
//                                    [self.mergeList addObject:dic];
//                                    
//                                } else {
//                                    
//                                    [RAUtils message_alert:[lock_dic objectForKey:@"err_msg"] title:@"Warning" controller:self];
//                                    
//                                }
//
//                                
//                            }
//                            else
//                            {
//                                closeOrder = NO;
//                                [RAUtils message_alert:[order_json valueForKey:@"err_msg"] title:@"Release Order" controller:self] ;
//                            }
//                            
//                            
//                            
//                        });
//
//                        
//                        
//                    }];
//                    
//                    [alertVC addAction:cancelAction];
//                    [alertVC addAction:closeOrderAction];
//                    
//                    [self presentViewController:alertVC animated:YES completion:nil];
//                    
//                } else {
//                    
//                    closeOrder = YES;
//                    // 锁订单／检查是否被别人锁定
//                    NSDictionary *lock_dic = [iSalesNetwork lock_order:orderCode]; // 和open一样，只不过不用更新car count
//                    
//                    if ([[lock_dic objectForKey:@"result"] integerValue] == RESULT_TRUE) {
//                        
//                        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//                        
//                        [dic setValue:orderid forKey:@"order_id"];
//                        [dic setValue:so forKey:@"so_id"];
//                        [dic setValue:create_by forKey:@"create_by"];
//                        [dic setValue:create_time forKey:@"create_time"];
//                        [dic setValue:[NSNumber numberWithInteger:0] forKey:@"check"]; // 合并到
//                        
//                        [self.mergeList addObject:dic];
//                        
//                    } else {
//                        
//                        [RAUtils message_alert:[lock_dic objectForKey:@"err_msg"] title:@"Warning" controller:self];
//                        
//                    }
//                }
//                
//            }
//            
//            [tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade];
//            
//            DebugLog(@"%@",self.mergeList);
//            
//        }];
//        add2MergeListAction.backgroundColor = UIColorFromRGB(0x336699);
        
        // Cancel Order Action
        UITableViewRowAction *cancelAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Cancel Order"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            DebugLog(@"edit click");
            
            
            
            NSString * title =[NSString stringWithFormat:@"Are you sure to cancel order SO#: %@",so];
            
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            
            
            UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                
                UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Cancel Order"];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* return_json = [iSalesNetwork cancel_Order:orderid order_code:nil];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                        
                        
                        if([[return_json valueForKey:@"result"] intValue]==2)
                        {
                            if([appDelegate.order_code isEqualToString: [self.content_data[indexPath.row] valueForKey:@"order_code"]])
                            {
                                appDelegate.order_code= nil;
                                //appDelegate.user_type = 0;
                                appDelegate.customerInfo = nil;
                                appDelegate.contact_id = nil;
                                appDelegate.order_customer_id = nil;
                                [appDelegate SetSo:nil];
                                appDelegate.cart_count=0;
                                [appDelegate update_count_mark];
                                
                                
                            }
                            [RAUtils message_alert:nil title:@"Order Canceled" controller:self] ;
                            [self ReloadData];
                        }
                        else
                        {
                            [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Cancel Order" controller:self] ;
                        }
                        
                        
                        
                        
                    });
                });
                
                
            }];
            
            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                DebugLog(@"Cancel");
            }];
            [alertControl addAction:actionOne];
            
            [alertControl addAction:alertthree];
            
            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
            
            
            [self presentViewController:alertControl animated:YES completion:nil];
            
            
            
            //
            
        }];
        
        
        cancelAction.backgroundColor = UIColorFromRGB(0xff9933);

        NSMutableArray *actionArr = [NSMutableArray array];
        // 取消订单
        if([order_status isEqualToString:@"Saved Order"]&&appDelegate.can_cancel_order)
            [actionArr addObject:cancelAction];
        
//        if ([Singleton sharedInstance].permissions_merge_order) {// 有合并订单的权限
//            if (self.orderType == 0) {// Sales Order不能合并
//                [actionArr addObject:add2MergeListAction];
//            }
//
//        }
        return actionArr;
    }
    
    return @[];
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(indexPath.row==self.content_data.count)
        return NO;
    
    if(self.init_style==OL_OPEN)
        return NO;
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    NSString* order_status= [self.content_data[indexPath.row] valueForKey:@"order_status"];
    
    
    if(appDelegate.user_type==USER_ROLE_CUSTOMER) {
        // saved && ((type==0 && merge_permission) || type == 1 || can_cancel)
//        if ([order_status isEqualToString:@"Saved Order"] && (([Singleton sharedInstance].permissions_merge_order && self.orderType == 0) || self.orderType == 1 || appDelegate.can_cancel_order)) {
//            DebugLog(@"%d Yes",indexPath.row);
//            return YES;
//        } else {
//            return NO;
//        }
        BOOL isSavedOrder = [order_status isEqualToString:@"Saved Order"];
        switch (self.orderType) {
            case 0:{ // Shop Order
                
                if (!isSavedOrder) {
                    return NO;
                } else {
                    if ([Singleton sharedInstance].permissions_merge_order || appDelegate.can_cancel_order) {
                        return YES;
                    } else {
                        return NO;
                    }
                }
                
            }
                break;
            case 1:{ // Sales Order
                if (isSavedOrder && appDelegate.can_cancel_order) {
                    return YES;
                }
                return NO;
            }
                break;
                
            default:
                break;
        }
        
    } else {
        return YES;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle  forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tv editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if(indexPath.row==self.content_data.count)
        return UITableViewCellEditingStyleNone;
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    bool offline_edit =[[self.content_data[indexPath.row] valueForKey:@"offline_edit"] boolValue];
    
    NSString* order_status= [self.content_data[indexPath.row] valueForKey:@"order_status"];
    
    if(![order_status isEqualToString:@"Saved Order"]&&! [order_status isEqualToString:@"Quote Saved"])
        return UITableViewCellEditingStyleNone;
    else
    {
        if(appDelegate.offline_mode==false||offline_edit)
            return UITableViewCellEditingStyleDelete;
        else
            return UITableViewCellEditingStyleNone;
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark EnumSelectViewControllerDelegate
-(void) EnumValueChanged:(NSMutableDictionary *)value indexPath :(NSIndexPath*) indexPath
{
    
    
    self.status_cadedate = value;
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    appDelegate.OrderFilter = value;
    
    
    //    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //    NSString *documents = [paths objectAtIndex:0];
    //    NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
    //    
    //    
    //    //    if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
    //    //
    //    //        DebugLog(@"文件已经存在了");
    //    //
    //    //    }
    //    //    else
    //    //    {
    //    //
    //    //
    //    //
    //            //        DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
    //    
    //NSData *data = [NSJSONSerialization dataWithJSONObject:self.status_cadedate options:kNilOptions error:nil];
    //    
    //            //        DebugLog(@"mainBundleFile==%@",mainBundleFile);
    //    
    //            [[NSFileManager defaultManager] createFileAtPath:dist_path
    //    
    //                                                    contents:data
    //    
    //                                                  attributes:nil];
    //
    //    }
    
    
    
    
    //    self.keywords=searchBar.text;
    //    self.offset = 0;
    //    [self.content_data removeAllObjects];
    self.reset_result=true;
    [self loadpage];
    
    //[self.btnStatusFilter setTitle:setTitle:alert ];
    
    
    
}

#pragma mark - button action

- (NSIndexPath *)indexPathOfDeleteOrder:(NSString *)orderID {
    for (NSIndexPath *indexPath in self.table_order.indexPathsForSelectedRows) {
        
        NSString* orderid= [NSString stringWithFormat:@"%@",[self.content_data[indexPath.row] valueForKey:@"order_id"]];
        if ([orderid isEqualToString:orderID]) {
            return indexPath;
        }
    }
    return nil;
}

- (IBAction)mergeListButtonClick:(UIBarButtonItem *)sender {
    
    if (!self.table_order.isEditing) {
        
        [RAUtils message_alert:@"You have to click select firstly then select some saved order" title:@"Warning" controller:self];
        return;
    }
    
    [self handleSelectedOrders];
    
    if (!self.mergeList.count) {
        
//        [RAUtils message_alert:@"Combine List is Empty" title:@"Warning" controller:self];
        return;
    }
    
    SelectUploadOrderViewController *mergeVC = [[UIStoryboard storyboardWithName:@"OLM" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SelectUploadOrderViewController"];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:mergeVC];
    
    mergeVC.mergeList = self.mergeList;
    
    mergeVC.title = @"Combine List";
    
    __weak typeof(self) weakself = self;
    
    mergeVC.mergeBlock = ^(NSDictionary *ret) {
      
        
        if (weakself) {
            
            __strong typeof(weakself) strongself = weakself;
            
            if([[ret objectForKey:@"result"]integerValue] == RESULT_TRUE) {
                
                [weakself.mergeList removeAllObjects];
                [strongself.table_order endEditing:YES];
                [strongself ReloadData];
                
                if ([Singleton sharedInstance].customer_can_see_sales_Order) {
                    
                    [strongself openOrder:ret];
                    
                }
                
            } else {
                
                NSString *msg = [ret objectForKey:@"err_msg"];
                [RAUtils message_alert:msg title:nil controller:strongself];
            }
        }
        
    };
    
    mergeVC.deleteBlock = ^(NSString *orderID){
        NSIndexPath *indexPath = [weakself indexPathOfDeleteOrder:orderID];
        [weakself.table_order deselectRowAtIndexPath:indexPath animated:YES];
    };
    
    mergeVC.clearBlock = ^{
        for (NSDictionary *order in self.mergeList) {
            
            NSString *order_id = [NSString stringWithFormat:@"%@",[order objectForKey:@"order_id"]];
            NSIndexPath *indexPath = [weakself indexPathOfDeleteOrder:order_id];
            [weakself.table_order deselectRowAtIndexPath:indexPath animated:YES];
        }
    };
    
    nav.modalPresentationStyle = UIModalPresentationFormSheet;
    
    [self presentViewController:nav animated:YES completion:nil];
    
}

- (void)handleSelectedOrders {
    
    [self.mergeList removeAllObjects];
    if (!self.table_order.isEditing) {
        return;
    }
    for (NSIndexPath *indexPath in self.table_order.indexPathsForSelectedRows) {
       
        if(indexPath.row==self.content_data.count)
            continue;
        
        NSString* so= [self.content_data[indexPath.row] valueForKey:@"so#"];
        NSString* orderid= [self.content_data[indexPath.row] valueForKey:@"order_id"];
        NSString *create_by = [self.content_data[indexPath.row] valueForKey:@"create_by"];
        NSString *create_time = [self.content_data[indexPath.row] valueForKey:@"purchase_time"];
        NSString *orderCode = [NSString stringWithFormat:@"%@",[self.content_data[indexPath.row] valueForKey:@"order_code"]];
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        
        [dic setValue:orderid forKey:@"order_id"];
        [dic setValue:orderCode forKey:@"order_code"];
        [dic setValue:so forKey:@"so_id"];
        [dic setValue:create_by forKey:@"create_by"];
        [dic setValue:create_time forKey:@"create_time"];
        [dic setValue:[NSNumber numberWithInteger:0] forKey:@"check"]; // 合并到
        
        [self.mergeList addObject:dic];

    }
    
}

- (IBAction)editOrderListButtonClick:(UIBarButtonItem *)sender {

    if ([Singleton sharedInstance].global_lock) { // Order list 被锁
        [RAUtils message_alert:@"Permission Needed.\nGoto Menu -> Unlock" title:@"Warning" controller:self];
        return;
    }
    
    UIImage *gray = [UIImage imageNamed:@"Combinegray"];
    UIImage *green = [[UIImage imageNamed:@"Combinegreen"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    if (self.table_order.isEditing) {
        [self mergeListButtonClick:nil];
        // 结束选择时恢复
        if ([Singleton sharedInstance].customer_can_see_sales_Order && ![Singleton sharedInstance].global_lock) { // 有查看Sales order 权限,并且app没有锁
            if (self.orderTypeSegmentControl.numberOfSegments == 1) {
                [self.orderTypeSegmentControl insertSegmentWithTitle:@"Purchase Order" atIndex:1 animated:YES];
            }
        }
        
        self.status_cadedate = self.shop_order_filter;
        [self ReloadData];
        
        [self.table_order setEditing:NO animated:YES];
//        sender.title = @"Select";
//        [self.mergeList removeAllObjects];
        [sender setImage:gray];
        
    } else {
        // 选择时不能选择Sales Order
        if(self.orderTypeSegmentControl.numberOfSegments > 1) {
            [self.orderTypeSegmentControl removeSegmentAtIndex:1 animated:YES];
        }
        // 切换filter
        NSData *data=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]  pathForResource:@"status_filter_cadedate_open" ofType:@"json" ]];
        NSError *error=nil;
        self.status_cadedate = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error] mutableCopy];
        // 刷新，取Saved Order
        [self ReloadData];
        
        [self.table_order setEditing:YES animated:YES];
//        sender.title = @"Exit";
        [sender setImage:green];
    }
    
}

- (void)changeOrderType:(NSInteger)ordertype {
    self.orderType = ordertype;
    [Singleton sharedInstance].customer_order_type = ordertype;
    if(self.init_style != OL_OPEN) {
        switch (ordertype) {
            case 0:{
                self.status_cadedate = self.shop_order_filter;
            }
                break;
            case 1:{
                self.status_cadedate = self.sales_order_filter;
            }
                break;
            default:
                break;
        }
        
        NSMutableArray *items = [self.toolbarView.items mutableCopy];
        if (ordertype == 1) {
            // 不能合并
//            if ([items containsObject:self.mergeListButton]) { // 显示button
//                [items removeObject:self.mergeListButton];
//            }
            if ([items containsObject:self.editOrderListButton]) { // 显示button
                [items removeObject:self.editOrderListButton];
            }
            
            self.toolbarView.items = items;
            
        } else {
            
            // 合并订单的权限
            if ([Singleton sharedInstance].permissions_merge_order) { // 能够合并
                
                // 4 6 顺序不能换
                if (![items containsObject:self.editOrderListButton]) { // 没显示button
                    [items insertObject:self.editOrderListButton atIndex:4];
                }
                
//                if (![items containsObject:self.mergeListButton]) { // 没显示button
//                    [items insertObject:self.mergeListButton atIndex:6];
//                }
                
                self.toolbarView.items = items;
                
            } else { // 不能合并
//                if ([items containsObject:self.mergeListButton]) { // 显示button
//                    [items removeObject:self.mergeListButton];
//                }
                if ([items containsObject:self.editOrderListButton]) { // 显示button
                    [items removeObject:self.editOrderListButton];
                }
                
                self.toolbarView.items = items;
            }
            
        }
        
    }
    
   
    
    [self ReloadData];
}

- (IBAction)orderTypeChanged:(UISegmentedControl *)sender {

    [self changeOrderType:sender.selectedSegmentIndex];
    
}

- (void)openOrder:(NSDictionary *)order {
    
    if (!order) {
        return;
    }
    
    NSString *orderCode = [order objectForKey:@"orderCode"];
    NSInteger orderStatus = [[order objectForKey:@"orderStatus"] integerValue];
    NSString *so = [order objectForKey:@"so#"];
    
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary* order_json = [iSalesNetwork open_Order:orderCode];
        
        dispatch_async(dispatch_get_main_queue(), ^{

            if([[order_json valueForKey:@"result"] intValue]==2)
            {
                AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                appDelegate.order_code = orderCode;
                appDelegate.order_status = orderStatus;
                [appDelegate SetSo:so];
                
                __weak MainViewController *mainVC = (MainViewController*)appDelegate.main_vc;
                
                [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
                [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
                [((MainViewController*)appDelegate.main_vc) reloadContact:true immediately:false];
                [((MainViewController*)appDelegate.main_vc) switchToCart];
                
                mainVC.cartViewController.onFinishLoad=^{
                    [mainVC.cartViewController placeOrder];
                    mainVC.cartViewController.onFinishLoad=nil;
                };
                
            }
            else
            {
                [RAUtils message_alert:[order_json valueForKey:@"err_msg"] title:@"Open Order" controller:weakself] ;
            }
            
            
            
        });
    });

    
}

#pragma mark - notification action

- (void)changePriceType:(id)notification {
    [self ReloadData];
}

- (void)lockOrderListNotification:(NSNotification *)notification {
    if ([notification.name isEqual:Lock_Permission_Notification]) {
        if (self.orderType == 1) {
            self.orderTypeSegmentControl.selectedSegmentIndex = 0;
//            [self changeOrderType:0];
            [self.orderTypeSegmentControl sendActionsForControlEvents:UIControlEventValueChanged];
        }
        
        if(self.orderTypeSegmentControl.numberOfSegments > 1) {
            [self.orderTypeSegmentControl removeSegmentAtIndex:1 animated:YES];
        }
    } else { // 解锁
        if ([Singleton sharedInstance].customer_can_see_sales_Order) { // 有查看Sales order 权限
            if (self.orderTypeSegmentControl.numberOfSegments == 1 && !self.table_order.isEditing) {
                [self.orderTypeSegmentControl insertSegmentWithTitle:@"Purchase Order" atIndex:1 animated:YES];
            }
        }
        
    }
}

- (void)handleUserLogin:(NSNotification *)notification {
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    self.orderType = 0;
    if (self.table_order.isEditing) {
        [self.table_order setEditing:NO animated:YES];
        self.editOrderListButton.image = [UIImage imageNamed:@"Combinegray"];
    }
    if (appDelegate.user_type == USER_ROLE_CUSTOMER) {
        self.orderTypeSegmentControl.selectedSegmentIndex = 0;
        [Singleton sharedInstance].customer_order_type = 0;
        
    }
}

@end
