package com.eugenefn.openapi.sample.view.screen;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.widget.NestedScrollView;

import com.eugenefn.openapi.intrf.IAccountPwdCheckListener;
import com.eugenefn.openapi.intrf.IRealDataListener;
import com.eugenefn.openapi.intrf.ITranDataListener;
import com.eugenefn.openapi.proc.SmartChampAPI;
import com.eugenefn.openapi.proc.SmartChampReal;
import com.eugenefn.openapi.proc.SmartChampTran;
import com.eugenefn.openapi.sample.view.control.AccountSelectSpinner;
import com.eugenefn.openapi.sample.view.control.ItemCodeSpinner;
import com.eugenefn.openapi.sample.view.control.ItemSelectSpinner;
import com.eugenefn.openapi.sample.view.data.CheMicheInfo;
import com.eugenefn.openapi.sample.view.data.JangoInfo;
import com.eugenefn.openapi.sample.view.data.SiseInfo;
import com.eugenefn.openapi.sample.view.util.ColorUtil;
import com.eugenefn.openapi.sample.view.util.LayoutUtil;
import com.eugenefn.openapi.sample.view.util.SampleUtil;
import com.eugenefn.openapi.sample.view.view.CheMicheListView;
import com.eugenefn.openapi.sample.view.view.ItemHogaView;
import com.eugenefn.openapi.sample.view.view.ItemPriceView;
import com.eugenefn.openapi.sample.view.view.JangoListView;
import com.eugenefn.openapi.sample.view.view.SiseListView;

import java.util.ArrayList;

