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.Common;
using Cosmos.CommonManager;
using Cosmos.ServiceProvider;

namespace Cosmos.Win
{
    public partial class frmVenderSearch : Form
    {
        #region 변수 선언
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출

        private IDataServiceUs m_cSchVender = null;                                    // 매입처 조회 인터페이스

        private string m_sPosMenuKeyOut;
        public string PosMenuKeyOut { set { m_sPosMenuKeyOut = value; } get { return m_sPosMenuKeyOut; } }
        private string m_sPosMenuKeyOut2;
        public string PosMenuKeyOut2 { set { m_sPosMenuKeyOut2 = value; } get { return m_sPosMenuKeyOut2; } }

        private DataTable m_dtItemInit;                                             // 조회 데이터 리스트

        private bool bNotDoubleClik = false;                                        // 더블 클릭 방지용
        #endregion 변수 선언

        #region 생성자 & 소멸자
        public frmVenderSearch()
        {
            InitializeComponent();

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

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cSchVender = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_BASIC.VENDER_SEARCH);  // 행사주문 취합내역조회 인터페이스
        }

        private void frmVenderSearch_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 frmVenderSearch_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);
        }
        #endregion 생성자 & 소멸자

        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                this.Size = new Size(788, 402);

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

                //버튼이미지 적용
                btnAllUp.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_UP2_BASIC);
                btnAllUp.ImageAlign = ContentAlignment.MiddleCenter;
                btnAllUp.BorderStyle = BorderStyle.None;
                btnAllDw.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_DOWN2_BASIC);
                btnAllDw.ImageAlign = ContentAlignment.MiddleCenter;
                btnAllDw.BorderStyle = BorderStyle.None;

                if (btnAllUp.Image != null) btnAllUp.Text = "";
                if (btnAllDw.Image != null) btnAllDw.Text = "";

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

                // 타이틀
                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0730);

                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0144);                         // 선택

                lblBizNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0974);                         // 사업자번호
                lblVenderNm.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0975);                      // 매입처명
                lblTel.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0279);                           // 전화번호

                txtBizNo.Text = "";                                                                                 // 고객번호
                txtVenderNm.Text = "";                                                                              // 고객명
                txtTel.Text = "";                                                                                   // 전화번호

                m_sPosMenuKeyOut = "";
                m_sPosMenuKeyOut2 = "";

                DataGridSetting();                                                                                 // 그리드 초기화

                // 조회
                SearchTxtInPut();

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

        #region 그리드 설정 및 사용
        private double DataGridSetting()
        {
            try
            {
                // 초기화
                dgvData.Rows.Clear();

                dgvData.AllowUserToAddRows = false;
                dgvData.EnableHeadersVisualStyles = false;
                dgvData.RowsDefaultCellStyle.BackColor = Color.White;
                dgvData.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(249, 249, 249);
                dgvData.Font = this.Font;
                dgvData.DefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 10);
                //dgvData.DefaultCellStyle.SelectionBackColor = Color.Transparent;

                dgvData.Font = new Font(m_cPosStatus.Base.FONT, 10);
                dgvData.RowHeadersDefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 10);

                // 타이틀 설정
                dgvData.Columns[0].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0974);
                dgvData.Columns[1].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0975);
                dgvData.Columns[2].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0279);
                dgvData.Refresh();

                txtBizNo.Text = "";                                                                                // 고객번호
                txtVenderNm.Text = "";                                                                             // 고객명
                txtTel.Text = "";                                                                                  // 전화번호

                return 0;
            }
            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 0;
        }

        #endregion
        #endregion 폼 컨트롤 초기화

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

                if ((UI.CsmButton)sender == btnAllUp)                               // 상단 그리드 Up
                {
                    if (dgvData.Rows.Count == 0)
                    {
                        bNotDoubleClik = false;
                        return;
                    }
                    if (dgvData.CurrentRow.Index > 0)
                    {
                        for (int iLoop = dgvData.CurrentRow.Index - 1; iLoop >= 0; iLoop--)
                        {
                            if (dgvData.Rows[iLoop].Visible == false) continue;

                            dgvData.Rows[iLoop].Selected = true;
                            dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                            break;
                        }
                    }
                }
                else if ((UI.CsmButton)sender == btnAllDw)                          // 상단 그리드 Down
                {
                    if (dgvData.Rows.Count == 0)
                    {
                        bNotDoubleClik = false;
                        return;
                    }

                    if (dgvData.CurrentRow.Index < dgvData.Rows.Count - 1)
                    {
                        if (dgvData.Rows.Count == 0)
                        {
                            bNotDoubleClik = false;
                            return;
                        }
                        for (int iLoop = dgvData.CurrentRow.Index + 1; iLoop <= dgvData.Rows.Count - 1; iLoop++)
                        {
                            if (dgvData.Rows[iLoop].Visible == false) continue;

                            dgvData.Rows[iLoop].Selected = true;
                            dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                            break;
                        }
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)                 // 선택
                {
                    // 선택
                    sRet = CompleteTxtInPut();

                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;

                    this.DialogResult = DialogResult.OK;
                    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;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 조회 처리
        /// </summary>
        /// <returns></returns>
        private string SearchTxtInPut()
        {
            string sRet = UserCom.RST_ERR;

            string sRetData = null;

            string[] sCol = null;
            string[] sDetailRow = null;

            try
            {
                // 조회
                string[] saRecvdData = null;

                DataGridSetting();                                                                                  // 그리드 초기화

                sRetData = (string)m_cSchVender.GetData(new string[] { "" });
                if (sRetData != UserCom.RST_ERR && sRetData != null && sRetData.Length > 0)
                {
                    sCol = sRetData.Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    for (int iLoop = 0; iLoop < sCol.Count(); iLoop++)
                    {
                        if (sCol[iLoop].Trim().Length <= 0) continue;

                        if (sCol.Length > 0)
                        {
                            sDetailRow = sCol[iLoop].Split('|');

                            int iRow = dgvData.Rows.Add();

                            dgvData.Rows[iRow].Visible = true;

                            dgvData.Rows[iRow].Cells[0].ReadOnly = false;
                            dgvData.Rows[iRow].DefaultCellStyle.ForeColor = Color.Black;
                            dgvData.Rows[iRow].DefaultCellStyle.SelectionForeColor = Color.Black;

                            dgvData.Rows[iRow].Cells[0].Value = sDetailRow[0].ToString();                                                            // 사업자번호
                            dgvData.Rows[iRow].Cells[1].Value = sDetailRow[1].ToString();                                                            // 매입처명
                            dgvData.Rows[iRow].Cells[2].Value = sDetailRow[2].ToString();                                                            // 전화번호
                            dgvData.Rows[iRow].Cells[3].Value = sDetailRow[3].ToString();                                                            // 매입처코드

                        }
                    }
                }

                dgvData.Refresh();

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

                sRet = UserCom.RST_ERR;
            }
            return sRet;
        }

        /// <summary>
        /// 선택 처리
        /// </summary>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private string CompleteTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (dgvData.RowCount <= 0) return sRet;

                DataGridViewRow dView = this.dgvData.SelectedRows[0];

                // 고객 선택시 어떤 고객을 선택했는지 확인 알림창을 띄워준다.
                if (WinManager.QuestionMessage(string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0634), dView.Cells[1].Value.ToString())) == false)
                {
                    return sRet;
                }

                m_sPosMenuKeyOut = dView.Cells[3].Value.ToString();
                m_sPosMenuKeyOut2 = dView.Cells[1].Value.ToString();

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

        #region 고객선택
        private void dgvData_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvData.RowCount <= 0) return;

                txtBizNo.Text = dgvData.SelectedRows[0].Cells[0].Value.ToString();
                txtVenderNm.Text = dgvData.SelectedRows[0].Cells[1].Value.ToString();
                txtTel.Text = dgvData.SelectedRows[0].Cells[2].Value.ToString();
            }
            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
        #endregion Control Event

        #region User Method
        
        #endregion User Method
    }
}
