//
//  TransactionViewController.m
//  EugineAPISample
//
//  Created by aaab on 2023/02/08.
//

#import "TransactionViewController.h"

#import "SmartChampAPI.h"
#import "SmartChampReal.h"
#import "SmartChampTran.h"
#import "ComUtil.h"
#import "TRTestViewController.h"
#import "ComboBox.h"
#import "Util.h"
#import "MyTextField.h"
#import "CustomTableViewCell.h"
//#import "NFilterChar.h"
//#import "NFilterNum.h"
//#import "EccEncryptor.h"
#import "UITextField+Addition.h"

@interface TransactionViewController () <IComboBox , ITranDataDelegate , UITextFieldDelegate , IRealDataDelegate , UITableViewDataSource >
{
    ComboBox *firstComboBox;
    ComboBox *secondComboBox;
    ComboBox *thirdComboBox;
    
    SmartChampReal *tranReal;
    SmartChampTran *tranNormal;
    
    CGFloat xPadding;
    CGFloat yPadding;
    CGFloat control_height;
    
    UITextField *textFieldCount;
    
    
    NSDictionary *normalTR;
    NSDictionary *orderTR;
    NSDictionary *realTR;
    
    UILabel     *selectTRName;
    UIButton    *requestButton;
    
    UIScrollView *inputScrollView;
    UIScrollView *outputScrollView;
    
    NSMutableArray  *arrayInputView;
    NSMutableArray  *arrayOutputView;
    NSMutableArray  *arrayWidth;
    NSMutableArray  *arrayTableData;
    NSMutableArray  *arrayColumnKey;
    UITableView  *outputTableView;
    
    NSDictionary    *dicTitleAttr;
    NSDictionary    *dicCellAttr;
    
//    NFilterChar *encKeyboardChar;
//    NFilterNum  *encKeyboardNum;
}
@end

@implementation TransactionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSParagraphStyle *style = [ComUtil makeParagraphStyle:nil lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft lineSpacing:0];
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:14];
    dicTitleAttr = [ComUtil makeFontAttrDictionary:font fontColor:[UIColor blackColor] underLine:NO letterSpace:0 paragraph:style];
    
    NSParagraphStyle *style2 = [ComUtil makeParagraphStyle:nil lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft lineSpacing:0];
    UIFont *font2 = [UIFont fontWithName:@"HelveticaNeue-Light" size:12];
    dicCellAttr = [ComUtil makeFontAttrDictionary:font2 fontColor:[UIColor blackColor] underLine:NO letterSpace:0 paragraph:style2];
    
    xPadding = 20;
    yPadding = 10;
    control_height = 25;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    normalTR = [[SmartChampAPI instance] getNormalTRList];
    orderTR = [[SmartChampAPI instance] getOrderTRList];
    realTR = [[SmartChampAPI instance] getRealTRList];
    
    NSArray *arrayKey = [NSArray arrayWithObjects:@"0", @"1" , @"2" , nil];
    NSArray *arrayName = [NSArray arrayWithObjects:@"일반", @"주문" , @"실시간" , nil];
    firstComboBox = [[ComboBox alloc] initWithFrame:CGRectMake(xPadding, 30, 50, control_height)];
    [firstComboBox setKeys:arrayKey title:arrayName];
    [firstComboBox setComboDelegate:self];
    [self.view addSubview:firstComboBox];
    
    textFieldCount = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(firstComboBox.frame) + xPadding, CGRectGetMinY(firstComboBox.frame), 30, CGRectGetHeight(firstComboBox.frame))];
    [textFieldCount setFont:[Util fontType:BOLD size:14]];
    [textFieldCount setText:@"20"];
    [textFieldCount setTextColor:[UIColor blackColor]];
    [textFieldCount setPlaceholder:@"조회건수"];
    [textFieldCount addNumericAccessory:NO];
    [self.view addSubview:textFieldCount];

    secondComboBox = [[ComboBox alloc] initWithFrame:CGRectMake(CGRectGetMaxX(textFieldCount.frame), CGRectGetMinY(textFieldCount.frame), 80, CGRectGetHeight(textFieldCount.frame))];
    [secondComboBox setKeys:[self getSecondList] title:[self getSecondList]];
    [secondComboBox setComboDelegate:self];
    [self.view addSubview:secondComboBox];

    thirdComboBox = [[ComboBox alloc] initWithFrame:CGRectMake(CGRectGetMaxX(secondComboBox.frame) + 5, CGRectGetMinY(textFieldCount.frame), CGRectGetWidth(self.view.frame) - CGRectGetMaxX(secondComboBox.frame) - xPadding, CGRectGetHeight(firstComboBox.frame))];
    [thirdComboBox setKeys:[self getThirdList:NO] title:[self getThirdList:YES]];
    [thirdComboBox setComboDelegate:self];
    [self.view addSubview:thirdComboBox];
    
    selectTRName = [[UILabel alloc] initWithFrame:CGRectMake(xPadding, CGRectGetMaxY(firstComboBox.frame) + 20, CGRectGetWidth(self.view.frame) - (xPadding * 2), CGRectGetHeight(firstComboBox.frame))];
    [selectTRName setTextColor:[UIColor blackColor]];
    [selectTRName setTextAlignment:NSTextAlignmentLeft];
    [self selectTRName];
    [self.view addSubview:selectTRName];
    
    requestButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [requestButton setFrame:CGRectMake(CGRectGetWidth(self.view.frame) - CGRectGetHeight(selectTRName.frame) - xPadding * 2, CGRectGetMinY(selectTRName.frame), CGRectGetHeight(selectTRName.frame) * 2, CGRectGetHeight(selectTRName.frame))];
