//
//  CondSearchViewController.m
//  EugineAPISample
//
//  Created by aaab on 2023/02/05.
//

#import "CondSearchViewController.h"
#import "SmartChampTran.h"
#import "SmartChampReal.h"
#import "CondSearchInfo.h"
#import "SmartChampAPI.h"
#import "FIDSelectButton.h"
#import "ComUtil.h"
#import "ITranDataDelegate.h"
#import "IRealDataDelegate.h"
#import "CondItemInfo.h"
#import "CustomTableViewCell.h"
#import "MutilSelectPopupView.h"
#import "iToast.h"

#define xPadding 20
#define yPadding 10

#define CONTROL_HEIGHT 35

@interface CondSearchViewController () < ITranDataDelegate , IRealDataDelegate , UITableViewDelegate , UITableViewDataSource , IMultiSelectDelegate , ICustomTableDelegate>
{
    // 화면 표시 뷰
    CondSearchInfo  *m_infoSelectedCond;
    // 데이터 처리
    SmartChampTran  *m_tranCondList;                // 조건 조회
    SmartChampTran  *m_tranItemList;       // 조건별 종목 조회
    SmartChampTran  *m_tranRegReal; // 조건검색 실시간 등록
    
    SmartChampReal  *m_realJ05;    // 조건검색 실시간
    
    NSString        *m_strPacketCode; // 실시간 등록코드
    
    UILabel         *m_viewCondName;
    FIDSelectButton *m_buttonSelectFID;
    
    UITableView     *m_viewCondList;
    NSMutableArray  *m_arrayCondList;
    UITableView     *m_viewItemList;
    NSMutableArray  *m_arrayItemList;
    UITableView     *m_viewSearchingList;
    NSMutableArray  *m_arraySearchingList;
    
    NSArray         *arrayCondWidth;
    NSArray         *arrayItemWidth;
    NSArray         *arrayTitle;
    
    NSArray         *arraySearchingTitle;
    NSArray         *arraySearchingWidth;

}
@end

@implementation CondSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self initTran];
    [self initLayout];

    
    [self requestCondList];
}

- (void)dealloc
{
    if(m_tranCondList != nil) [m_tranCondList clearRequest];
    if(m_tranItemList != nil) [m_tranItemList clearRequest];
    if(m_tranRegReal != nil) [m_tranRegReal clearRequest];

    [m_realJ05 releaseReal];
    if(m_realJ05 != nil) [m_realJ05 clearRequest];
    
    m_tranCondList = nil;
    m_tranItemList = nil;
    m_tranRegReal = nil;
    m_realJ05 = nil;
}

- (void)initTran{
    
    // TR 초기화
    m_tranCondList = [[SmartChampTran alloc] initWithTrCode:@"msvf007" delegate:self];
    [m_tranCondList setTranID:@"조건리스트조회"];

    m_tranItemList = [[SmartChampTran alloc] initWithTrCode:@"msvf027" delegate:self];
    [m_tranItemList setTranID:@"조건종목시세조회"];

    m_tranRegReal = [[SmartChampTran alloc] initWithTrCode:@"msvf028" delegate:self];
    [m_tranRegReal setTranID:@"조건종목실시간등록"];

    // Real 초기화
    m_realJ05 = [[SmartChampReal alloc] initWithTrCode:@"J05" delegate:self];
    [m_realJ05 setRealID:@"조검검색실시간감시"];
    
    m_arrayCondList = [NSMutableArray array];
    m_arrayItemList = [NSMutableArray array];
    m_arraySearchingList = [NSMutableArray array];
    arraySearchingWidth = [NSMutableArray array];
}

- (void)initLayout{
    CGFloat selfWidth = CGRectGetWidth(self.view.frame);
    CGFloat selfHeight = CGRectGetHeight(self.view.frame);
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xPadding, yPadding, selfWidth * 0.7, CONTROL_HEIGHT)];
    [label setText:@"조건 리스트"];
    [self.view addSubview:label];
    
    UIButton *conRefreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [conRefreshButton setFrame:CGRectMake(CGRectGetMaxX(label.frame), yPadding, CONTROL_HEIGHT, CONTROL_HEIGHT)];
    [ComUtil setColorInButton:conRefreshButton color:[UIColor blackColor]];
    [ComUtil makeRoundView:conRefreshButton radius:1 width:1 bordercolor:[UIColor blackColor]];
    [ComUtil setTitleInButton:conRefreshButton title:@"조회"];
