using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

namespace Cosmos.Win
{
    public partial class frmTPayConnectList : Form
    {
        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 ITPaygleUs m_cDeviceTPaygle = null;

        /// <summary>
        /// 접속고객정보
        /// </summary>
        private Column.TPAY_CONNECT_INFO m_connectInfo = null;
        /// <summary>
        /// 수신 OTB 
        /// </summary>
        private string m_OTB = string.Empty;
        /// <summary>
        /// 중복입력방지 
        /// </summary>
        private bool isBusy = false; 

        /// <summary>
        /// 수신 OTB 
        /// </summary>
        public string OTB { get { return m_OTB; } }
        /// <summary>
        /// 수신 OTB Clear
        /// </summary>
        public void ClearOTB()
        {
            CmUtil.ZeroFillClear(ref m_OTB);
        }
        
        public frmTPayConnectList()
        {
            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;                        //POS 장치정보

            m_cDeviceTPaygle = (ITPaygleUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_TPAYGLE);
        }

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

                if (PosMstManager.GetPosOption(POS_OPTION.OPT319) != "1")
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0414);
                    this.ClearOTB();
                    this.DialogResult = System.Windows.Forms.DialogResult.Abort;
                    this.Close();
                    return;
                }

                this.Tag = "START";

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

        private void Form_Activated(object sender, EventArgs e)
        {
            try
            {
                PosOLEDevice.SetEventHandle(null);

                // BLE 스캔 
                if (this.Tag.ToString() == "START")
                {
                    this.Tag = string.Empty;
                    GetConnectList();
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }

        private void Form_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }

        private void Form_Closing(object sender, FormClosingEventArgs e)
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.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);
            }
        }

        /// <summary>
        /// 화면 컨트롤 초기화 
        /// </summary>
        private void InitControls()
        {
            try
            {
                this.picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                this.picBack.Location = new Point(0, 0);
                this.picBack.SendToBack();
                this.pnlBleBack.Location = new Point(22, 67);
                this.pnlBleBack.Visible = true;
                this.Size = this.picBack.Size = this.picBack.Image.Size;

                FormManager.MovePopUpForm(this, true, m_cPosStatus.Sale.ScreenSizeUser);
                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);

                //테마색상 적용!
                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);

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

                btnGridUp.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_GRID_UP_ARROW);
                btnGridUp.ImageAlign = ContentAlignment.MiddleCenter;
                btnGridUp.BorderStyle = BorderStyle.None;
                btnGridDown.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_GRID_DOWN_ARROW);
                btnGridDown.ImageAlign = ContentAlignment.MiddleCenter;
                btnGridDown.BorderStyle = BorderStyle.None;

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0835) + " - "
                              + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0836);
                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0309);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0126);

                isBusy = false;

                this.ClearOTB();
            }
            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.CsmGridClear();
                gridList.CsmGridDataSource = null;

                gridList.CsmGridColumnHeadersVisible = true;
                gridList.CsmGridColumnHeadersHeight = 38;
                gridList.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 11, FontStyle.Bold);

                gridList.CsmGridColumnCount = 4;
                gridList.CsmGridRowsHeight = 37;
                gridList.CsmGridShowPageRowsCount = 6;
                gridList.Font = new Font(m_cPosStatus.Base.FONT, 11, FontStyle.Regular);

                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.CsmGridSetColumnWidth(new int[] { 40, 150, 150, 377 });
                // 컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                gridList.CsmGridAlignment(new int[] { 1, 0, 0, 0, 0 });

                // 컬럼명 설정
                gridList.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                gridList.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0367));
                gridList.CsmGridColumnName(2, string.Empty);
                gridList.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0279));
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }

        private void Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.isBusy) return;

                if (sender == btnExit)
                {
                    this.ClearOTB();
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();                
                }
                else if (sender == btnGridUp)
                {
                    gridList.CsmGridScroll("UP");
                }
                else if (sender == btnGridDown)
                {
                    gridList.CsmGridScroll("DOWN");
                }
                else if (sender == btnSearch)           // 고객 검색
                {
                    GetConnectList();
                }
                else if (sender == btnEnter)            // 고객 등록 (OTB 요청/수신)
                {
                    if (SetCustomer() == true)
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }

        private void picBLE_Click(object sender, EventArgs e)
        {
            Button_Click(btnSearch, new EventArgs());
        }

        /// <summary>
        /// 접속고객목록 검색 
        /// </summary>
        private void GetConnectList()
        {
            try
            {
                this.isBusy = true;

                this.pnlBleBack.Visible = true;
                //this.lblGuidMsg.ForeColor = Color.RoyalBlue;
                this.lblGuidMsg.ForeColor = Color.FromArgb(70, 86, 98);
                this.lblGuidMsg.Text = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0006);
                this.Update();

                gridList.CsmGridClear();
                gridList.CsmGridDataSource = null;
                gridList.SuspendLayout();

                m_connectInfo = null;
                int cnt = this.m_cDeviceTPaygle.GetConnectList(out m_connectInfo);
                if (cnt < 0)
                {
                    this.lblGuidMsg.ForeColor = Color.OrangeRed;
                    this.lblGuidMsg.Text = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0007);
                    return;
                }
                if (cnt == 0)
                {
                    //this.lblGuidMsg.ForeColor = Color.RoyalBlue;
                    this.lblGuidMsg.ForeColor = Color.FromArgb(70, 86, 98);
                    this.lblGuidMsg.Text = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0007);
                    return;
                }

                DataTable dt = new DataTable("CONNECT_LIST");
                dt.Columns.Add(new DataColumn("NO", typeof(string)));
                dt.Columns.Add(new DataColumn("NAME", typeof(string)));
                dt.Columns.Add(new DataColumn("ALIAS", typeof(string)));
                dt.Columns.Add(new DataColumn("TELNO", typeof(string)));

                for (var i = 0; i < m_connectInfo.LIST.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["NO"] = i + 1;
                    dr["NAME"] = m_connectInfo.LIST[i].NAME;
                    dr["ALIAS"] = m_connectInfo.LIST[i].NICK_NAME;
                    dr["TELNO"] = m_connectInfo.LIST[i].MDN;
                    dt.Rows.Add(dr);
                }

                gridList.CsmGridDataSource = dt;
                gridList.ResumeLayout();
                gridList.CsmGridSelectRow(0);

                this.pnlBleBack.Visible = false;

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

        /// <summary>
        /// 고객등록
        /// </summary>
        /// <returns></returns>
        private bool SetCustomer()
        {
            try
            {
                this.isBusy = true;

                if (gridList.CsmGridRowsCount == 0) return false;

                int idx = gridList.CsmGridSelectedRowIndex;
                if (idx < 0) return false;
                if (idx > gridList.CsmGridRowsCount) return false;

                this.pnlBleBack.Visible = true;
                //this.lblGuidMsg.ForeColor = Color.RoyalBlue;
                this.lblGuidMsg.ForeColor = Color.FromArgb(70, 86, 98);
                this.lblGuidMsg.Text = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0008);
                this.Update();

                bool ret = false;
                string errMsg = string.Empty;
                ret = m_cDeviceTPaygle.ReqPosProvide(m_connectInfo.LIST[idx].XPT, m_connectInfo.POSID, m_connectInfo.LIST[idx].DEVICE_TYPE, out errMsg);
                if (ret == false)
                {
                    errMsg = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0540);        // +"\n(" + errMsg + ")";
                    WinManager.ErrorMessage(errMsg);
                    return false;
                }

                string result = string.Empty;
                ret = m_cDeviceTPaygle.GetOTB(out result);
                if (ret == false)
                {
                    errMsg = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0541);        // +"\n(" + result + ")";
                    WinManager.ErrorMessage(errMsg);
                    return false;
                }

                // 수신 OTB 저장 
                this.m_OTB = result;
                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;
            }
            finally
            {
                if (gridList.CsmGridRowsCount > 0) 
                    this.pnlBleBack.Visible = false;
                this.isBusy = false; 
            }
        }
    }
}