//    UIImage *imageRefresh = [UIImage imageNamed:@"btn_bottom_reflash_n.png"];
    [ComUtil setTitleInButton:requestButton title:@"조회"];
    [ComUtil setColorInButton:requestButton color:[UIColor blackColor]];
//    [requestButton setImage:imageRefresh forState:UIControlStateNormal];
    [requestButton setImageEdgeInsets:UIEdgeInsetsMake(6, 6, 6, 6)];
    [requestButton addTarget:self action:@selector(onRequestButton:) forControlEvents:UIControlEventTouchUpInside];
    [ComUtil makeRoundView:requestButton radius:4 width:1 bordercolor:[UIColor blackColor]];
    [self.view addSubview:requestButton];
    
    inputScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(selectTRName.frame), CGRectGetWidth(self.view.frame), control_height * 7)];
    [self.view addSubview:inputScrollView];
    
    UILabel *inputLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMinY(inputScrollView.frame), CGRectGetHeight(self.view.frame), control_height)];
    [inputLabel setText:@"Input"];
    [inputLabel setFont:[Util fontType:BOLD size:16]];
    [inputLabel setTextColor:[UIColor whiteColor]];
    [inputLabel setBackgroundColor:[UIColor lightGrayColor]];
//    [inputLabel setAlpha:0.4];
    [self.view addSubview:inputLabel];
    
    UIView *lineView = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(inputScrollView.frame), CGRectGetWidth(self.view.frame), 1)];
    [lineView setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:lineView];
    
    outputScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lineView.frame) + 1, CGRectGetWidth(inputScrollView.frame), CGRectGetHeight(self.view.frame) - CGRectGetMaxY(lineView.frame) - 100)];
    [self.view addSubview:outputScrollView];
    [outputScrollView setBounces:NO];
    
    UILabel *outputLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMinY(outputScrollView.frame), CGRectGetHeight(self.view.frame), control_height)];
    [outputLabel setText:@"OutPut"];
    [outputLabel setFont:[Util fontType:BOLD size:16]];
    [outputLabel setTextColor:[UIColor whiteColor]];
    
    [outputLabel setBackgroundColor:[UIColor lightGrayColor]];
//    [outputLabel setAlpha:0.4];
    [self.view addSubview:outputLabel];
    
    [self selectTRName];
    
    [self makeCloseButton];
}

- (void)dealloc
{
    if (tranReal != nil){
        [tranReal cancelRealData];
        [tranReal releaseReal];
    }
}

- (void)makeCloseButton
{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(CGRectGetWidth(self.view.frame) - 50 , 15, 35, 35)];
    [button addTarget:self action:@selector(onCloseButton:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image = [UIImage imageNamed:@"ic_floating_close_48.png"];
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:image forState:UIControlStateHighlighted];
    [self.view addSubview:button];
}

- (void)onCloseButton:(UIButton*)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)onRequestButton:(UIButton*)sender
{
    [arrayTableData removeAllObjects];
    [outputTableView reloadData];
    if (tranNormal != nil){
        
        for (UIView *subView in inputScrollView.subviews) {
            if ( [subView isKindOfClass:[MyTextField class]]){
                MyTextField *inputTextField = (MyTextField*)subView;
                BOOL isItemCode = [tranNormal isItemCodeField:[inputTextField getBlockID] fieldID:[inputTextField getField]];
                if (isItemCode){
                    NSString *sFullCode = [[SmartChampAPI instance] getItemFullCode:inputTextField.text];
                    if (sFullCode == nil || [sFullCode length] == 0){
                        [tranNormal setDataValue:[inputTextField getBlockID] fieldID:[inputTextField getField] index:[inputTextField getIndex] value:inputTextField.text];
                    }else{
                        [tranNormal setDataValue:[inputTextField getBlockID] fieldID:[inputTextField getField] index:[inputTextField getIndex] value:sFullCode];
                    }
                }else{
                    [tranNormal setDataValue:[inputTextField getBlockID] fieldID:[inputTextField getField] index:[inputTextField getIndex] value:inputTextField.text];
                }
            }
        }
        
        [tranNormal setDataHeader:@"DETAIL_CONT" data:@"1"]; // 연속조회
        [tranNormal setDataHeader:@"DETAIL_QRY_CNT" data:textFieldCount.text]; // 조회개수
        
        [tranNormal requestData];
    }
    
    if (tranReal != nil){
        [tranReal cancelRealData];
        [tranReal releaseReal];
        
        if (arrayOutputView != nil){
            for (UIView *view in arrayOutputView) {
                [view removeFromSuperview];
            }
            [arrayOutputView removeAllObjects];
            outputTableView = nil;
            
            for (UIView *subview in outputScrollView.subviews) {
                [subview removeFromSuperview];
            }
        }
        
        for (UIView *subView in inputScrollView.subviews) {
            if ( [subView isKindOfClass:[MyTextField class]]){
                MyTextField *inputTextField = (MyTextField*)subView;
                BOOL isItemCode = [tranReal isItemCodeField:[inputTextField getBlockID] fieldID:[inputTextField getField]];
                if (isItemCode){
                    NSString *sFullCode = [[SmartChampAPI instance] getItemFullCode:inputTextField.text];
                    if (sFullCode == nil || [sFullCode length] == 0){
                        [tranReal setDataValue:[inputTextField getBlockID] fieldID:[inputTextField getField] index:[inputTextField getIndex] value:inputTextField.text];
                    } else {
                        [tranReal setDataValue:[inputTextField getBlockID] fieldID:[inputTextField getField] index:[inputTextField getIndex] value:sFullCode];
                    }
                }else{
                    [tranReal setDataValue:[inputTextField getBlockID] fieldID:[inputTextField getField] index:[inputTextField getIndex] value:inputTextField.text];
                }
            }
        }
        
        
        [tranReal requestReal];
    }
}