//    UIImage *imageRefresh = [UIImage imageNamed:@"btn_bottom_reflash_n.png"];
//    [conRefreshButton setImage:imageRefresh forState:UIControlStateNormal];
    [conRefreshButton setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [conRefreshButton addTarget:self action:@selector(onCondRefreshButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:conRefreshButton];
    
    m_viewCondList = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(label.frame) + 10, selfWidth, CONTROL_HEIGHT * 5) style:UITableViewStylePlain];
    [m_viewCondList setDelegate:self];
    [m_viewCondList setDataSource:self];
    [m_viewCondList setTag:1];
    [self.view addSubview:m_viewCondList];
    
    CustomTableViewCell *cellView =[[CustomTableViewCell alloc] initWithFrame:CGRectMake(0, 0, selfWidth, CONTROL_HEIGHT) reuseIdentifier:@"Cell1"];
    [cellView setHeaderType:YES];
    [cellView setBackgroundColor:[UIColor lightGrayColor]];
    [m_viewCondList setTableHeaderView:cellView];
    
    
    arrayCondWidth = [NSArray arrayWithObjects:[NSNumber numberWithFloat:80.f],
                      [NSNumber numberWithFloat:80.f],
                      [NSNumber numberWithFloat:80.f],
                      [NSNumber numberWithFloat:250.f],
                      [NSNumber numberWithFloat:100.f],
                      [NSNumber numberWithFloat:600.f],
                      nil];
    
    arrayTitle = [NSArray arrayWithObjects:@"저장날짜",@"저장시간",@"시퀀스번호",@"그룹명",@"조건명",@"조건설명", nil];
    NSArray *arrayMask = [NSArray arrayWithObjects:[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT], nil];
    [cellView setColumnWidth:arrayCondWidth title:arrayTitle mask:nil];
    
    CGFloat width = selfWidth * 0.6	;
    m_viewCondName = [[UILabel alloc] initWithFrame:CGRectMake(xPadding / 2, CGRectGetMaxY(m_viewCondList.frame) + yPadding, width, CONTROL_HEIGHT)];
    [m_viewCondName setTextAlignment:NSTextAlignmentCenter];
    [m_viewCondName setTextColor:[UIColor blackColor]];
    [self.view addSubview:m_viewCondName];
    [ComUtil makeRoundView:m_viewCondName radius:0 width:1 bordercolor:[UIColor grayColor]];
    
    m_buttonSelectFID = [FIDSelectButton buttonWithType:UIButtonTypeCustom];
    [m_buttonSelectFID addTarget:self action:@selector(onSelectFID:) forControlEvents:UIControlEventTouchUpInside];
    width = selfWidth * 0.20;
    [m_buttonSelectFID setFrame:CGRectMake(CGRectGetMaxX(m_viewCondName.frame) + (xPadding / 2 ), CGRectGetMinY(m_viewCondName.frame), width, CGRectGetHeight(m_viewCondName.frame))];
    [self.view addSubview:m_buttonSelectFID];
    [m_buttonSelectFID setDefaultList];
    
    UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [refreshButton setTag:9999];
    [refreshButton setFrame:CGRectMake(CGRectGetMaxX(m_buttonSelectFID.frame) + (xPadding / 2), CGRectGetMinY(m_viewCondName.frame), CONTROL_HEIGHT, CONTROL_HEIGHT)];
    [refreshButton addTarget:self action:@selector(onRefreshButton:) forControlEvents:UIControlEventTouchUpInside];
    [ComUtil setTitleInButton:refreshButton title:@"조회"];
    [ComUtil setColorInButton:refreshButton color:[UIColor blackColor]];
    [ComUtil makeRoundView:refreshButton radius:1 width:1 bordercolor:[UIColor blackColor]];
