//
//  PDFListViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 11/23/15.
//  Copyright © 2015 United Software Applications, Inc. All rights reserved.
//

#import "PDFListViewController.h"
#import "PDFListTableViewCell.h"
#import "iSalesNetwork.h"
#import "PDFViewController.h"
#import "MainViewController.h"
#import "DefaultAppearance.h"
#import "DefaultTableHeaderView.h"
#import "SortItemViewController.h"
#import "UIColor+JK_HEX.h"

@interface PDFListViewController ()


@end

@implementation PDFListViewController


-(void) logout
{
    self.offset = 0;
    self.limit = 25;
    [self.content_data removeAllObjects];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.offset = 0;
    self.limit = 25;
    self.content_data = [[NSMutableArray alloc]init];
    
    
    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 addSubview:ref];
    
    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;
    
    
    CGPoint center = self.mum.center;
    self.mum.frame = CGRectMake(0, 0, 100, 100);
    self.mum.center = center;
    self.mum.backgroundColor = [UIColor colorWithHEX:0xA5A5A5 alpha:0.5];
    self.mum.layer.cornerRadius = 5.0f;
    self.mum.layer.masksToBounds = YES;
    
    
    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.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) reload_container_getdata:(bool) update_data
{
    [super reload_container_getdata:update_data];
    if(update_data)
    {
    self.offset = 0;
    [self.content_data removeAllObjects];
    self.norefresh=true;
    [self loadpage];
    }
    else
        [self.table reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

        
//        if(!self.norefresh)//避免 多次刷新
//        {
//            self.norefresh = true;
//            self.offset = 0;
//            [self.content_data removeAllObjects];
//            [self loadpage];
//            
//        }
    
    
    [[self navigationController] setNavigationBarHidden:YES animated:NO];
    
}


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

-(void)ReloadData
{
    
    
    [self.content_data removeAllObjects];
    [self.table 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.content_data removeAllObjects];
    //    [self.table_order reloadData];
    
    
    [self loadpage];
    
    //   [self loadpage];
    
}
-(void) loadpage
{

    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.isrefreshing)
            return;
        self.label_net_err.hidden=true;
        self.isrefreshing=true;
        self.table.hidden =true;
    self.mum.center = self.view.center;

        
        self.mum.hidden = false;
        [self.mum startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        
        
        
        NSMutableDictionary* content=nil;
        content=[[iSalesNetwork request_PDFList:self.offset limit : self.limit keywords:self.keywords] mutableCopy];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            
            
            [self.mum stopAnimating];
            
            int result=[[content valueForKey:@"result"] intValue];
            
            if(result==2||result==0)
            {
                self.table.hidden =false;
                
                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]];
                    DebugLog(@"content_data: %@",self.content_data);
                }
                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 reloadData ];
            }
            else if(result==RESULT_NET_ERROR)
            {
                self.label_net_err.hidden=false;
                self.table.hidden=true;
            }
            else
            {
                [RAUtils message_alert:[content valueForKey:@"err_msg"]  title:@"Loading Portfilio 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:^{
            //
            //                }];
            //            }
            self.isrefreshing=false;
            
            
        });
            
        });
    });
}