- (void)selectTRName
{
    NSString *sName = [NSString stringWithFormat:@"%@(%@)" , [thirdComboBox getSelectName] , [thirdComboBox getSelectkey]];
    [selectTRName setText:sName];
    
    if (tranNormal != nil){
        [tranNormal clearRequest];
    }
    
    if (tranReal != nil){
        [tranReal releaseReal];
    }
    tranNormal  = nil;
    tranReal = nil;
    NSString *sKey = [firstComboBox getSelectkey];
    NSString *sTranKey = [thirdComboBox getSelectkey];
    if ([sKey isEqualToString:@"0"] || [sKey isEqualToString:@"1"]){
        tranNormal = [[SmartChampTran alloc] initWithTrCode:sTranKey delegate:self];
    }else{
        tranReal = [[SmartChampReal alloc] initWithTrCode:sTranKey delegate:self];
    }
    
    [self makeInputLayout];
}

- (NSArray*)getSecondList
{
    NSArray *arrOrder = nil;
    if ([[firstComboBox getSelectkey] isEqualToString:@"0"]){
        arrOrder = [normalTR objectForKey:@"order"];
    }else if ([[firstComboBox getSelectkey] isEqualToString:@"1"]){
        arrOrder = [orderTR objectForKey:@"order"];
    }else if ([[firstComboBox getSelectkey] isEqualToString:@"2"]){
        arrOrder = [realTR objectForKey:@"order"];
    }
    
    return arrOrder;
}

- (NSArray*)getThirdList:(BOOL)isName
{
    NSString *skey = [secondComboBox getSelectkey];
    
    NSArray *arrayThird = nil;
    if ([[firstComboBox getSelectkey] isEqualToString:@"0"]){
        arrayThird = [normalTR objectForKey:skey];
    }else if ([[firstComboBox getSelectkey] isEqualToString:@"1"]){
        arrayThird = [orderTR objectForKey:skey];
    }else if ([[firstComboBox getSelectkey] isEqualToString:@"2"]){
        arrayThird = [realTR objectForKey:skey];
    }
    
    NSMutableArray *arrayTemp = [NSMutableArray array];
    for ( NSDictionary *dic in arrayThird){
        NSString *sTTT = nil;
        if (isName){
            sTTT = [dic objectForKey:@"name"];
        }else{
            sTTT = [dic objectForKey:@"tr"];
        }
        if (sTTT != nil){
            [arrayTemp addObject:sTTT];
        }
    }
    
    return arrayTemp;
}

- (void)selectComboBox:(ComboBox*)box selectKey:(NSString*)key
{
    if (box == firstComboBox){
        [secondComboBox setKeys:[self getSecondList] title:[self getSecondList]];
        [thirdComboBox setKeys:[self getThirdList:NO] title:[self getThirdList:YES]];
        
    }else if (box == secondComboBox){
        [thirdComboBox setKeys:[self getThirdList:NO] title:[self getThirdList:YES]];
    }else if (box == thirdComboBox){
        
    }
    [self selectTRName];
}

- (void)makeInputLayout
{
    CGFloat pos = 0;
    if (tranNormal != nil){
        pos = [self makeTranInputFieldLayout:pos];
    }else if (tranReal != nil){
        pos = [self makeRealInputFieldLayout:pos];
    }
    
    [inputScrollView setContentSize:CGSizeMake(0, pos + 20)];
}


- (CGFloat)makeTranInputFieldLayout:(CGFloat)yPos
{
    NSArray *array = [tranNormal getInputBlockNames];
    CGFloat width = (CGRectGetWidth(self.view.frame) - xPadding * 2) / 2;
    
    if (arrayInputView == nil){
        arrayInputView = [NSMutableArray array];
    }
    for (UIView *view in arrayInputView) {
        [view removeFromSuperview];
    }
    
    [arrayInputView removeAllObjects];
    
    for ( NSInteger i = 0 ; i < [array count] ; i++){
        NSString *sBlockName = array[i];
        
//        UILabel *inputLabel = [[UILabel alloc] initWithFrame:CGRectMake(xPadding, yPos, width, control_height)];
//        [inputLabel setText:sBlockName];
//        [inputLabel setFont:[Util fontType:BOLD size:12]];
//        [inputScrollView addSubview:inputLabel];
        yPos += (control_height + yPadding);
        UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:13];
        NSArray *arrayFieldName = [tranNormal getFieldNames:sBlockName];
        for (NSInteger j = 0 ; j < [arrayFieldName count] ; j++) {
            NSString *sFieldName = arrayFieldName[j];
            if (![tranNormal isOccursBlock:sBlockName])
            {
                BOOL isEncrypt = [tranNormal isEncryptField:sBlockName fieldID:sFieldName];
                BOOL isAccount = [tranNormal isAccountNoField:sBlockName fieldID:sFieldName];
                BOOL isPassword = [tranNormal isPasswordField:sBlockName fieldID:sFieldName];
//                BOOL isItemCoe = [tranNormal isItemCodeField:sBlockName fieldID:sFieldName];
                NSString *fieldName = [tranNormal getFieldName:sBlockName fieldID:sFieldName];
                MyTextField *textField = [[MyTextField alloc] initWithFrame:CGRectMake(xPadding, yPos, width, control_height)];
                [textField setFont:font];
                [textField setAccount:isAccount];
                [textField addNumericAccessory:YES];
                [textField setDelegate:self];
                [textField setIndex:i];
                [textField setBlockID:sBlockName];
                [textField setField:sFieldName];
//                UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, control_height)];;
//                [leftView setBackgroundColor:[UIColor blackColor]];
//                textField.leftView = leftView;
//                textField.leftViewMode = UITextFieldViewModeAlways;
                
                if (isEncrypt || isPassword){
                    [textField setSecureTextEntry:YES];
                }
                
                // 게좌 비밀번호
                if (isEncrypt && [sFieldName isEqualToString:@"AC_PWD"]){
                    [textField setKeyboardType:UIKeyboardTypeNumberPad];
                }
                
                [textField setPlaceholder:fieldName];
                [inputScrollView addSubview:textField];
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(textField.frame), yPos, CGRectGetWidth(self.view.frame) - CGRectGetMaxX(textField.frame) - xPadding , control_height)];
                [label setTextAlignment:NSTextAlignmentLeft];
                [label setText:[NSString stringWithFormat:@"%@(%@)" , fieldName , sFieldName]];
                [label setFont:font];
                [inputScrollView addSubview:label];
                
                [arrayInputView addObject:textField];
                [arrayInputView addObject:label];
            }
            
            yPos += (control_height + yPadding);
        }
        
    }
    
    return yPos;
}