//    [ComUtil makeRoundView:refreshButton radius:4 width:1 bordercolor:[UIColor grayColor]];
//    imageRefresh = [UIImage imageNamed:@"btn_bottom_reflash_n.png"];
//    [refreshButton setImage:imageRefresh forState:UIControlStateNormal];
    [refreshButton setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [self.view addSubview:refreshButton];
    
    
    CGFloat yPos = CGRectGetMaxY(refreshButton.frame) + 10;
    selfHeight = yPos;
    m_viewItemList = [[UITableView alloc] initWithFrame:CGRectMake(0, yPos, selfWidth, CONTROL_HEIGHT * 5)];
    [m_viewItemList setDelegate:self];
    [m_viewItemList setDataSource:self];
    [m_viewItemList setTag:2];
    [self.view addSubview:m_viewItemList];
    arrayItemWidth = [NSArray arrayWithObjects:[NSNumber numberWithFloat:70.f],
                  [NSNumber numberWithFloat:70.f],
                  [NSNumber numberWithFloat:250.f],
                  [NSNumber numberWithFloat:100.f],
                  [NSNumber numberWithFloat:100.f],
                  [NSNumber numberWithFloat:100.f],
                  [NSNumber numberWithFloat:400.f],
                  nil];
    arrayTitle = [NSArray arrayWithObjects:@"종목명",@"종목코드",@"기준가",@"고가",@"시가",@"저가",@"결과필드", nil];
    arrayMask = [NSArray arrayWithObjects:[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT],[NSNumber numberWithInteger:COLUMN_MASK_TEXT], nil];
    CustomTableViewCell *cellView2 =[[CustomTableViewCell alloc] initWithFrame:CGRectMake(0, 0, selfWidth, CONTROL_HEIGHT) reuseIdentifier:@"Cell2"];
    [cellView2 setColumnWidth:arrayItemWidth title:arrayTitle mask:arrayMask];
    [cellView2 setBackgroundColor:[UIColor lightGrayColor]];
    [cellView2 setHeaderType:YES];
    [m_viewItemList setTableHeaderView:cellView2];
    
    CGFloat searchingHeight = CGRectGetHeight(self.view.frame) - CGRectGetMaxY(m_viewItemList.frame);
    m_viewSearchingList = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(m_viewItemList.frame), selfWidth, searchingHeight) style:UITableViewStylePlain];
    [m_viewSearchingList setDelegate:self];
    [m_viewSearchingList setDataSource:self];
    [m_viewSearchingList setTag:3];
    [self.view addSubview:m_viewSearchingList];
    
    arraySearchingWidth = [NSArray arrayWithObjects:[NSNumber numberWithFloat:70.f],
                           [NSNumber numberWithFloat:70.f],
                           [NSNumber numberWithFloat:150.f],
                           [NSNumber numberWithFloat:70.f],
                           [NSNumber numberWithFloat:30.f],
                           [NSNumber numberWithFloat:100.f],
                           [NSNumber numberWithFloat:100.f],
                           [NSNumber numberWithFloat:100.f], // 현재만족종목수
                           [NSNumber numberWithFloat:100.f], // 전송종목수
                           [NSNumber numberWithFloat:100.f], // 신호발생
                           [NSNumber numberWithFloat:100.f], // 신규/재진입/탈퇴
                           [NSNumber numberWithFloat:100.f], // 현재가
                           [NSNumber numberWithFloat:100.f], // 전일종가
                           [NSNumber numberWithFloat:100.f], // 시가
                           [NSNumber numberWithFloat:100.f], // 고가
                           [NSNumber numberWithFloat:100.f], // 저가
                           [NSNumber numberWithFloat:150.f], // 거래량
                           [NSNumber numberWithFloat:30.f], // 결과
                           nil];
    arraySearchingTitle = [NSArray arrayWithObjects:@"종목코드" , @"종목명" , @"데이터구분",@"패킷구분코드",@"System",@"신호발생일자",@"신호발생시간",@"현재만족종목수",@"전송종목수",@"신호발생" ,@"신규/재진입/탈퇴" , @"현재가" , @"전일종가" , @"시가" , @"저가",  @"고가", @"거래량" , @"결과" , nil];
    
    
    CustomTableViewCell *cellView3 =[[CustomTableViewCell alloc] initWithFrame:CGRectMake(0, 0, selfWidth, CONTROL_HEIGHT) reuseIdentifier:@"Cell3"];
    [cellView3 setColumnWidth:arraySearchingWidth title:arraySearchingTitle mask:nil];
    [cellView3 setBackgroundColor:[UIColor lightGrayColor]];
    [cellView3 setHeaderType:YES];
    [m_viewSearchingList setTableHeaderView:cellView3];
    
    [self makeCloseButton];
}

