//
//  PrintViewController.m
//
//  Created by mac on 2019/3/13.
//  Copyright © 2019年 zyl. All rights reserved.
//

#import "PrintViewController.h"
#import "PrintPictureViewController.h"
#import "PrintTextTableViewCell.h"
#import "PrintQRTableViewCell.h"
#import "PrintImageTableViewCell.h"
#import "PrintTextData.h"
#import "PrintQRData.h"
#import "PrintImageData.h"
#import "Utils.h"
#import "System.h"
#import <ASR033WSDK/ASR033WSDK.h>

#define IS_IPhoneX_All [UIScreen mainScreen].bounds.size.height >= 812
@interface PrintViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource,ASR033WDelegate, PrintPictureDelegate, ASR033WPrinterDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)NSString *dateString;
@property (nonatomic, strong)NSString *timeString;

@property (nonatomic, strong)PrintQRData *QRData;
@property (nonatomic, strong)PrintImageData *ImageData;

@property (nonatomic, strong)UILabel *cutLabel;
@property (nonatomic, strong)UILabel *cashLabel;
@property (nonatomic, strong)UISegmentedControl *cutSegment;
@property (nonatomic, strong)UIButton *statusButton;

@end

@implementation PrintViewController{
    System *_system;
    UIAlertController *alert;
    NSMutableArray *_printArray;
    ASR033W *asr033w;
    ASR033WPrinter *asr033wPrinter;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    asr033w.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    asr033w = [ASR033W sharedInstance];
    if (asr033w.isConnected) {
        if (asr033wPrinter) {
            asr033wPrinter = nil;
        }
        asr033wPrinter = [asr033w getASR033WPrinter];
        asr033wPrinter.printDelegate = self;
    }
    _system = [System sharedSystem];
    _printArray  = [[NSMutableArray alloc] init];
    NSArray *array = [_system getPrintTextData];
    if (array && array.count != 0) {
        self.dataArray = [NSMutableArray arrayWithArray:array];
    }
    self.QRData = [[PrintQRData alloc] init];
    self.QRData = [_system getPrintQRData];
    self.ImageData = [[PrintImageData alloc] init];
    self.ImageData = [_system getPrintImageData];
    [self setUI];
}