- (CGFloat)makeRealInputFieldLayout:(CGFloat)yPos
{
    NSArray *array = [tranReal getInputBlockNames];
    CGFloat width = (CGRectGetWidth(self.view.frame) - xPadding * 2) / 3;
    
    if (arrayInputView == nil){
        arrayInputView = [NSMutableArray array];
    }
    for (UIView *view in arrayInputView) {
        [view removeFromSuperview];
    }
    
    [arrayInputView removeAllObjects];
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:13];
    for ( NSInteger i = 0 ; i < [array count] ; i++){
        NSString *sBlockName = array[i];
        
        UILabel *inputLabel = [[UILabel alloc] initWithFrame:CGRectMake(xPadding, yPos, width, control_height)];
        [inputLabel setText:sBlockName];
        [inputLabel setFont:[Util fontType:BOLD size:12]];
        [inputScrollView addSubview:inputLabel];
        yPos += (control_height + yPadding);
        NSArray *arrayFieldName = [tranReal getFieldNames:sBlockName];
        
        for (NSInteger j = 0 ; j < [arrayFieldName count] ; j++) {
            NSString *sFieldName = arrayFieldName[j];
//            if (![tranReal isOccursBlock:sBlockName])
            {
                BOOL isEncrypt = [tranReal isEncryptField:sBlockName fieldID:sFieldName];
                BOOL isAccount = [tranReal isAccountNoField:sBlockName fieldID:sFieldName];
                BOOL isItemCoe = [tranReal isItemCodeField:sBlockName fieldID:sFieldName];
                NSString *fieldName = [tranReal getFieldName:sBlockName fieldID:sFieldName];
                MyTextField *textField = [[MyTextField alloc] initWithFrame:CGRectMake(xPadding, yPos, width, control_height)];
                [textField setDelegate:self];
                [textField setFont:font];
                [textField setIndex:i];
                [textField setBlockID:sBlockName];
                [textField setField:sFieldName];
//                UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, control_height)];;
//                [leftView setBackgroundColor:[UIColor blackColor]];
//                textField.leftView = leftView;
//                textField.leftViewMode = UITextFieldViewModeAlways;
                
                if (isEncrypt){
                    [textField setSecureTextEntry:isEncrypt];
                }
                
//                if (isItemCoe) {
//                    [textField setKeyboardType:UIKeyboardTypeNumberPad];
//                }
                
                [textField addNumericAccessory:YES];
                
                [textField setPlaceholder:fieldName];
                [inputScrollView addSubview:textField];
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(textField.frame), yPos, CGRectGetWidth(self.view.frame) - CGRectGetMaxX(textField.frame) - xPadding , control_height)];
                [label setTextAlignment:NSTextAlignmentLeft];
                [label setFont:font];
                [label setText:[NSString stringWithFormat:@"%@(%@)" , fieldName , sFieldName]];
                [inputScrollView addSubview:label];
                
                [arrayInputView addObject:textField];
                [arrayInputView addObject:label];
            }
            
            yPos += (control_height + yPadding);
        }
        
    }
    
    return yPos;
}