- (void)makeCloseButton
{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(CGRectGetWidth(self.view.frame) - 50 , 00, 50, 50)];
    [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)onCondRefreshButton:(UIButton*)sender
{
    [self requestCondList];
}

- (void)onRefreshButton:(UIButton*)sender
{
    [m_arraySearchingList removeAllObjects];
    [self requestItemList];
}

- (void)onSelectFID:(FIDSelectButton*)sender
{
    MutilSelectPopupView *popupView = [[MutilSelectPopupView alloc] initWithFrame:CGRectZero];
    [popupView setDelegate:self];
    [popupView setTitles:[sender getTitle] select:[sender getSelectArray]];
    
    [self.view addSubview:popupView];
    
}

- (void)popupCancel{
    
}

- (void)popupSelectItem:(NSArray*)items
{
    [m_buttonSelectFID setTemp:items];
    [m_buttonSelectFID rebuildSelectedList];
    [m_buttonSelectFID updateButtonText];
    
    [self requestItemList];
}


- (void)requestCondList
{
    [self releaseRealReg];

    [self selectCondSearchInfo:nil];

    if(m_tranCondList == nil) return;

    [m_tranCondList clearInputData];
    [m_tranCondList clearOutputData];

    NSString *strUserId = [[SmartChampAPI instance] getLoginUserID];

    [m_tranCondList setDataValue:@"InBlock1" fieldID:@"sUserID" index:0 value:strUserId];
    [m_tranCondList requestData];
}

- (void)requestItemList
{
    [self releaseRealReg];

//    if(m_viewItemList != null)
//        m_viewItemList.clearList();

    if(m_infoSelectedCond == nil) return;

    if(m_tranItemList == nil) return;

    [m_tranItemList clearInputData];
    [m_tranItemList clearOutputData];

    NSString *strUserId = [[SmartChampAPI instance] getLoginUserID];
    NSString *strFIDCount =[m_buttonSelectFID getFIDCount];
    NSString *strFIDList = [m_buttonSelectFID getFIDList];

    [m_tranItemList setDataValue:@"InBlock1" fieldID:@"sUserID" index:0 value:strUserId];
    [m_tranItemList setDataValue:@"InBlock1" fieldID:@"sDate" index:0 value:m_infoSelectedCond.m_strSavedDate];
    [m_tranItemList setDataValue:@"InBlock1" fieldID:@"sTime" index:0 value:m_infoSelectedCond.m_strSavedTime];
    [m_tranItemList setDataValue:@"InBlock1" fieldID:@"lSeq" index:0 value:m_infoSelectedCond.m_strSeqNo];
    [m_tranItemList setDataValue:@"InBlock1" fieldID:@"lFieldEditCnt" index:0 value:strFIDCount];
    [m_tranItemList setDataValue:@"InBlock1" fieldID:@"sFiledList" index:0 value:strFIDList];

    [m_tranItemList requestData];
}