- (void)loadmore
{
    //    self.btnrefresh.enabled = NO;
    //    self.btnrefresh.titleLabel.text =NSLocalizedString(@"loading",nil);
    
    //    [self.btnrefresh setTitle:@"Loading..." forState:UIControlStateNormal];
    [self loadpage];
}
/*
#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 - 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(color);
    
    myView.layer.shadowColor = [UIColor blackColor].CGColor;
    myView.layer.shadowOffset = CGSizeMake(0, 0);
    myView.layer.shadowOpacity = 0.5;
    myView.layer.shadowRadius = 2.0;
    
    
    UILabel *namelabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 11, 75, 22)];
    namelabel.textColor=UIColorFromRGB(color);
    namelabel.backgroundColor = [UIColor clearColor];
    namelabel.text=NSLocalizedString(@"Name", nil);
    [namelabel sizeToFit];
    [myView addSubview:namelabel];
    
//    UILabel *solabel = [[UILabel alloc] initWithFrame:CGRectMake(173, 5.5, 130, 22)];
//    solabel.textColor=[UIColor whiteColor];
//    solabel.backgroundColor = [UIColor clearColor];
//    solabel.text=NSLocalizedString(@"Name", nil);
//    [solabel sizeToFit];
//    [myView addSubview:solabel];
    
    UILabel *notelabel = [[UILabel alloc] initWithFrame:CGRectMake(250, 11, 75, 22)];
    notelabel.textColor=UIColorFromRGB(color);
    notelabel.backgroundColor = [UIColor clearColor];
    notelabel.text=NSLocalizedString(@"Notes", nil);
    [notelabel sizeToFit];
    [myView addSubview:notelabel];
    
    
    
    UILabel *timelabel = [[UILabel alloc] initWithFrame:CGRectMake(self.table.frame.size.width-163,11, 148, 22)];
    timelabel.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin;
    timelabel.textColor=UIColorFromRGB(color);
    timelabel.backgroundColor = [UIColor clearColor];

    timelabel.text=@"Create time";

    [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
{
    //    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.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 = @"PDFListTableViewCell";
        PDFListTableViewCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
       // int _id= [[self.content_data[indexPath.row] valueForKey:@"_id"] intValue];
        NSString* name= [self.content_data[indexPath.row] valueForKey:@"tear_name"];
        NSString* note= [self.content_data[indexPath.row] valueForKey:@"tear_note"];
        NSString* create_time= [self.content_data[indexPath.row] valueForKey:@"create_time"];
      //  NSString* type = [self.content_data[indexPath.row] valueForKey:@"type"] ;
      //  NSString* file_name = [self.content_data[indexPath.row] valueForKey:@"file_name"];

        cell.labelName.text = name;
        cell.labelTime.text = create_time;
        cell.labelNote.text = note;
   //     cell.labelType.text = type;
//        cell.labelprice.text=price;
//        cell.label_date.text=purchase_time;
//        cell.label_contact.text=customer_name;
//        cell.label_model.text = model_count;
//        
//        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(self.content_data.count== indexPath.row)
        return;
    NSString* name=[self.content_data[indexPath.row] valueForKey:@"tear_name"];
    NSString* url= [self.content_data[indexPath.row] valueForKey:@"pdf_path"];
    
    if(url==nil)
    {
        
        NSMutableDictionary* params = [RAUtils string2dict:[self.content_data[indexPath.row] valueForKey:@"off_params"]];
        NSMutableDictionary* values = [RAUtils string2dict:[self.content_data[indexPath.row] valueForKey:@"model_info"]];
        params[@"replaceValue"]=values;
        params[@"tearsheetsId"]=[self.content_data[indexPath.row] valueForKey:@"tearsheetsId"];
        NSString* createpdf = [iSalesNetwork create_portfolio:params];
        if(createpdf!=nil)
            url=createpdf;
       // if()
        
    }

    BOOL isLocalFile= [[self.content_data[indexPath.row] valueForKey:@"isLocalFile"] boolValue];
    
    PDFViewController *ViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PDFViewController"];
    ViewController.url = url;
    ViewController.canSave = false;
    ViewController.isLocalfile=isLocalFile;
    NSString* subject;
    //                    if (company.length==0) {
    
    NSString* cur_time =[RAUtils current_date];
    subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                        NSString* customer_email=    [appDelegate.customerInfo valueForKey:@"customer_email"];
    
    
                        NSMutableArray* send_to = [[NSMutableArray alloc]init];
                        if(customer_email.length>0)
                        {
                            send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
//                            customer_email compo
//                            [send_to addObject:customer_email];
                        }
                        ViewController.mail_to = send_to;

    //                    }
    //                    else
    //                    {
    //                        subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
    //                    }
    ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
    ViewController.mail_subject = subject;

    ViewController.hidenavi = false;
    [self.navigationController pushViewController:ViewController animated:YES];
    //[self.navigationController setNavigationBarHidden:NO animated:NO];

}


#pragma mark - searchBar delegate;
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.keywords=searchBar.text;
    self.offset = 0;
    [self.content_data removeAllObjects];
    [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 loadpage];
    }
    else
        self.reset = false;
}

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

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

{
    
    NSString* listid= [self.content_data[indexPath.row] valueForKey:@"tearsheetsId"];
    
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        DebugLog(@"delete click");
        
        
        
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Delete confirm", nil) message:NSLocalizedString(@"Are you sure to remove portfolio?", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"NO", nil) otherButtonTitles:NSLocalizedString(@"YES", nil), nil];
//    //    alert.tag = ALERT_DEL;
//        // alert.
//        [alert show];
//        
        

        
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Are you sure to remove this portfolio?" message:nil preferredStyle:UIAlertControllerStyleAlert];
            //block代码块取代了delegate
            
            
            
            UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Remove Portfilio"];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    NSDictionary* cart_json = [iSalesNetwork delete_portfoliolist:listid];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                        
                        if([[cart_json valueForKey:@"result"] intValue]==2)
                        {
                            
                            [self ReloadData];
                        }
                        else
                        {
                            [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Delete Portfolio" controller:self] ;
                        }
                        
                        
                        
                    });
                });
                
                
            }];
            
            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                DebugLog(@"No");
            }];
            [alertControl addAction:actionOne];
            
            [alertControl addAction:alertthree];
            
            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
            
            
            [self presentViewController:alertControl animated:YES completion:nil];
            

            
            
        
        
        
        
        
        
    }];
    deleteRowAction.backgroundColor = UIColorFromRGB(0x336699);
    
    
    
    NSString* create_user= [self.content_data[indexPath.row] valueForKey:@"create_user"];
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if([create_user isEqualToString:appDelegate.user])
    {
         return @[deleteRowAction];
    }
    return nil;

    
    
}


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


@end