- (CGFloat)makeTranOutputFieldLayout:(CGFloat)yPos;
{
    NSArray *array = [tranNormal getOutBlockNames];
    CGFloat width = (CGRectGetWidth(self.view.frame) - xPadding * 2) / 2.5;
    
    if (arrayOutputView == nil){
        arrayOutputView = [NSMutableArray array];
    }
    for (UIView *view in arrayOutputView) {
        [view removeFromSuperview];
    }
    [arrayOutputView removeAllObjects];
    outputTableView = nil;
    
    if (arrayTableData == nil) arrayTableData = [NSMutableArray array];
    [arrayTableData removeAllObjects];
    for ( int i = 0 ; i < [array count] ; i++){
        NSString *sBlockName = array[i];
        
//        UILabel *inputLabel = [[UILabel alloc] initWithFrame:CGRectMake(xPadding, yPos, width, control_height)];
//        [inputLabel setText:sBlockName];
//        [inputLabel setFont:[Util fontType:BOLD size:12]];
//        [outputScrollView addSubview:inputLabel];
        yPos += (control_height + yPadding);
        NSArray *arrayFieldName = [tranNormal getFieldNames:sBlockName];
        
        
        if (![tranNormal isOccursBlock:sBlockName]) // 싱글
        {
            for (int j = 0 ; j < [arrayFieldName count] ; j++) {
                NSString *sFieldName = arrayFieldName[j];
//                BOOL isEncrypt = [tranNormal isEncryptField:sBlockName fieldID:sFieldName];
//                BOOL isAccount = [tranNormal isAccountNoField:sBlockName fieldID:sFieldName];
//                BOOL isItemCoe = [tranNormal isItemCodeField:sBlockName fieldID:sFieldName];
                NSString *fieldName = [tranNormal getFieldName:sBlockName fieldID:sFieldName];
                
                NSString *sValue = [ComUtil trim:[tranNormal getDataValue:sBlockName fieldID:sFieldName index:0]];
                UILabel *textField = [[UILabel alloc] initWithFrame:CGRectMake(xPadding / 5, yPos, width, control_height)];
                UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:13];
                [textField setFont:font];
                [textField setText:sValue];
                [outputScrollView addSubview:textField];
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(textField.frame), yPos, CGRectGetWidth(self.view.frame) - CGRectGetMaxX(textField.frame) - xPadding , control_height)];
                [label setTextAlignment:NSTextAlignmentLeft];
                [label setText:[NSString stringWithFormat:@"%@(%@)" , fieldName , sFieldName]];
                [label setFont:font];
                [outputScrollView addSubview:label];
                
                [arrayOutputView addObject:textField];
                [arrayOutputView addObject:label];
                yPos += (control_height + yPadding);
            }
        }else{ // 멀티 블럭
            int nDataCount = [tranNormal getDataCount:sBlockName];
            for (int k = 0; k < nDataCount ; k++) {
                NSMutableDictionary *dicField = [NSMutableDictionary dictionary];
                for (int j = 0 ; j < [arrayFieldName count] ; j++) {
                    NSString *sFieldName = arrayFieldName[j];
                    NSString *value = [ComUtil trim:[tranNormal getDataValue:sBlockName fieldID:sFieldName index:k]];
                    NSString *sKeyValue = [NSString stringWithFormat:@"%@^%@", sFieldName, value];
                    [dicField setObject:sKeyValue forKey:[NSString stringWithFormat:@"%03d", j]];
                }
                [arrayTableData addObject:dicField];
            }
            
            if (outputTableView == nil){
                outputTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, yPos, CGRectGetWidth(self.view.frame), control_height * 7) style:UITableViewStylePlain];
                [outputTableView setBounces:NO];
                [outputTableView setDelegate:self];
                [outputTableView setDataSource:self];
                [outputTableView setRowHeight:control_height];
                [outputScrollView addSubview:outputTableView];
            }else{
                [outputTableView setFrame:CGRectMake(0, yPos, CGRectGetWidth(self.view.frame), control_height * 7)];
            }
            [arrayOutputView addObject:outputTableView];
            [outputTableView setHidden:NO];
            
            if (arrayTableData != nil && [arrayTableData count] > 0)
                [self setTableViewItem:arrayTableData];
            
            [outputTableView reloadData];
            yPos += CGRectGetHeight(outputTableView.frame);
        }
    }
    
    [outputScrollView setContentSize:CGSizeMake(0, yPos)];
    
    return yPos;
}

- (CGFloat)makeRealOutputFieldLayout:(CGFloat)yPos;
{
    
    CGFloat width = (CGRectGetWidth(self.view.frame) - xPadding * 2) / 3;
    
    if (arrayOutputView == nil){
        arrayOutputView = [NSMutableArray array];
    }
    for (UIView *view in arrayOutputView) {
        [view removeFromSuperview];
    }
    [arrayOutputView removeAllObjects];
    
    if ( outputTableView != nil){
        [outputTableView setHidden:NO];
        [outputTableView reloadData];
        return 0;
    }
    
    if (outputTableView == nil){
        outputTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, yPos, CGRectGetWidth(self.view.frame), CGRectGetHeight(outputScrollView.frame) - yPos) style:UITableViewStylePlain];
        [outputTableView setBounces:NO];
        [outputTableView setDataSource:self];
        [outputScrollView addSubview:outputTableView];
    }
    [outputTableView setHidden:NO];

    
    
    [outputScrollView setContentSize:CGSizeMake(0, yPos)];
    
    return yPos;
}

- (void)processRealOutputData
{
    if (arrayTableData == nil){
        arrayTableData = [NSMutableArray array];
    }
    
    NSArray *array = [tranReal getOutBlockNames];
    for ( int i = 0 ; i < [array count] ; i++){
        NSString *sBlockName = array[i];
        NSArray *arrayFieldName = [tranReal getFieldNames:sBlockName];
        if (![tranReal isOccursBlock:sBlockName]) // 싱글 ( 실시간은 싱글 밖에 없음..)
        {
            NSMutableDictionary *dicField = [NSMutableDictionary dictionary];
            for (int j = 0 ; j < [arrayFieldName count] ; j++) {
                NSString *sFieldName = arrayFieldName[j];
                NSString *fieldName = [tranReal getFieldName:sBlockName fieldID:sFieldName];
                NSString *sValue = [tranReal getDataValue:sBlockName fieldID:sFieldName index:0];
                NSString *sKeyValue = [NSString stringWithFormat:@"%@^%@", sFieldName, sValue];
                [dicField setObject:sKeyValue forKey:[NSString stringWithFormat:@"%03d", j]];   
            }
            [arrayTableData insertObject:dicField atIndex:0];
            
            if ([arrayTableData count] == 1){
                [self setTableViewItem:arrayTableData];
            }else{
                [outputTableView reloadData];
            }
        }else{ // 멀티 블럭

        }
    }
}

- (void)onTranBeforeRequest:(NSString*)sTranID nextQuery:(BOOL)isNextQuery{
    
}
- (void)onTranDataReceived:(NSString*)tran msgCode:(NSString*)code msgText:(NSString*)text
{
    [self makeTranOutputFieldLayout:0];
}
- (void)onTranError:(NSString*)tran msgCode:(NSString*)code msgText:(NSString*)text
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:tran
                               message:[NSString stringWithFormat:@"[%@] : %@" , code , text]
                               preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"확인" style:UIAlertActionStyleDefault
                                   handler:^(UIAlertAction * action) {
        
    }];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)onTranTimeout:(NSString*)tran{
    
}


