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

namespace Cosmos.Win
{
    public partial class frmSchStorArrvInfo : Form
    {
        #region 변수 선언
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private IStorArrvList m_cStorArrvInfo = null;                                // 테스트모드 서비스
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private IDataServiceUs cWebBiz = null;

        private DataTable m_dtItemInit;                                             // 조회 리스트
        #endregion 변수 선언

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

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

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cStorArrvInfo = (IStorArrvList)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.SCH_STOR_ARRV_INFO);
            cWebBiz = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.WEB_POS);
            GetBtnImg();
        }

        private void frmSchStorArrvInfo_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();

            //GetEventOrderList("", "");

            tmrStart.Enabled = true;
        }

        private void frmSchStorArrvInfo_FormClosing(object sender, FormClosingEventArgs e)
        {

            tmrStart.Enabled = false;

            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
            {
                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);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);

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

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

                // 라벨 이름 설정
                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0454);

                lblMessage01.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0935);
                lblMessage02.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0936);
                lblMessage03.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0937);
                lblMessage04.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0932);
                lblMessage05.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0933);
                lblMessage06.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0934);

                lblCoorseType.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0919);
                lblDriverName.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0920);
                lblCarNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0921);
                lblHandPhone.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0922);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0923);

                lblMsgShow.Text = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0231), lblTitle.Text);

                lblMsgShow.Visible = true;

                FormManager.SetControlSize(lblMsgShow, 13, 210, 775, 160);

                InputLabelInit();

                // 그리드 설정
                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);
            }
        }

        /// <summary>
        /// 그리드 초기화
        /// </summary>
        private void InitializeGrid()
        {
            try
            {
                // 상품권 등록정보 표시 그리드
                grdSearchItem.CsmGridColumnHeadersVisible = true;                                   //DataGridView 자체의 컬럼 헤더 Visible 여부
                grdSearchItem.CsmGridColumnHeadersHeight = 40;                                      //DataGridView 자체의 컬럼 헤더 높이
                grdSearchItem.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 12, FontStyle.Bold);  //DataGridView 자체의 컬럼 헤더 폰트
                grdSearchItem.CsmGridRowsHeight = 38;
                //그리드컬럼 수 수정(2017.07.05)
                //grdSearchItem.CsmGridColumnCount = 22;                                               //그리드의 컬럼수
                grdSearchItem.CsmGridColumnCount = 23;                                              //그리드의 컬럼수
                grdSearchItem.CsmGridShowPageRowsCount = 4;                                         //그리드의 한 화면에 보이는 로우수
                grdSearchItem.CsmGridSetHeaderBackColor(236, 238, 239);                             //그리드 헤더 배경색
                grdSearchItem.CsmGridDefaultRowBackColor = Color.FromArgb(255, 255, 255);           //그리드 홀수(Default)행의 배경색 지정
                grdSearchItem.CsmGridAlternateRowBackColor = Color.FromArgb(251, 253, 255);         //그리드 짝수(Alternate)행의 배경색 지정
                grdSearchItem.CsmGridBackGroundColor = Color.FromArgb(251, 253, 255);               //기본 백그라운드 컬러
                grdSearchItem.CsmGridHighlightColor = Color.FromArgb(255, 251, 211);                //그리드 선택 백 컬러
                grdSearchItem.CsmGridHighlightTextColor = Color.Black;                              //그리드 선택 글자 컬러
                //grdSearchItem.CsmGridSetColumnWidth(new int[] { 50, 200, 105, 370, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });   //컬럼넓이 지정(499)
                grdSearchItem.CsmGridSetColumnWidth(new int[] { 50, 200, 105, 370, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });   //컬럼넓이 지정(499)
                //grdSearchItem.CsmGridAlignment(new int[] { 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });               //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                grdSearchItem.CsmGridAlignment(new int[] { 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });               //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                //각 컬럼별 이름 지정
                grdSearchItem.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0519)); //차수
                grdSearchItem.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0735)); //도착예정시간
                grdSearchItem.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0736)); //배송상태
                grdSearchItem.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0737)); //차량최종위치
                grdSearchItem.CsmGridColumnName(4, "driver_name");  //배송기사명
                grdSearchItem.CsmGridColumnName(5, "car_number");   //배송차량번호
                grdSearchItem.CsmGridColumnName(6, "hand_phone");   //배송기사연락처
                grdSearchItem.CsmGridColumnName(7, "car_code");     //차량번호

                for (int iRow = 8; iRow < 23; iRow++)
                {
                    grdSearchItem.CsmGridColumnShowHide(iRow, true);
                }

                //그리드 초기화 테이블
                m_dtItemInit = new DataTable("INIT");

                m_dtItemInit.Columns.Add(new DataColumn("course_type", typeof(string)));//11
                //m_dtItemInit.Columns.Add(new DataColumn("center_departure_time", typeof(string)));//8
                m_dtItemInit.Columns.Add(new DataColumn("cust_pre_arrival_time", typeof(string)));//8
                m_dtItemInit.Columns.Add(new DataColumn("final_cust_status", typeof(string)));//22
                m_dtItemInit.Columns.Add(new DataColumn("last_location", typeof(string)));//12
                m_dtItemInit.Columns.Add(new DataColumn("driver_name", typeof(string)));//5
                m_dtItemInit.Columns.Add(new DataColumn("car_number", typeof(string)));//4
                m_dtItemInit.Columns.Add(new DataColumn("hand_phone", typeof(string)));//6
                m_dtItemInit.Columns.Add(new DataColumn("car_code", typeof(string)));//3
                m_dtItemInit.Columns.Add(new DataColumn("cnt", typeof(string)));//0
                m_dtItemInit.Columns.Add(new DataColumn("d_day", typeof(string)));//1
                m_dtItemInit.Columns.Add(new DataColumn("cust_name", typeof(string)));//2
                m_dtItemInit.Columns.Add(new DataColumn("center_name", typeof(string)));//7
                m_dtItemInit.Columns.Add(new DataColumn("center_arrival_time", typeof(string)));//9
                m_dtItemInit.Columns.Add(new DataColumn("course_name", typeof(string)));//10
                m_dtItemInit.Columns.Add(new DataColumn("last_location_time", typeof(string)));//13
                //m_dtItemInit.Columns.Add(new DataColumn("cust_pre_arrival_time", typeof(string)));//14
                m_dtItemInit.Columns.Add(new DataColumn("cust_arrival_time", typeof(string)));//15
                m_dtItemInit.Columns.Add(new DataColumn("cust_departure_time", typeof(string)));//16
                m_dtItemInit.Columns.Add(new DataColumn("last_via_cust_name", typeof(string)));//17
                m_dtItemInit.Columns.Add(new DataColumn("last_via_cust_arrival_time", typeof(string)));//18
                m_dtItemInit.Columns.Add(new DataColumn("last_via_cust_departure_time", typeof(string)));//19
                m_dtItemInit.Columns.Add(new DataColumn("current_car_status", typeof(string)));//20
                m_dtItemInit.Columns.Add(new DataColumn("current_cust_status", typeof(string)));//21

                m_dtItemInit.Columns.Add(new DataColumn("center_departure_time", typeof(string)));//8

                m_dtItemInit.Clear();
            }
            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 GetBtnImg()
        {
            try
            {
                //네이게이션 버튼 이미지 적용!
                btnUp.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnDw.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN1_BASIC);

                if (btnUp.Image != null) btnUp.Text = "";
                if (btnDw.Image != null) btnDw.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 InputLabelInit()
        {
            try
            {
                txtFlag.Text = "";
                txtDriverName.Text = "";
                txtDriverCarNum.Text = "";
                txtDriverCarTel.Text = "";
                btnSearch.Tag = "";
                txtFlag.Tag = "";
            }
            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 Control Event

        /// <summary>
        /// 조회 그리드 업/다운 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelProc_Click(object sender, EventArgs e)
        {

            try
            {
                if ((UI.CsmButton)sender == btnUp)
                {
                    grdSearchItem.CsmGridScroll("UP");
                }
                else if ((UI.CsmButton)sender == btnDw)
                {
                    grdSearchItem.CsmGridScroll("DOWN");
                }
            }
            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>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string sRepWebLink = "";
            string sCarcode = "";
            string sCourseType = "";

            try
            {

                if (txtFlag.Tag.ToString() == "" || btnSearch.Tag.ToString() == "")
                {
                    return;
                }

                sCarcode = btnSearch.Tag.ToString();
                sCourseType = txtFlag.Tag.ToString();

                string sData = (string)cWebBiz.GetData(new string[] { PosKey.MENU_KEY.WEB_STOR_ARRV_DETAIL });

                if (sData != null || sData != "")
                {
                    sRepWebLink = CmUtil.MidH(sData, 31, 100).Trim() + CmUtil.MidH(sData, 131, 100).Trim();

                    if (sRepWebLink != "")
                    {
                        // 점포코드
                        sRepWebLink = sRepWebLink.Replace("<CAR_CODE>", sCarcode).Replace("<COURSE_TYPE>", sCourseType);
                    }

                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("IExplore.exe");
                    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
                    startInfo.Arguments = sRepWebLink;
                    System.Diagnostics.Process.Start(startInfo);
                }

            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        /// <summary>
        /// 그리드 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="rowIndex"></param>
        private void grdSearchItem_GridClickEvent(object sender, string rowIndex)
        {
            try
            {

                if (grdSearchItem.CsmGridRowsCount == 0) return;
                int iRow = grdSearchItem.CsmGridSelectedRowIndex;
                if (iRow < 0) return;

                InputLabelInit();

                txtFlag.Text = string.Format("{0} {1}", grdSearchItem.CsmGridGetCell(iRow, 0), MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0919));
                txtFlag.Tag = grdSearchItem.CsmGridGetCell(iRow, 0);
                txtDriverName.Text = grdSearchItem.CsmGridGetCell(iRow, 4);
                txtDriverCarNum.Text = grdSearchItem.CsmGridGetCell(iRow, 5);
                txtDriverCarTel.Text = grdSearchItem.CsmGridGetCell(iRow, 6);
                btnSearch.Tag = grdSearchItem.CsmGridGetCell(iRow, 7);

            }
            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>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmrStart_Tick(object sender, EventArgs e)
        {
            try
            {
                tmrStart.Stop();

                GetEventOrderList("", "");

                lblMsgShow.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);
            }
        }

        #endregion

        #region User Method
        /// <summary>
        /// 계정선택 DataGridView와 Data 연결
        /// </summary>
        private void GetEventOrderList(string sDateFrom, string sDateTo)
        {
            string sRetData = null;

            int nRet = 0;

            DataTable dtDate = m_dtItemInit.Clone();

            try
            {
                sRetData = (string)m_cStorArrvInfo.SendReceiveForStorArrInfo(new object[] { }, ref dtDate, ref nRet);
                
                if (nRet != 1 || dtDate.Rows.Count == 0)
                {
                    dtDate = m_dtItemInit.Clone();
                }
                else
                {
                    foreach (DataRow dr in dtDate.Rows)
                    {
                        // 배송상태 오류 관련 수정
                        // current_car_status 와 current_cust_status 를 혼용해서 사용 (20170512-조충연K)
                        // 배송상태
                        //if ((dr["current_car_status"].ToString()).Equals(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0924)))
                        //{
                        //    if ((dr["current_car_status"].ToString()).Equals(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0925)))
                        //    {
                        //        dr["final_cust_status"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0925);
                        //    }
                        //    else if ((dr["current_car_status"].ToString()).Equals(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0926)))
                        //    {
                        //        dr["final_cust_status"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0926);
                        //    }
                        //    else if ((dr["current_car_status"].ToString()).Equals(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0927)))
                        //    {
                        //        dr["final_cust_status"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0925);
                        //    }
                        //}
                        //else
                        //{
                        //    dr["final_cust_status"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0927);
                        //}
                        if ((CmUtil.GetDataRowStr(dr, "current_cust_status")).Equals(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0924)))
                        {
                            if ((CmUtil.GetDataRowStr(dr, "current_car_status")).Equals(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0925)))
                            {
                                dr["final_cust_status"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0925);
                            }
                            else if ((CmUtil.GetDataRowStr(dr, "current_car_status")).Equals(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0926)))
                            {
                                dr["final_cust_status"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0926);
                            }
                            else if ((CmUtil.GetDataRowStr(dr, "current_car_status")).Equals(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0927)))
                            {
                                dr["final_cust_status"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0925);
                            }
                        }
                        else
                        {
                            dr["final_cust_status"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0927);
                        }

                        
                    }
                }

                dtDate.DefaultView.Sort = "center_departure_time DESC";
                grdSearchItem.CsmGridDataSource = dtDate;

                grdSearchItem.FirstClick();
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }
        #endregion
    }
}
