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.Runtime.InteropServices;
using System.Net; 
using System.IO;

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

namespace Cosmos.Win
{
    public partial class frmWebBiz2 : Form
    {
        #region 변수 선언
        [DllImport("Ole32.dll", SetLastError = true)]
        private static extern void CoFreeUnusedLibraries();  

        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 IDataServiceUs m_cWebBiz = null;                                    // WEBPOS 서비스

        private string m_sPosMenuKey = "";
        /// <summary>
        /// POS 기능 키
        /// </summary>
        public string PosMenuKey { get { return this.m_sPosMenuKey; } set { this.m_sPosMenuKey = value; } }
        
        private string m_sPosMenuName = "";
        /// <summary>
        /// POS 기능 명
        /// </summary>
        public string PosMenuName { get { return this.m_sPosMenuName; } set { this.m_sPosMenuName = value; } }

        private string m_sPosWebMenuURL = "";
        /// <summary>
        /// POS WEB URL
        /// </summary>
        public string PosWebMenuURL { get { return this.m_sPosWebMenuURL; } set { this.m_sPosWebMenuURL = value; } }

        private string m_sPosWebMenuId = "";
        /// <summary>
        /// POS WEB 화면코드
        /// </summary>
        public string PosWebMenuId { get { return this.m_sPosWebMenuId; } set { this.m_sPosWebMenuId = value; } }


        private string m_sPosWebParam = "";
        /// <summary>
        /// POS WEB 화면 파라메터
        /// </summary>
        public string PosWebParam { get { return this.m_sPosWebParam; } set { this.m_sPosWebParam = value; } }

        #endregion 변수 선언

        #region 생성자 & 소멸자
        public frmWebBiz2()
        {
            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_cWebBiz = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.WEB_BIZ);
        }

        private void frmWebBiz_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();  // 콘트롤 초기화 처리
            this.Tag = "START";
        }

        private void frmWebPos2_Activated(object sender, EventArgs e)
        {
            if (this.Tag.ToString() == "START")
            {
                this.Tag = "";
                LoadWebPos();
            }
        }

        private void frmWebBiz_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);
        }

        private void frmWebBiz2_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (this.axNexacroAXCtrl != null)
                {
                    // v8.dll Unload
                    ((IDisposable)this.axNexacroAXCtrl).Dispose();
                }
                // CoFreeUnusedLibraries();
            }
            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 InitControl()
        {
            this.Location = new Point(0, 0);
            if (m_cPosStatus.Sale.ScreenSizeUser == 1024)
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_FULL_SIZE);
                //this.Size = new Size(1024, 696);
                //this.Location = new Point(0, 50);

                FormManager.SetControlSize(this, 0, 0, 1024, 768);
                FormManager.SetControlSize(this.picBack, 0, 0, 1024, 35);
                FormManager.SetControlSize(this.lblTitle, 10, 2, 964, 33);
                FormManager.SetControlSize(this.btnExit, 976, 2, 46, 32);
                FormManager.SetControlSize(this.axNexacroAXCtrl, 0, 35, 1024, 768 - 35);
            }
            else
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);
                FormManager.SetControlSize(this, 0, 0, 800, 600);
                FormManager.SetControlSize(this.picBack, 0, 0, 800, 35);
                FormManager.SetControlSize(this.lblTitle, 10, 2, 740, 33);
                FormManager.SetControlSize(this.btnExit, 752, 2, 46, 32);
                FormManager.SetControlSize(this.axNexacroAXCtrl, 0, 35, 800, 600 - 35);
            }

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

            //axNexacroAXCtrl.Location = new Point(0, 35);
            //axNexacroAXCtrl.Size = new Size(1024, 768 - 35);

            FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);
            FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);

            axNexacroAXCtrl.Visible = false;

            FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);

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

        #region Control Event
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                m_sPosMenuKey = "";
                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);
            }
        }
        #endregion Control Event

        #region User Method
        /// <summary>
        /// WEB POS 화면 로딩
        /// </summary>
        public bool LoadWebPos()
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");

                lblTitle.Text = m_sPosMenuName;
                //lblTitle.Text = m_sPosMenuName + "[" + PosWebMenuURL + "," + m_cPosStatus.Base.CashierNo + "," + m_sPosWebMenuId + m_sPosWebParam + "]";

                // 최초 화면 로딩
                string sBrowerKey = m_cPosStatus.Mst.BrowserKey;

                //if (m_cPosStatus.Base.CmpCd == ItemConst.COMPANY_CODE.BRKR) sBrowerKey += m_cPosStatus.Base.BrandCd;
                if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.BR) sBrowerKey += m_cPosStatus.Base.BrandCd;
                
                axNexacroAXCtrl.key = sBrowerKey;
                axNexacroAXCtrl.bjson = PosWebMenuURL;      // "http://10.0.40.98:7003/spcwps/start.json";
                axNexacroAXCtrl.run();

                if (m_cPosStatus.Base.OlePosPrinterModel != "99")
                    this.TopMost = true;
                else
                    this.TopMost = false;

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

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

                if (m_sPosMenuKey == PosKey.MENU_KEY.WEB_WORK)
                {
                    // ID/화면코드를 글로벌 변수에서 가져온다.
                    if (!axNexacroAXCtrl.setvariablevalue("gv_param", "ceo=Y!@#$decodeYn=Y!@#$id=" + m_cPosStatus.Base.CashierNo + "!@#$pw=" + m_cPosStatus.Base.CashierWebPosPwd))
                    {
                        string sgv = (axNexacroAXCtrl.getvariablevalue("gv_param") == null ? "null" : axNexacroAXCtrl.getvariablevalue("gv_param").ToString());

                        UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", sgv);
                    }
                }
                else
                {
                    string sUserID = UserLog.UserAES.StaticKeyEncrypt(m_cPosStatus.Base.CashierNo);
                    // ID/화면코드
                    if (!axNexacroAXCtrl.setvariablevalue("gv_param", "null!@#$null!@#$null!@#$USER_ID=" + sUserID + "!@#$SCRN=" + m_sPosWebMenuId + m_sPosWebParam))
                    {
                        string sgv = (axNexacroAXCtrl.getvariablevalue("gv_param") == null ? "null" : axNexacroAXCtrl.getvariablevalue("gv_param").ToString());

                        UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", sgv);
                    }
                }
            }
            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 axNexacroAXCtrl_beforeexit(object sender, AxNexacroAXLib._INexacroAXCtrlEvents_beforeexitEvent e)
        {
            try
            {
                e.pbcloseflag = true;
                e.pbhandledflag = true;
            }
            catch { }
        }

        private void axNexacroAXCtrl_exit(object sender, EventArgs e)
        {
            try
            {
                this.axNexacroAXCtrl.quit();
            }
            catch { }
        }
        #endregion 

        private void axNexacroAXCtrl_usernotify(object sender, AxNexacroAXLib._INexacroAXCtrlEvents_usernotifyEvent e)
        { 
            try
            {
                axNexacroAXCtrl.Visible = true;
            }
            catch { }
        }
        
    }
}