- (void)requestRealReg
{
    if(m_realJ05 != nil){
        [m_realJ05 releaseReal];
    }
    if(m_tranRegReal == nil) return;
    if(m_infoSelectedCond == nil) return;

    [m_tranRegReal clearInputData];
    [m_tranRegReal clearOutputData];

    NSString *strUserId = [[SmartChampAPI instance] getLoginUserID];

    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sUserID" index:0 value:strUserId];
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sDate" index:0 value:m_infoSelectedCond.m_strSavedDate];
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sTime" index:0 value:m_infoSelectedCond.m_strSavedTime];
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"lSeq" index:0 value:m_infoSelectedCond.m_strSeqNo];
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sGubun" index:0 value:@"E"];
    [m_tranRegReal requestData];
}

- (void)releaseRealReg
{
    if(m_realJ05 != nil){
        [m_realJ05 releaseReal];
    }
    if(m_tranRegReal == nil) return;
    if(m_infoSelectedCond == nil) return;
    if([ComUtil isTextEmpty:m_strPacketCode]) return;

    [m_tranRegReal clearInputData];
    [m_tranRegReal clearOutputData];

    NSString *strUserId = [[SmartChampAPI instance] getLoginUserID];

    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sUserID" index:0 value:strUserId];
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sDate" index:0 value:m_infoSelectedCond.m_strSavedDate];
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sTime" index:0 value:m_infoSelectedCond.m_strSavedTime];
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"lSeq" index:0 value:m_infoSelectedCond.m_strSeqNo];
    // 해제
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sGubun" index:0 value:@"D"];
    [m_tranRegReal setDataValue:@"InBlock1" fieldID:@"sDelSeq" index:0 value:m_strPacketCode];

    [m_tranRegReal requestData];

    m_strPacketCode = @"";
//    m_viewRealName.setText("실시간 감시 중지됨");
}

- (void)requestCondReal:(NSString*)strPacketCode
{
    
//    [m_arraySearchingList addObject:[NSArray arrayWithObjects:@"000660" , @"하이닉스", @"1", @"1" ,@"1" , @"2023.02.11" , @"09:00:12" , @"3" , @"5" , @"ㄹㅁ댐ㄷㄹ" , @"1"  ,@"10,0202" , @"90000" , @"120202" , @"88888" , @"00000" , @"8272712738" , @"1" , nil]];
//    [m_viewSearchingList reloadData];
    if(m_realJ05 == nil) return;

    [m_realJ05 releaseReal];

    m_strPacketCode = strPacketCode;

    NSString *strRegCode = [strPacketCode length] > 4 ? [strPacketCode substringFromIndex:[strPacketCode length] - 4] : strPacketCode;
    [m_realJ05 setDataValue:@"InBlock1" fieldID:@"sPacketCode" index:0 value:strRegCode];
    [m_realJ05 requestReal];
}

- (void)selectCondSearchInfo:(CondSearchInfo*)info
{
    if(info == nil)
    {
        [m_viewCondName setText:@"조건별 종목 리스트"];
    } else {
        [m_viewCondName setText:info.m_strCondName];
    }

    m_infoSelectedCond = info;

    
    UIButton *button = [self.view viewWithTag:9999];
    if ( info == nil){
        [button setEnabled:NO];
    }else{
        [button setEnabled:YES];
    }
}

- (void)onTranBeforeRequest:(NSString *)sTranID nextQuery:(BOOL)isNextQuery
{
}

