//
//  ScanResultViewController.m
//  Project
//
//  Created by Vae on 2018/6/21.
//

#import "ScanResultViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "TableViewCellWrapper.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "Product.h"
#import "SoldStock.h"
#import "UIViewController+Privilege.h"
#import "PurchaseRecordResponseJsonMapper.h"
#import "PerlWS.h"
#import "CheckInActionHandler.h"
#import "CheckInScanViewController.h"
#import "SalesEntryDetailViewController.h"
#import "Vars.h"
@interface ScanResultViewController ()

@property (nonatomic, weak) IBOutlet TableViewCellWrapper *stockCellView;
@property (nonatomic, weak) IBOutlet UILabel *messageLabel;
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@property (nonatomic, weak) IBOutlet UIButton *actionButton;
@property (nonatomic, weak) IBOutlet UIButton *scanButton;

@property (nonatomic, strong) Sales *order;
@property (nonatomic, strong, readonly) SalesEntry *entry;

@property (nonatomic, strong, readonly) UITableViewCell *stockCell;

- (IBAction)toggleCheckIn:(id)sender;
- (IBAction)popToParent:(id)sender;

@end

@implementation ScanResultViewController

- (instancetype)init {
    if (self = [super init]) {
        // Custom initialization
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.title = @"Check-In";
        [[Vars appDelegate] applyDefaultConfigurationForViewController:self];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    @weakify(self)
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] im_initWithBarButtonSystemItem:UIBarButtonSystemItemCancel handler:^(UIBarButtonItem *barButtonItem) {
        @strongify(self)
        [CocoaUtils popViewControllerInQuantity:2 onNavigationController:self.navigationController animated:YES];
    }];
    
    self.stockCellView.style = UITableViewCellStyleSubtitle;
    [self.stockCellView addGestureRecognizer:[UITapGestureRecognizer bk_recognizerWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
        @strongify(self)
        if (self.entry) {
            [self showDetail];
        } else {
            [self findUniqueOrder];
        }
    }]];
    self.stockCell.textLabel.textColor = [Vars defaultTintColor];
    self.stockCell.detailTextLabel.textColor = [Vars defaultTintColor];
    self.stockCell.accessoryView = [DrawUtils tableViewCellAccessoryDisclosureIndicatorRightWithColor:[Vars defaultTintColor]];
    self.stockCell.textLabel.text = self.stock.cn;
    self.stockCell.detailTextLabel.text = self.stock.sold_to_name;
    [Utility addRoundedBorderToView:self.stockCellView];
    
    self.actionButton.backgroundColor = [Vars defaultTintColor];
    self.scanButton.backgroundColor = [Vars defaultTintColor];
    [Utility addRoundedBorderToButtons:@[self.actionButton, self.scanButton]];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self notifyTicketStatus:[self lookupStock:self.entry.stocks] reverse:NO];
    [self performSelector:@selector(processData)];
}

#pragma mark - Action

- (IBAction)toggleCheckIn:(id)sender {
    [CheckInActionHandler updateStocks:@[self.stock] toCheckIn:!self.stock.vendor_checkin commit:^(NSString *message) {
        [self performSelector:@selector(processData)];
    }];
}

- (IBAction)popToParent:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showDetail {
    [self notifyTicketStatus:[self lookupStock:self.entry.stocks] reverse:YES];
    SalesEntryDetailViewController *viewController = [[SalesEntryDetailViewController alloc] init];
    viewController.entry = self.entry;
    viewController.stock_id = self.stock.stock_id;
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Property

- (SalesEntry *)entry {
    return [self.order.entries bk_match:^BOOL (SalesEntry *obj) {
        return [obj.stocks bk_any:^BOOL (SoldStock *obj) {
            return obj.stock_id == self.stock.stock_id;
        }];
    }];
}

- (UITableViewCell *)stockCell {
    return [self.stockCellView get];
}

#pragma mark - Network

- (void)findUniqueOrder {
    FindUniqueOrder *record = [[FindUniqueOrder alloc] init];
    record.stock_id = self.stock.stock_id;
    
    NSDictionary *requestDict = [Utility perlParamXml:[record innerXML] action:record.name];
    
    [Utility getXMLFromRequestWithMethod:@"GET" url:record.address parameters:requestDict success:^(NSString *xml) {
        NSString *responseStr = xml;
        
        PurchaseRecordResponseJsonMapper *mapper = [[PurchaseRecordResponseJsonMapper alloc] init];
        NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
        if (![mapper parseWithJSONObject:jsonDict]) {
            PurchaseRecordResponse *response = mapper.response;
            if (![StringUtils isEmpty:response.error]) {
                [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error];
            } else {
                if (response.orders.count > 0) {
                    self.order = response.orders.firstObject;
                }
                if (self.entry) {
                    [self showDetail];
                } else {
                    [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:[Vars responseException]];
                }
            }
        }
    }];
}

#pragma mark - Private

- (void)processData {
    if (!self.stock) {
        self.actionButton.hidden = YES;
    }else if (self.stock.vendor_checkin){
        self.actionButton.hidden = NO;
		self.messageLabel.text = @"The ticket is checked in";
        [self.actionButton setTitle:@"Undo Check-In" forState:UIControlStateNormal];
    }else{
        self.actionButton.hidden = NO;
		self.messageLabel.text = @"The ticket is unchecked";
        [self.actionButton setTitle:@"Check-In" forState:UIControlStateNormal];
    }
    
    if (self.status) {
        self.imageView.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome checkCircleIconWithSize:CGRectGetHeight(self.imageView.frame)] fillColor:[UIColor cloverColor]];
            self.messageLabel.textColor = [UIColor cloverColor];
    }else{
        self.imageView.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome timesCircleIconWithSize:CGRectGetHeight(self.imageView.frame)] fillColor:[Vars defaultTintColor]];
        self.messageLabel.textColor = [Vars defaultTintColor];
    }

}

- (void)notifyTicketStatus:(SoldStock *)stock reverse:(BOOL)reverse {
    if (stock) {
        if (reverse) {
            stock.vendor_checkin = self.stock.vendor_checkin;
            stock.checked = self.stock.checked;
        } else {
            self.stock.vendor_checkin = stock.vendor_checkin;
            self.stock.checked = stock.checked;
        }
    }
}

- (SoldStock *)lookupStock:(NSArray *)stocks {
    return [stocks bk_match:^BOOL (SoldStock *obj) {
        return obj.stock_id == self.stock.stock_id;
    }];
}



@end