#pragma mark - UI
- (void)setUI {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    UIView *viewVC = [[UIView alloc] init];
    if (IS_IPhoneX_All) {
        viewVC.frame = CGRectMake(0, self.view.bounds.size.height - 220 - 20 - 34, self.view.bounds.size.width, 220);
    } else {
        viewVC.frame = CGRectMake(0, self.view.bounds.size.height - 220 - 20, self.view.bounds.size.width, 220);
    }
    viewVC.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:viewVC];
    
    self.cutLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 10, 100, 30)];
    self.cutLabel.text = @"Cut Paper";
    self.cutLabel.font = [UIFont systemFontOfSize:16];
    [viewVC addSubview:self.cutLabel];
    
    NSArray *array = @[@"Not", @"Half", @"Full"];
    self.cutSegment = [[UISegmentedControl alloc]initWithItems:array];
    self.cutSegment.frame = CGRectMake(self.view.bounds.size.width - 186 - 25, self.cutLabel.frame.origin.y, 186, 33);
    if ([_system getPrintCutPaper] == 0) {
        [self.cutSegment setSelectedSegmentIndex:0];
    } else if ([_system getPrintCutPaper] == 1) {
        [self.cutSegment setSelectedSegmentIndex:1];
    } else {
        [self.cutSegment setSelectedSegmentIndex:2];
    }
    [viewVC addSubview:self.cutSegment];
    [self.cutSegment addTarget:self action:@selector(cutSegmentAction:) forControlEvents:UIControlEventValueChanged];
    
    UIButton *printButton = [[UIButton alloc] initWithFrame:CGRectMake(20, self.cutLabel.frame.origin.y + self.cutLabel.frame.size.height + 15, viewVC.bounds.size.width - 40, 40)];
    [printButton setTitle:@"Print" forState:UIControlStateNormal];
    [printButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [printButton setBackgroundColor:[UIColor redColor]];
    [printButton addTarget:self action:@selector(print) forControlEvents:UIControlEventTouchUpInside];
    [viewVC addSubview:printButton];
    
    UIButton *openDrawerButton = [[UIButton alloc] initWithFrame:CGRectMake(20, printButton.frame.origin.y + printButton.frame.size.height + 15, viewVC.bounds.size.width - 40, 40)];
    [openDrawerButton setTitle:@"Open Drawer" forState:UIControlStateNormal];
    [openDrawerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [openDrawerButton setBackgroundColor:[UIColor redColor]];
    [openDrawerButton addTarget:self action:@selector(openDrawer) forControlEvents:UIControlEventTouchUpInside];
    [viewVC addSubview:openDrawerButton];
}

#pragma mark -KeyBoardNotification
- (void)keyboardWillShow:(NSNotification *)note
{
    [UIView animateWithDuration:0.1 animations:^{
        CGRect keyBoardRect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
    }];
}

- (void)keyboardWillHide:(NSNotification *)note
{
    [UIView animateWithDuration:0.1 animations:^{
        self.tableView.contentInset = UIEdgeInsetsZero;
    }];
}

#pragma mark - TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return self.dataArray.count;
            break;
        case 1:
            return 1;

            break;
        case 2:
            return 1;

            break;
        default:
            return 0;
            break;
    }
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (0 == indexPath.section) {
        NSString *cellIdentifier = @"PrintText";
        PrintTextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell =  [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
        }
        
        PrintTextData *data = [self.dataArray objectAtIndex:indexPath.row];
        cell.textField.text = data.textString;
        [cell.alignmetSegment setSelectedSegmentIndex:[data.alignmentString intValue]];
        [cell.fontSegment setSelectedSegmentIndex:[data.fontString intValue]];
        
        cell.alignmetSegment.tag = indexPath.row;
        cell.fontSegment.tag = indexPath.row;

        [cell.alignmetSegment addTarget:self action:@selector(textAlignSegmentAction:) forControlEvents:UIControlEventValueChanged];
        [cell.fontSegment addTarget:self action:@selector(textFontSegmentAction:) forControlEvents:UIControlEventValueChanged];

        cell.textField.delegate = self;
        cell.textField.tag = indexPath.row;
        [cell.textField addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.selected = NO;
        return cell;
        
    } else if (1 == indexPath.section) {
        NSString *cellIdentifier = @"PrintQR";
        PrintQRTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell =  [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
        }
        cell.textField.text = self.QRData.textString;
        [cell.alignmentSegment setSelectedSegmentIndex:[self.QRData.alignmentString intValue]];
        [cell.fontSegment setSelectedSegmentIndex:[self.QRData.fontString intValue]];
        
        cell.textField.delegate = self;
        [cell.textField addTarget:self action:@selector(QRTextField:) forControlEvents:UIControlEventEditingChanged];

        [cell.alignmentSegment addTarget:self action:@selector(QRAlignSegmentAction:) forControlEvents:UIControlEventValueChanged];
        [cell.fontSegment addTarget:self action:@selector(QRFontSegmentAction:) forControlEvents:UIControlEventValueChanged];

        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.selected = NO;
        return cell;
        
    } else {
        
        NSString *cellIdentifier = @"PrintImage";
        PrintImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell =  [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
        }
        if ([self.ImageData.picString isEqualToString:@"Select Image"]) {
            [cell.pictureButton setTitle:self.ImageData.picString forState:UIControlStateNormal];
            [cell.pictureButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        } else {
            [cell.pictureButton setTitle:nil forState:UIControlStateNormal];
            [cell.pictureButton setImage:[UIImage imageNamed:self.ImageData.picString] forState:UIControlStateNormal];
            cell.pictureButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        }
        [cell.aligmentSegment setSelectedSegmentIndex:[self.ImageData.alignmentString intValue]];
        cell.widthTextField.text = self.ImageData.widthString;
        cell.heightTextField.text = self.ImageData.heightString;

        cell.widthTextField.delegate = self;
        cell.heightTextField.delegate = self;
        [cell.widthTextField addTarget:self action:@selector(widthTextField:) forControlEvents:UIControlEventEditingChanged];
        [cell.heightTextField addTarget:self action:@selector(heightTextField:) forControlEvents:UIControlEventEditingChanged];

        [cell.pictureButton addTarget:self action:@selector(choosePic) forControlEvents:UIControlEventTouchUpInside];
        [cell.aligmentSegment addTarget:self action:@selector(imageAlignSegmentAction:) forControlEvents:UIControlEventValueChanged];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.selected = NO;
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return 110;
            break;
        case 1:
            return 130;
            break;
        case 2:
            return 145;
            
            break;
        default:
            return 0;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 50;
            break;
        case 1:
            return 30;
            break;
        case 2:
            return 30;
            break;
        default:
            return 0;
            break;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *viewVC = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)];
    viewVC.backgroundColor = [UIColor colorWithRed:231 / 255.f green:231 / 255.f blue:235 / 255.f alpha:1];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 100, 20)];
    label.textColor = [UIColor colorWithRed:120 / 255.f green:120 / 255.f blue:125 / 255.f alpha:1];
    label.font = [UIFont systemFontOfSize:14];
    [viewVC addSubview:label];
    
    if (0 == section) {
        [viewVC setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
        [label setFrame:CGRectMake(20, 10, 100, 30)];
        label.text = @"TEXT";
        UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 25 - 30, 10, 30, 30)];
        [addButton setBackgroundImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
        [addButton addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
        [viewVC addSubview:addButton];
    } else if (1 == section) {
        label.text = @"QRCODE";
    } else {
        label.text = @"IMAGE";
    }
    return viewVC;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return YES;
    }
    return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"Delete";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (indexPath.section == 0) {
            if (self.dataArray.count != 1) {
                [self.dataArray removeObjectAtIndex:indexPath.row];
                [self.tableView beginUpdates];
                [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                [self.tableView endUpdates];
            }
        }
    }
}