- (void)onRealBeforeRequest:(NSString*)sRealId
{
    
}
- (void)onRealDataReceived:(NSString*)sRealId
{
    if ( [[tranReal getRealID] isEqualToString:sRealId] )
    {
        [self makeRealOutputFieldLayout:40];
        [self processRealOutputData];
    }
}

- (BOOL)textFieldShouldEndEditing:(MyTextField *)textField
{
    if (tranNormal != nil) {
        BOOL isItemCode = [tranNormal isItemCodeField:[textField getBlockID] fieldID:[textField getField]];
        if (isItemCode) {
            NSString *sFullCode = [[SmartChampAPI instance] getItemFullCode:textField.text];
            if (![sFullCode isEqualToString:@""])
                textField.text = sFullCode;
        }
        return YES;
    }
    else if (tranReal != nil){
        BOOL isItemCode = [tranReal isItemCodeField:[textField getBlockID] fieldID:[textField getField]];
        if (isItemCode) {
            NSString *sFullCode = [[SmartChampAPI instance] getItemFullCode:textField.text];
            if (![sFullCode isEqualToString:@""])
                textField.text = sFullCode;
        }
        return YES;
    }
    
    return YES;
}



- (BOOL)textFieldShouldBeginEditing:(MyTextField *)textField
{
//    if (textField.isSecureTextEntry){
//
//        if (textField.keyboardType == UIKeyboardTypeNumberPad){
//            [self makeEncNumberEdit:textField];
//        }else{
//            [self makeEncCharEdit:textField];
//        }
//
//        return NO;
//    }
    
    
    
    
    
    return YES;
}


- (void)setTableViewItem:(NSArray*)array
{
    NSMutableArray *sSortArray = [NSMutableArray array];
    
    arrayTableData = [NSMutableArray arrayWithArray:array];
    for (NSInteger i = 0 ; i < [array count]; i++) {
        NSDictionary *dicItem = array[i];
        
        if ( i == 0 ){
            arrayColumnKey = [dicItem.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
                return [obj1 compare:obj2];
            }];
            
            arrayWidth = [NSMutableArray array];
            for (NSInteger k = 0; k < [arrayColumnKey count]; k++) {
                [arrayWidth addObject:[NSNumber numberWithFloat:0.0f]];
            }
        }
        
        for ( NSInteger j = 0 ; j < [arrayColumnKey count] ; j++ ) {
            NSString *sIdx = arrayColumnKey[j];
            NSString *sTemp = dicItem[sIdx];
            NSArray *arrSplit = [sTemp componentsSeparatedByString:@"^"];
            NSNumber *numberWidth = arrayWidth[j];
            NSString *sKey = [arrSplit objectAtIndex:0];
            NSString *sItem = [arrSplit objectAtIndex:1];
            [sSortArray addObject:sKey];
            
            CGFloat width = [sKey sizeWithAttributes:dicTitleAttr].width + 40;
            if ([numberWidth floatValue] < width ){
                [arrayWidth replaceObjectAtIndex:j withObject:[NSNumber numberWithFloat:width]];
            }
            
            width = [sItem sizeWithAttributes:dicTitleAttr].width + 40;
            numberWidth = arrayWidth[j];
            if ([numberWidth floatValue] < width ){
                [arrayWidth replaceObjectAtIndex:j withObject:[NSNumber numberWithFloat:width]];
            }
        }
    }
    
    CustomTableViewCell *headerView = [[CustomTableViewCell alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(outputTableView.frame), outputTableView.rowHeight * 1.5) reuseIdentifier:@"bottomtablecell"];
    [headerView setTitleAttr:dicTitleAttr];
    [headerView setBackgroundColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5]];
    [headerView setColumnWidth:arrayWidth title:sSortArray mask:nil];
    [headerView setHeaderType:YES];
    [outputTableView setTableHeaderView:headerView];
    [outputTableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return control_height;
}
//



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (arrayTableData == nil) return 0;
    
    return [arrayTableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"bottomtablecell";
    UILabel *codelabel = nil;
    CustomTableViewCell *cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        [cell setDelegate:self];
        codelabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, CGRectGetWidth(cell.frame) - 40, CGRectGetHeight(cell.frame))];
        [codelabel setTag:1];
        [cell.contentView addSubview:codelabel];
        [cell setTitleAttr:dicCellAttr];
        [cell setBackgroundColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5]];
        [cell setColumnWidth:arrayWidth];
    }
    [cell setRowIndex:indexPath.row];
    NSDictionary *dic = [arrayTableData objectAtIndex:indexPath.row];
    NSMutableArray *arrayCellItem = [NSMutableArray array];
    for (NSInteger i = 0 ; i < [arrayColumnKey count] ; i++){
        NSString *skey = arrayColumnKey[i];
        NSString *value = dic[skey];
        NSArray *arrItem = [value componentsSeparatedByString:@"^"];
        NSString *val2 = [ComUtil trim:[arrItem objectAtIndex:1]];
        
        [arrayCellItem addObject:val2];
    }
    [cell setColumnTitle:arrayCellItem];
    
    return cell;
}



