using System.IO;
using System.Net;
using System.Data;
using System.Net.NetworkInformation;

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 기본 마스터 로딩 처리
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Service
{
    class LoadMasterInfo : IServiceUs
    {
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus;                                             // 기본정보 참조
        private TranStatus m_cTrnStatus;                                            // 거래정보 참조
        private DeviceStatus m_cDevStatus;                                          // 장치정보 참조

        private IDataProcessUs m_cDataSrv = null;                                   // 거래데이터 합계금액 계산 및 관리
        private IDataCommonUs m_cDataCommSrv = null;                                // 거래 공통 함수 관리
        private IServiceUs m_cSaveCfgSrv = null;                                    // 설정파일 저장
        private IServiceUs m_cReadCfgSrv = null;                                    // 설정파일 읽기
        private IMasterUs m_cMstService = null;                                     // 마스터 인터페이스
        private IICReaderUs m_cIcReader = null;                                     // IC Reader 관리
        private ISignPadUs m_cSignPad = null;                                       // Signpad 관리

        public LoadMasterInfo()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;              // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;            // POS 거래정보
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;        // POS 장치정보

            m_cDataSrv = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommSrv = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cSaveCfgSrv = (IServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.SAVE_CONFIGINFO);
            m_cReadCfgSrv = (IServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.READ_CONFIGINFO);
            m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
            m_cIcReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            m_cSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);
        }

        /// <summary>
        /// 프로그램 시작(환경파일로딩, 기본마스터 로딩, 서비스 시작)
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string Execute(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                if (aParam.Length == 0)
                {
                    // POS 메시지 마스터 로딩
                    LoadMessageMaster();

                    // 점포마스터 로딩
                    LoadStoreMaster();

                    // 스크린 마스터 로딩
                    LoadScreenMaster();

                    // POS마스터 로딩
                    LoadPosMaster();

                    //// 외식후불 주문(서브)포스 일때 메인포스 데이터베이스 IP 설정
                    //SetMainPosInfo();

                    // 문화마스터 로딩
                    LoadCultureMaster();

                    // POS 옵션 마스터 로딩
                    LoadOptionMaster();

                    // 할인 결제 마스터 로딩
                    LoadPayDcMaster();

                    // 담당자 권한 마스터 로딩
                    LoadPicAuthMaster();

                    // 최종거래번호 설정
                    LoadLastTradeNo();

                    // 현금 알람 금액
                    LoadCashAlarm();

                    // 외부 I/F 정보 조회
                    LoadJoinStorInfo();

                    //#20180418 고객 구매이력 정보 표시 및 해피쿠폰 발송 start, 20180510
                    //적용시 주석 해제
                    LoadSendCpnMstInfo();
                    //#20180418 고객 구매이력 정보 표시 및 해피쿠폰 발송 end, 20180510
                }
                else if (aParam.Length > 0 && aParam[0] == "BASIC_MST_LOAD")
                {
                    // POS 메시지 마스터 로딩
                    LoadMessageMaster();
                    // 점포마스터 로딩
                    LoadStoreMaster();
                    // POS마스터 로딩
                    LoadPosMaster();
                    // POS 옵션 마스터 로딩
                    LoadOptionMaster();
                }
                else if (aParam.Length > 0 && aParam[0] == "CHANGE_MAINPOS_DB")
                {
                    // 외식후불 주문(서브)포스 일때 메인포스 데이터베이스 IP 설정
                    SetMainPosInfo();
                }
                else
                {
                    // POS 메시지 마스터 로딩
                    LoadMessageMaster();
                }

                // IC 리더기 초기화
                m_cIcReader.InitializeDevice();
                // PosDevice.INI --> SpcnPosCfg.ini
                m_cSignPad.UpdateIniConfig();

                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }

        /// <summary>
        /// 점포 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadStoreMaster()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // 점포 마스터 로딩
                sQuery = "SELECT * FROM POSMST..MST_STOR WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";
                DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    PosMstManager.SetMstStore(dtDataInfo.Rows[0]);      // 점포마스터 설정

                    DataRow dr = dtDataInfo.Rows[0];

                    m_cPosStatus.Mst.StorOwnName = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.STOR_OWN_NM);
                    m_cPosStatus.Mst.StorName = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.STORNM);
                    m_cPosStatus.Mst.StorAddr = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.STOR_ADDR);
                    m_cPosStatus.Mst.StorBizPsnNo = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.BIZ_PSN_NO);
                    m_cPosStatus.Mst.StorTelNo = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.TELNO);

                    m_cPosStatus.Mst.VatRudDwLoc = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.VAT_RUD_DW_LOC);
                    m_cPosStatus.Mst.VatRudDwLocMethd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.VAT_RUD_DW_METHD);
                    m_cPosStatus.Mst.DcRudDwLoc = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.DC_RUD_DW_LOC);
                    m_cPosStatus.Mst.DcRudDwLocMethd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.DC_RUD_DW_METHD);
                    m_cPosStatus.Mst.ItemRudDwLoc = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ITEM_RUD_DW_LOC);
                    m_cPosStatus.Mst.ItemRudDwLocMethd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.DC_RUD_DW_METHD);

                    m_cPosStatus.Mst.SeriveFreeDiv = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.SVC_FEE_DIV);
                    m_cPosStatus.Mst.SeriveFreeApplyDiv = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.SVC_FEE_APPLYTRGT_DIV);
                    m_cPosStatus.Mst.SeriveFreeTaxAmtDiv = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.SVC_FEE_TAX_AMT_APPLYDIV);
                    m_cPosStatus.Mst.DrtFrcsDiv = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.DRT_FRCS_DIV);
                    m_cPosStatus.Mst.TaxAmtApplydiv = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.TAX_AMT_APPLY_DIV);
                    m_cPosStatus.Mst.TaxAmtIncludeYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.TAX_AMT_INCLUDE_YN);
                    m_cPosStatus.Mst.TaxAmtCalcMethd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.TAX_AMT_CALC_METHD);
                    m_cPosStatus.Mst.BasicTakeInTaxCd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.BASIC_TAKE_IN_TAX_CD);
                    m_cPosStatus.Mst.BasicTakeOutTaxCd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.BASIC_TAKE_OUT_TAX_CD);
                    // 마스터의 브랜드코드와 문화코드 필드가 null 이면 ini 값으로 정의(2017/03/23)
                    //m_cPosStatus.Mst.MltCultCd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.MLT_CULT_CD);
                    m_cPosStatus.Mst.MltCultCd = CmUtil.IsNull(CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.MLT_CULT_CD), m_cPosStatus.Base.CultureID);
                    m_cPosStatus.Mst.HpyOrdAgreeYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.HPYORD_AGREEYN);
                    m_cPosStatus.Mst.GiftSaleYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.GIF_SALE_YN);
                    m_cPosStatus.Mst.BillMsgDupPrmtYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.BILL_MSG_DUP_PRMT_YN);
                    m_cPosStatus.Mst.BillMsgDupPrtRank = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.BILL_MSG_PRT_RANK);
                    m_cPosStatus.Mst.ReservSaleYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.RESERV_SALE_YN);
                    m_cPosStatus.Mst.ComplexShopType = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.COMPLEX_SHOP_TYPE);
                    m_cPosStatus.Mst.TestStorYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.TEST_STOR_YN);

                    m_cPosStatus.Mst.ETC_IF_DIV = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_DIV);
                    m_cPosStatus.Mst.ETC_IF_FTP_IP = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_FTP_IP);
                    m_cPosStatus.Mst.ETC_IF_FTP_PORT = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_FTP_PORT);
                    m_cPosStatus.Mst.ETC_IF_FTP_ID = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_FTP_ID);
                    m_cPosStatus.Mst.ETC_IF_FTP_PW = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_FTP_PW);
                    m_cPosStatus.Mst.ETC_IF_FTP_PASSIVE = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_FTP_PASSIVE);
                    m_cPosStatus.Mst.ETC_IF_FTP_PATH = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_FTP_PATH);
                    m_cPosStatus.Mst.ETC_IF_URL1 = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_URL1);
                    m_cPosStatus.Mst.ETC_IF_URL2 = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_URL2);
                    m_cPosStatus.Mst.ETC_IF_POS_DIV = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.ETC_IF_POS_DIV);

                    m_cPosStatus.Mst.CdpUseYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.CDP_USE_YN);
                    m_cPosStatus.Mst.CdpMessage = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.CDP_MSG);
                    m_cPosStatus.Mst.LoanLawCertfYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.LOAN_LAW_CERTF_YN);    


                    m_cPosStatus.Mst.PayRudDwLocMethd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.DC_RUD_DW_METHD);
                    //m_cPosStatus.Mst.PayRudDwLoc = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.DC_RUD_DW_LOC);
                    m_cPosStatus.Mst.PayRudDwLoc = "2";//CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.DC_RUD_DW_LOC);

                    // 브랜드코드를 INI로 관리(2016/10/28)
                    // 마스터의 브랜드코드와 문화코드 필드가 null 이면 ini 값으로 정의(2017/03/23)
                    //m_cPosStatus.Base.BrandCd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.BRAND_CD);
                    m_cPosStatus.Base.BrandCd = CmUtil.IsNull(CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.BRAND_CD), m_cPosStatus.Base.BrandCd);
                    m_cPosStatus.Base.CultureID = m_cPosStatus.Mst.MltCultCd;

                    //// 도로공사, 공항공사 관리코드를 DB로 관리(2017/01/11)
                    //m_cPosStatus.Base.OutSDVendConNo = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.OUT_SD_VEND_CON_NO);
                    //m_cPosStatus.Base.OutSDVendCrnrCd = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.OUT_SD_VEND_CRNR_CD);

                    // 해피버즈 사용 여부
                    m_cPosStatus.Mst.HappyBuzzUseYn = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.HAPPY_BUZZ_USE_YN);
                    // 브라우저 키
                    m_cPosStatus.Mst.BrowserKey = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.BROWSER_KEY);
                    if (m_cPosStatus.Mst.BrowserKey == "") m_cPosStatus.Mst.BrowserKey = "SPCPos";
                    // 회사 구분
                    m_cPosStatus.Mst.CorpDiv = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.CORP_DIV).Trim().ToUpper();
                    // 국가 구분
                    m_cPosStatus.Mst.CntryDiv = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.CNTRY_DIV).Trim().ToUpper();
                    // 해피포인트 적립율
                    m_cPosStatus.Mst.HpyPntAccumRate = CmUtil.GetDataRowDouble(dr, PosMst.MST_STORE.DATA.HPY_PNT_ACCUMRATE);

                    //#15274 영수증 문구 추가 요청 start
                    m_cPosStatus.Mst.CompNm = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.COMP_NM);
                    //#15274 영수증 문구 추가 요청 end

                    // INI 파일 설정(마스터 데이터를 INI에 저장)
                    CmMessage m_PosConfig = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);
                    m_PosConfig.GetMessage("POS").MakeMessageOverWrite("BrandCd", m_cPosStatus.Base.BrandCd);
                    // 원격제어 관리를 위한 필드 추가(20170303-CHOCY)
                    m_PosConfig.GetMessage("STORE").MakeMessageOverWrite("Name", m_cPosStatus.Mst.StorName);
                    m_PosConfig.GetMessage("STORE").MakeMessageOverWrite("Address", m_cPosStatus.Mst.StorAddr);
                    m_PosConfig.GetMessage("STORE").MakeMessageOverWrite("Tel", m_cPosStatus.Mst.StorTelNo);

                    m_PosConfig.GetMessage("GLOBAL").MakeMessageOverWrite("CultureID", m_cPosStatus.Base.CultureID);
                    m_PosConfig.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);

                    UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                            , "PayRudDwLoc =>" +m_cPosStatus.Mst.PayRudDwLoc);
                }
                else
                {
                    PosMstManager.SetMstStore(null);
                }
                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }


        /// <summary>
        /// 스크린 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadScreenMaster()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // 스크린 마스터 로딩
                sQuery = "SELECT * FROM POSMST..MST_ITEM_KEY_COMPNT WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";
                DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtDataInfo.Rows)
                    {
                        if (m_cPosStatus.Base.StoreNo == CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.SUB_STOR_CD))
                        {
                            PosMstManager.SetMstScreen(dr);      // 스크린 마스터 설정

                            m_cPosStatus.ScnMst.PosScrnType = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.POS_SCRN_TYPE);
                            m_cPosStatus.ScnMst.FuncScrollUseYn = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.FUNC_SCROLL_USE_YN);
                            m_cPosStatus.ScnMst.ThemeColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.THEME_COLOR);
                            m_cPosStatus.ScnMst.LoginImg = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.LOGIN_IMG);
                            m_cPosStatus.ScnMst.BrandCiImg = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.BRAND_CI_IMG);
                            m_cPosStatus.ScnMst.MainImg = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.MAIN_IMG);
                            m_cPosStatus.ScnMst.WaitImg = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.WAIT_IMG);
                            m_cPosStatus.ScnMst.BookmkUseYn = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.BOOKMK_USE_YN);
                            m_cPosStatus.ScnMst.BookmkItemKeyArray = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.BOOKMK_ITEM_KEY_ARRAY);
                            m_cPosStatus.ScnMst.HqItemKeyLayout = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.HQ_ITEMKEY_LAYOUT);
                            m_cPosStatus.ScnMst.ShopItemkeyLayout = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.SHOP_ITEMKEY_LAYOUT);
                            m_cPosStatus.ScnMst.LClssKeyBasicColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.L_CLSS_KEY_BASIC_COLOR);
                            m_cPosStatus.ScnMst.LClssKeyBasicFontColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.L_CLSS_KEY_BASIC_FONT_COLOR);
                            m_cPosStatus.ScnMst.LClssKeySelColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.L_CLSS_KEY_SEL_COLOR);
                            m_cPosStatus.ScnMst.LClssKeySelFontColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.L_CLSS_KEY_SEL_FONT_COLOR);
                            m_cPosStatus.ScnMst.ItemKeyBasicColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.ITEM_KEY_BASIC_COLOR);
                            m_cPosStatus.ScnMst.ItemKeyBasicFontColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.ITEM_KEY_BASIC_FONT_COLOR);
                            m_cPosStatus.ScnMst.ItemKeySelColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.ITEM_KEY_SEL_COLOR);
                            m_cPosStatus.ScnMst.ItemKeySelFontColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.ITEM_KEY_SEL_FONT_COLOR);
                            m_cPosStatus.ScnMst.ItemKeySelFontColor = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.ITEM_KEY_SEL_FONT_COLOR);
                            m_cPosStatus.ScnMst.FixItemClssCnt = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY_COMPNT.DATA.FIX_ITEM_CLSS_CNT);

                            m_cPosStatus.Base.DesignType = m_cPosStatus.ScnMst.PosScrnType;
                            m_cPosStatus.Base.ThemeType = m_cPosStatus.ScnMst.ThemeColor;

                            break;
                        }
                    }
                }
                else
                {
                    PosMstManager.SetMstScreen(null);
                }
                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }



        /// <summary>
        /// POS 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadPosMaster()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // POS 마스터 로딩
                //sQuery = "SELECT * FROM POSMST..MST_POS WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' AND POS_NO = '" + m_cPosStatus.Base.PosNo + "'";
                //sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";

                // 2017.02.03, 복합매장 서브매장코드 반영
                var fmt = "SELECT A.*, B.COMPLEX_SHOP_STOR_NM AS SUB_STOR_NM  \n"
                        + "  FROM MST_POS A LEFT JOIN MST_COMPLEX_SHOP_STOR B \n"
                        + "    ON A.CMP_CD = B.CMP_CD AND A.STOR_CD = B.STOR_CD AND A.SUB_STOR_CD = B.COMPLEX_SHOP_STOR_CD \n"
                        + "   AND A.USE_YN = '{3}' AND (B.USE_YN = '{3}' OR B.USE_YN IS NULL) \n"
                        + " WHERE A.CMP_CD = '{0}' AND A.STOR_CD = '{1}' AND A.POS_NO = '{2}' ";
                sQuery = string.Format(fmt, m_cPosStatus.Base.CmpCd, m_cPosStatus.Base.StoreNo, m_cPosStatus.Base.PosNo, PosConst.MST_USE_YN.YES);

                DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    PosMstManager.SetMstPos(dtDataInfo.Rows[0]);      // POS 마스터 설정

                    DataRow dr = dtDataInfo.Rows[0];

                    // POS 구분 설정(0:선불, 1:후불)
                    m_cPosStatus.Base.PosType = CmUtil.GetDataRowStr(dr, PosMst.MST_POS.DATA.POS_TYPE);
                    // 메인POS 구분 설정(0:서브POS, 1:메인POS)
                    m_cPosStatus.Base.PosCommunicationType = CmUtil.GetDataRowStr(dr, PosMst.MST_POS.DATA.MAIN_YN);
                    if (m_cPosStatus.Base.PosType == PosConst.POS_TYPE.PRE_PAYMENT) m_cPosStatus.Base.PosCommunicationType = PosConst.MAIN_POS_DIV.MAIN_POS;

                    // 여전법 인증 버전
                    //m_cPosStatus.Base.Auth_POS_SW_Ver = CmUtil.GetDataRowStr(dr, PosMst.MST_POS.DATA.CERTF_VER);
                    // DB관리에서 하드코딩으로 변경 - 문성진대리 요청 2016.11.08
                    // 차후 POS 인증버전이 여러개일 경우 해당 부분 수정하시면 됩니다.
                    //m_cPosStatus.Base.Auth_POS_SW_Ver = "#####SPCPOS11101";

                    //m_cPosStatus.Base.Auth_POS_SW_Ver = "###SPCPCPOS11101";
                    m_cPosStatus.Base.Auth_POS_SW_Ver = "###SPCCLHS011101";


                    // 2017.02.03,  메인포스번호 초기화
                    // m_cPosStatus.Base.MainPosNo = string.Empty;
                    // 2017.02.03,  서브매장정보
                    m_cPosStatus.Base.SubShopNo = CmUtil.GetDataRowStr(dr, PosMst.MST_POS.DATA.SUB_STOR_CD).Trim();
                    m_cPosStatus.Base.SubShopNm = CmUtil.GetDataRowStr(dr, PosMst.MST_POS.DATA.SUB_STOR_NM).Trim();

                    // INI 파일 설정(마스터 데이터를 INI에 저장)
                    // 마스터에서 가져 오기 때문에 INI 저장 안 함(2017.03.24)
                    //CmMessage m_PosConfig = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);
                    //m_PosConfig.GetMessage("POS").MakeMessageOverWrite("PosType", m_cPosStatus.Base.PosType);
                    //m_PosConfig.GetMessage("POS").MakeMessageOverWrite("PosCommunicationType", m_cPosStatus.Base.PosCommunicationType);
                    //m_PosConfig.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);
                }
                else
                {
                    PosMstManager.SetMstPos(null);
                }
                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sRet;
        }

        /// <summary>
        /// 외식후불 주문(서브)포스 일때 메인포스 데이터베이스 IP 설정 
        /// </summary>
        /// <returns></returns>
        private bool SetMainPosInfo()
        {
            try
            {
                if (m_cPosStatus.Base.PosType != PosConst.POS_TYPE.DEFERRED_PAYMENT) return true;

                // 복합매장이고 후불일때는 복합매장구성점포(서브매장코드)가 필수이다.
                if (m_cPosStatus.Mst.ComplexShopType == "2")
                {
                    if (string.IsNullOrWhiteSpace(m_cPosStatus.Base.SubShopNo) || string.IsNullOrWhiteSpace(m_cPosStatus.Base.SubShopNm))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0632);
                        return true;
                    }
                }

                // 메인포스번호 초기화
                m_cPosStatus.Base.MainPosNo = m_cPosStatus.Base.PosNo;
                if (m_cPosStatus.Base.PosCommunicationType != PosConst.MAIN_POS_DIV.SUB_POS) return true;

                var fmt = string.Empty;
                var sql = string.Empty;

                if (m_cPosStatus.Mst.ComplexShopType == "2")
                {
                    // 복합매장

                    //#20171026 복합매장 메인포스가 아닌 주문포스인 경우 자기POS번호에 설정된 IP로 메인포스 IP 설정 start
                    //기존
                    /*
                    fmt = "SELECT TOP 1 * FROM POSMST..MST_POS WHERE CMP_CD = '{0}' AND STOR_CD = '{1}' AND POS_TYPE = '{2}' AND MAIN_YN = '{3}' AND USE_YN = '{4}' AND SUB_STOR_CD = '{5}' ORDER BY POS_NO ";
                    sql = string.Format(fmt, m_cPosStatus.Base.CmpCd
                                           , m_cPosStatus.Base.StoreNo
                                           , PosConst.POS_TYPE.DEFERRED_PAYMENT
                                           , PosConst.MAIN_POS_DIV.MAIN_POS
                                           , PosConst.MST_USE_YN.YES
                                           , m_cPosStatus.Base.SubShopNo
                                           );
                    */
                    //변경
                    
                    fmt = "SELECT B.POS_NO, A.POS_IP \n"
                        + "  FROM POSMST..MST_POS A LEFT OUTER JOIN POSMST..MST_POS B ON A.CMP_CD = B.CMP_CD AND A.STOR_CD = B.STOR_CD AND A.POS_IP = B.POS_IP \n"
                        + " WHERE A.CMP_CD = '{0}' AND A.STOR_CD = '{1}' AND A.POS_TYPE = '{2}' AND A.USE_YN = '{3}' AND A.POS_NO = '{4}' \n"
                        + "   AND B.MAIN_YN = '1' \n"
                        + "   AND B.USE_YN = '1'";
                    sql = string.Format(fmt, m_cPosStatus.Base.CmpCd
                                           , m_cPosStatus.Base.StoreNo
                                           , PosConst.POS_TYPE.DEFERRED_PAYMENT
                                           , PosConst.MST_USE_YN.YES
                                           , m_cPosStatus.Base.PosNo                                           
                                           );
                    
                    //#20171026 복합매장 메인포스가 아닌 주문포스인 경우 자기POS번호에 설정된 IP로 메인포스 IP 설정 end
                }
                else
                {
                    // 단독매장
                    fmt = "SELECT TOP 1 * FROM POSMST..MST_POS WHERE CMP_CD = '{0}' AND STOR_CD = '{1}' AND POS_TYPE = '{2}' AND MAIN_YN = '{3}' AND USE_YN = '{4}' ORDER BY POS_NO ";
                    sql = string.Format(fmt, m_cPosStatus.Base.CmpCd
                                           , m_cPosStatus.Base.StoreNo
                                           , PosConst.POS_TYPE.DEFERRED_PAYMENT
                                           , PosConst.MAIN_POS_DIV.MAIN_POS
                                           , PosConst.MST_USE_YN.YES
                                           );
                }
                DataTable dtData = m_cMstService.Select(new string[] { sql });
                if (dtData == null || dtData.Rows.Count == 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0379);
                    return false;
                }

                var dr = dtData.Rows[0];
                var mainIP = CmUtil.GetDataRowStr(dr, PosMst.MST_POS.DATA.POS_IP).Trim();
                if (string.IsNullOrWhiteSpace(mainIP))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0379);
                    return false;
                }

                // 메인포스 데이터베이스 IP 설정 
                var tmpDbSource = m_cPosStatus.Base.LocalDbSource;
                var arg = mainIP.Split('\\');
                if (arg.Length > 1)
                {
                    m_cPosStatus.Base.LocalDbSource = mainIP.Trim();
                }
                else
                {
                    m_cPosStatus.Base.LocalDbSource = mainIP.Trim() + @"\SPCPOS";
                }

                // 후불 메인POS 번호 
                m_cPosStatus.Base.MainPosNo = CmUtil.GetDataRowStr(dr, PosMst.MST_POS.DATA.POS_NO).Trim();

                // 변경로그 
                var log = string.Empty;
                if (tmpDbSource != m_cPosStatus.Base.LocalDbSource)
                {
                    log = string.Format("Change Database Connection Infomatoin [LocalDatabase:{0}] => [MainPos Database:{1}]"
                                        , tmpDbSource, m_cPosStatus.Base.LocalDbSource);
                }
                else
                {
                    log = string.Format("Database Connection Infomatoin [LocalDatabase:{0}]]", m_cPosStatus.Base.LocalDbSource);
                }
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()", log);


                // Del, 2017.03.17, 변경된 메인POS DB 정보 저장 안함.
                // INI 파일 설정(마스터 데이터를 INI에 저장)
                //CmMessage m_PosConfig = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);
                //m_PosConfig.GetMessage("DATABASE").MakeMessageOverWrite("LocalSource", m_cPosStatus.Base.LocalDbSource);
                //m_PosConfig.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);

                return true;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                return false; 
            }
        }

        /// <summary>
        /// 메시지 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadMessageMaster()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // POS 메시지 마스터 로딩
                sQuery = "SELECT * FROM POSMST..MST_MSG WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND LANG_CD = '" + m_cPosStatus.Base.Country + "'";
                sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";
                DataTable dtMessageData = m_cMstService.Select(new string[] { sQuery });

                MessageManager.Clear();
                if (dtMessageData != null && dtMessageData.Rows.Count > 0)
                {
                    //POS 메시지 마스터 --> 메시지매니저 저장
                    foreach (DataRow dr in dtMessageData.Rows)
                    {
                        MessageManager.SetMessage(
                            CmUtil.GetDataRowStr(dr, PosMst.MST_MSG.DATA.MSG_TYPE),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_MSG.DATA.MSG_NO),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_MSG.DATA.MSG1),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_MSG.DATA.MSG2),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_MSG.DATA.MSG3),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_MSG.DATA.MSG4),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_MSG.DATA.MSG5));
                    }
                    sRet = UserCom.RST_OK;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }

        /// <summary>
        /// 옵션 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadOptionMaster()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // POS 옵션 마스터 로딩
                sQuery = "SELECT * FROM POSMST..MST_POS_OPTN WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' AND (POS_NO = '00' OR POS_NO = '" + m_cPosStatus.Base.PosNo + "')";
                sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";
                sQuery += " ORDER BY POS_NO ASC "; 

                DataTable dtOptionData = m_cMstService.Select(new string[] { sQuery });

                PosMstManager.OptionClear();
                if (dtOptionData != null && dtOptionData.Rows.Count > 0)
                {
                    //POS 옵션 마스터
                    foreach (DataRow dr in dtOptionData.Rows)
                    {
                        PosMstManager.SetPosOption(
                            CmUtil.GetDataRowStr(dr, PosMst.MST_POS_OPTN.DATA.OPTN_CD),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_POS_OPTN.DATA.OPTN_VAL),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_POS_OPTN.DATA.OPTN_NM),
                            CmUtil.GetDataRowStr(dr, PosMst.MST_POS_OPTN.DATA.OPTN_EXPLN));
                    }
                    //sRet = UserCom.RST_OK;
                }

                // 2017.02.03, 후불 주문POS의 특정옵션(주방출력관련)은 메인포스 옵션 우선
                // 2017.03.16, 익일개점여부 는 메인포스 옵션 우선
                if (m_cPosStatus.Base.PosType == PosConst.POS_TYPE.DEFERRED_PAYMENT && 
                    m_cPosStatus.Base.PosCommunicationType == PosConst.MAIN_POS_DIV.SUB_POS)
                {
                    // 메인옵션 대상 
                    // OPT425   주방프린터 자동출력 사용여부	    0:자동 1:수동(프린터선택) 2:수동(상품선택)
                    // OPT506   주방프린터 사용	                0 : 사용 안 함/ 1 : 사용 함
                    // OPT302   익일개점허용여부                 0: 미사용, 1:사용
                    sQuery = "SELECT * FROM POSMST..MST_POS_OPTN \n"
                           + " WHERE CMP_CD = '{0}' AND STOR_CD = '{1}' AND POS_NO = '{2}' AND USE_YN = '{3}' \n"
                           + "   AND OPTN_CD IN ('OPT506','OPT425', 'OPT302') ";
                    sQuery = string.Format(sQuery, m_cPosStatus.Base.CmpCd
                                                 , m_cPosStatus.Base.StoreNo
                                                 , m_cPosStatus.Base.MainPosNo
                                                 , PosConst.MST_USE_YN.YES
                                                 );
                    dtOptionData = m_cMstService.Select(new string[] { sQuery });
                    if (dtOptionData != null && dtOptionData.Rows.Count > 0)
                    {
                        //POS 옵션 마스터
                        foreach (DataRow dr in dtOptionData.Rows)
                        {
                            PosMstManager.SetPosOption(
                                CmUtil.GetDataRowStr(dr, PosMst.MST_POS_OPTN.DATA.OPTN_CD),
                                CmUtil.GetDataRowStr(dr, PosMst.MST_POS_OPTN.DATA.OPTN_VAL),
                                CmUtil.GetDataRowStr(dr, PosMst.MST_POS_OPTN.DATA.OPTN_NM),
                                CmUtil.GetDataRowStr(dr, PosMst.MST_POS_OPTN.DATA.OPTN_EXPLN));
                        }
                    }
                }

                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }

        /// <summary>
        /// 문화 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadCultureMaster()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // 문화 마스터 로딩
                sQuery = "SELECT * FROM POSMST..MST_CULTURE WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND CULTURE_CD = '" + m_cPosStatus.Base.CultureID + "'";
                sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";
                DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    DataRow dr = dtDataInfo.Rows[0];
                    // 문화마스터 설정
                    m_cPosStatus.Global.m_stCultureMaster.strCultureName = CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.CULTURE_NM);
                    m_cPosStatus.Global.m_stCultureMaster.strDatePattern = CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.DT_PATTERN);
                    m_cPosStatus.Global.m_stCultureMaster.strCurrencySymbol = CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.CURR_SYMBL);
                    m_cPosStatus.Global.m_stCultureMaster.strCurrencyName = CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.CURR_NM);
                    m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits = CmUtil.GetDataRowInt(dr, PosMst.MST_CULTURE.DATA.DEC_PNT_DIGITS);
                    m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol = CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.DEC_PNT_SYMBL);
                    m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits = CmUtil.GetDataRowInt(dr, PosMst.MST_CULTURE.DATA.GRP_DIGITS);
                    m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol = CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.GRP_SYMBL);

                    if ( m_cPosStatus.Base.Country != CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.LANG_TYPE))
                    {
                        m_cPosStatus.Base.Country = CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.LANG_TYPE);
                        LoadMessageMaster();
                    }
                    else
                    {
                        m_cPosStatus.Base.Country = CmUtil.GetDataRowStr(dr, PosMst.MST_CULTURE.DATA.LANG_TYPE);
                    }

                    if (System.Threading.Thread.CurrentThread.CurrentCulture.Name == "fr-FR")
                    {
                        // 프랑스 문화권 이면 내부처리 문화는 영어 문화권으로 변경
                        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
                    }
                }

                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }

        /// <summary>
        /// 결제 할인 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadPayDcMaster()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // 결제 할인 마스터 로딩
                {
                    sQuery = "SELECT * FROM POSMST..MST_PAY_DC WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                    sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";
                    sQuery += "  ORDER BY SALE_POS_PRT_QUE, PAY_DC_GRP_TYPE, PAY_DC_CD ";       // 영수증 출력시 중요.

                    DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });
                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                    {
                        PosMstManager.SetMstPayDc(dtDataInfo);
                    }
                }

                // VAN 마스터 로딩
                {
                    sQuery = "SELECT * FROM POSMST..MST_VAN WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                    sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";

                    DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });
                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                    {
                        // VAN마스터의 터미널ID 하드코딩 (2017.05.23)
                        if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.PC)
                        {
                            // 부산역사점(0013096), 08,09번 POS
                            if (m_cPosStatus.Base.StoreNo == "0013096" && (m_cPosStatus.Base.PosNo == "08" || m_cPosStatus.Base.PosNo == "09"))     
                            {
                                foreach(DataRow dr in dtDataInfo.Rows)
                                {
                                    if (CmUtil.GetDataRowStr(dr, PosMst.MST_VAN.DATA.APPR_ID) == "PCR0005121")
                                    {
                                        dr[PosMst.MST_VAN.DATA.APPR_ID] = "PCR0006076";
                                    }
                                }
                            }
                        }

                        PosMstManager.SetMstVan(dtDataInfo);

                        // BIN\SpcnPosCfg.ini 설정 변경용 변수 담기
                        m_cDevStatus.ICReader.VanIP = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.IP);

                        if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                        {
                            // iC Port
                            m_cDevStatus.ICReader.VanPort = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.PORT);
                        }
                        else
                        {
                            // MSR Port
                            m_cDevStatus.ICReader.VanPort = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.MSR_PORT);
                        }

                        m_cIcReader.UpdateIniConfig(m_cDevStatus.ICReader.VanIP, m_cDevStatus.ICReader.VanPort);
                    }
                }

                // 터미널 ID 설정
                m_cPosStatus.Base.OlePosICReaderSerialNumber = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.APPR_ID);

                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }

        /// <summary>
        /// 담당자 권한 마스터 로딩
        /// </summary>
        /// <returns></returns>
        public string LoadPicAuthMaster()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // 담당자 권한 마스터 로딩
                sQuery  = "SELECT * ";
                sQuery += "  FROM POSMST..MST_PIC_AUTH";
                sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "   AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "   AND USE_YN = '" + PosConst.MST_USE_YN.YES + "'";

                DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });
                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    PosMstManager.SetMstPicAuth(dtDataInfo);
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }

        /// <summary>
        /// 최종 거래번호 설정
        /// </summary>
        /// <returns></returns>
        public string LoadLastTradeNo()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;

            try
            {
                // 최종등록번호 로딩
                sQuery = " SELECT MAX(REG_NO) REG_NO FROM POSLOG..ETC_SALE_HEADER ";
                sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'  ";
                sQuery += "  AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                sQuery += "  AND SALE_DT = '" + m_cPosStatus.Base.SaleDate + "' ";
                sQuery += "  AND POS_NO = '" + m_cPosStatus.Base.PosNo + "' ";

                DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    DataRow dr = dtDataInfo.Rows[0];

                    int nRegNo = (int)CmUtil.LongParse(CmUtil.GetDataRowStr(dr, "REG_NO"));
                    if (CmUtil.LongParse(m_cPosStatus.Base.RegNo) <= nRegNo)
                    {
                        m_cPosStatus.Base.RegNo = string.Format("{0:D5}", nRegNo + 1);
                    }
                }

                // 최종거래번호 로딩
                sQuery = " SELECT ISNULL(MAX(TRADE_NO),0) TRADE_NO FROM POSLOG..TR_SALE_HEADER ";
                sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'  ";
                sQuery += "  AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                sQuery += "  AND SALE_DT = '" + m_cPosStatus.Base.SaleDate + "' ";
                sQuery += "  AND POS_NO = '" + m_cPosStatus.Base.PosNo + "' ";
                sQuery += "  AND TRADE_KINDPER NOT IN('90','91','92','93') ";

                DataTable dtTradeInfo = m_cMstService.Select(new string[] { sQuery });

                if (dtTradeInfo != null && dtTradeInfo.Rows.Count > 0)
                {
                    DataRow dr = dtTradeInfo.Rows[0];

                    int nTradeNo = (int)CmUtil.LongParse(CmUtil.GetDataRowStr(dr, "TRADE_NO"));
                    if (CmUtil.LongParse(m_cPosStatus.Base.TradeNo) <= nTradeNo)
                    {
                        m_cPosStatus.Base.TradeNo = string.Format("{0:D5}", nTradeNo + 1);
                    }
                }

                // 최종 중간마감 차수 로딩
                sQuery = " SELECT ISNULL(MAX(MID_CLOSE_SEQ),'0') MID_CLOSE_SEQ FROM POSLOG..TR_SALE_HEADER ";
                sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'  ";
                sQuery += "  AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                sQuery += "  AND SALE_DT = '" + m_cPosStatus.Base.SaleDate + "' ";
                sQuery += "  AND POS_NO = '" + m_cPosStatus.Base.PosNo + "' ";
                sQuery += "  AND TRADE_KINDPER = '" + ItemConst.TRAN_KIND.STATEMENT.MIDDLE_ADJUSTMENT + "' ";
                sQuery += "  AND ISNULL(MID_CLOSE_SEQ, '0') <> '99' ";

                DataTable dtMidCloseSeqInfo = m_cMstService.Select(new string[] { sQuery });

                if (dtMidCloseSeqInfo != null && dtMidCloseSeqInfo.Rows.Count > 0)
                {
                    DataRow dr = dtMidCloseSeqInfo.Rows[0];

                    int nMidCloseSeq = (int)CmUtil.LongParse(CmUtil.GetDataRowStr(dr, "MID_CLOSE_SEQ"));
                    if (CmUtil.LongParse(m_cPosStatus.Base.MidCloseSeq) <= nMidCloseSeq)
                    {
                        m_cPosStatus.Base.MidCloseSeq = string.Format("{0:00}", nMidCloseSeq + 1);
                    }
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }

       
        /// <summary>
        /// 현금 알람 금액
        /// </summary>
        /// <returns></returns>
        public string LoadCashAlarm()
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;
            DataTable dtDataInfo = null;

            try
            {

                m_cPosStatus.Mst.CashAlarmAmt = 0;

                if (CmUtil.IsNull(PosMstManager.GetPosOption(POS_OPTION.OPT310), "0") != "0")
                {
                    //입출금 체크
                    sQuery = " SELECT ISNULL(SUM(CASE WHEN DPST_WTHDR_CD ='01' THEN DPST_WTHDR_AMT ELSE DPST_WTHDR_AMT * (-1) END),0) AS CASH_AMT ";
                    sQuery += "   FROM POSLOG..ETC_SALE_DPST_WTHDR ";
                    sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'  ";
                    sQuery += "  AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                    sQuery += "  AND SALE_DT = '" + m_cPosStatus.Base.SaleDate + "' ";
                    sQuery += "  AND POS_NO = '" + m_cPosStatus.Base.PosNo + "' ";

                    dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                    {
                        DataRow dr = dtDataInfo.Rows[0];
                        m_cPosStatus.Mst.CashAlarmAmt = CmUtil.DoubleParse(CmUtil.GetDataRowStr(dr, "CASH_AMT"));
                    }

                    //현금 결제 금액 체크
                    sQuery = " SELECT ";
                    sQuery += " ISNULL(SUM(CASE WHEN P.PAY_WAY_CD = '" + ItemConst.TR_ITEM_ID.CASH_ITEM + "' OR P.PAY_WAY_CD = '" + ItemConst.TR_ITEM_ID.CHECK_ITEM + "' THEN  ";
                    sQuery += "              CASE WHEN H.TRADE_DIV ='"+ ItemConst.TRAN_DIV.NORMAL +"' THEN P.PAY_AMT ELSE P.PAY_AMT * (-1) END";
                    sQuery += "            ELSE ";
                    sQuery += "              CASE WHEN H.TRADE_DIV ='" + ItemConst.TRAN_DIV.NORMAL + "' THEN P.AMT_ENTRY_02 * (-1) ELSE P.AMT_ENTRY_02 END ";
                    sQuery += "            END ),0) AS CASH_AMT ";
                    sQuery += " FROM POSLOG.dbo.TR_SALE_HEADER H WITH(NOLOCK) ";
                    sQuery += "     INNER JOIN POSLOG.dbo.TR_SALE_PAY P WITH(NOLOCK) ";
                    sQuery += "      ON H.CMP_CD   = P.CMP_CD ";
                    sQuery += "     AND H.SALE_DT  = P.SALE_DT ";
                    sQuery += "     AND H.STOR_CD  = P.STOR_CD ";
                    sQuery += "     AND H.POS_NO   = P.POS_NO ";
                    sQuery += "     AND H.TRADE_NO = P.TRADE_NO ";
                    sQuery += "  WHERE H.CMP_CD  = '" + m_cPosStatus.Base.CmpCd + "'  ";
                    sQuery += "    AND H.STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                    sQuery += "    AND H.SALE_DT = '" + m_cPosStatus.Base.SaleDate + "' ";
                    sQuery += "    AND H.POS_NO  = '" + m_cPosStatus.Base.PosNo + "' ";
                    sQuery += "    AND H.TRADE_DIV IN ('" + ItemConst.TRAN_DIV.NORMAL + "','" + ItemConst.TRAN_DIV.REFUND + "')  ";                     // 정상, 반품
                    sQuery += "    AND H.TRAIN_MODE_YN = '0'   ";                       // 일반
                    sQuery += "    AND H.TRADE_KINDPER IN ('" + ItemConst.TRAN_KIND.NORMAL.SALE + "','" + ItemConst.TRAN_KIND.UNDECIDED.RESERVATION_REG + "','" + ItemConst.TRAN_KIND.UNDECIDED.RESERVATION_COMPLETE + "')  ";          // 매출, 예약(등록/완료)
                    sQuery += "    AND ( ";
                    sQuery += "          P.PAY_WAY_CD IN ('" + ItemConst.TR_ITEM_ID.CASH_ITEM + "','" + ItemConst.TR_ITEM_ID.CHECK_ITEM + "','" + ItemConst.TR_ITEM_ID.GIFT_ITEM + "','" + ItemConst.TR_ITEM_ID.FOREIGNEX_ITEM + "') ";       // 현금, 수표, 상품권, 외환
                    sQuery += "       OR P.PAY_WAY_CD + P.PAY_DTL_CD_01 IN ('" + ItemConst.TR_ITEM_ID.PAYETC_ITEM + ItemConst.TR_ITEM_ID.PAYETC.MEAL_TIKET + "') ";  //식권
                    sQuery += "         )  ";

                    dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                    {
                        DataRow dr = dtDataInfo.Rows[0];
                        m_cPosStatus.Mst.CashAlarmAmt = CmUtil.DoubleAdd(m_cPosStatus.Mst.CashAlarmAmt, CmUtil.DoubleParse(CmUtil.GetDataRowStr(dr, "CASH_AMT")));
                    }
                }

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return sRet;
        }

        #region I/F 점포정보 조회
        /// <summary>
        /// I/F 점포정보 조회
        /// </summary> 
        /// <returns></returns>
        private void LoadJoinStorInfo()
        {
            string sQuery = string.Empty;
            DataTable dtDataInfo = null;

            try
            {
                m_cPosStatus.Mst.JOIN_CMP_CD = "";
                m_cPosStatus.Mst.JOIN_BRAND_CD = "";
                m_cPosStatus.Mst.JOIN_STOR_CD = "";
                m_cPosStatus.Mst.JOIN_ITEM_CD = "";

                sQuery = "";
                sQuery += "SELECT TOP 1  \n";
                sQuery += "		CMP_CD  \n";
                sQuery += "	,	STOR_CD \n";
                sQuery += "	,	ISNULL(JOIN_CMP_CD, '')		JOIN_CMP_CD \n";
                sQuery += "	,	ISNULL(JOIN_BRAND_CD, '')	JOIN_BRAND_CD \n";
                sQuery += "	,	ISNULL(JOIN_STOR_CD, '')	JOIN_STOR_CD \n";
                sQuery += "	,	ISNULL(JOIN_ITEM_CD, '')	JOIN_ITEM_CD \n";
                sQuery += "FROM POSMST..MST_OUT_SD_VEND_STOR \n";
                sQuery += "WHERE  \n";
                sQuery += "	   CMP_CD	= '" + m_cPosStatus.Base.CmpCd + "' \n";
                sQuery += "AND STOR_CD  = '" + m_cPosStatus.Base.StoreNo + "' \n";
                sQuery += "AND POS_NO	IN ('00', '" + m_cPosStatus.Base.PosNo + "') \n";
                sQuery += "AND USE_YN	= '" + PosConst.MST_USE_YN.YES + "' \n";
                sQuery += "ORDER BY POS_NO DESC \n";

                // 조회
                dtDataInfo = m_cMstService.Select(new string[] { sQuery });
                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    DataRow dr = dtDataInfo.Rows[0];
                    m_cPosStatus.Mst.JOIN_CMP_CD = CmUtil.GetDataRowStr(dr, "JOIN_CMP_CD");
                    m_cPosStatus.Mst.JOIN_BRAND_CD = CmUtil.GetDataRowStr(dr, "JOIN_BRAND_CD");
                    m_cPosStatus.Mst.JOIN_STOR_CD = CmUtil.GetDataRowStr(dr, "JOIN_STOR_CD");
                    m_cPosStatus.Mst.JOIN_ITEM_CD = CmUtil.GetDataRowStr(dr, "JOIN_ITEM_CD");
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return;
        }
        #endregion 

        //#20180418 고객 구매이력 정보 표시 및 해피쿠폰 발송 start, 20180510
        
        #region 고객 구매이력 조회 마스터 조회
        /// <summary>
        /// 고객 구매이력 조회 마스터 조회
        /// </summary> 
        /// <returns></returns>
        private void LoadSendCpnMstInfo()
        {
            string sQuery = string.Empty;
            DataTable dtDataInfo = null;

            try
            {
                m_cPosStatus.Mst.HpyCokStorYn   = "0";
                m_cPosStatus.Mst.BuyHistShowYn  = "0";
                m_cPosStatus.Mst.CpnSendYn      = "0";

                sQuery = "";
                sQuery += "SELECT CMP_CD  \n";
                sQuery += "	    , STOR_CD \n";
                sQuery += "	    , ISNULL(HAPPY_YN, '0')	HAPPY_YN \n";
                sQuery += "	    , ISNULL(PRINT_YN, '0')	PRINT_YN \n";
                sQuery += "	    , ISNULL(SEND_YN, '0')	SEND_YN \n";
                //#20180418 고객 구매이력 정보 표시 및 해피쿠폰 발송 start, 20180528
                //쿠폰 발송 횟수 제한 기능
                sQuery += "	    , ISNULL(CPN_SEND_LIMIT_CNT, '0')	CPN_SEND_LIMIT_CNT \n";
                //#20180418 고객 구매이력 정보 표시 및 해피쿠폰 발송 end, 20180528
                sQuery += "  FROM POSMST..STR_SEND_CPN_MST \n";
                sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' \n";
                sQuery += "   AND STOR_CD  = '" + m_cPosStatus.Base.StoreNo + "' \n";

                // 조회
                dtDataInfo = m_cMstService.Select(new string[] { sQuery });
                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    DataRow dr = dtDataInfo.Rows[0];
                    m_cPosStatus.Mst.HpyCokStorYn   = CmUtil.GetDataRowStr(dr, "HAPPY_YN");
                    m_cPosStatus.Mst.BuyHistShowYn  = CmUtil.GetDataRowStr(dr, "PRINT_YN");
                    m_cPosStatus.Mst.CpnSendYn      = CmUtil.GetDataRowStr(dr, "SEND_YN");

                    //#20180418 고객 구매이력 정보 표시 및 해피쿠폰 발송 start, 20180528
                    //쿠폰 발송 횟수 제한 기능
                    m_cPosStatus.Mst.CpnSendLimitCnt = CmUtil.GetDataRowStr(dr, "CPN_SEND_LIMIT_CNT");
                    //#20180418 고객 구매이력 정보 표시 및 해피쿠폰 발송 end, 20180528
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return;
        }
        #endregion
        
        //#20180418 고객 구매이력 정보 표시 및 해피쿠폰 발송 end, 20180510
    }
}
