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

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
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.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 FutOptSiseView 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_FUTOPT = 99;

    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_CHEGYUL = 201;  // 미체결 재조회
    private static final int    CTRL_ID_REFRESH_JANGO = 202;    // 계좌별잔고 재조회

    // 화면 표시 뷰
    private Button m_buttonFutOpt;
    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_viewChegyul;                  // 체결 리스트 뷰

    // 데이터 처리
    private SmartChampTran m_tranFuturesPrice = null;				// 지수선물 현재가 조회
    private SmartChampTran m_tranOptionsPrice = null;				// 지수옵션 현재가 조회

    private SmartChampReal m_realFuturesPrice = null;			// 지수선물 체결 실시간
    private SmartChampReal m_realFuturesHoga = null;				// 지수선물 호가 실시간
    private SmartChampReal m_realOptionsPrice = null;            // 지수옵션 체결 실시간
    private SmartChampReal m_realOptionsHoga = null;             // 지수옵션 호가 실시간

    private SmartChampTran m_tranFutOptBuy = null;				// 매수 주문
    private SmartChampTran m_tranFutOptSell = null;				// 매도 주문
    private SmartChampTran m_tranFutOptModify = null;			// 정정 주문
    private SmartChampTran m_tranFutOptCancel = null;			// 취소 주문

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

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

        setBackgroundColor(Color.WHITE);

        // 시세 TR 초기화
        m_tranFuturesPrice = new SmartChampTran(context);
        m_tranFuturesPrice.initInstance(this);
        m_tranFuturesPrice.setQueryFile("ffcur");
        m_tranFuturesPrice.setTranId("지수선물현재가");

        m_tranOptionsPrice = new SmartChampTran(context);
        m_tranOptionsPrice.initInstance(this);
        m_tranOptionsPrice.setQueryFile("ogibon");
        m_tranOptionsPrice.setTranId("지수옵션현재가");

        // 주문 TR 초기화
        m_tranFutOptBuy = new SmartChampTran(context);
        m_tranFutOptBuy.initInstance(this);
        m_tranFutOptBuy.setQueryFile("OFU1101U");
        m_tranFutOptBuy.setTranId("선옵매수주문");

        m_tranFutOptSell = new SmartChampTran(context);
        m_tranFutOptSell.initInstance(this);
        m_tranFutOptSell.setQueryFile("OFU1101U");
        m_tranFutOptSell.setTranId("선옵매도주문");

        m_tranFutOptModify = new SmartChampTran(context);
        m_tranFutOptModify.initInstance(this);
        m_tranFutOptModify.setQueryFile("OFU1102U");
        m_tranFutOptModify.setTranId("선옵정정주문");

        m_tranFutOptCancel = new SmartChampTran(context);
        m_tranFutOptCancel.initInstance(this);
        m_tranFutOptCancel.setQueryFile("OFU1102U");
        m_tranFutOptCancel.setTranId("선옵취소주문");

        m_tranJango = new SmartChampTran(context);
        m_tranJango.initInstance(this);
        m_tranJango.setQueryFile("OFU4793Q");
        m_tranJango.setTranId("선옵잔고조회");

        m_tranMiChegyul = new SmartChampTran(context);
        m_tranMiChegyul.initInstance(this);
        m_tranMiChegyul.setQueryFile("OFU4772Q");
        m_tranMiChegyul.setTranId("선옵미체결내역");

        // 실시간 초기화
        m_realFuturesPrice = new SmartChampReal(context);
        m_realFuturesPrice.initInstance(this);
        m_realFuturesPrice.setQueryFile("F00");
        m_realFuturesPrice.setRealId("선물체결실시간");

        m_realFuturesHoga = new SmartChampReal(context);
        m_realFuturesHoga.initInstance(this);
        m_realFuturesHoga.setQueryFile("F01");
        m_realFuturesHoga.setRealId("선물호가실시간");

        m_realOptionsPrice = new SmartChampReal(context);
        m_realOptionsPrice.initInstance(this);
        m_realOptionsPrice.setQueryFile("O00");
        m_realOptionsPrice.setRealId("옵션체결실시간");

        m_realOptionsHoga = new SmartChampReal(context);
        m_realOptionsHoga.initInstance(this);
        m_realOptionsHoga.setQueryFile("O01");
        m_realOptionsHoga.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, 2, 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 = makeChegyulView(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_tranFuturesPrice != null) m_tranFuturesPrice.clearInstance();
        if(m_tranOptionsPrice != null) m_tranOptionsPrice.clearInstance();

        if(m_tranFutOptBuy != null) m_tranFutOptBuy.clearInstance();
        if(m_tranFutOptSell != null) m_tranFutOptSell.clearInstance();
        if(m_tranFutOptModify != null) m_tranFutOptModify.clearInstance();
        if(m_tranFutOptCancel != null) m_tranFutOptCancel.clearInstance();

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

        if(m_realFuturesPrice != null) m_realFuturesPrice.clearInstance();
        if(m_realFuturesHoga != null) m_realFuturesHoga.clearInstance();
        if(m_realOptionsPrice != null) m_realOptionsPrice.clearInstance();
        if(m_realOptionsHoga != null) m_realOptionsHoga.clearInstance();
    }

    private LinearLayout makeItemCodeInput(Context context)
    {
        // 종목코드
        //TextView textCode = LayoutUtil.makeTextView(context, "종목코드");
        m_buttonFutOpt = LayoutUtil.makeCtrlButton(context, CTRL_ID_FUTOPT, "F");
        m_buttonFutOpt.setOnClickListener(this);

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

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

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

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

        //layoutCode.addView(textCode, new LinearLayout.LayoutParams(TITLE_WIDTH, LayoutParams.MATCH_PARENT));
        layoutCode.addView(m_buttonFutOpt, 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 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(), "futopt.account.no", strNo);

                if(m_editAccountPwd != null)
                {
                    m_editAccountPwd.setText("");
                    m_editAccountPwd.requestFocus();
                }
            }
        });
        m_spinnerAccount.setAccountNo(SampleUtil.getConfig(getContext(), "futopt.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();
                                        requestChegyul();

                                    } 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, 2, 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 makeChegyulView(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_CHEGYUL, "재조회");
        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_viewChegyul = new CheMicheListView(context, 2, this);
        layoutFrame.addView(m_viewChegyul.makeHeadView(context), new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        layoutFrame.addView(m_viewChegyul, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 200)));

        return layoutFrame;
    }

    public void onRefreshView()
    {
        requestCurrPrice();
        requestJango();
        requestChegyul();
    }

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

        String strItemCode = m_spinnerItemCode.getItemCode();
        String strFullCode = SmartChampAPI.getInstance().getItemFullCode(strItemCode);
        if(TextUtils.isEmpty(strFullCode)) return;

        String strItemType = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "type");

        // 현재 지정된 종목으로, 현재가/호가 조회 요청
        // 지수선물
        if(strItemType.equals("J")) {
            m_viewSiseList.clearList(2);

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

                m_tranFuturesPrice.setDataValue("InRec1", "sCode", 0, strFullCode);

                m_tranFuturesPrice.requestData();
            }
        } else if(strItemType.equals("L")) {
            m_viewSiseList.clearList(2);

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

                m_tranOptionsPrice.setDataValue("InRec1", "sCode", 0, strFullCode);

                m_tranOptionsPrice.requestData();
            }
        }
    }

    private void requestFuturesPriceReal()
    {
        if(m_tranFuturesPrice == null || m_realFuturesPrice == null) return;

        m_realFuturesPrice.releaseReal();

        String strFullCode = m_tranFuturesPrice.getDataValue("OutRec1", "sCode", 0).trim();

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

    private void requestFuturesHogaReal()
    {
        if(m_tranFuturesPrice == null || m_realFuturesHoga == null) return;

        m_realFuturesHoga.releaseReal();

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

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

    private void requestOptionsPriceReal()
    {
        if(m_tranOptionsPrice == null || m_realOptionsPrice == null) return;

        m_realOptionsPrice.releaseReal();

        String strFullCode = m_tranOptionsPrice.getDataValue("OutRec1", "sCode", 0).trim();

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

    private void requestOptionsHogaReal()
    {
        if(m_tranOptionsPrice == null || m_realOptionsHoga == null) return;

        m_realOptionsHoga.releaseReal();

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

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

    // 선옵 매수 주문
    private void requestOrderBuy()
    {
        if(m_tranFutOptBuy == null) return;

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

        // 종목
		String strItemCode = m_spinnerItemCode.getItemCode();
        //String strFullCode = SmartChampAPI.getInstance().getItemFullCode(strItemCode);

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

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

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

        m_tranFutOptBuy.setDataValue("InRec1", "ITEM_COD", 0, strItemCode);	// 종목코드
        m_tranFutOptBuy.setDataValue("InRec1", "ORD_Q", 0, strOrderCount);   // 주문수량
        m_tranFutOptBuy.setDataValue("InRec1", "ORD_UPR", 0, strOrderPrice);  // 주문단가
        // 매수매도거래구분코드 (10:매도, 20:매수)
        m_tranFutOptBuy.setDataValue("InRec1", "BUY_SEL_TR_TCD", 0, "20");
        // 주문매매구분코드 (010:지정가, 020:시장가, 030:조건부지정가, 040:최유리지정가)
        m_tranFutOptBuy.setDataValue("InRec1", "ORD_BNS_TCD", 0, "010");
        // 주문조건구분코드 (0:없음, 1:IOC, 2:FOK)
        m_tranFutOptBuy.setDataValue("InRec1", "ORD_COND_TCD", 0, "0");

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

    // 선옵 매도 주문
    private void requestOrderSell()
    {
        if(m_tranFutOptSell == null) return;

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

        // 종목정보
        String strItemCode = m_spinnerItemCode.getItemCode();
        //String strFullCode = SmartChampAPI.getInstance().getItemFullCode(strItemCode);

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

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

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

        m_tranFutOptSell.setDataValue("InRec1", "ITEM_COD", 0, strItemCode);	// 종목코드
        m_tranFutOptSell.setDataValue("InRec1", "ORD_Q", 0, strOrderCount);   // 주문수량
        m_tranFutOptSell.setDataValue("InRec1", "ORD_UPR", 0, strOrderPrice);  // 주문단가
        // 매수매도거래구분코드 (10:매도, 20:매수)
        m_tranFutOptSell.setDataValue("InRec1", "BUY_SEL_TR_TCD", 0, "10");
        // 주문매매구분코드 (010:지정가, 020:시장가, 030:조건부지정가, 040:최유리지정가)
        m_tranFutOptSell.setDataValue("InRec1", "ORD_BNS_TCD", 0, "010");
        // 주문조건구분코드 (0:없음, 1:IOC, 2:FOK)
        m_tranFutOptSell.setDataValue("InRec1", "ORD_COND_TCD", 0, "0");

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

    // 선옵 정정 주문
    private void requestOrderModify()
    {
        if(m_tranFutOptModify == null) return;

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

        // 종목 정보
        String strItemCode = m_spinnerItemCode.getItemCode();
        //String strFullCode = SmartChampAPI.getInstance().getItemFullCode(strItemCode);

        // 주문수량, 주문가격, 원주문번호
        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_tranFutOptModify.clearInputData();
        m_tranFutOptModify.clearOutputData();

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

        m_tranFutOptModify.setDataValue("InRec1", "OORD_NO", 0, strOrgOrderNo);  // 원주문번호
        // 정정취소구분 (20: 정정, 30:취소)
        m_tranFutOptModify.setDataValue("InRec1", "ORD_MDFY_CNCL_TCD", 0, "20");
        // 일부전부구분 (10: 일부, 20:전부)
        m_tranFutOptModify.setDataValue("InRec1", "PAT_ALL_TCD", 0, strRemainAll);

        m_tranFutOptModify.setDataValue("InRec1", "ITEM_COD", 0, strItemCode);	// 종목코드
        m_tranFutOptModify.setDataValue("InRec1", "ORD_Q", 0, strOrderCount);   // 주문수량
        m_tranFutOptModify.setDataValue("InRec1", "ORD_UPR", 0, strOrderPrice);  // 주문단가
        // 주문매매구분코드 (010:지정가, 020:시장가, 030:조건부지정가, 040:최유리지정가)
        m_tranFutOptModify.setDataValue("InRec1", "ORD_BNS_TCD", 0, "010");
        // 주문조건구분코드 (0:없음, 1:IOC, 2:FOK)
        m_tranFutOptModify.setDataValue("InRec1", "ORD_COND_TCD", 0, "0");

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

    // 선옵 취소 주문
    private void requestOrderCancel()
    {
        if(m_tranFutOptCancel == null) return;

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

        // 종목 정보
        String strItemCode = m_spinnerItemCode.getItemCode();
        String strFullCode = SmartChampAPI.getInstance().getItemFullCode(strItemCode);

        // 주문수량, 주문가격, 원주문번호
        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_tranFutOptCancel.clearInputData();
        m_tranFutOptCancel.clearOutputData();

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

        m_tranFutOptCancel.setDataValue("InRec1", "OORD_NO", 0, strOrgOrderNo);  // 원주문번호
        // 정정취소구분 (20: 정정, 30:취소)
        m_tranFutOptCancel.setDataValue("InRec1", "ORD_MDFY_CNCL_TCD", 0, "30");
        // 일부전부구분 (10: 일부, 20:전부)
        m_tranFutOptCancel.setDataValue("InRec1", "PAT_ALL_TCD", 0, strRemainAll);

        m_tranFutOptCancel.setDataValue("InRec1", "ITEM_COD", 0, strFullCode);	// 종목코드
        m_tranFutOptCancel.setDataValue("InRec1", "ORD_Q", 0, strOrderCount);   // 주문수량
        m_tranFutOptCancel.setDataValue("InRec1", "ORD_UPR", 0, strOrderPrice);  // 주문단가
        // 주문매매구분코드 (010:지정가, 020:시장가, 030:조건부지정가, 040:최유리지정가)
        m_tranFutOptCancel.setDataValue("InRec1", "ORD_BNS_TCD", 0, "010");
        // 주문조건구분코드 (0:없음, 1:IOC, 2:FOK)
        m_tranFutOptCancel.setDataValue("InRec1", "ORD_COND_TCD", 0, "0");

        // 서버에 요청
        m_tranFutOptCancel.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("InRec1", "ACNO", 0, strAccountNo);		// 계좌번호
        m_tranJango.setDataValue("InRec1", "AC_PWD", 0, strAccountPwd);	// 계좌비번

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

        m_tranJango.requestData();
    }

    private void requestChegyul()
    {
        m_viewChegyul.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", "SORT_TURN_IO1CD", 0, "2");
        m_tranMiChegyul.setDataValue("InBlock1", "CLSN_TP_IO1CD", 0, "2");
        m_tranMiChegyul.setDataValue("InBlock1", "BUY_SEL_TR_TCD", 0, "%");
        m_tranMiChegyul.setDataValue("InBlock1", "ITEM_TP_IO1CD", 0, "%");

        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("InRec1", "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));

		if(sTranID.equals("지수선물현재가"))
		{
            // 현재가
            String strPrice = m_tranFuturesPrice.getDataValue("OutRec1", "lCPrice", 0);
            int nPriceAttr = m_tranFuturesPrice.getDataAttr("OutRec1", "lCPrice", 0);
            // 등락
            String strDiff = m_tranFuturesPrice.getDataValue("OutRec1", "lDiff", 0);
            int nDiffAttr = m_tranFuturesPrice.getDataAttr("OutRec1", "lDiff", 0);
            // 등락기호
            String strSign = m_tranFuturesPrice.getDataValue("OutRec1", "cPCheck", 0);
            int nSignAttr = m_tranFuturesPrice.getDataAttr("OutRec1", "cPCheck", 0);
            // 등락률
            String strDiffRatio = m_tranFuturesPrice.getDataValue("OutRec1", "lDiffRate", 0);
            int nDiffRatioAttr = m_tranFuturesPrice.getDataAttr("OutRec1", "lDiffRate", 0);

            String strTradeAmount = m_tranFuturesPrice.getDataValue("OutRec1", "lVolume", 0);
            String strTradeMoney = m_tranFuturesPrice.getDataValue("OutRec1", "lValue", 0);

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

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

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

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

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

			requestFuturesPriceReal();
            requestFuturesHogaReal();
		}
        else if(sTranID.equals("지수옵션현재가"))
        {
            // 현재가
            String strPrice = m_tranOptionsPrice.getDataValue("OutRec1", "lCPrice", 0);
            int nPriceAttr = m_tranOptionsPrice.getDataAttr("OutRec1", "lCPrice", 0);
            // 등락
            String strDiff = m_tranOptionsPrice.getDataValue("OutRec1", "lDiff", 0);
            int nDiffAttr = m_tranOptionsPrice.getDataAttr("OutRec1", "lDiff", 0);
            // 등락기호
            String strSign = m_tranOptionsPrice.getDataValue("OutRec1", "cPCheck", 0);
            int nSignAttr = m_tranOptionsPrice.getDataAttr("OutRec1", "cPCheck", 0);
            // 등락률
            String strDiffRatio = m_tranOptionsPrice.getDataValue("OutRec1", "lDiffRate", 0);
            int nDiffRatioAttr = m_tranOptionsPrice.getDataAttr("OutRec1", "lDiffRate", 0);

            String strTradeAmount = m_tranOptionsPrice.getDataValue("OutRec1", "lVolume", 0);
            String strTradeMoney = m_tranOptionsPrice.getDataValue("OutRec1", "lValue", 0);

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

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

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

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

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

            requestOptionsPriceReal();
            requestOptionsHogaReal();
        }
        else if(sTranID.equals("선옵매수주문"))
		{
			String strOrderNo = m_tranFutOptBuy.getDataValue("OutRec1", "ORD_NO", 0);

            m_editTradeNo.setText(strOrderNo);

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

            requestChegyul();
            requestJango();
		}
        else if(sTranID.equals("선옵매도주문"))
		{
            String strOrderNo = m_tranFutOptSell.getDataValue("OutRec1", "ORD_NO", 0);

            m_editTradeNo.setText(strOrderNo);

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

            requestChegyul();
            requestJango();
		}
        else if(sTranID.equals("선옵정정주문"))
		{
            String strOrderNo = m_tranFutOptModify.getDataValue("OutRec1", "ORD_NO", 0);

            m_editTradeNo.setText(strOrderNo);

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

            requestChegyul();
            requestJango();
		}
        else if(sTranID.equals("선옵취소주문"))
		{
            String strOrderNo = m_tranFutOptCancel.getDataValue("OutRec1", "ORD_NO", 0);

            m_editTradeNo.setText(strOrderNo);

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

            requestChegyul();
            requestJango();
        }
        else if(sTranID.equals("선옵잔고조회"))
        {
            int nDataCount = m_tranJango.getDataCount("OutRec2");

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

                info.m_strItemCode = m_tranJango.getDataValue("OutRec2", "ITEM_COD", i);
                info.m_strItemName = m_tranJango.getDataValue("OutRec2", "ITEM_NM", i);
                info.m_strGubunName = m_tranJango.getDataValue("OutRec2", "BUY_SEL_TP_NM", i);
                info.m_strAvailQty = m_tranJango.getDataValue("OutRec2", "LQDT_ABLE_Q", i);
                info.m_strHaveQty = m_tranJango.getDataValue("OutRec2", "FUOP_USCTR_Q", i);
                info.m_strUnitPrice = m_tranJango.getDataValue("OutRec2", "USCTR_UPR", i);
                info.m_strAvgPrice = m_tranJango.getDataValue("OutRec2", "FUOP_EA", i);
                info.m_strProfit = m_tranJango.getDataValue("OutRec2", "PL_A", i);

                m_viewJango.addList(info);
            }
        }
        else if(sTranID.equals("선옵미체결내역"))
        {
            int nDataCount = m_tranMiChegyul.getDataCount("OutBlock2");

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

                String strDate = m_tranMiChegyul.getDataValue("OutBlock2", "ORD_DT", i);
                info.m_strOrderNo = m_tranMiChegyul.getDataValue("OutBlock2", "ORD_NO", i);
                info.m_strItemCode = m_tranMiChegyul.getDataValue("OutBlock2", "ITEM_COD", i);
                info.m_strItemName = m_tranMiChegyul.getDataValue("OutBlock2", "ITEM_NM", i);
                info.m_strOrderQty = m_tranMiChegyul.getDataValue("OutBlock2", "ORD_Q", i);
                info.m_strChegyulQty = m_tranMiChegyul.getDataValue("OutBlock2", "CLSN_Q", i);
                info.m_strMicheQty = m_tranMiChegyul.getDataValue("OutBlock2", "ORD_RQ", i);
                info.m_strOrderPrice = m_tranMiChegyul.getDataValue("OutBlock2", "ORD_UPR", i);
                info.m_strChegyulPrice = m_tranMiChegyul.getDataValue("OutBlock2", "CLSN_UPR", i);
                info.m_strOderInfo = m_tranMiChegyul.getDataValue("OutBlock2", "TP_NM", i);

                m_viewChegyul.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)
    {
		if(strRealId.equals("선물체결실시간"))
        {
            int nDataCount = m_realFuturesPrice.getDataCount("OutBlock1");

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

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

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

                if(i == 0) {
                    m_viewItemPrice.setFutPriceInfo(strPrice, nPriceAttr,
                            strSign, nSignAttr, strDiff, nDiffAttr, strDiffRatio, nDiffRatioAttr);
                    m_viewItemPrice.setFutOptTradeInfo(strTradeAmount, strTradeMoney);
                }

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

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

                m_viewItemHoga.setHogaF2(true, nDataIndex, strMaedoHoga, nMaedoHogaAttr, strMaedoRemains);
                m_viewItemHoga.setHogaF2(false, nDataIndex, strMaesuHoga, nMaesuHogaAttr, strMaesuRemains);
            }
		}
        else if(strRealId.equals("옵션체결실시간"))
        {
            int nDataCount = m_realOptionsPrice.getDataCount("OutBlock1");

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

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

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

                if(i == 0) {
                    m_viewItemPrice.setFutPriceInfo(strPrice, nPriceAttr,
                            strSign, nSignAttr, strDiff, nDiffAttr, strDiffRatio, nDiffRatioAttr);
                    m_viewItemPrice.setFutOptTradeInfo(strTradeAmount, strTradeMoney);
                }

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

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

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

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

        if(nId == CTRL_ID_FUTOPT)
        {
            if(m_buttonFutOpt.getText().equals("F"))
            {
                m_buttonFutOpt.setText("O");
                m_spinnerItemCode.setItemList(SmartChampAPI.getInstance().getOptionsCodeList());
            } else {
                m_buttonFutOpt.setText("F");
                m_spinnerItemCode.setItemList(SmartChampAPI.getInstance().getFuturesCodeList());
            }

            m_spinnerItemCode.setItemCode("");
        } else 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_CHEGYUL)
        {
            // 미체결 재조회
            requestChegyul();
        }
    }

    @Override
    public void onSiseListScrollEnd() {

    }

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

        String strType = SmartChampAPI.getInstance().getItemCodeInfo(strItemCode, "type");

        if(strType.equals("J"))
        {
            m_buttonFutOpt.setText("F");
            m_spinnerItemCode.setItemList(SmartChampAPI.getInstance().getFuturesCodeList());
        } else {
            m_buttonFutOpt.setText("O");
            m_spinnerItemCode.setItemList(SmartChampAPI.getInstance().getOptionsCodeList());
        }

        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();
        }
    }

}