- (void)makeEncCharEdit:(UITextField*)textField
{
//    encKeyboardChar = [[NFilterChar alloc] initWithNibName:@"NFilterChar" bundle:nil];
//    encKeyboardChar.useInitialVector = YES;
//
//    [encKeyboardChar setCallbackMethod:self
//                    methodOnConfirm:@selector(onConfirmNFilter:encText:dummyText:tagName:)
//                       methodOnPrev:@selector(onPrevNFilter:encText:dummyText:tagName:)
//                       methodOnNext:@selector(onNextNFilter:encText:dummyText:tagName:)
//                      methodOnPress:@selector(onPressNFilter:encText:dummyText:tagName:)
//                  methodOnReArrange:@selector(onReArrangeNFilter)
//     ];
//
//    [encKeyboardChar setTopBarText:@"유진투자증권"];
//    NSString *sPlaceHolder = textField.placeholder;
//    [encKeyboardChar setTagName:sPlaceHolder];
//    [encKeyboardChar setNoPadding:NO];
//    [encKeyboardChar setNoSound:YES];
//    [encKeyboardChar setSupportBackgroundEvent:YES];
//    [encKeyboardChar setSupportViewRotatation:NO];
//    [encKeyboardChar setMasking:NFilterMaskingDefault];
//    [encKeyboardChar setAttachType:NFilterAttachViewController];
//    [encKeyboardChar setShowHanguleText:YES];
//    [encKeyboardChar setNFilterHeight:250];
//    [encKeyboardChar setSupportBackGroundClose:NO];
//    [encKeyboardChar setDeepSecMode:NO];
//    encKeyboardChar.fontBigChar = [UIFont systemFontOfSize:20];
//    encKeyboardChar.fontSmallChar = [UIFont systemFontOfSize:16];
//
////        [encKeyboardChar setUseSpeakerInVoiceOver:YES];          // 구버전에선 이거
//    [encKeyboardChar setUseVoiceOverViaSpreaker:YES];      // 새버전에선 이거
//
//    [encKeyboardChar setTitleText:textField.placeholder];
//    [encKeyboardChar setLengthWithTagName:textField.placeholder length:50];    // NFilter Library 변경
//    [encKeyboardChar setFullMode:YES];
//    [encKeyboardChar setServerPublickey:[[SmartChampAPI instance] getSecKeyPublicKey]];
//
//    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
//        [encKeyboardChar setVerticalFrame:0];
//    } else {
//        [encKeyboardChar setVerticalFrame:20];
//    }
//
//    [encKeyboardChar showKeypad:[UIApplication sharedApplication].statusBarOrientation parentViewController:self];
}


- (void)makeEncNumberEdit:(MyTextField*)textField
{
//    encKeyboardNum = [[NFilterNum alloc] initWithNibName:@"NFilterNum" bundle:nil];// 일반넘패드
//    [encKeyboardNum setServerPublickey:[[SmartChampAPI instance] getSecKeyPublicKey]];
//
//
//    [encKeyboardNum setCallbackMethod:self
//                   methodOnConfirm:@selector(onConfirmNFilter:encText:dummyText:tagName:)
//                      methodOnPrev:@selector(onPrevNFilter:encText:dummyText:tagName:)
//                      methodOnNext:@selector(onNextNFilter:encText:dummyText:tagName:)
//                     methodOnPress:@selector(onPressNFilter:encText:dummyText:tagName:)
//                 methodOnReArrange:@selector(onReArrangeNFilter)
//     ];
//    [encKeyboardNum setCallbackMethod:self methodOnConfirm:@selector(onConfirmNFilter:encText:dummyText:tagName:) methodOnCancel:@selector(onCancelNFilter:encText:dummyText:tagName:)];
//
//    NSString *sPlaceHolder = textField.placeholder;
//    [encKeyboardNum setTagName:sPlaceHolder];
//    [encKeyboardNum setFullMode:YES];
//    [encKeyboardNum setTopBarText:@"유진투자증권"];
//    [encKeyboardNum setLengthWithTagName:sPlaceHolder length:[sPlaceHolder length]];// NFilter Library
//    [encKeyboardNum setTitleText:@"계좌 비밀번호 입력"];
//    [encKeyboardNum setFullMode:YES];
//    [encKeyboardNum setNoSound:YES];
//    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
//        [encKeyboardNum setVerticalFrame:0];
//    } else {
//        [encKeyboardNum setVerticalFrame:60];
//    }
//
//    [encKeyboardNum showKeypad:[UIApplication sharedApplication].statusBarOrientation parentViewController:self];

}