- (void)onTranDataReceived:(NSString *)tran msgCode:(NSString *)code msgText:(NSString *)text
{
    NSLog(@"onTranDataReceived [%@] [%@] [%@]" , tran , code , text);
    
    NSString *strBlockName = @"OutBlock1";

    if([tran isEqualToString:@"조건리스트조회"])
    {
        strBlockName = @"OutBlock2";

        int nDataCount = [m_tranCondList getDataCount:strBlockName];
        for(int i = 0; i < nDataCount; i++)
        {
            CondSearchInfo *info = [[CondSearchInfo alloc] init];
            
            
            info.m_strSavedDate = [m_tranCondList getDataValue:strBlockName fieldID:@"sDate" index:i];
            info.m_strSavedTime = [m_tranCondList getDataValue:strBlockName fieldID:@"sTime" index:i];
            info.m_strSeqNo = [m_tranCondList getDataValue:strBlockName fieldID:@"lSeq" index:i];
            info.m_strCondName = [m_tranCondList getDataValue:strBlockName fieldID:@"sContName" index:i];
            info.m_strGroupName = [m_tranCondList getDataValue:strBlockName fieldID:@"sGroupName" index:i];
            info.m_strCondDesc = [m_tranCondList getDataValue:strBlockName fieldID:@"sMemo" index:i];

            [m_arrayCondList addObject:info];
        }
        [m_viewCondList reloadData];
    } else if([tran isEqualToString:@"조건종목시세조회"])
    {
        int nFieldCount = [[m_tranItemList getDataValue:strBlockName fieldID:@"lOutFiledCnt" index:0] intValue];
        int nFieldLength = [[m_tranItemList getDataValue:strBlockName fieldID:@"sOutListpacketSize" index:0] intValue];
        int nResultSize = nFieldCount * 16;

        [m_arrayItemList removeAllObjects];
        strBlockName = @"OutBlock2";
        int nDataCount = [m_tranItemList getDataCount:strBlockName];
        for(int i = 0; i < nDataCount; i++)
        {
            CondItemInfo *info = [[CondItemInfo alloc] init];

            info.m_strItemCode = [m_tranItemList getDataValue:strBlockName fieldID:@"sCode" index:i];
            info.m_strName = [m_tranItemList getDataValue:strBlockName fieldID:@"sHname" index:i];
            info.m_strBasePrice = [m_tranItemList getDataValue:strBlockName fieldID:@"sPrePrice" index:i];
            info.m_strOpenPrice = [m_tranItemList getDataValue:strBlockName fieldID:@"sOpen" index:i];
            info.m_strHighPrice = [m_tranItemList getDataValue:strBlockName fieldID:@"sHigh" index:i];
            info.m_strLowPrice = [m_tranItemList getDataValue:strBlockName fieldID:@"sLow" index:i];
            info.m_strResult = [[m_tranItemList getDataValue:strBlockName fieldID:@"sResultFiled" index:i] substringWithRange:NSMakeRange(0, nResultSize)];

            [m_arrayItemList addObject:info];
        }
        [m_viewItemList reloadData];

        [self requestRealReg];
    } else if([tran isEqualToString:@"조건종목실시간등록"])
    {
        NSString *strGubun = [m_tranRegReal getDataValue:strBlockName fieldID:@"sGubun" index:0];

        if([@"D" isEqualToString:strGubun])
        {
            if(m_realJ05 != nil) [m_realJ05 releaseReal];
            m_strPacketCode = @"";
        } else {
            NSString *strPacketCode = [m_tranRegReal getDataValue:strBlockName fieldID:@"sRegSeq" index:0];
            [self requestCondReal:strPacketCode];
        }
    }
}

