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 System.IO;
using System.Diagnostics;
using System.Threading;

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

namespace Cosmos.Win
{
    public partial class frmRembOrderPrint : Form
    {
        #region 변수 선언
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조 

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private ISaleReceipt m_cTradeDeal = null;                                   // 출력 서비스
        private IDataServiceUs m_cWebBiz = null;                                    // 웹업무 서비스
        #endregion 변수 선언

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

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

            m_cPosStatus = (PosStatus)StateObject.POS;          // POS 기본정보
            m_cTradeDeal = (ISaleReceipt)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.SALE_RECEIPT);
            m_cWebBiz = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.WEB_POS);
        }

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

            //17.07.25 dkshin PBILL실행 및 종료
            #region ASIS PBILL.exe 실행(연습모드가 아닐때)
            try
            {
                if (m_cPosStatus.Base.TrainingFlag == "0")
                {
                    //#20170918 기념일 배송 출력 start
                    //기존
                    //// PBILL 환경 설정 프로그램 실행
                    //string fileName = "C:\\SPCPOS\\EXE\\PBILL.exe";
                    ///*if (m_cTrnStatus.Head.CmpCd == "SLKR")
                    //{
                    //    fileName = "C:\\SLPOS\\EXE\\PBILL.exe";
                    //}
                    //*/
                    //ProcessStartInfo startInfo_PBILL = new ProcessStartInfo(fileName);
                    //startInfo_PBILL.WindowStyle = ProcessWindowStyle.Normal;
                    //startInfo_PBILL.CreateNoWindow = false;
                    //Process.Start(startInfo_PBILL);
                    
                    //변경

                    //#20180511 기념일배송시 구포스 PBILL 실행되는 증상 수정 start
                    //기존 주석처리
                    
                    string fileName = "C:\\SPCPOS\\EXE\\PBILL.exe";
                    //구포스 EXE 폴더 안에 PBILL 있으면 그것 실행.
                    if (File.Exists(fileName) == true) 
                    {
                        // PBILL 데몬 실행
                        ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        startInfo.CreateNoWindow = false;
                        Process.Start(startInfo);
                    }
                    //차세대 포스 BIN 폴더 안에 PBILL 실행.
                    else
                    {
                        // PBILL 데몬 실행
                        ProcessStartInfo startInfo = new ProcessStartInfo(Directory.GetCurrentDirectory().ToString() + @"\PBILL.exe");
                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        startInfo.CreateNoWindow = false;
                        Process.Start(startInfo);                        
                    }
                    //#20170918 기념일 배송 출력 end
                    
                    //변경
                    /*
                    // PBILL 데몬 실행
                    ProcessStartInfo startInfo = new ProcessStartInfo(Directory.GetCurrentDirectory().ToString() + @"\PBILL.exe");
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.CreateNoWindow = false;
                    Process.Start(startInfo);
                    */
                    //#20180511 기념일배송시 구포스 PBILL 실행되는 증상 수정 end
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.ToString());
            }
            
            #endregion
        }

        private void frmRembOrderPrint_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
            {
                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);

                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);

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

                btnOpen.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                btnWebLink.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0765);
                btnPrint.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0257);

                //this.Location = new Point(216, 173);
                this.Size = new Size(788, 402);

                txtPrtData.Text = "";
                txtPath.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);
            }
        }
        #endregion 폼 컨트롤 초기화

        #region Control Event
        /// <summary>
        /// 출력 파일 열기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            // 출력파일 열기
            ShowFileOpenDialog();
        }

        /// <summary>
        /// 출력
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (txtPrtData.Text == "")
            {
                WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0302));
                return;
            }

            PrintRembOrder();
        }

        /// <summary>
        /// 주문관리 페이지 접속하기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnWebLink_Click(object sender, EventArgs e)
        {
            WinBasic.ShowWebPos(PosKey.MENU_KEY.REMB_ORDER_PRINT);
            //WebStart(PosKey.MENU_KEY.REMB_ORDER_PRINT);
        }

        /// <summary>
        /// 종료
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            //17.07.25 dkshin PBILL실행 및 종료
            try
            {
                if (m_cPosStatus.Base.TrainingFlag == "0")
                {
                    //#20170918 기념일 배송 출력 start
                    //기존
                    /*
                    // PBILL 프로그램 강제 종료(구포스 WBP.exe가 실행이 되지 않았을 경우)
                    Process[] arPosPgm_WBP = Process.GetProcessesByName("WBP");
                    bool WBP_Check = false;

                    foreach (Process pPosPgm in arPosPgm_WBP)
                    {
                        WBP_Check = true;
                    }

                    if (!WBP_Check)
                    {
                        Process[] arPosPgm_PBILL = Process.GetProcessesByName("PBILL");
                        foreach (Process pPosPgm in arPosPgm_PBILL)
                        {
                            pPosPgm.Kill();
                            Thread.Sleep(1000);
                        }
                    }                    
                    */

                    //변경
                    // PBILL 프로그램 강제 종료(구포스 WBP.exe가 실행이 되지 않았을 경우)

                    //#20180511 기념일배송시 구포스 PBILL 실행되는 증상 수정 start
                    //기존 주석처리
                    
                    Process[] arPosPgm_WBP = Process.GetProcessesByName("WBP");
                    bool WBP_Check = false;

                    foreach (Process pPosPgm in arPosPgm_WBP)
                    {
                        WBP_Check = true;
                    }

                    if (!WBP_Check) 
                    {
                        Process[] arPosPgm_PBILL = Process.GetProcessesByName("PBILL");
                        foreach (Process pPosPgm in arPosPgm_PBILL)
                        {
                            pPosPgm.Kill();
                            Thread.Sleep(1000);
                        }
                    }
                    else
                    {
                        string fileName = "C:\\SPCPOS\\EXE\\PBILL.exe";
                        if (File.Exists(fileName) != true)
                        {
                            Process[] arPosPgm_PBILL = Process.GetProcessesByName("PBILL");
                            foreach (Process pPosPgm in arPosPgm_PBILL)
                            {
                                pPosPgm.Kill();
                                Thread.Sleep(1000);
                            }
                        }
                    }
                    //#20170918 기념일 배송 출력 end
                    
                    //변경
                    /*
                    Process[] arPosPgm_PBILL = Process.GetProcessesByName("PBILL");
                    foreach (Process pPosPgm in arPosPgm_PBILL)
                    {
                        pPosPgm.Kill();
                        Thread.Sleep(1000);
                    }
                    */
                    //#20180511 기념일배송시 구포스 PBILL 실행되는 증상 수정 end
                }
            }
            catch { }

            this.Close();
        }
        #endregion Control Event

        #region User Method
        /// <summary>
        /// 출력 파일 선택 창 열기
        /// </summary>
        /// <returns></returns>
        private string ShowFileOpenDialog()
        {
            string sRet = UserCom.RST_ERR;
            string sData = string.Empty;

            try
            {
                // 파일 오픈창 생성 및 설정
                OpenFileDialog ofd = new OpenFileDialog();
                //ofd.Filter = "텍스트 파일(*.txt) |*.txt|모든파일 (*.*)|*.*";
                ofd.Filter = "텍스트 파일(*.txt) |*.txt";

                //파일 오픈창 로드
                DialogResult dr = ofd.ShowDialog();

                if (dr == DialogResult.OK)
                {
                    //file명과 확장자를 가지고 온다.
                    string fileName = ofd.SafeFileName;
                    //file경로와 확장자를 가지고 온다.
                    string fileFullName = ofd.FileName;
                    //file경로만 가지고 온다.
                    string filePath = fileFullName.Replace(fileName, "");

                    txtPath.Text = fileFullName;

                    FileStream fsVersion = new FileStream(fileFullName, FileMode.Open, FileAccess.Read);
                    StreamReader srVersion = new StreamReader(fsVersion, Encoding.GetEncoding("ks_c_5601-1987"));
                    //StreamReader srVersion = new StreamReader(fsVersion, Encoding.UTF8);
                    srVersion.BaseStream.Seek(0, SeekOrigin.Begin);

                    txtPrtData.Text = "";
                    txtPrtData.Tag = "";

                    while (srVersion.Peek() > -1)
                    {
                        //기념일배송 주문정보 출력 수정(2017.07.21)
                        //sData = srVersion.ReadToEnd().Replace("\r\n","");
                        //txtPrtData.Text = PrintDispCuting(sData);
                        sData = srVersion.ReadToEnd();
                        txtPrtData.Text = PrintDispCuting(sData);
                        txtPrtData.Text = sData;
                        txtPrtData.Tag = sData;
                    }

                    srVersion.Close();
                    fsVersion.Close();

                    sRet = UserCom.RST_OK;
                }
                else
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0441));
                    return sRet;
                }
            }
            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);
            }
            return sRet;
        }

        /// <summary>
        /// 기념일 배송 주문정보 출력
        /// </summary>
        /// <returns></returns>
        private bool PrintRembOrder()
        {
            bool bRet = false;

            try
            {
                if (txtPrtData.Tag.ToString() == "")
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0413));
                    return bRet;
                }

                bRet = m_cTradeDeal.PrintReceipt(txtPrtData.Tag.ToString());
                if (bRet != true)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0442));
                }
            }
            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 bRet;
        }

        /// <summary>
        /// 저널 데이터 컷팅
        /// </summary>
        /// <param name="sPrtData"></param>
        /// <returns></returns>
        private string PrintDispCuting(string sPrtData)
        {
            string sRecvData = string.Empty;
            int iDataLen = 0;

            try
            {
                while (iDataLen <= sPrtData.Length)
                {
                    sRecvData += CmUtil.MidH(sPrtData, iDataLen + 5, 42) + Convert.ToChar(13).ToString() + Convert.ToChar(10).ToString();
                    iDataLen += 47;
                }
            }
            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 sRecvData;
        }

        ///// <summary>
        ///// 웹브라우저 띄우기
        ///// </summary>
        ///// <param name="sFuncKey"></param>
        ///// <returns></returns>
        //private string WebStart(string sFuncKey)
        //{
        //    string sRet = UserCom.RST_ERR;
        //    try
        //    {
        //        string sUrl = string.Empty;

        //        sUrl = (string)m_cWebBiz.GetData(new string[] { sFuncKey });
        //        if (sUrl == null || sUrl == "") return sRet;

        //        if (sUrl.StartsWith("2") == true)           // 1: WEB POS, 2:WEB LINK
        //        {
        //            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("IExplore.exe");
        //            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
        //            startInfo.Arguments = CmUtil.MidH(sUrl, 31, 100).Trim() + CmUtil.MidH(sUrl, 131, 100).Trim();

        //            System.Diagnostics.Process.Start(startInfo);

        //            sRet = UserCom.RST_OK;
        //        }

        //        if (sUrl != UserCom.ERROR && sUrl != null)
        //        {
        //            System.Diagnostics.Process.Start("iexplore.exe", sUrl);
        //            sRet = UserCom.RST_OK;
        //            return sRet;
        //        }

        //        return sRet;
        //    }
        //    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;
        //}

        #endregion User Method
    }
}
