using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using System.Data;

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 온라인쿠폰(중국)
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmOnLineCoupon : frm_PayMainBack
    {

        #region 변수 선언

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조        
        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private IDataProcessUs m_cDataService = null;                               // 거래데이터 합계금액 계산 및 관리
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IPaymentUs m_cOnLineCoupon = null;
        
        private bool bNotDoubleClik = false;                                        // 더블 클릭 방지용

        private string m_sPosMenuKey;
        /// <summary>
        /// POS 기능키
        /// </summary>
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } }

        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = "";
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";
        
        /// <summary>
        /// 리스트 데이터
        /// </summary>
        private DataTable m_dtGridList;
        
        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmOnLineCoupon()
        {
            InitializeComponent();

            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
            //this.UpdateStyles();

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

            m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cOnLineCoupon = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.ONLINE_COUPON);
        }

        private void frmOnLineCoupon_Load(object sender, EventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
            InitControl();
        }

        private void frmOnLineCoupon_Activated(object sender, EventArgs e)
        {

        }

        private void frmOnLineCoupon_Deactivate(object sender, EventArgs e)
        {

        }

        private void frmOnLineCoupon_FormClosing(object sender, FormClosingEventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
        }

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
                FormManager.SetTextBoxGlobalInfo(this, m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits, m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol
                    , m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits, m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol);

                // 온라인 쿠폰 등록
                this.Location = new Point(0, 50);
                this.Size = new Size(1024, 525);
                btnUp.Visible = false;
                btnDown.Visible = false;
                gridList.Visible = false;
                lblCouponInfo.Visible = true;

                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0057);

                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);

                // 버튼이미지 적용
                btnUp.Image         = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnUp.ImageAlign    = ContentAlignment.MiddleCenter;
                btnUp.BorderStyle   = BorderStyle.None;
                if (btnUp.Image != null) btnUp.Text = "";
                btnDown.Image       = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                btnDown.ImageAlign  = ContentAlignment.MiddleCenter;
                btnDown.BorderStyle = BorderStyle.None;
                if (btnDown.Image != null) btnDown.Text = "";

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0958);
                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0139);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                
                InitializeGrid();
                InitPayMainBack(m_cPosStatus, m_cDataCommon, m_sPosMenuKey, PosConst.MOT_MSG_TYPE.PAY_STEP_2, "");

                ClearCardInfo();                // 입력 정보 클리어
                bNotDoubleClik = false;

                lblCouponInfo.Text = "";
                txtCardNo.Value = "";
                txtCardNo.ReadOnly = false;
                txtCardNo.Select();
                txtCardNo.SelectText();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        /// <summary>
        /// 그리드 초기화
        /// </summary>
        private void InitializeGrid()
        {
            try
            {
                gridList.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 10, gridList.CsmGridColumnHeadersFont.Style);

                //DataGridView 자체의 컬럼 헤더 Visible 여부
                gridList.CsmGridColumnHeadersVisible = true;
                //DataGridView 자체의 컬럼 헤더 높이
                gridList.CsmGridColumnHeadersHeight = 32;
                gridList.CsmGridRowsHeight = 33;

                //그리드의 컬럼 수
                gridList.CsmGridColumnCount = 2;
                //그리드의 한 화면에 보이는 로우수
                gridList.CsmGridShowPageRowsCount = 5;

                gridList.CsmGridSetHeaderBackColor(236, 238, 239);                             //그리드 헤더 배경색
                gridList.CsmGridDefaultRowBackColor = Color.FromArgb(255, 255, 255);           //그리드 홀수(Default)행의 배경색 지정
                gridList.CsmGridAlternateRowBackColor = Color.FromArgb(251, 253, 255);         //그리드 짝수(Alternate)행의 배경색 지정
                gridList.CsmGridBackGroundColor = Color.FromArgb(251, 253, 255);               //기본 백그라운드 컬러
                gridList.CsmGridHighlightColor = Color.FromArgb(255, 251, 211);                //그리드 선택 백 컬러
                gridList.CsmGridHighlightTextColor = Color.Black;                              //그리드 선택 글자 컬러

                //각 컬럼별 이름 지정
                gridList.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0178));
                gridList.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0015));

                //컬럼넓이 지정(406)
                gridList.CsmGridSetColumnWidth(new int[] { 110, 300 });

                //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                gridList.CsmGridAlignment(new int[] { 0, 0 });

                m_dtGridList = new DataTable("GRID_LIST");
                m_dtGridList.Columns.Add(new DataColumn("PLU_CD", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("PLU_NM", typeof(string)));
                
                m_dtGridList.Clear();
                gridList.CsmGridDataSource = m_dtGridList;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// 쿠폰 입력 정보 클리어
        /// </summary>
        private void ClearCardInfo()
        {
            try
            {
                m_sInPutType = "";      // 입력구분
                m_sInPutData = "";      // 입력데이터
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

                if (((Cosmos.UI.CsmButton)sender) == btnSearch)         // 조회
                {
                    SearchTxtInPut();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)     // 승인
                {
                    CompleteTxtInPut();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnUp)
                {
                    gridList.CsmGridScroll("UP");
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnDown)
                {
                    gridList.CsmGridScroll("DOWN");
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnExit)
                {
                    bNotDoubleClik = false;

                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                    return;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                bNotDoubleClik = false;
            }
            bNotDoubleClik = false;
        }
        #endregion

        #region 텍스트박스 키 입력 이벤트 처리
        /// <summary>
        /// 텍스트박스 키 입력 이벤트 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sFuncValue"></param>
        private void txtEditBox_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

                if (sFuncValue == PosKey.MENU_KEY.ENTER)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                    {
                        if (CheckTxtInPut(sender) == false)
                        {
                            bNotDoubleClik = false;
                            return;
                        }
                        if (m_sInPutData == "")
                        {
                            SearchTxtInPut();       // 쿠폰조회
                        }
                        else
                        {
                            CompleteTxtInPut();     // 쿠폰승인
                        }
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    // 입력 정보 클리어
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo) ClearCardInfo();        
                    if (((Cosmos.UI.CsmPosEditBox)sender).ReadOnly == false) ((Cosmos.UI.CsmPosEditBox)sender).Text = "";
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                bNotDoubleClik = false;
            }
            bNotDoubleClik = false;
        }

        /// <summary>
        /// 텍스트박스 활성화 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtEditBox_EnterEvent(object sender, EventArgs e)
        {
            try
            {
                padInPut.SetActiveControl = (Control)sender;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 텍스트박스 입력 유효성 체크
        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender)
        {
            try
            {
                // 쿠폰번호 길이 체크
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                {
                    if (txtCardNo.Value.Length != 16)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0080);
                        txtCardNo.Focus();
                        txtCardNo.SelectText();
                        return false;
                    }

                    string sCouponKind = CmUtil.MidH(txtCardNo.Value, 8, 1);     // 쿠폰종류	1	1:교환권, 2:증정권, 3:금액권, 4:할인권, 5:상품지정할인권
                    if (CmUtil.IntParse(sCouponKind) < 1 || CmUtil.IntParse(sCouponKind) > 5)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0080);
                        txtCardNo.Focus();
                        txtCardNo.SelectText();
                        return false;
                    }

                    // 입력된 번호 변경 체크
                    if (txtCardNo.Value != m_sInPutData)
                    {
                        ClearCardInfo();        // 입력 정보 클리어
                    }
                }
                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;
        }
        #endregion

        #region 입력 완료 처리
        /// <summary>
        /// 온라인 쿠폰 조회
        /// </summary>
        /// <returns></returns>
        private bool SearchTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (CheckTxtInPut(null) == false) return false;

                m_sInPutType = "K";         // WCC(리딩구분자)	1	N	A: Barcode, K: Keyin 
                m_sInPutData = "";

                // 쿠폰 조회
                string[] saRecvdData = null;
                sRet = m_cOnLineCoupon.SearchPayment(new string[] { m_sInPutType, txtCardNo.Value, "20" }, ref saRecvdData);
                
                Column.TR_PAYMENT.DATA cPayItem = (Column.TR_PAYMENT.DATA)m_cOnLineCoupon.GetPayment(new string[] { });
                if (sRet == UserCom.RST_OK)
                {
                    m_sInPutData = txtCardNo.Value;

                    //#20180821 해피포인트 고객이름 마스킹 start
                    if (cPayItem.HP_CUST_NAME != "") { cPayItem.HP_CUST_NAME = m_cDataCommon.NameMasking(cPayItem.HP_CUST_NAME); }
                    //#20180821 해피포인트 고객이름 마스킹 end
                    lblCouponInfo.Text = cPayItem.HP_CUST_NAME + PosConst.CRLF + PosConst.CRLF;             // 쿠폰명
                    lblCouponInfo.Text += cPayItem.OCCUR_ENTRY_19 + PosConst.CRLF + PosConst.CRLF;          // 쿠폰종류명

                    string sCouponKind = CmUtil.MidH(m_sInPutData, 8, 1);     // 쿠폰종류	1	1:교환권, 2:증정권, 3:금액권, 4:할인권, 5:상품지정할인권
                    if (sCouponKind == "3")
                    {
                        lblCouponInfo.Text += m_cPosStatus.Global.NumericTOCurrency(cPayItem.AMT_ENTRY_01); // 액면가
                    }
                    else if (sCouponKind == "4")
                    {
                        lblCouponInfo.Text += m_cPosStatus.Global.NumericTOCurrency(cPayItem.AMT_ENTRY_03); // 할인금액
                    }
 
                    gridList.Visible = false;
                    btnUp.Visible = false;
                    btnDown.Visible = false;
                    lblCouponInfo.Visible = true;
                }
                else
                {
                    m_dtGridList.Clear();
                    gridList.CsmGridDataSource = m_dtGridList;

                    // 앞자리 3자리: 상품코드 개수, 승인정상응답시 해당교환상품코드
                    if (cPayItem.HP_RESERVED.Length > 3)
                    {
                        int nResPluCnt = CmUtil.IntParse(CmUtil.MidH(cPayItem.HP_RESERVED, 0, 3));
                        for (int i = 0; i < nResPluCnt; i++)
                        {
                            string sResPluCode = CmUtil.MidH(cPayItem.HP_RESERVED, i * 10 + 3, 10).Trim();
                            string sResPluName = "";

                            DataTable dt = m_cDataCommon.SeletItemMstToItemCode(m_cPosStatus.Base.StoreNo, sResPluCode);
                            if ( dt != null && dt.Rows.Count > 0)
                            {
                                DataRow dr = dt.Rows[0];
                                sResPluName = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);
                            }

                            if (sResPluName != "")
                            {
                                DataRow drNewRow = m_dtGridList.NewRow();
                                drNewRow["PLU_CD"] = sResPluCode;
                                drNewRow["PLU_NM"] = sResPluName;

                                m_dtGridList.Rows.Add(drNewRow);
                            }
                        }
                    }

                    gridList.CsmGridDataSource = m_dtGridList;
                    gridList.CsmGridSelectRow(0);

                    gridList.Visible = true;
                    btnUp.Visible = true;
                    btnDown.Visible = true;
                    lblCouponInfo.Visible = false;
                }

                txtCardNo.SelectText();

                if (sRet == UserCom.RST_OK) 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>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private bool CompleteTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (CheckTxtInPut(null) == false) return false;

                // 쿠폰 승인
                m_sInPutType = "K";         // WCC(리딩구분자)	1	N	A: Barcode, K: Keyin 
                if (m_sInPutData == "")
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0593);
                    txtCardNo.SelectText();
                    return false;
                }

                // 온라인 쿠폰 등록 처리
                sRet = m_cOnLineCoupon.SetPayment(new string[] { m_sInPutType, txtCardNo.Value });
                if (sRet != UserCom.RST_OK)
                {
                    txtCardNo.SelectText();
                    return false;
                }

                this.DialogResult = DialogResult.OK;
                this.Close();

                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;
        }
        #endregion

        private void gridList_Enter(object sender, EventArgs e)
        {
            padInPut.SetActiveFocus();
        }

        private void gridList_GridClickEvent(object sender, string rowIndex)
        {
            try
            {
                txtCardNo.Focus();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }        

    }
}