#pragma mark - Action
- (void)add {
    PrintTextData *textData = [[PrintTextData alloc] init];
    textData.textString = @"";
    textData.alignmentString = @"0";
    textData.fontString = @"0";
    [self.dataArray addObject:textData];
    
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

- (void)choosePic {
    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    PrintPictureViewController *picVC = [mainStoryBoard instantiateViewControllerWithIdentifier:@"picID"];
    picVC.nameDelegate = self;
    [self.navigationController pushViewController:picVC animated:YES];
}

- (void)changedTextField:(id)sender {
    UITextField *tempTextField = (UITextField *)sender;
    PrintTextData *data = [self.dataArray objectAtIndex:tempTextField.tag];
    data.textString = tempTextField.text;
}

- (void)QRTextField:(id)sender {
    UITextField *tempTextField = (UITextField *)sender;
    self.QRData.textString = tempTextField.text;
}

- (void)widthTextField:(id)sender {
    UITextField *tempTextField = (UITextField *)sender;
    self.ImageData.widthString = tempTextField.text;
}

- (void)heightTextField:(id)sender {
    UITextField *tempTextField = (UITextField *)sender;
    self.ImageData.heightString = tempTextField.text;
}

- (void)textAlignSegmentAction:(UISegmentedControl*)sender
{
    PrintTextData *data = [self.dataArray objectAtIndex:sender.tag];
    switch (sender.selectedSegmentIndex) {
        case 0:
            data.alignmentString = @"0";
            break;
        case 1:
            data.alignmentString = @"1";
            break;
        case 2:
            data.alignmentString = @"2";
            break;
        default:
            break;
    }
}

- (void)textFontSegmentAction:(UISegmentedControl*)sender
{
    PrintTextData *data = [self.dataArray objectAtIndex:sender.tag];
    switch (sender.selectedSegmentIndex) {
        case 0:
            data.fontString = @"0";
            break;
        case 1:
            data.fontString = @"1";
            break;
        case 2:
            data.fontString = @"2";
            break;
        case 3:
            data.fontString = @"3";
            break;
        case 4:
            data.fontString = @"4";
            break;
        case 5:
            data.fontString = @"5";
            break;
        case 6:
            data.fontString = @"6";
            break;
        case 7:
            data.fontString = @"7";
            break;
        default:
            break;
    }
}

- (void)QRAlignSegmentAction:(UISegmentedControl*)sender
{
    switch (sender.selectedSegmentIndex) {
        case 0:
            self.QRData.alignmentString = @"0";
            break;
        case 1:
            self.QRData.alignmentString = @"1";
            break;
        case 2:
            self.QRData.alignmentString = @"2";
            break;
        default:
            break;
    }
}

- (void)QRFontSegmentAction:(UISegmentedControl*)sender
{
    switch (sender.selectedSegmentIndex) {
        case 0:
            self.QRData.fontString = @"0";
            break;
        case 1:
            self.QRData.fontString = @"1";
            break;
        case 2:
            self.QRData.fontString = @"2";
            break;
        case 3:
            self.QRData.fontString = @"3";
            break;
        case 4:
            self.QRData.fontString = @"4";
            break;
        case 5:
            self.QRData.fontString = @"5";
            break;
        case 6:
            self.QRData.fontString = @"6";
            break;
        default:
            break;
    }
}

- (void)imageAlignSegmentAction:(UISegmentedControl*)sender
{
    switch (sender.selectedSegmentIndex) {
        case 0:
            self.ImageData.alignmentString = @"0";
            break;
        case 1:
            self.ImageData.alignmentString = @"1";
            break;
        case 2:
            self.ImageData.alignmentString = @"2";
            break;
        default:
            break;
    }
}

- (void)cutSegmentAction:(UISegmentedControl*)sender
{
    if (0 == sender.selectedSegmentIndex) {
        [_system setPrintCutPaper:0];
    }
    if (1 == sender.selectedSegmentIndex) {
        [_system setPrintCutPaper:1];
    }
    if (2 == sender.selectedSegmentIndex) {
        [_system setPrintCutPaper:2];
    }
}


- (IBAction)clearAction:(id)sender {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Are you sure you want to clear the data?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self clearData];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)clearData {
    self.QRData.textString = @"";
    self.QRData.alignmentString = @"0";
    self.QRData.fontString = @"0";
    
    self.ImageData.picString = @"Select Image";
    self.ImageData.alignmentString = @"0";
    self.ImageData.widthString = @"";
    self.ImageData.heightString = @"";
    
    [_printArray removeAllObjects];
    [self.dataArray removeAllObjects];
    PrintTextData *textData = [[PrintTextData alloc] init];
    textData.textString = @"";
    textData.alignmentString = @"0";
    textData.fontString = @"0";
    [self.dataArray addObject:textData];
    
    [self.cutSegment setSelectedSegmentIndex:0];
    [self.tableView reloadData];

    [_system setPrintTextData:self.dataArray];
    [_system setPrintQRData:self.QRData];
    [_system setPrintImageData:self.ImageData];
}