public class WStockSiseView extends SiseBaseView
        implements ITranDataListener, IRealDataListener, View.OnClickListener, CheMicheListView.OnCheMicheListListener, JangoListView.OnJangoListListener, SiseListView.OnSiseListListener {
    private static final String LOG_TAG = " 해외시세";

    private static final int    CTRL_ID_BUY = 100;
    private static final int    CTRL_ID_SELL = 101;
    private static final int	CTRL_ID_MODIFY = 102;
    private static final int	CTRL_ID_CANCEL = 103;
    private static final int    CTRL_ID_REMAINALL = 104;

    private static final int CTRL_ID_REFRESH_MICHEGYUL = 201;  // 미체결 재조회
    private static final int    CTRL_ID_REFRESH_JANGO = 202;    // 계좌별잔고 재조회

    // 화면 표시 뷰
    private ItemSelectSpinner m_spinnerExchg;               // 거래소선택
    private TextView m_viewItemCode;						// 종목코드
    private ItemCodeSpinner m_spinnerItemCode;					// 종목 선택

    private ItemPriceView m_viewItemPrice;					// 종목 현재가 정보
    private ItemHogaView m_viewItemHoga;						// 종목 호가 (5호가)
    private SiseListView m_viewSiseList;                    // 종목 체결 시세 리스트

    private AccountSelectSpinner m_spinnerAccount;				// 계좌 선택
    private EditText         m_editAccountPwd;				// 계좌 비번

    private EditText			m_editTradeCount;					// 거래수량
    private EditText			m_editTradeUnitPrice;				// 거래단가
    private EditText			m_editTradeNo;						// 주문번호
    private CheckBox m_checkTradeAll;                    // 잔량전부

    private JangoListView       m_viewJango;                    // 잔고 리스트 뷰
    private CheMicheListView m_viewMichegyul;                  // 미체결 리스트 뷰

    // 데이터 처리
    private SmartChampTran m_tranCurrPrice = null;				// 주식 현재가 조회
    private SmartChampTran m_tranCurrHoga = null;				// 주식 호가 조회

    private SmartChampReal m_realCurrPrice = null;				// 주식 체결 실시간
    private SmartChampReal m_realCurrHoga = null;				// 주식 호가 실시간

    private SmartChampTran m_tranStockBuy = null;				// 주식 매수 주문
    private SmartChampTran m_tranStockSell = null;				// 주식 매도 주문
    private SmartChampTran m_tranStockModify = null;			// 정정 주문
    private SmartChampTran m_tranStockCancel = null;			// 취소 주문

    private SmartChampTran m_tranJango = null;                 // 잔고조회
    private SmartChampTran m_tranMichegyul = null;               // 미체결내역

    public WStockSiseView(Context context)
    {
        super(context);

        setBackgroundColor(Color.WHITE);

        // 시세 TR 초기화
        m_tranCurrPrice = new SmartChampTran(context);
        m_tranCurrPrice.initInstance(this);
        m_tranCurrPrice.setQueryFile("gbmst");
        m_tranCurrPrice.setTranId("주식현재가");

        m_tranCurrHoga = new SmartChampTran(context);
        m_tranCurrHoga.initInstance(this);
        m_tranCurrHoga.setQueryFile("gbpbid");
        m_tranCurrHoga.setTranId("주식호가");

        // 주문 TR 초기화
        m_tranStockBuy = new SmartChampTran(context);
        m_tranStockBuy.initInstance(this);
        m_tranStockBuy.setQueryFile("OTD6101U");
        m_tranStockBuy.setTranId("주식매수주문");

        m_tranStockSell = new SmartChampTran(context);
        m_tranStockSell.initInstance(this);
        m_tranStockSell.setQueryFile("OTD6101U");
        m_tranStockSell.setTranId("주식매도주문");

        m_tranStockModify = new SmartChampTran(context);
        m_tranStockModify.initInstance(this);
        m_tranStockModify.setQueryFile("OTD6103U");
        m_tranStockModify.setTranId("주식정정주문");

        m_tranStockCancel = new SmartChampTran(context);
        m_tranStockCancel.initInstance(this);
        m_tranStockCancel.setQueryFile("OTD6103U");
        m_tranStockCancel.setTranId("주식취소주문");

        m_tranJango = new SmartChampTran(context);
        m_tranJango.initInstance(this);
        m_tranJango.setQueryFile("OTD6209Q");
        m_tranJango.setTranId("주식잔고조회");

        m_tranMichegyul = new SmartChampTran(context);
        m_tranMichegyul.initInstance(this);
        m_tranMichegyul.setQueryFile("OTD6216Q");
        m_tranMichegyul.setTranId("주식미체결내역");

        // 실시간 초기화
        m_realCurrPrice = new SmartChampReal(context);
        m_realCurrPrice.initInstance(this);
        m_realCurrPrice.setQueryFile("G00");
        m_realCurrPrice.setRealId("주식체결실시간");

        m_realCurrHoga = new SmartChampReal(context);
        m_realCurrHoga.initInstance(this);
        m_realCurrHoga.setQueryFile("G01");
        m_realCurrHoga.setRealId("주식호가실시간");
    }

    //화면 초기화
    @Override
    public void initView(Context context, Activity activity)
    {
        super.initView(context, activity);

        NestedScrollView viewScroll = new NestedScrollView(context);

        LinearLayout layoutFrame = new LinearLayout(context);
        layoutFrame.setOrientation(LinearLayout.VERTICAL);

        LinearLayout layoutItemCode = makeItemCodeInput(context);
        layoutFrame.addView(layoutItemCode, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 45)));

        m_viewItemPrice = new ItemPriceView(context);
        m_viewItemPrice.setPadding(PADDING_H, 0, PADDING_H, 0);
        layoutFrame.addView(m_viewItemPrice, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 50)));

        LinearLayout layoutPrice = new LinearLayout(context);
        layoutPrice.setOrientation(LinearLayout.HORIZONTAL);

        m_viewItemHoga = new ItemHogaView(context);
        m_viewItemHoga.setOnHogaViewListener(new ItemHogaView.OnHogaViewListener()
        {
            @Override
            public void onHogaClicked(String strPrice)
            {
                if(m_editTradeUnitPrice != null)
                    m_editTradeUnitPrice.setText(strPrice);
            }
        });
        m_viewSiseList = new SiseListView(context, 4, this);

        layoutPrice.addView(m_viewItemHoga, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 2));
        layoutPrice.addView(m_viewSiseList, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1));

        layoutFrame.addView(layoutPrice, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 25 * 10)));


        LinearLayout layoutAccount = makeAccountInput(context);
        layoutFrame.addView(layoutAccount, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        LinearLayout layoutTrade = makeTradeInput(context);
        layoutFrame.addView(layoutTrade, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.SECTION_SEP_LINE, 1);

        LinearLayout layoutChegyul = makeMichegyulView(context);
        layoutFrame.addView(layoutChegyul, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.SECTION_SEP_LINE, 1);

        LinearLayout layoutJango = makeJangoView(context);
        layoutFrame.addView(layoutJango, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        viewScroll.addView(layoutFrame, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        addView(viewScroll, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    }

    public void releaseView()
    {
        removeAllViews();

        if(m_tranCurrPrice != null) m_tranCurrPrice.clearInstance();
        if(m_tranCurrHoga != null) m_tranCurrHoga.clearInstance();

        if(m_tranStockBuy != null) m_tranStockBuy.clearInstance();
        if(m_tranStockSell != null) m_tranStockSell.clearInstance();
        if(m_tranStockModify != null) m_tranStockModify.clearInstance();
        if(m_tranStockCancel != null) m_tranStockCancel.clearInstance();

        if(m_tranJango != null) m_tranJango.clearInstance();
        if(m_tranMichegyul != null) m_tranMichegyul.clearInstance();

        if(m_realCurrPrice != null) m_realCurrPrice.clearInstance();
        if(m_realCurrHoga != null) m_realCurrHoga.clearInstance();
    }

    private LinearLayout makeItemCodeInput(Context context)
    {
        // 종목코드
        ArrayList<Pair<String,String>> arrExchg = new ArrayList<>();
        arrExchg.add(new Pair<>("US,NYS", "미국 뉴욕"));
        arrExchg.add(new Pair<>("US,AMX", "미국 아멕스"));
        arrExchg.add(new Pair<>("US,NAS", "미국 나스닥"));
        arrExchg.add(new Pair<>("CN,SHS", "중국 상해"));
        arrExchg.add(new Pair<>("CN,SZS", "중국 심천"));
        arrExchg.add(new Pair<>("HK,HKS", "홍콩"));

        m_spinnerExchg = new ItemSelectSpinner(context, "거래소선택");
        m_spinnerExchg.setItemList(arrExchg);
        m_spinnerExchg.setOnItemSelectedListener(new ItemSelectSpinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(String strKey, String srValue) {
                SampleUtil.setConfig(getContext(), "wstock.type.code", strKey);

                selectExchange(strKey);
            }
        });

        m_spinnerExchg.selectItemByKey(SampleUtil.getConfig(getContext(), "wstock.type.code", ""));

        m_viewItemCode = LayoutUtil.makeTextView(context, "");

        m_spinnerItemCode = new ItemCodeSpinner(context);
        m_spinnerItemCode.setOnItemCodeSelectedListener(new ItemCodeSpinner.OnItemCodeSelectedListener()
        {
            @Override
            public void onItemSelected(String strCode, String strName, String strMarket)
            {
                m_viewItemCode.setText(strCode);
                SampleUtil.setConfig(getContext(), "wstock.item.code", strCode);
                requestCurrPrice();
            }
        });

        selectExchange(m_spinnerExchg.getSelectedKey());

        LinearLayout layoutCode = new LinearLayout(context);
        layoutCode.setOrientation(LinearLayout.HORIZONTAL);

        layoutCode.addView(m_spinnerExchg, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 2);
        param.rightMargin = (int)SampleUtil.dipToPixels(context, 10);
        layoutCode.addView(m_viewItemCode, param);
        layoutCode.addView(m_spinnerItemCode, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 3));

        layoutCode.setPadding(PADDING_H, PADDING_V, PADDING_H, PADDING_V);

        return layoutCode;
    }

    private void selectExchange(String strKey)
    {
        String [] arrKey = strKey.split(",");
        m_spinnerItemCode.setItemList(SmartChampAPI.getInstance().getOverseasStockCodeList(arrKey[0], arrKey[1]));

        m_spinnerItemCode.setItemCode(SampleUtil.getConfig(getContext(), "wstock.item.code", ""));
    }

    private LinearLayout makeAccountInput(Context context)
    {
        // 계좌번호
        TextView textCode = LayoutUtil.makeTextView(context, "보유계좌");

        m_spinnerAccount = new AccountSelectSpinner(context);

        m_spinnerAccount.resetAccountList();

        SmartChampAPI mngNet = SmartChampAPI.getInstance();

        ArrayList<String> arrAcc = mngNet.getAccountList();
        for(String strAccNo : arrAcc)
            m_spinnerAccount.addAccountList(strAccNo, mngNet.getAccountName(strAccNo));

        m_spinnerAccount.setOnAccountSelectedListener(new AccountSelectSpinner.OnAccountSelectedListener() {

            @Override
            public void onAccountSelected(String strNo)
            {
                SampleUtil.setConfig(getContext(), "wstock.account.no", strNo);

                if(m_editAccountPwd != null)
                {
                    m_editAccountPwd.setText("");
                    m_editAccountPwd.requestFocus();
                }
            }
        });
        m_spinnerAccount.setAccountNo(SampleUtil.getConfig(getContext(), "wstock.account.no", ""));

        m_editAccountPwd = LayoutUtil.makeEditView(context, "");
        LayoutUtil.setEditText(m_editAccountPwd, false, true);
        m_editAccountPwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if(actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT)
                {
                    String strText = v.getText().toString();
                    if(TextUtils.isEmpty(strText)) return false;

                    SmartChampAPI.getInstance().checkAccPwd(m_spinnerAccount.getAccountNo(), strText,
                            new IAccountPwdCheckListener()
                            {
                                @Override
                                public void onAccountPwdCheckResult(boolean isSuccess, String strAccNo, String strMessage)
                                {
                                    if(isSuccess)
                                    {
                                        Toast.makeText(getContext(), "계좌 비밀번호 체크 완료", Toast.LENGTH_LONG).show();

                                        requestJango();

                                    } else {
                                        Toast.makeText(getContext(), strMessage, Toast.LENGTH_LONG).show();
                                        m_editAccountPwd.setText("");
                                    }
                                }
                            });
                }
                return false;
            }
        });

        LinearLayout layoutAccount = new LinearLayout(context);
        layoutAccount.setOrientation(LinearLayout.HORIZONTAL);
        layoutAccount.setBackgroundColor(ColorUtil.SECTION_INPUT_BACK);

        layoutAccount.addView(textCode, new LinearLayout.LayoutParams(TITLE_WIDTH, LayoutParams.MATCH_PARENT));
        layoutAccount.addView(m_spinnerAccount, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 5));
        layoutAccount.addView(m_editAccountPwd, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 2));

        layoutAccount.setPadding(PADDING_H, PADDING_V, PADDING_H, PADDING_V);

        return layoutAccount;
    }

    public LinearLayout makeTradeInput(Context context)
    {
        // 1. 컨트롤 생성

        // 1.1. 거래단가
        TextView textPrice = LayoutUtil.makeTextView(context,"단가");
        m_editTradeUnitPrice = LayoutUtil.makeEditView(context,"");
        m_editTradeUnitPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

        // 1.2. 거래수량
        TextView textCount = LayoutUtil.makeTextView(context,"수량");
        m_editTradeCount = LayoutUtil.makeEditView(context,"");
        m_editTradeCount.setInputType(InputType.TYPE_CLASS_NUMBER);

        m_checkTradeAll = LayoutUtil.makeCheckBox(context, CTRL_ID_REMAINALL, "전량");

        // 1.3. 주문번호
        TextView textNo = LayoutUtil.makeTextView(context,"주문번호");
        m_editTradeNo = LayoutUtil.makeEditView(context,"");
        m_editTradeNo.setInputType(InputType.TYPE_CLASS_NUMBER);
        m_editTradeNo.setEnabled(false);

        // 1.4. 주문버튼
        Button buttonBuy = LayoutUtil.makeCtrlButton(context, CTRL_ID_BUY, "매수");
        buttonBuy.setOnClickListener(this);
        Button buttonSell = LayoutUtil.makeCtrlButton(context, CTRL_ID_SELL, "매도");
        buttonSell.setOnClickListener(this);
        Button buttonModify = LayoutUtil.makeCtrlButton(context, CTRL_ID_MODIFY, "정정");
        buttonModify.setOnClickListener(this);
        Button buttonCancel = LayoutUtil.makeCtrlButton(context, CTRL_ID_CANCEL, "취소");
        buttonCancel.setOnClickListener(this);

        // 2. 레이아웃 구성
        LinearLayout layoutTrade = new LinearLayout(context);
        layoutTrade.setOrientation(LinearLayout.VERTICAL);

        // 2.1. 입력라인
        LinearLayout layoutLine1 = new LinearLayout(context);
        layoutLine1.setOrientation(LinearLayout.HORIZONTAL);

        layoutLine1.addView(textPrice, new LinearLayout.LayoutParams(TITLE_WIDTH, LayoutParams.MATCH_PARENT));
        layoutLine1.addView(m_editTradeUnitPrice, new LinearLayout.LayoutParams(INPUT_WIDTH, LayoutParams.MATCH_PARENT));

        LinearLayout layoutLine2 = new LinearLayout(context);
        layoutLine2.setOrientation(LinearLayout.HORIZONTAL);

        layoutLine2.addView(textCount, new LinearLayout.LayoutParams(TITLE_WIDTH, LayoutParams.MATCH_PARENT));
        layoutLine2.addView(m_editTradeCount, new LinearLayout.LayoutParams(INPUT_WIDTH, LayoutParams.MATCH_PARENT));
        layoutLine2.addView(m_checkTradeAll, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));

        LinearLayout layoutLine3 = new LinearLayout(context);
        layoutLine3.setOrientation(LinearLayout.HORIZONTAL);

        layoutLine3.addView(textNo, new LinearLayout.LayoutParams(TITLE_WIDTH, LayoutParams.MATCH_PARENT));
        layoutLine3.addView(m_editTradeNo, new LinearLayout.LayoutParams(INPUT_WIDTH, LayoutParams.MATCH_PARENT));

        // 2.2. 버튼 라인
        LinearLayout layoutLine4 = new LinearLayout(context);
        layoutLine4.setOrientation(LinearLayout.HORIZONTAL);
        layoutLine4.setPadding(0, PADDING_V, 0, 0);

        layoutLine4.addView(buttonBuy, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        layoutLine4.addView(buttonSell, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        layoutLine4.addView(buttonModify, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        layoutLine4.addView(buttonCancel, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));

        // 3. 구성 완료
        layoutTrade.addView(layoutLine1, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        layoutTrade.addView(layoutLine2, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        layoutTrade.addView(layoutLine3, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        layoutTrade.addView(layoutLine4, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        layoutTrade.setPadding(PADDING_H, PADDING_V, PADDING_H, PADDING_V);

        return layoutTrade;
    }

    public LinearLayout makeJangoView(Context context)
    {
        LinearLayout layoutFrame = new LinearLayout(context);
        layoutFrame.setOrientation(LinearLayout.VERTICAL);

        LinearLayout layoutTitle = new LinearLayout(context);
        layoutTitle.setOrientation(LinearLayout.HORIZONTAL);

        TextView viewTitle = LayoutUtil.makeTextView(context, "해외주식 잔고");
        viewTitle.setPadding(PADDING_H, PADDING_V, PADDING_H, PADDING_V);

        Button buttonRefresh = LayoutUtil.makeCtrlButton(context, CTRL_ID_REFRESH_JANGO, "재조회");
        buttonRefresh.setOnClickListener(this);

        layoutTitle.addView(viewTitle, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        layoutTitle.addView(buttonRefresh, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        layoutFrame.addView(layoutTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        m_viewJango = new JangoListView(context, 4, this);
        layoutFrame.addView(m_viewJango.makeHeadView(context), new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        layoutFrame.addView(m_viewJango, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 200)));

        return layoutFrame;
    }

    public LinearLayout makeMichegyulView(Context context)
    {
        LinearLayout layoutFrame = new LinearLayout(context);
        layoutFrame.setOrientation(LinearLayout.VERTICAL);

        LinearLayout layoutTitle = new LinearLayout(context);
        layoutTitle.setOrientation(LinearLayout.HORIZONTAL);

        TextView viewTitle = LayoutUtil.makeTextView(context, "해외주식 당일미체결");
        viewTitle.setPadding(PADDING_H, PADDING_V, PADDING_H, PADDING_V);

        Button buttonRefresh = LayoutUtil.makeCtrlButton(context, CTRL_ID_REFRESH_MICHEGYUL, "재조회");
        buttonRefresh.setOnClickListener(this);

        layoutTitle.addView(viewTitle, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        layoutTitle.addView(buttonRefresh, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        layoutFrame.addView(layoutTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        m_viewMichegyul = new CheMicheListView(context, 4, this);
        layoutFrame.addView(m_viewMichegyul.makeHeadView(context), new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        layoutFrame.addView(m_viewMichegyul, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 200)));

        return layoutFrame;
    }

    // 앱 활성화 또는 통신 단절로 인한 재접속시 화면 갱신
    public void onRefreshView()
    {
        requestCurrPrice();
        requestJango();
        requestMichegyul();
    }

    private void requestCurrPrice()
    {
        // 조회 요청 전에, 실시간 요청을 먼저 클리어 한다
        if(m_realCurrPrice != null) m_realCurrPrice.cancelRealData();
        if(m_realCurrHoga != null) m_realCurrHoga.cancelRealData();

        m_viewSiseList.clearList(4);

        String strItemCode = m_spinnerItemCode.getItemCode();
        String strExchg = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "exchgcode");
        String strSymbolId = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "symbolid");
        String strFullCode = strExchg + strSymbolId;//SmartChampAPI.getInstance().getItemFullCode(strItemCode);
        if(TextUtils.isEmpty(strFullCode)) return;

        // 현재 지정된 종목으로, 현재가/호가 조회 요청
        if(m_tranCurrPrice != null)
        {
            m_tranCurrPrice.clearInputData();
            m_tranCurrPrice.clearOutputData();

            m_tranCurrPrice.setDataValue( "InBlock1", "sCode", 0, strFullCode);

            m_tranCurrPrice.requestData();
        }


        if(m_tranCurrHoga != null)
        {
            m_tranCurrHoga.clearInputData();
            m_tranCurrHoga.clearOutputData();

            m_tranCurrHoga.setDataValue( "InBlock1", "sCode", 0, strFullCode);

            m_tranCurrHoga.requestData();
        }
    }

    private void requestCurrPriceReal()
    {
        if(m_tranCurrPrice == null || m_realCurrPrice == null) return;

        m_realCurrPrice.releaseReal();

        String strFullCode = m_tranCurrPrice.getDataValue("InBlock1", "sCode", 0).trim();

        m_realCurrPrice.setDataValue("InBlock1", "sCode", 0, strFullCode);
        m_realCurrPrice.requestReal();
    }

    private void requestCurrHogaReal()
    {
        if(m_tranCurrHoga == null || m_realCurrHoga == null) return;

        m_realCurrHoga.releaseReal();

        String strFullCode = m_tranCurrHoga.getDataValue("InBlock1", "sCode", 0).trim();	// 호가 데이터 요청한 종목코드

        m_realCurrHoga.setDataValue("InBlock1", "sCode", 0, strFullCode);
        m_realCurrHoga.requestReal();
    }

    // 주식 매수 주문
    private void requestOrderBuy()
    {
        if(m_tranStockBuy == null) return;

        // 계좌
        String strAccountNo = m_spinnerAccount.getAccountNo();
        String strAccountPwd = m_editAccountPwd.getText().toString();

        // 종목
        String strItemCode = m_spinnerItemCode.getItemCode();
        String strEuExchg = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "exchgcode_eugene");
        String strSymbol = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "symbolid");

        // 주문수량, 주문가격
        String strOrderCount = m_editTradeCount.getText().toString();
        String strOrderPrice = m_editTradeUnitPrice.getText().toString();

        // 데이터 요청전에 입력데이터, 출력데이터 클리어
        m_tranStockBuy.clearInputData();
        m_tranStockBuy.clearOutputData();

        // 입력 데이터 설정
        m_tranStockBuy.setDataValue("InBlock1", "ACNO", 0, strAccountNo);		// 계좌번호
        m_tranStockBuy.setDataValue("InBlock1", "AC_PWD", 0, strAccountPwd);	// 계좌비번

        m_tranStockBuy.setDataValue("InBlock1", "EXG_COD", 0, strEuExchg);	// 거래소코드
        m_tranStockBuy.setDataValue("InBlock1", "ITEM_COD", 0, strSymbol);	// 종목코드
        m_tranStockBuy.setDataValue("InBlock1", "ORD_Q", 0, strOrderCount);   // 주문수량
        m_tranStockBuy.setDataValue("InBlock1", "FGST_ORD_UPR", 0, strOrderPrice);  // 주문단가
        // 매수매도거래구분코드 (10:매도, 20:매수)
        m_tranStockBuy.setDataValue("InBlock1", "BUY_SEL_TR_TCD", 0, "20");
        // 해외증권매매구분코드 (010:지정가, 020:시장가, 720:MOO, 740:MOC, 710:LOO, 730:LOC, 750:TWAP, 760:VWAP)
        m_tranStockBuy.setDataValue("InBlock1", "FGST_BNS_TCD", 0, "010");

        // 서버에 요청
        m_tranStockBuy.requestData();
    }

    // 주식 매도 주문
    private void requestOrderSell()
    {
        if(m_tranStockSell == null) return;

        // 주문계좌
        String strAccountNo = m_spinnerAccount.getAccountNo();
        String strAccountPwd = m_editAccountPwd.getText().toString();

        // 종목정보
        String strItemCode = m_spinnerItemCode.getItemCode();
        String strEuExchg = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "exchgcode_eugene");
        String strSymbol = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "symbolid");

        // 주문수량, 주문가격
        String strOrderCount = m_editTradeCount.getText().toString();
        String strOrderPrice = m_editTradeUnitPrice.getText().toString();

        // 데이터 요청전에 입력/출력 데이터 클리어
        m_tranStockSell.clearInputData();
        m_tranStockSell.clearOutputData();

        // 입력 데이터 설정
        m_tranStockSell.setDataValue("InBlock1", "ACNO", 0, strAccountNo);		// 계좌번호
        m_tranStockSell.setDataValue("InBlock1", "AC_PWD", 0, strAccountPwd);	// 계좌비번

        m_tranStockSell.setDataValue("InBlock1", "EXG_COD", 0, strEuExchg);	// 거래소코드
        m_tranStockSell.setDataValue("InBlock1", "ITEM_COD", 0, strSymbol);	// 종목코드
        m_tranStockSell.setDataValue("InBlock1", "ORD_Q", 0, strOrderCount);   // 주문수량
        m_tranStockSell.setDataValue("InBlock1", "FGST_ORD_UPR", 0, strOrderPrice);  // 주문단가
        // 매수매도거래구분코드 (10:매도, 20:매수)
        m_tranStockSell.setDataValue("InBlock1", "BUY_SEL_TR_TCD", 0, "10");
        // 해외증권매매구분코드 (010:지정가, 020:시장가, 720:MOO, 740:MOC, 710:LOO, 730:LOC, 750:TWAP, 760:VWAP)
        m_tranStockSell.setDataValue("InBlock1", "FGST_BNS_TCD", 0, "010");

        // 서버에 요청
        m_tranStockSell.requestData();
    }

    // 주식 정정 주문
    private void requestOrderModify()
    {
        if(m_tranStockModify == null) return;

        // 계좌 정보
        String strAccountNo = m_spinnerAccount.getAccountNo();
        String strAccountPwd = m_editAccountPwd.getText().toString();

        // 종목 정보
        String strItemCode = m_spinnerItemCode.getItemCode();
        String strEuExchg = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "exchgcode_eugene");
        String strSymbol = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "symbolid");

        // 주문수량, 주문가격, 원주문번호
        String strOrderCount = m_checkTradeAll.isChecked() ? "" : m_editTradeCount.getText().toString();
        String strOrderPrice = m_editTradeUnitPrice.getText().toString();
        String strOrgOrderNo = m_editTradeNo.getText().toString();

        String strRemainAll = m_checkTradeAll.isChecked() ? "20" : "10";

        // 서비스 요청전 입력/출력 데이터 클리어
        m_tranStockModify.clearInputData();
        m_tranStockModify.clearOutputData();

        // 입력 데이터 설정
        m_tranStockModify.setDataValue("InBlock1", "ACNO", 0, strAccountNo);		// 계좌번호
        m_tranStockModify.setDataValue("InBlock1", "AC_PWD", 0, strAccountPwd);	// 계좌비번
        // 원주문번호
        m_tranStockModify.setDataValue("InBlock1", "OORD_NO", 0, strOrgOrderNo);  // 원주문번호
        // 정정취소구분 (20: 정정, 30:취소)
        m_tranStockModify.setDataValue("InBlock1", "ORD_MDFY_CNCL_TCD", 0, "20");
        // 일부전부구분 (10: 일부, 20:전부)
        m_tranStockModify.setDataValue("InBlock1", "PAT_ALL_TCD", 0, strRemainAll);

        m_tranStockModify.setDataValue("InBlock1", "EXG_COD", 0, strEuExchg);	// 거래소코드
        m_tranStockModify.setDataValue("InBlock1", "ITEM_COD", 0, strSymbol);	// 종목코드
        m_tranStockModify.setDataValue("InBlock1", "ORD_Q", 0, strOrderCount);   // 주문수량
        m_tranStockModify.setDataValue("InBlock1", "FGST_ORD_UPR", 0, strOrderPrice);  // 주문단가
        // 해외증권매매구분코드 (010:지정가, 020:시장가, 720:MOO, 740:MOC, 710:LOO, 730:LOC, 750:TWAP, 760:VWAP)
        m_tranStockModify.setDataValue("InBlock1", "FGST_BNS_TCD", 0, "010");

        // 서버에 요청
        m_tranStockModify.requestData();
    }

    // 주식 취소 주문
    private void requestOrderCancel()
    {
        if(m_tranStockCancel == null) return;

        // 계좌 정보
        String strAccountNo = m_spinnerAccount.getAccountNo();
        String strAccountPwd = m_editAccountPwd.getText().toString();

        // 종목 정보
        String strItemCode = m_spinnerItemCode.getItemCode();
        String strEuExchg = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "exchgcode_eugene");
        String strSymbol = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "symbolid");

        // 주문수량, 주문가격, 원주문번호
        String strOrderCount = m_checkTradeAll.isChecked() ? "" : m_editTradeCount.getText().toString();
        String strOrderPrice = m_editTradeUnitPrice.getText().toString();
        String strOrgOrderNo = m_editTradeNo.getText().toString();

        String strRemainAll = m_checkTradeAll.isChecked() ? "20" : "10";

        // 서비스 요청전 입력/출력 데이터 클리어
        m_tranStockCancel.clearInputData();
        m_tranStockCancel.clearOutputData();

        // 입력 데이터 설정
        m_tranStockCancel.setDataValue("InBlock1", "ACNO", 0, strAccountNo);		// 계좌번호
        m_tranStockCancel.setDataValue("InBlock1", "AC_PWD", 0, strAccountPwd);	// 계좌비번
        // 원주문번호
        m_tranStockCancel.setDataValue("InBlock1", "OORD_NO", 0, strOrgOrderNo);  // 원주문번호
        // 정정취소구분 (20: 정정, 30:취소)
        m_tranStockCancel.setDataValue("InBlock1", "ORD_MDFY_CNCL_TCD", 0, "30");
        // 일부전부구분 (10: 일부, 20:전부)
        m_tranStockCancel.setDataValue("InBlock1", "PAT_ALL_TCD", 0, strRemainAll);

        m_tranStockCancel.setDataValue("InBlock1", "EXG_COD", 0, strEuExchg);	// 거래소코드
        m_tranStockCancel.setDataValue("InBlock1", "ITEM_COD", 0, strSymbol);	// 종목코드
        m_tranStockCancel.setDataValue("InBlock1", "ORD_Q", 0, strOrderCount);   // 주문수량
        m_tranStockCancel.setDataValue("InBlock1", "FGST_ORD_UPR", 0, strOrderPrice);  // 주문단가
        // 해외증권매매구분코드 (010:지정가, 020:시장가, 720:MOO, 740:MOC, 710:LOO, 730:LOC, 750:TWAP, 760:VWAP)
        m_tranStockCancel.setDataValue("InBlock1", "FGST_BNS_TCD", 0, "010");

        // 서버에 요청
        m_tranStockCancel.requestData();
    }

    private void requestJango()
    {
        m_viewJango.clearList();

        if(m_tranJango == null) return;

        String strAccountNo = m_spinnerAccount.getAccountNo();
        String strAccountPwd = m_editAccountPwd.getText().toString();

        if(TextUtils.isEmpty(strAccountNo) || TextUtils.isEmpty(strAccountPwd)) return;

        m_tranJango.clearInputData();
        m_tranJango.clearOutputData();

        m_tranJango.setDataValue("InBlock1", "ACNO", 0, strAccountNo);		// 계좌번호
        m_tranJango.setDataValue("InBlock1", "AC_PWD", 0, strAccountPwd);	// 계좌비번

        m_tranJango.setDataHeader("DETAIL_CONT", "1");  // 연속조회
        m_tranJango.setDataHeader("DETAIL_QRY_CNT", "10");  // 조회개수

        m_tranJango.requestData();
    }

    private void requestMichegyul()
    {
        m_viewMichegyul.clearList();

        if(m_tranMichegyul == null) return;

        String strAccountNo = m_spinnerAccount.getAccountNo();
        String strAccountPwd = m_editAccountPwd.getText().toString();

        if(TextUtils.isEmpty(strAccountNo) || TextUtils.isEmpty(strAccountPwd)) return;

        m_tranMichegyul.clearInputData();
        m_tranMichegyul.clearOutputData();

        m_tranMichegyul.setDataValue("InBlock1", "ACNO", 0, strAccountNo);		// 계좌번호
        m_tranMichegyul.setDataValue("InBlock1", "AC_PWD", 0, strAccountPwd);	// 계좌비번

        m_tranMichegyul.setDataValue("InBlock1", "BUY_SEL_TR_TCD", 0, "%");
        m_tranMichegyul.setDataValue("InBlock1", "ITEM_COD", 0, "%");
        m_tranMichegyul.setDataValue("InBlock1", "EXG_COD", 0, "%");
        //m_tranMichegyul.setDataValue("InRec1", "SCR_QRY_TCD", 0, "01");

        m_tranMichegyul.setDataHeader("DETAIL_CONT", "1");  // 연속조회
        m_tranMichegyul.setDataHeader("DETAIL_QRY_CNT", "10");  // 조회개수

        m_tranMichegyul.requestData();
    }

    @Override
    public void onTranBeforeRequest(String sTranID, boolean isNextQuery) {

        // 계좌비번,사용자비번 등은 서버에 요청 후 삭제됨
        // 요청시마다 다시 설정 필요...
        if(sTranID.equals("주식체결내역"))
        {
            // 비번 조회
            String strAccountPwd = m_editAccountPwd.getText().toString();
            m_tranMichegyul.setDataValue("InBlock1", "AC_PWD", 0, strAccountPwd);	// 계좌비번
        } else if(sTranID.equals("주식잔고조회"))
        {
            // 비번 조회
            String strAccountPwd = m_editAccountPwd.getText().toString();
            m_tranJango.setDataValue("InBlock1", "AC_PWD", 0, strAccountPwd);	// 계좌비번
        }
    }

    @Override
    public void onTranDataReceived(String sTranID, String sMsgCode, String sMsgText)
    {
        SampleUtil.writeLog(LOG_TAG, String.format("onTranDataReceived [%s][%s][%s]", sTranID, sMsgCode, sMsgText));

        String strBlockName = "OutBlock1";

		if(sTranID.equals("주식현재가")) {

            // 현재가
            String strPrice = m_tranCurrPrice.getDataValue(strBlockName, "lCPrice", 0);
            int nPriceAttr = m_tranCurrPrice.getDataAttr(strBlockName, "lCPrice", 0);
            // 등락
            String strDiff = m_tranCurrPrice.getDataValue(strBlockName, "lDiff", 0);
            int nDiffAttr = m_tranCurrPrice.getDataAttr(strBlockName, "lDiff", 0);
            // 등락기호
            String strSign = m_tranCurrPrice.getDataValue(strBlockName, "cPCheck", 0);
            int nSignAttr = m_tranCurrPrice.getDataAttr(strBlockName, "cPCheck", 0);
            // 등락률
            String strDiffRatio = m_tranCurrPrice.getDataValue(strBlockName, "lDiffRatio", 0);
            int nDiffRatioAttr = m_tranCurrPrice.getDataAttr(strBlockName, "lDiffRatio", 0);

            String strTradeAmount = m_tranCurrPrice.getDataValue(strBlockName, "lVolume", 0);
            String strTradeMoney = m_tranCurrPrice.getDataValue(strBlockName, "lValue", 0);

            SampleUtil.writeLog(LOG_TAG, String.format("price[%s][%02x]", strPrice, (nPriceAttr & 0xff)));

            m_viewItemPrice.setWStockPriceInfo(strPrice, nPriceAttr,
                    strSign, nSignAttr, strDiff, nDiffAttr, strDiffRatio, nDiffRatioAttr);
            m_viewItemPrice.setWStockTradeInfo(strTradeAmount, strTradeMoney);

            requestCurrPriceReal();
        } else if(sTranID.equals("주식호가"))
        {
            String strItemCode = m_tranCurrHoga.getDataValue(strBlockName, "sCode", 0);
            String strCurrPrice = m_tranCurrHoga.getDataValue(strBlockName, "lCPrice", 0);

            SampleUtil.writeLog(LOG_TAG, "주식호가 수신 : " + strItemCode);
            SampleUtil.writeLog(LOG_TAG, "현재가 [" + strCurrPrice + "]");

            // 5호가 데이터만 추출
            for(int nDataIndex = 0; nDataIndex < 5; nDataIndex++)
            {
                // 매도 호가
                String strMaedoHoga = m_tranCurrHoga.getDataValue(strBlockName, String.format("lOffer%d", nDataIndex + 1), 0);
                int nMaedoHogaAttr = (byte)0x32;
                String strMaedoRemains = m_tranCurrHoga.getDataValue(strBlockName, String.format("lOfferRest%d", nDataIndex + 1), 0);

                // 매수 호가
                String strMaesuHoga = m_tranCurrHoga.getDataValue(strBlockName, String.format("lBid%d", nDataIndex + 1), 0);
                int nMaesuHogaAttr = (byte)0x35;
                String strMaesuRemains = m_tranCurrHoga.getDataValue(strBlockName, String.format("lBidRest%d", nDataIndex + 1), 0);

                m_viewItemHoga.setHogaF4(true, nDataIndex, strMaedoHoga, nMaedoHogaAttr, strMaedoRemains);
                m_viewItemHoga.setHogaF4(false, nDataIndex, strMaesuHoga, nMaesuHogaAttr, strMaesuRemains);
            }

			requestCurrHogaReal();
		}
        else if(sTranID.equals("주식매수주문"))
        {
            String strOrderNo = m_tranStockBuy.getDataValue(strBlockName, "ORD_NO", 0);

            m_editTradeNo.setText(strOrderNo);

            // 성공
            Toast.makeText(getContext(), m_tranStockBuy.getDataMsgText(), Toast.LENGTH_LONG).show();

            requestMichegyul();
            requestJango();
        }
        else if(sTranID.equals("주식매도주문"))
        {
            String strOrderNo = m_tranStockSell.getDataValue(strBlockName, "ORD_NO", 0);

            m_editTradeNo.setText(strOrderNo);

            // 성공
            Toast.makeText(getContext(), m_tranStockSell.getDataMsgText(), Toast.LENGTH_LONG).show();

            requestMichegyul();
            requestJango();
        }
        else if(sTranID.equals("주식정정주문"))
        {
            String strOrderNo = m_tranStockModify.getDataValue(strBlockName, "ORD_NO", 0);

            m_editTradeNo.setText(strOrderNo);

            // 성공
            Toast.makeText(getContext(), m_tranStockModify.getDataMsgText(), Toast.LENGTH_LONG).show();

            requestMichegyul();
            requestJango();
        }
        else if(sTranID.equals("주식취소주문"))
        {
            String strOrderNo = m_tranStockCancel.getDataValue(strBlockName, "ORD_NO", 0);

            m_editTradeNo.setText(strOrderNo);

            // 성공
            Toast.makeText(getContext(), m_tranStockCancel.getDataMsgText(), Toast.LENGTH_LONG).show();

            requestMichegyul();
            requestJango();
        }
        else if(sTranID.equals("주식잔고조회"))
        {
            int nDataCount = m_tranJango.getDataCount("OutBlock1");

            for(int i = 0; i < nDataCount; i++) {
                JangoInfo info = new JangoInfo();

                info.m_strItemCode = m_tranJango.getDataValue("OutBlock1", "ITEM_COD", i);
                info.m_strItemName = m_tranJango.getDataValue("OutBlock1", "ITEM_NM", i);
                info.m_strAvailQty = m_tranJango.getDataValue("OutBlock1", "SEL_ABLE_Q", i);
                info.m_strHaveQty = m_tranJango.getDataValue("OutBlock1", "BAL_QHLDG_Q", i);
                info.m_strUnitPrice = m_tranJango.getDataValue("OutBlock1", "BUY_UPR", i);
                info.m_strAvgPrice = m_tranJango.getDataValue("OutBlock1", "BNS_BAL_EA", i);
                info.m_strProfit = m_tranJango.getDataValue("OutBlock1", "EV_PL_SUM_A", i);

                m_viewJango.addList(info);
            }
        }
        else if(sTranID.equals("주식미체결내역"))
        {
            strBlockName = "OutBlock2";

            int nDataCount = m_tranMichegyul.getDataCount(strBlockName);

            for(int i = 0; i < nDataCount; i++) {
                CheMicheInfo info = new CheMicheInfo();

                String strExchgCode = m_tranMichegyul.getDataValue(strBlockName, "EXG_COD", i);
                String strMarketGubun = m_tranMichegyul.getDataValue(strBlockName, "FRGN_STK_MKT_TCD", i);
                String strSymbol = m_tranMichegyul.getDataValue(strBlockName, "ITEM_COD", i);

                info.m_strItemCode = (strExchgCode.equals("020") ?
                        ((strMarketGubun.equals("03") || strMarketGubun.equals("09")) ? "0537" :
                                strMarketGubun.equals("08") ? "0321" : "0066") :
                        strExchgCode.equals("014") ? "0215" :
                                strExchgCode.equals("018") ? "0214" :
                                        strExchgCode.equals("001") ? "0104" : "") + strSymbol;

                info.m_strOrderNo = m_tranMichegyul.getDataValue(strBlockName, "ORD_NO", i);
                //info.m_strItemCode = m_tranMichegyul.getDataValue(strBlockName, "ITEM_COD", i);
                info.m_strItemName = m_tranMichegyul.getDataValue(strBlockName, "ITEM_NM", i);
                info.m_strOrderQty = m_tranMichegyul.getDataValue(strBlockName, "FRGN_ORD_Q", i);
                info.m_strChegyulQty = m_tranMichegyul.getDataValue(strBlockName, "TFST_CLSN_Q", i);
                info.m_strMicheQty = m_tranMichegyul.getDataValue(strBlockName, "FRGN_NCLSN_Q", i);
                info.m_strOrderPrice = m_tranMichegyul.getDataValue(strBlockName, "FGST_ORD_UPR", i);
                info.m_strChegyulPrice = m_tranMichegyul.getDataValue(strBlockName, "FGST_CLSN_UPR", i);
                info.m_strOrderKind = m_tranMichegyul.getDataValue(strBlockName, "BUY_SEL_TR_TCD", i);
                info.m_strModCancelGubun = m_tranMichegyul.getDataValue(strBlockName, "FGST_ORD_SCD", i);
                info.setWStockOrderInfo();

                m_viewMichegyul.addList(info);
            }
        }
    }

    @Override
    public void onTranError(String sTranID, String sErrCode, String sErrText) {
        SampleUtil.writeLog(LOG_TAG, String.format("onTranError [%s] [%s][%s]", sTranID, sErrCode, sErrText));

        //if(sTranID.equals("주식매수주문"))
        {
            Toast.makeText(getContext(), sErrText, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onTranTimeout(String sTranID)
    {
        SampleUtil.writeLog(LOG_TAG, String.format("TranId:%s ", sTranID));
    }

    @Override
    public void onRealBeforeRequest(String sRealId)
    {
    }

    @Override
    public void onRealDataReceived(String strRealId)
    {
        String strBlockName = "OutBlock1";

        if(strRealId.equals("주식체결실시간"))
        {
            int nDataCount = m_realCurrPrice.getDataCount(strBlockName);

            for(int i = 0; i < nDataCount; i++) {
                // 현재가
                String strPrice = m_realCurrPrice.getDataValue(strBlockName, "lCPrice", i);
                int nPriceAttr = m_realCurrPrice.getDataAttr(strBlockName, "lCPrice", i);
                // 등락
                String strDiff = m_realCurrPrice.getDataValue(strBlockName, "lDiff", i);
                int nDiffAttr = m_realCurrPrice.getDataAttr(strBlockName, "lDiff", i);
                // 등락기호
                String strSign = m_realCurrPrice.getDataValue(strBlockName, "cPCheck", i);
                int nSignAttr = m_realCurrPrice.getDataAttr(strBlockName, "cPCheck", i);
                // 등락률
                String strDiffRatio = m_realCurrPrice.getDataValue(strBlockName, "lDiffRate", i);
                int nDiffRatioAttr = m_realCurrPrice.getDataAttr(strBlockName, "lDiffRate", i);
                // 체결량
                String strTradeVol = m_realCurrPrice.getDataValue(strBlockName, "lCurVolume", i);
                int nTradeVolAttr = m_realCurrPrice.getDataAttr(strBlockName, "lCurVolume", i);

                // 누적거래량
                String strTradeAmount = m_realCurrPrice.getDataValue(strBlockName, "lVolume", i);
                // 누적거래대금
                String strTradeMoney = m_realCurrPrice.getDataValue(strBlockName, "lValue", i);

                SampleUtil.writeLog(LOG_TAG, String.format("price[%s][%02x]", strPrice, (nPriceAttr & 0xff)));

                // 리스트에 누적되는 형태가 아니면, 최종 데이터만 표시
                if(i == 0) {
                    m_viewItemPrice.setWStockPriceInfo(strPrice, nPriceAttr,
                            strSign, nSignAttr, strDiff, nDiffAttr, strDiffRatio, nDiffRatioAttr);
                    m_viewItemPrice.setWStockTradeInfo(strTradeAmount, strTradeMoney);
                }

                m_viewSiseList.addList(new SiseInfo(strPrice, nPriceAttr, strTradeVol, nTradeVolAttr), i);
            }
        }
        else if(strRealId.equals("주식호가실시간"))
        {
            String strItemCode = m_realCurrHoga.getDataValue(strBlockName, "sCode", 0);
            SampleUtil.writeLog(LOG_TAG, "호가 실시간 [" + strItemCode + "]");
            // 5호가 데이터만 추출
            for(int nDataIndex = 0; nDataIndex < 5; nDataIndex++)
            {
                // 매도 호가
                String strMaedoHoga = m_realCurrHoga.getDataValue(strBlockName, String.format("lOffer%d", nDataIndex + 1), 0);
                int nMaedoHogaAttr = (byte)0x32;
                String strMaedoRemains = m_realCurrHoga.getDataValue(strBlockName, String.format("lOfferRest%d", nDataIndex + 1), 0);

                // 매수 호가
                String strMaesuHoga = m_realCurrHoga.getDataValue(strBlockName, String.format("lBid%d", nDataIndex + 1), 0);
                int nMaesuHogaAttr = (byte)0x35;
                String strMaesuRemains = m_realCurrHoga.getDataValue(strBlockName, String.format("lBidRest%d", nDataIndex + 1), 0);

                m_viewItemHoga.setHogaF4(true, nDataIndex, strMaedoHoga, nMaedoHogaAttr, strMaedoRemains);
                m_viewItemHoga.setHogaF4(false, nDataIndex, strMaesuHoga, nMaesuHogaAttr, strMaesuRemains);
            }
        }
    }

    @Override
    public void onClick(View view)
    {
        int nId = view.getId();

        if(nId == CTRL_ID_BUY)
        {
            // 매수주문
            requestOrderBuy();
        } else if(nId == CTRL_ID_SELL)
        {
            // 매도주문
            requestOrderSell();
        } else if(nId == CTRL_ID_MODIFY)
        {
            // 정정주문
            requestOrderModify();
        } else if(nId == CTRL_ID_CANCEL)
        {
            // 취소주문
            requestOrderCancel();
        } else if(nId == CTRL_ID_REFRESH_JANGO)
        {
            // 잔고 재조회
            requestJango();
        } else if(nId == CTRL_ID_REFRESH_MICHEGYUL)
        {
            // 체결/미체결 재조회
            requestMichegyul();
        }
    }

    @Override
    public void onSiseListScrollEnd() {

    }

    // 체결 리스트 눌린 경우 -> 미체결인 경우 주문번호
    @Override
    public void onCheMicheItemClicked(CheMicheInfo info)
    {
        String strItemCode = info.m_strItemCode;

        String strExchgCode = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "exchgcode");

        String strGubun = strExchgCode.equals("0104") ? "HK,HKS" : // 홍콩
                strExchgCode.equals("0215") ? "CN,SHS" : // 상해
                strExchgCode.equals("0214") ? "CN,SZS" : // 심천
                strExchgCode.equals("0321") ? "US,NYS" : // 뉴욕
                strExchgCode.equals("0537") ? "US,NAS" : // 나스닥
                strExchgCode.equals("0066") ? "US,AMX" : ""; // 아멕스

        m_spinnerExchg.selectItemByKey(strGubun);
        m_spinnerItemCode.setItemCode(strItemCode);  // 종목 변경

        m_editTradeUnitPrice.setText(info.m_strOrderPrice);
        m_editTradeCount.setText(info.m_strMicheQty);
        m_editTradeNo.setText(info.m_strOrderNo); // 주문번호 설정해서 정정/취소시 사용
    }

    // 체결 리스트 스크롤 마지막 -> 다음 데이터 조회
    @Override
    public void onCheMicheScrollEnd()
    {
        if(m_tranMichegyul == null) return;
        if(m_tranMichegyul.isMoreNextData())
        {
            m_tranMichegyul.requestNextData();
        }
    }
    // 잔고 리스트 스크롤 마지막 -> 다음 데이터 조회
    @Override
    public void onJangoScrollEnd()
    {
        if(m_tranJango == null) return;
        if(m_tranJango.isMoreNextData())
        {
            m_tranJango.requestNextData();
        }
    }

}