- (MyTextField*)getFieldTextField:(NSString*)placeholder
{
    for (UIView *subView in inputScrollView.subviews) {
        if ( [subView isKindOfClass:[MyTextField class]]){
            MyTextField *inputTextField = (MyTextField*)subView;
            
            if ([inputTextField.placeholder isEqualToString:placeholder]){
                return inputTextField;
            }
        }
    }
    return nil;
}
//
//#pragma mark -
//#pragma mark NFilter 키패드 callback 함수
//- (void)onReArrangeNFilter
//{
//    
//}
//
///*--------------------------------------------------------------------------------------
// 엔필터 '이전' 버튼 눌렀을 때 발생하는 콜백함수
// ---------------------------------------------------------------------------------------*/
//- (void)onPrevNFilter:(NSString *)secureText encText:(NSString *)encText dummyText:(NSString *)dummyText tagName:(NSString *)tagName {
//    NSLog(@"이전버튼 눌림");
//    NSLog(@"태그: %@", tagName);
//    NSLog(@"암호문 : %@", secureText);
//    NSLog(@"더미: %@", dummyText);
//    NSLog(@"서버에 보낼 암호문: %@", encText);
//}
//
///*--------------------------------------------------------------------------------------
// 엔필터 '다음' 버튼 눌렀을 때 발생하는 콜백함수
// ---------------------------------------------------------------------------------------*/
//- (void)onNextNFilter:(NSString *)secureText encText:(NSString *)encText dummyText:(NSString *)dummyText tagName:(NSString *)tagName
//{
//    NSLog(@"다음버튼 눌림");
//    NSLog(@"태그: %@", tagName);
//    NSLog(@"암호문 : %@", secureText);
//    NSLog(@"더미: %@", dummyText);
//    NSLog(@"서버에 보낼 암호문: %@", encText);
//}
//
///*--------------------------------------------------------------------------------------
// 엔필터 '키' 버튼 눌렀을 때 발생하는 콜백함수
// ---------------------------------------------------------------------------------------*/
//- (void)onPressNFilter:(NSString *)secureText encText:(NSString *)encText dummyText:(NSString *)dummyText tagName:(NSString *)tagName
//{
//    NSLog(@"엔필터 키눌림");
//    NSLog(@"태그: %@", tagName);
//    NSLog(@"암호문 : %@", secureText);
//    NSLog(@"더미: %@", dummyText);
//    NSLog(@"서버에 보낼 암호문: %@", encText);
//    
//}
//
///*--------------------------------------------------------------------------------------
// 엔필터 '취소' 버튼 눌렀을 때 발생하는 콜백함수
// ---------------------------------------------------------------------------------------*/
//- (void)onCancelNFilter:(NSString *)secureText encText:(NSString *)encText dummyText:(NSString *)dummyText tagName:(NSString *)tagName
//{
//    NSLog(@"엔필터 닫힘 : onCancelNFilter");
//    NSLog(@"태그: %@", tagName);
//    NSLog(@"암호문 : %@", secureText);
//    NSLog(@"더미: %@", dummyText);
//    NSLog(@"서버에 보낼 암호문: %@", encText);
//    //비대면 계좌개설 2022.07 bkkim
////    m_dummylength = (int)[dummyText length];
//    //비대면 계좌개설 2022.07 bkkim
//    [self closeFilterKeyboard];
//}
//
//
///*--------------------------------------------------------------------------------------
// 엔필터 '취소' 버튼 눌렀을 때 발생하는 콜백함수
// ---------------------------------------------------------------------------------------*/
//- (void)onCancel {
//    NSLog(@"엔필터 닫힘");
//    
//    [self closeFilterKeyboard];
//}
//
///*--------------------------------------------------------------------------------------
// 엔필터 'Background Close'동작할때 발생하는 콜백 함수
// ---------------------------------------------------------------------------------------*/
//- (void)onCloseNFilter:(NSString *)secureText encText:(NSString *)encText dummyText:(NSString *)dummyText tagName:(NSString *)tagName
//{
//    NSLog(@"엔필터 닫힘 : onCloseNFilter");
//    NSLog(@"태그: %@", tagName);
//    NSLog(@"암호문 : %@", secureText);
//    NSLog(@"더미: %@", dummyText);
//    NSLog(@"서버에 보낼 암호문: %@", encText);
//}
//- (void)onConfirmNFilter:(NSString *)secureText encText:(NSString *)encText dummyText:(NSString *)dummyText tagName:(NSString *)tagName
//{
//    NSLog(@"엔필터 닫힘");
//    NSLog(@"태그: %@", tagName);
//    NSLog(@"암호문 : %@", secureText);
//    NSLog(@"더미: %@", dummyText);
//    NSLog(@"서버에 보낼 암호문: %@", encText);
//    
//    
//    int ndummylength = (int)[dummyText length];
//    
//    
//    //비대면 계좌개설 2022.07 bkkim
////    m_dummylength = ndummylength;
//    //비대면 계좌개설 2022.07 bkkim
//    if (ndummylength == 0)
//    {
//        
//    }
//    else
//    {
//        //    EccEncryptor      // 이전버전 nFilter의 NFilterNum 소스내에 평문을 암호화하는 과정이 있어서 그대로 구현함. 2017.02.03. - cory
////        NSString* sss = [[EccEncryptor sharedInstance] makeDecNoPadWithSeedkey:secureText];
//        
//        char* output = NULL;   // 복호화된 평문 결과
//        int outlen = 0; // 복호화된 평문 길이
//        [[EccEncryptor sharedInstance] makeDecNoPadWithSeedkey:secureText output:&output outlen:&outlen];
//        
//        NSString* sss = [NSString stringWithUTF8String:output];
//        NSString* encript = [self StringtoEncript:sss];
//        
//        MyTextField *textField = [self getFieldTextField:tagName];
//        if (textField != nil){
//            [textField setText:encript];
//        }
//        
//        if(output)
//        {
//            for(int i=0; i<outlen; i++)
//            {
//                output[i] = 0;
//            }
//            free(output);
//            output = NULL;
//        }
//    }
//    
//    // allowCloseKeypadConfirmPressed 속성이 NO여서 키패드가 안닫힐때 내려가게하고 싶으면 아래와 같이 closeKeypad를 호출하면 키패드가 내려갑니다.
//    [self closeFilterKeyboard];
//}
//
//- (void) closeFilterKeyboard
//{
//    if (encKeyboardNum != nil){
//        [encKeyboardNum closeKeypad];
//        encKeyboardNum = nil;
//    }
//    
//    if (encKeyboardChar != nil){
//        [encKeyboardChar closeKeypad];
//        encKeyboardChar = nil;
//    }
//}
//
//-(NSString*)StringtoEncript:(NSString*)data
//{
//    // 1. 서버공개키를 지정하여 클라이언트공개키와 시드키를 생성한다.
//    EccEncryptor *ec = [EccEncryptor sharedInstance];
//    NSString *refClientPublickey;
//    NSData *refSeedKey;
//    
//    [ec getSeedKeyNClientPublickeyWithServerPublickey:[[SmartChampAPI instance] getSecKeyPublicKey] ClientPublickey:&refClientPublickey SeedKey:&refSeedKey];
//    
//    //     2.1 암호화 작업 (문자형 암호화)
////    NSString *encData = [ec makeEncNoPadding:data];
//    NSString *encData = [ec makeEncNoPadding:[data dataUsingEncoding:NSUTF8StringEncoding] ];    // NFilter Library 변경
//    
//    return encData;
//}
//
//- (void)didselectItem:(long)cellTag row:(NSInteger)rowIndex
//{
//    
//}

@end