- (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
{
    NSString *strBlockName = @"OutBlock1";

    if([sRealId isEqualToString:@"조검검색실시간감시"])
    {
        
        NSString *strDataSection = [m_realJ05 getDataValue:strBlockName fieldID:@"sDataSection" index:0]; // 데이터구분
        NSString *strPacketCode = [m_realJ05 getDataValue:strBlockName fieldID:@"sPacketCode" index:0]; // 패킷구분코드
        NSString *sAlertBody = [m_realJ05 getDataValue:strBlockName fieldID:@"sAlertBody" index:0]; // System/User
        NSString *strDate = [m_realJ05 getDataValue:strBlockName fieldID:@"sSignaldate" index:0]; // 신호 발생일자
        NSString *strTime = [m_realJ05 getDataValue:strBlockName fieldID:@"sSignaltime" index:0]; // 신호 발생시간
        NSString *strTranCount = [m_realJ05 getDataValue:strBlockName fieldID:@"sNowItemCnt" index:0]; // 현재만족 종목수
        NSString *sSendItemCnt = [m_realJ05 getDataValue:strBlockName fieldID:@"sSendItemCnt" index:0]; // 전송종목수
        NSString *sSignalBirth = [m_realJ05 getDataValue:strBlockName fieldID:@"sSignalBirth" index:0]; // 신호발생
        NSString *strJobFlag = [m_realJ05 getDataValue:strBlockName fieldID:@"sJobflag" index:0];  // 신규/재진입/탈퇴
        NSString *strItemCode = [m_realJ05 getDataValue:strBlockName fieldID:@"sItemCode" index:0]; // 종목코드
        NSString *strItemName = [m_realJ05 getDataValue:strBlockName fieldID:@"sItemName" index:0]; // 종목명
        NSString *sPrice = [m_realJ05 getDataValue:strBlockName fieldID:@"sPrice" index:0]; // 현재가
        NSString *sPrePrice = [m_realJ05 getDataValue:strBlockName fieldID:@"sPrePrice" index:0]; // 전일종가
        NSString *sOpen = [m_realJ05 getDataValue:strBlockName fieldID:@"sOpen" index:0]; // 시가
        NSString *sHigh = [m_realJ05 getDataValue:strBlockName fieldID:@"sHigh" index:0]; // 고가
        NSString *sLow = [m_realJ05 getDataValue:strBlockName fieldID:@"sLow" index:0]; // 저가
        NSString *sVolume = [m_realJ05 getDataValue:strBlockName fieldID:@"sVolume" index:0]; // 거래량
        NSString *sResult = [m_realJ05 getDataValue:strBlockName fieldID:@"sResult" index:0]; // 결과
        
        [m_arraySearchingList addObject:[NSArray arrayWithObjects:strItemCode , strItemName, strDataSection, strPacketCode ,sAlertBody , strDate , strTime , strTranCount , sSendItemCnt , sSignalBirth , strJobFlag  ,sPrice , sPrePrice , sOpen , sHigh , sLow , sVolume , sResult , nil]];

        [m_viewSearchingList reloadData];
//        NSString *sMessge = [NSString stringWithFormat:@"[%@] %@이(가) 감시 되었습니다.", strItemCode , strItemName];
//        [[iToast instance] showText:sMessge duration:iToastDurationLong gravity:iToastGravityBottom];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (m_viewCondList == tableView){
        return m_arrayCondList == nil ? 0 : [m_arrayCondList count];
    }else if (m_viewItemList == tableView){
        return m_arrayItemList == nil ? 0 : [m_arrayItemList count];
    }else if (m_viewSearchingList == tableView){
        return m_arraySearchingList == nil ? 0 : [m_arraySearchingList count];
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (m_viewCondList == tableView){
        static NSString *CellIdentifier = @"Cell1";
        CustomTableViewCell *cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            [cell setColumnWidth:arrayCondWidth title:nil mask:nil];
            [cell setDelegate:self];
            [cell setTag:tableView.tag];
        }
        [cell setRowIndex:indexPath.row];
        [cell setSearchItemInfo:m_arrayCondList[indexPath.row]];
        return cell;
    }else if (m_viewItemList == tableView){
        static NSString *CellIdentifier = @"Cell2";
        CustomTableViewCell *cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            [cell setColumnWidth:arrayItemWidth title:nil mask:nil];
            [cell setDelegate:self];
            [cell setTag:tableView.tag];
        }
        [cell setRowIndex:indexPath.row];
        [cell setItemInfo:m_arrayItemList[indexPath.row]];
        
        return cell;
    }else if (m_viewSearchingList == tableView){
        static NSString *CellIdentifier = @"Cell3";
        CustomTableViewCell *cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            [cell setColumnWidth:arraySearchingWidth title:nil mask:nil];
            [cell setDelegate:self];
            [cell setTag:tableView.tag];
        }
        [cell setRowIndex:indexPath.row];
        [cell setColumnTitle:m_arraySearchingList[indexPath.row]];
        return cell;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (m_viewCondList == tableView){
        [self selectCondSearchInfo:m_arrayCondList[indexPath.row]];
    }
}

- (void)didselectItem:(long)cellTag row:(NSInteger)rowIndex
{
    if (m_viewCondList.tag == cellTag){
        [self selectCondSearchInfo:m_arrayCondList[rowIndex]];
    }
}

@end