- (IBAction)backAction:(UIBarButtonItem *)sender {
    [_system setPrintTextData:self.dataArray];
    [_system setPrintQRData:self.QRData];
    [_system setPrintImageData:self.ImageData];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - PrintPictureDelegateDelegate
- (void)backPicName:(NSString *)name width:(NSString *)w height:(NSString *)h {
    if (name && ![name isEqualToString:@""]) {
        self.ImageData.picString = name;
        self.ImageData.widthString = w;
        self.ImageData.heightString = h;
        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:2];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)currentTimeAction {
    NSString *string = [Utils getCurrentTimes];
    if (string && ![string isEqualToString:@""] && string.length == 19) {
        self.dateString = [string substringToIndex:10];
        self.dateString = [self.dateString stringByReplacingCharactersInRange:NSMakeRange(4, 1) withString:@"年"];
        self.dateString = [self.dateString stringByReplacingCharactersInRange:NSMakeRange(7, 1) withString:@"月"];
        self.dateString = [NSString stringWithFormat:@"%@日", self.dateString];
        self.timeString = [string substringFromIndex:11];
    }
}

//------------------------------------------------------
#pragma mark - ASR033WPrinter
//------------------------------------------------------
- (void)print {
    if (!asr033w.isConnected) {
        [self asReader033WNotConnectInstructions];
        return;
    }
    if (self.dataArray && self.dataArray.count != 0) {
        _printArray = [[NSMutableArray alloc] init];
        _printArray = [NSMutableArray arrayWithArray:self.dataArray];
    }
    if (![self printStatus]) {
        return;
    }
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Are you sure you want to print?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self->_system setPrintTextData:self.dataArray];
        [self->_system setPrintQRData:self.QRData];
        [self->_system setPrintImageData:self.ImageData];
        [self printData];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (BOOL)printStatus {
    for (PrintQRData *data in _printArray) {
        if (![data.textString isEqualToString:@""]) {
            return YES;
        }
    }
    if (![self.QRData.textString isEqualToString:@""] || (![self.ImageData.picString isEqualToString:@""] && ![self.ImageData.picString isEqualToString:@"Select Image"])) {
        return YES;
    }
    [self printerNoData];
    return NO;
}

- (void)printData {
    [asr033wPrinter cleanPrintData];
    //文本
    for (PrintTextData *data in _printArray) {
        ASR033WPrintAlignment type = [self alignmentAction:[data.alignmentString intValue]];
        ASR033WPrintFont fot = [self fontSizeAction:[data.fontString intValue]];
        [asr033wPrinter addPrintText:data.textString font:fot printerAlignment:type];
    }
    //QRCode
    if (self.QRData.textString && ![self.QRData.textString isEqualToString:@""]) {
        ASR033WPrintAlignment type = [self alignmentAction:[self.QRData.alignmentString intValue]];
        ASR033WPrintQrDotSize fot = [self fontAction:[self.QRData.fontString intValue]];
        [asr033wPrinter addPrintQRCode:self.QRData.textString
                                  size:fot
                      printerAlignment:type];
    }
    //图片
    if (self.ImageData.picString && ![self.ImageData.picString isEqualToString:@"Select Image"]) {
        UIImage *image = [UIImage imageNamed:self.ImageData.picString];
        ASR033WPrintAlignment type = [self alignmentAction:[self.ImageData.alignmentString intValue]];
        [asr033wPrinter addPrintImage:image width:[self.ImageData.widthString floatValue] height:[self.ImageData.heightString floatValue] printerAlignment:type];
    }
    [asr033wPrinter addPrintText:@"\n " font:ASR033WPrintFont_1 printerAlignment:ASR033WPrintAlignmentRight];
    [asr033wPrinter addPrintText:@"\n " font:ASR033WPrintFont_1 printerAlignment:ASR033WPrintAlignmentRight];
    [asr033wPrinter addPrintText:@"\n " font:ASR033WPrintFont_1 printerAlignment:ASR033WPrintAlignmentRight];
    [asr033wPrinter addPrintText:@"\n " font:ASR033WPrintFont_1 printerAlignment:ASR033WPrintAlignmentRight];
    [asr033wPrinter addPrintText:@"\n " font:ASR033WPrintFont_1 printerAlignment:ASR033WPrintAlignmentRight];
    //切纸
    if ([_system getPrintCutPaper] == 1) {
        [asr033wPrinter addCutCommand:ASR033WPrintCutTypeHalf];
    } else if ([_system getPrintCutPaper] == 2) {
        [asr033wPrinter addCutCommand:ASR033WPrintCutTypeFull];
    }
    [asr033wPrinter getPrinterStatus];
}

- (ASR033WPrintAlignment)alignmentAction:(int)align {
    ASR033WPrintAlignment type;
    switch (align) {
        case 0:
            type = ASR033WPrintAlignmentLeft;
            break;
        case 1:
            type = ASR033WPrintAlignmentCenter;
            break;
        case 2:
            type = ASR033WPrintAlignmentRight;
            break;
        default:
            type = ASR033WPrintAlignmentLeft;
            break;
    }
    return type;
}

- (ASR033WPrintFont)fontSizeAction:(int)fot {
    ASR033WPrintFont type;
    switch (fot) {
        case 0:
            type = ASR033WPrintFont_1;
            break;
        case 1:
            type = ASR033WPrintFont_2;
            break;
        case 2:
            type = ASR033WPrintFont_3;
            break;
        case 3:
            type = ASR033WPrintFont_4;
            break;
        case 4:
            type = ASR033WPrintFont_5;
            break;
        case 5:
            type = ASR033WPrintFont_6;
            break;
        case 6:
            type = ASR033WPrintFont_7;
            break;
        case 7:
            type = ASR033WPrintFont_8;
            break;
        default:
            type = ASR033WPrintFont_1;
            break;
    }
    return type;
}

- (ASR033WPrintQrDotSize)fontAction:(int)fot {
    ASR033WPrintQrDotSize type;
    switch (fot) {
        case 0:
            type = ASR033WPrintQrDotSize_1;
            break;
        case 1:
            type = ASR033WPrintQrDotSize_2;
            break;
        case 2:
            type = ASR033WPrintQrDotSize_3;
            break;
        case 3:
            type = ASR033WPrintQrDotSize_4;
            break;
        case 4:
            type = ASR033WPrintQrDotSize_5;
            break;
        case 5:
            type = ASR033WPrintQrDotSize_6;
            break;
        case 6:
            type = ASR033WPrintQrDotSize_7;
            break;
        default:
            type = ASR033WPrintQrDotSize_1;
            break;
    }
    return type;
}

- (void)printerNoData {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"No Data" message:@"Please to add Data" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)openDrawer {
    if (!asr033w.isConnected) {
        [self asReader033WNotConnectInstructions];
        return;
    }
    [asr033wPrinter openDrawer];
}

- (void)asReader033WNotConnectInstructions{
    [Utils showAlert:@"Warning" message:@"Please connect to 033W first!"];
}

//------------------------------------------------------
#pragma mark - ASR033WPrinterDelegate
//------------------------------------------------------
- (void)AsReaderWiredBOXTypePrinterConnected:(BOOL)isConnected {

}

- (void)ASR033WPrinterStatus:(ASR033WPrinterStatus)printerStatus {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{

        NSString *titleStr = @"";
        if (printerStatus == ASR033WPrinterStatus_NOPAPER) {
            titleStr = @"No Paper";
        } else if (printerStatus == ASR033WPrinterStatus_InstitutionalFailure) {
            titleStr = @"InstitutionalFailure";
        } else if (printerStatus == ASR033WPrinterStatus_CoverOpen) {
            titleStr = @"Cover Open";
        } else {
            [self->asr033wPrinter doPrint];
            return;
        }
        UIAlertController *alert = [UIAlertController
                                    alertControllerWithTitle:titleStr
                                    message:nil
                                    preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:nil];
        [alert addAction:ok];
        [self presentViewController:alert animated:YES completion:nil];
    }];

}

- (BOOL)retryPrintOnError{
    return YES;
}

- (void)whenPrintSuccessed{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{

        UIAlertController *alert = [UIAlertController
                                    alertControllerWithTitle:@"Printed successfully"
                                    message:nil
                                    preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:nil];
        [alert addAction:ok];
        [self presentViewController:alert animated:YES completion:nil];
    }];

}
#pragma mark - ASR033WDelegate
- (void)receivedASR033WNetworkState:(ASR033WNetworkState)state error:(NSError *)error {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        if (state != ASR033WNetworkStateConnected) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }];
}
@end
