using FBS0000;
using FCOMMON;
using Project.Dialog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Web.Services.Description;
using System.Windows.Forms;

namespace Project
{
    public partial class fMain : fBase
    {
        string SearchKey = string.Empty;
        private ChatClientService chatService;
        private System.Windows.Forms.Timer chatBlinkTimer;
        private bool chatHasNewMessage = false;
        private Dictionary<string, string> chatMessageSenders = new Dictionary<string, string>(); // employeeId -> nickName


        public fMain()
        {
            InitializeComponent();

            // Initialize chat blink timer
            chatBlinkTimer = new System.Windows.Forms.Timer();
            chatBlinkTimer.Interval = 500; // 500ms blink
            chatBlinkTimer.Tick += ChatBlinkTimer_Tick;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.F12) btSetting.PerformClick();
                //else if (e1.KeyCode == Keys.F11) btLog.PerformClick();
                else if (e1.KeyCode == Keys.F1 && e1.Control && e1.Shift)
                {
                    Dialog.fDebug f = new Dialog.fDebug();
                    f.Show();
                }
                else if (e1.KeyCode == Keys.F2 && e1.Control && e1.Shift)
                {
                    var f = new fLog();
                    f.Show();
                }

                if (DateTime.Now > Pub.LastInputTime) Pub.LastInputTime = DateTime.Now;
            };

            this.MouseMove += (s1, e1) => { if (DateTime.Now > Pub.LastInputTime) Pub.LastInputTime = DateTime.Now; };
            this.FormClosing += __Closing;
            this.FormClosed += FMain_FormClosed;
        }

        //private void Server_ClientConnected(Receiver receiver)
        //{
        //    this.BeginInvoke(new Action(() =>
        //    {
        //        var f = new Dialog.fChat(receiver);
        //        f.Show();
        //        f.Activate();
        //    }));
        //}

        private void FMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //if (server != null)
            //    server.CloseChild();
            //연결종료
            //try
            //{
            //    var db = new EEEntitiesMain();
            //    var dr = db.EETGW_LoginInfo.Where(t => t.uid == FCOMMON.info.Login.no).FirstOrDefault();
            //    if (dr != null)
            //    {
            //        db.EETGW_LoginInfo.Remove(dr);
            //        db.SaveChanges();
            //    }
            //}
            //catch { }
            FCOMMON.Pub.FlushLog();
        }

        bool closeforce = false;

        private void __Closing(object sender, FormClosingEventArgs e)
        {
            MessageWindow.CloseAll();
            if (closeforce == false)
            {
                var rlt = Util.MsgQ(Lang.Question_Exit);
                if (rlt != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }

            // Stop chat service
            chatService?.Stop();
            chatBlinkTimer?.Stop();

            FCOMMON.Pub.log.Add("Program Close");
            FCOMMON.Pub.log.Flush();
        }


        //ConnectionMultiplexer redisConnection;
        //IDatabase db;

        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            this.Text = Application.ProductName + " v" + Application.ProductVersion;

            // 실행환경 체크는 fWarning에서 이미 완료됨
            setToolbar();

            _SetLang();
            if (Pub.setting.FullScreen) this.WindowState = FormWindowState.Maximized;
            else this.WindowState = FormWindowState.Normal;
            this.Show();
            Application.DoEvents();

            // 바코드 이벤트 연결
            Pub.barcode.ReceiveData += barcode_ReceiveData;

            UpdateControls();
            tmDisplay.Start();  //display timer

            // WebView2 초기화 재시도 (필요시)
            if (Pub.InitWebView == 0)
            {
                try
                {
                    Console.WriteLine("WebView2 재초기화 시도...");
                    Pub.InitializeWebView2();
                }
                catch (Exception retryEx)
                {
                    Console.WriteLine($"WebView2 재초기화 실패: {retryEx.Message}");
                    // 실패해도 계속 진행
                }
            }

            // WebView2 대기 (짧게 조정)
            var wat = new System.Diagnostics.Stopwatch();
            wat.Restart();
            while (true)
            {
                if (Pub.InitWebView != 0) break;
                if (wat.ElapsedMilliseconds > 3000) break; // 5초에서 3초로 단축
                System.Threading.Thread.Sleep(500); // 1초에서 0.5초로 단축
                Application.DoEvents();
            }

            Console.WriteLine($"WebView2 초기화 상태: {Pub.InitWebView}");



            // WebView2 로그인이 아닌 경우에만 여기서 후처리 실행
            // WebView2 로그인의 경우 OnLoginCompleted()에서 호출됨
            //if (Pub.InitWebView != 1)
            //{
            Menu_Dashboard();
            //OnLoginCompleted();
            //}
        }

        /// <summary>
        /// 로그인 완료 후 실행되는 처리
        /// WebView2 로그인의 경우 MachineBridge에서 호출됨
        /// </summary>
        public void OnLoginCompleted()
        {
            menuStrip1.Enabled = true;
            toolStrip1.Enabled = true;
            this.mn_purchase.Visible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_purchase);
            this.mn_project.Visible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_project);
            this.mn_dailyhistory.Visible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_history);
            this.mn_jago.Visible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_jago);
            //this.mn_eq.Visible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_equipment);
            this.mn_kuntae.Visible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_workday);

            //220421
            FCOMMON.info.Disable_8hourover = Pub.setting.Disable8HourOver;

            if (FCOMMON.info.Login.level >= 10) btDev.Visible = true;

            sbLogin.Text = string.Format("[{0}] ({1}-{2} T:{3}) - ({5}){4}",
                FCOMMON.info.Login.title,
                FCOMMON.info.Login.no,
                FCOMMON.info.Login.nameK,
                FCOMMON.info.Login.tel,
                FCOMMON.info.Login.dept,
                FCOMMON.info.Login.gcode);
            FCOMMON.Pub.log.Add("Program Start");

            sbLoginUseTime.Text = "접속시간:" + FCOMMON.info.Login.loginusetime.ToString("N1") + "ms";

            // Start chat service after login
            StartChatService();

            // 즐겨찾기 목록 갱신
            Update_FavoriteSite();

            UpdateControls();

            // 사용기록추적
            var remark = $"{FCOMMON.info.Login.gcode}|{FCOMMON.info.Login.dept}";
            Pub.CheckNRegister5(Application.ProductName, "chi", Application.ProductVersion, FCOMMON.info.Login.no, remark);
        }

        void Update_FavoriteSite()
        {
            //즐겨찾기 없데이트 g=17
            //타입
            var dt_type = FCOMMON.DBM.getCodeTable("17");
            foreach (DataRow dr in dt_type.Rows)
            {
                var bt = new ToolStripMenuItem();
                bt.Text = dr["value"].ToString();
                bt.Tag = dr["svalue"].ToString();
                bt.Click += bt_Click;
                즐겨찾기ToolStripMenuItem.DropDownItems.Add(bt);
            }
        }

        void bt_Click(object sender, EventArgs e)
        {
            var bt = sender as ToolStripMenuItem;
            var cmd = bt.Tag.ToString();
            Util.RunExplorer(cmd);
        }

        //void Func_Login()
        //{
        //    this.sbWeb.Text = $"WebView:{Pub.InitWebView}";
        //    if (Pub.InitWebView == 1)
        //    {
        //        // WebView2 기반 대시보드 로그인
        //        Menu_Dashboard();
        //    }
        //    else
        //    {
        //        // 기존 WinForms 로그인
        //        using (var f = new Dialog.fLogin())
        //            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK)
        //                Application.ExitThread();
        //    }
        //}
        void Func_RunStartForm()
        {
            var menu_purchaseVisible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_purchase);
            var menu_projectVisible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_project);
            var menu_dailyhistoryVisible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_history);
            var menu_jagoVisible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_jago);
            var menu_eqVisible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_equipment);
            var menu_kuntaeVisible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_workday);
            var menu_logdata = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_logdata);

        }
        void Menu_WorkTable()
        {
            string formkey = "HOLY";
            if (!ShowForm(formkey))
            {
                AddForm(formkey, new FBS0000.fHolyday());
            }
        }

        void _SetLang()
        {
            //btSetting.Text = Lang.Setting;
        }

        void barcode_ReceiveData(object sender, Device.Barcode.ReceiveDataEventArgs e)
        {
            #region "invoke"
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<Device.Barcode.ReceiveDataEventArgs>(barcode_ReceiveData), new object[] { sender, e });
                return;
            }
            #endregion
            FCOMMON.Pub.log.Add("BCD", "Rx:" + e.StrValue);
        }

        void Menu_Log()
        {
            var f = new fLog();
            f.TopMost = true;
            f.Show();
        }

        void Menu_Setting()
        {
            fSetting f = new fSetting();
            if (f.ShowDialog() == DialogResult.OK)
            {
                FCOMMON.info.camIndex = Pub.setting.CamIndex;
                FCOMMON.info.Disable_8hourover = Pub.setting.Disable8HourOver;
                Pub.setting.Save();
                FCOMMON.Pub.log.AddI("Setting Save");
                FCOMMON.Pub.log.Add(Pub.setting.ToString());
                UpdateControls();
                setToolbar();
            }
        }

        void setToolbar()
        {
            if (Pub.setting.HideToolbar == eToolPosition.Hide)
            {
                this.toolStrip1.Visible = false;
            }
            else
            {
                switch (Pub.setting.HideToolbar)
                {
                    case eToolPosition.Bottom: this.toolStrip1.Dock = DockStyle.Bottom; break;
                    case eToolPosition.Top: this.toolStrip1.Dock = DockStyle.Top; break;
                    case eToolPosition.Left: this.toolStrip1.Dock = DockStyle.Left; break;
                    case eToolPosition.Right: this.toolStrip1.Dock = DockStyle.Right; break;
                }
                this.toolStrip1.Visible = true;
            }
        }

        #region "util"

        void UpdateControls()
        {

            //환율재적용 - 210711
            //FCOMMON.info.dollertowon = Pub.setting.wondoller;
            FCOMMON.info.NotShowJobReportview = Pub.setting.NotShowJobreportPRewView;
        }

        #endregion

        private void settingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Menu_Setting();
        }

        private void logToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Menu_Log();
        }

        private void listToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_projecT_list();
        }

        void menu_work_reportautoinput()
        {
            string formkey = "WORKBOOKAI";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fJobReportAI());
        }
        void menu_work_report()
        {
            string formkey = "WORKBOOK";
            if (!ShowForm(formkey))
            {
                //if (this.webok && Pub.InitWebView == 1 && System.Diagnostics.Debugger.IsAttached)
                //    AddForm(formkey, new Dialog.fJobReport());
                //else
                AddForm(formkey, new FPJ0000.fJobReport());
            }


        }
   

        void menu_dayhistory()
        {
            string formkey = "DAYHISTORY";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fProjectList());
        }
        void menu_projecT_list()
        {
            string formkey = "PROJECTS";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fProjectList());

        }
        void menu_projecTU_list()
        {
            string formkey = "PROJECTSU";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fProjectListU());

        }
        private void helpToolStripButton_Click(object sender, EventArgs e)
        {
            menu_projecT_list();
        }

        private void itemsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_pumname();
        }

        void menu_pumname()
        {
            string formkey = "ITEMS";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fItems());
        }


        private void personalInventoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Menu_InventoryUser();
        }

        void Menu_Inventory()
        {
            string formkey = "INVENTORY";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fInventory());
        }
        void Menu_InventoryUser()
        {
            string formkey = "INVENTORYUSER";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fInventoryUser());
        }
        private void minutesToolStripMenuItem_Click(object sender, EventArgs e)
        {

            string formkey = "MINUTES";
            if (!ShowForm(formkey))
                AddForm(formkey, new FBS0000.fMinutes());


        }

        private void holidayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "HOLYDAY";
            if (!ShowForm(formkey))
                AddForm(formkey, new FBS0000.fHolyday());

        }

        private void codesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FCM0000.fCode();
            f.ShowDialog();
        }

        void menu_itemin()
        {
            string formkey = "ITEMIPKO";
            if (!ShowForm(formkey))
                AddForm(formkey, new FEQ0000.fItemin(), "품목입고");
        }
        void menu_nrpurchase()
        {
            string formkey = "PUCHASENR";
            if (!ShowForm(formkey))
                AddForm(formkey, new FEQ0000.fPurchaseNR(), "일반구매");
        }
        void menu_crpurchase()
        {
            //	FCOMMON.Util.MsgE("CR구매현황은 신규 개발 기능으로 아직 open 되지 않았습니다");
            string formkey = "PUCHASECR";
            if (!ShowForm(formkey))
                AddForm(formkey, new FEQ0000.fPurchaseCR(), "CR구매");
        }
        void menu_sprpurchase()
        {
            //if(System.Diagnostics.Debugger.IsAttached==false)
            //{
            //    FCOMMON.Util.MsgE("SPR구매현황은 신규 개발 기능으로 아직 open 되지 않았습니다");
            //    return;
            //}

            string formkey = "PUCHASEEB";
            if (!ShowForm(formkey))
                AddForm(formkey, new FEQ0000.fPurchaseEB(), "해외지원+전자실 구매");
        }

        private void nRPurchaseToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void purchaseImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FEQ0000.fPurchase_Import();
            // f.MdiParent = this;
            f.Show();
        }

        private void purchaseDataConvertToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FEQ0000.fPurchase_Data();
            //  f.MdiParent = this;
            f.Show();
        }

        private void customerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "CUSTOMS";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fCustoms());
            var f = new FCM0000.fCustoms();
        }


        private void userAccountToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new _Common.fAddNewUser(FCOMMON.info.Login.dept, FCOMMON.info.Login.no);//.fUserInfo();

            f.ShowDialog();
        }


        private void myAccouserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new _Common.fUserList();
            f.ShowDialog();
        }


        private void customerImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FCM0000.Customer_Import();
            // f.MdiParent = this;
            f.Show();
        }

        Boolean ShowForm(string key)
        {
            int tabIndex = this.tabControl1.TabPages.IndexOfKey(key);
            if (tabIndex != -1)
            {
                this.tabControl1.SelectedIndex = tabIndex;
                return true;
            }
            return false;
        }
        void AddForm(string key, Form f, string Title = "")
        {
            f.TopLevel = false;
            f.Dock = DockStyle.Fill;
            f.ControlBox = false;
            f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            f.FormClosed += f_FormClosed;
            f.Tag = key;
            this.tabControl1.TabPages.Add(key, (Title.isEmpty() ? f.Text : Title));
            this.tabControl1.TabPages[this.tabControl1.TabPages.Count - 1].BorderStyle = BorderStyle.Fixed3D;
            this.tabControl1.TabPages[this.tabControl1.TabPages.Count - 1].Padding = new Padding(10, 10, 10, 10);
            this.tabControl1.TabPages[this.tabControl1.TabPages.Count - 1].BackColor = Color.LightGray;
            this.tabControl1.TabPages[this.tabControl1.TabPages.Count - 1].ContextMenuStrip = this.cmTab;
            this.tabControl1.TabPages[this.tabControl1.TabPages.Count - 1].Controls.Add(f);
            this.tabControl1.TabPages[this.tabControl1.TabPages.Count - 1].Tag = key;
            this.tabControl1.SelectedIndex = this.tabControl1.TabPages.Count - 1;
            f.Show();
        }

        void f_FormClosed(object sender, FormClosedEventArgs e)
        {
            var f = sender as Form;
            var key = f.Tag.ToString();
            foreach (TabPage tab in this.tabControl1.TabPages)
            {
                if (tab.Visible == true)
                {
                    this.tabControl1.TabPages.Remove(tab);
                    break;
                }
            }
            if (this.tabControl1.TabPages.Count > 0) this.tabControl1.SelectedIndex = this.tabControl1.TabCount - 1;
        }

        private void 라인코드관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Management.fLineCode f = new _Management.fLineCode();
            f.ShowDialog();
        }

        private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
        {
            //e.Graphics.FillRectangle(Brushes.Red, e.Bounds);
            e.DrawBackground();
            e.DrawFocusRectangle();
            e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, new SolidBrush(e.ForeColor), e.Bounds);
            var tabpos = this.PointToClient(new Point(tabControl1.Left, tabControl1.Top));
            e.Graphics.DrawString("X", this.Font, Brushes.Black, tabControl1.Right - 50, tabControl1.Top);
        }


        private void materialImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FCM0000.fMaterial_Import();
            f.Show();
        }

        private void projectImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FPJ0000.Import();
            f.Show();
        }

        private void 프로젝트ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }


        private void todoListToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void projectImportCompleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FPJ0000.ImportC();
            f.Show();
        }

        private void purchaseOrderImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FEQ0000.fPurchase_ImportO();
            // f.MdiParent = this;
            f.Show();
        }

        //private void 로그인ToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    CloseAllForm();
        //    Func_Login();
        //}

        void CloseAllForm()
        {
            while (tabControl1.TabPages.Count > 0)
            {
                var tab = this.tabControl1.TabPages[0];
                var f = tab.Controls[0] as System.Windows.Forms.Form;
                f.Close();
                f.Dispose();
                tabControl1.TabPages.Remove(tab);
                this.tabControl1.Refresh();
            }
        }

        /// <summary>
        /// MachineBridge에서 호출 가능한 public 메서드
        /// </summary>
        public void CloseAllFormPublic()
        {
            CloseAllForm();

            // 상태바 정보 초기화
            sbLogin.Text = "";
            sbLoginUseTime.Text = "";

            // 메뉴/툴바 비활성화
            menuStrip1.Enabled = false;
            toolStrip1.Enabled = false;
            btDev.Visible = false;

            Menu_Dashboard();
        }


        private void workReportImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FPJ0000.JobReport_.fJobReportImport();
            f.ShowDialog();
        }

        private void 월별근무표ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //string formkey = "HOLIS";
            //if (!ShowForm(formkey))
            //    AddForm(formkey, new FCM0000.fHolidaytable());
            var f = new FCM0000.fHolidaytable();
            f.ShowDialog();
        }


        private void addSIdDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sql = "select idx from items where isnull([sid],'') = ''";
            var cn = FCOMMON.DBM.getCn();
            cn.Open();

            //string sql = "select " + field + " from " + table + " where idx = " + idx.ToString();
            var cmdupdate = new System.Data.SqlClient.SqlCommand("update items set [sid] = @sid where idx = @idx", cn);
            cmdupdate.Parameters.Add("sid", SqlDbType.VarChar);
            cmdupdate.Parameters.Add("idx", SqlDbType.Int);

            var cmd = new System.Data.SqlClient.SqlCommand(sql, cn);
            var dar = cmd.ExecuteReader();

            List<int> idxlist = new List<int>();
            while (dar.Read())
            {
                var idx = int.Parse(dar[0].ToString());
                idxlist.Add(idx);
            }
            dar.Close();
            dar.Dispose();

            //임시SID는 전체 19자리이며 #TEMP#으로 시작하낟.
            foreach (var idx in idxlist)
            {
                var newsid = "#TEMP#" + idx.ToString("000000000000000");
                cmdupdate.Parameters[0].Value = newsid;
                cmdupdate.Parameters[1].Value = idx;
                cmdupdate.ExecuteNonQuery();
            }

            cn.Close();
            cn.Dispose();
        }

        private void 계정목록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (FCOMMON.info.Login.level < 10)
            {
                FCOMMON.Util.MsgE("개발자 이상 사용가능한 메뉴 입니다.");
                return;
            }

            var f = new _Common.fADSUserList();
            f.ShowDialog();
        }

        private void 그룹정보ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (FCOMMON.info.Login.level < 10)
            {
                FCOMMON.Util.MsgE("개발자 이상 사용가능한 메뉴 입니다.");
                return;
            }

            var f = new FCM0000.fUserGroupDev();
            f.ShowDialog();
        }

        private void 권한설정ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
            if (curLevel < 5)
            {
                FCOMMON.Util.MsgE("(관리자/계정담당자) 전용 메뉴 입니다");
                return;
            }

            string formkey = "fUserAuth";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fUserAuth());

        }

        private void 관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Menu_Inventory();
        }


        void Menu_InventoryList()
        {
            string formkey = "INVENTORYLIST";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fInventoryJagoList());
        }
       
        private void 재고현황ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Menu_InventoryList();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string formkey = "STAFFGRID";
            if (!ShowForm(formkey))
                AddForm(formkey, new _Info.fInfo_Staff());
        }


        private void 임의테이블조작ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            var sql = "select * from Purchase where pdate = '2019-08-01' and orderno = '210000657'";
            var cn = FCOMMON.DBM.getCn();
            var cnU = FCOMMON.DBM.getCn();
            cn.Open();
            cnU.Open();

            //string sql = "select " + field + " from " + table + " where idx = " + idx.ToString();
            var sqlU = "update Purchase set supply=@supply where pdate = '2019-08-01' and orderno = '210000657'";
            var cmdupdate = new System.Data.SqlClient.SqlCommand(sqlU, cn);
            cmdupdate.Parameters.Add("supply", SqlDbType.VarChar);
            cmdupdate.Parameters["supply"].Value = "";
            //cmdupdate.Parameters.Add("sidx", SqlDbType.Int);


            var cmd = new System.Data.SqlClient.SqlCommand(sql, cnU);
            var dar = cmd.ExecuteReader();

            List<int> idxlist = new List<int>();
            while (dar.Read())
            {
                //sid 가 잇다면 해당 sid 의 suuply를 찾아서 업데이트한다.
                var sid = dar["sid"].ToString().Trim();
                var itemname = dar["pumname"].ToString().Trim();
                var itemmodel = dar["pumscale"].ToString().Trim();

                if (itemname == "FIBER SENSOR(반사형)")
                {

                }


                bool sidOK = false;
                if (sid.Length == 9)
                {
                    cmdupdate.CommandText = "select isnull(itemsupply,'') from ProjectsPart where project=212 and isnull(itemsid,'') = '" + sid + "'";
                    var data = cmdupdate.ExecuteScalar();
                    if (data != null && data.ToString().Trim() != "")
                    {
                        var supplyname = cmdupdate.ExecuteScalar().ToString().Trim();
                        if (supplyname != "")
                        {
                            cmdupdate.CommandText = "update Purchase set supply=@supply where pdate = '2019-08-01' and orderno = '210000657' and sid='" + sid + "'";
                            cmdupdate.Parameters["supply"].Value = supplyname;
                            if (cmdupdate.ExecuteNonQuery() > 0) sidOK = true;
                        }
                    }
                }

                if (sidOK == false && itemname != "")
                {
                    if (itemname == "FIBER SENSOR(반사형)")
                    {

                    }
                    //아이템으로 찾아야함
                    cmdupdate.CommandText = "select isnull(itemsupply,'') from ProjectsPart where project=212 and isnull(ItemName,'') = '" + itemname + "' and isnull(itemmodel,'') = '" + itemmodel + "'";
                    var data = cmdupdate.ExecuteScalar();
                    if (data != null && data.ToString().Trim() != "")
                    {
                        var supplyname = data.ToString().Trim();
                        if (supplyname != "")
                        {
                            cmdupdate.CommandText = "update Purchase set supply=@supply where pdate = '2019-08-01' and orderno = '210000657' and pumname='" + itemname + "' and isnull(pumscale,'') = '" + itemmodel + "'";
                            cmdupdate.Parameters["supply"].Value = supplyname;
                            var cnt1 = cmdupdate.ExecuteNonQuery();
                        }
                    }

                }
            }


            cmd.Dispose();
            dar.Close();
            dar.Dispose();


            cn.Close();
            cn.Dispose();
            cnU.Close();
            cnU.Dispose();

            FCOMMON.Util.MsgI("complete");
        }

        private void 메일양식ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "MAILFORM";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fMailform());
        }

        private void mailBackupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FCM0000.Mail.fMailBackup();
            f.TopMost = true;
            f.Show();
        }


        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            menu_nrpurchase();
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            menu_projecT_list();
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            menu_work_report();
        }



        private void 근태입력ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Menu_WorkTable();
        }

        private void 근로명부ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "WTABLEUSER";
            if (!ShowForm(formkey))
                AddForm(formkey, new FBS0000.fWorkTableUser());
        }

      
        private void 목록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_projecT_list();
        }



        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            menu_pumname();
        }

        private void 목록ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            menu_work_report();
        }

        private void 자동입력ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //업무일지 자동 입력
            menu_work_reportautoinput();
        }


        private void 품목검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // OWIN 서버 제거로 인해 기능 비활성화
            Util.MsgI("품목검색 기능은 대시보드에서 이용해 주세요.");
        }

        private void layoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "PLYOU";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fProjectLayout());
        }


        private void 양식ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "JRFORM";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fJRForm());
        }

        private void 라이선스ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "LICENSE";
            if (!ShowForm(formkey))
                AddForm(formkey, new FED0000.fLicenseList());
        }


        private void 휴일연장근무승인ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "OTCONFIRM";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fOTConfirm());
        }

        private void 휴일연장근무집계표출력ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.otconfirm));
            //if(curLevel < 5)
            //{
            //    Util.MsgE("이 기능을 사용할 권한이 없습니다");
            //    return;
            //}
            var f = new FPJ0000.JobReport_.rJobReportOT();
            f.Show();
        }

        private void 메일자동발신테스트ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "AUTOMAIL";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.Mail.fAutoSendSetting());
        }

        private void 출근부출력ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FBS0000.WorkTable();
            f.Show();
        }

        private void 휴가신청ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            휴가요청();
        }
        void 휴가요청()
        {
            string formkey = "HOLYREQ";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fHolyRequest());
        }

        private void 아이템비활성화하기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new Dev.fDisableItem();
            f.ShowDialog();
        }

        private void 휴가사용현황ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FBS0000.rHolidaySummary();
            f.Show();
        }

        private void 개인별근태원장ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var uid = FCOMMON.info.Login.nameK + "(" + FCOMMON.info.Login.no + ")";
            var f = new FBS0000.fHolyDayData(DateTime.Now.ToString("yyyy-MM-dd"), uid);
            f.Show();
        }

        private void 근태입력오류확인ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FBS0000.Holiday.fErrorChk();
            f.Show();
        }

        private void 버젼확인ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var MaxVerstion = FCOMMON.DBM.GetMaxVersion();
            if (MaxVerstion.isEmpty() == false)
            {
                var curversion = Application.ProductVersion;
                var verchk = curversion.CompareTo(MaxVerstion);
                if (verchk < 0)
                {
                    //내버젼이 낮다
                    if (Util.MsgQ("현재 구 버젼을 사용하고 있습니다.\n업데이트를 실행 할까요?") == DialogResult.OK)
                        UpdateRun();
                }
                else
                {
                    Util.MsgI("최신 버젼을 사용하고 있습니다\n\n" +
                        "서버 : " + MaxVerstion + "\n" +
                       "현재 : " + curversion);
                }
            }
            else Util.MsgE("버젼 확인 불가");
        }

        private void 근태마감ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FCOMMON.fMagam();
            f.ShowDialog();
        }

        private void 업데이트ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            closeforce = true;
            UpdateRun();
        }

        void UpdateRun()
        {
            var pn = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            System.Text.StringBuilder script = new StringBuilder();
            script.AppendLine($"echo \"실행중인 프로그램을 확인 하고 있습니다\"");
            script.AppendLine($"$nid = (get-process {pn}).id");
            script.AppendLine($"echo \"종료 대기 중(ID:$nid) 종료되지 않으면 강제로 실행을 종료 해주세요\"");
            script.AppendLine($"wait-process -id $nid");
            var fn = $"{AppDomain.CurrentDomain.BaseDirectory}update.exe";
            script.AppendLine($"echo \"start update {fn}\"");
            script.AppendLine($"start-process \"{fn}\"");
            byte[] byteArray = Encoding.Unicode.GetBytes(script.ToString());
            string scriptBase64Encoded = Convert.ToBase64String(byteArray);
            var processStartInfo = new System.Diagnostics.ProcessStartInfo()
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy unrestricted -EncodedCommand {scriptBase64Encoded}",
                UseShellExecute = false
            };
            System.Diagnostics.Process.Start(processStartInfo);
            Application.Exit();
            //this.Close();
        }

        private void sPR설정ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var lines = Clipboard.GetText().Replace("\r", "").Split('\n');
            List<string> items = new List<string>();
            foreach (var lin in lines)
            {
                if (string.IsNullOrEmpty(lin)) continue;
                if (lin.Length == 9) items.Add(lin.Trim());
            }

            var dlg = FCOMMON.Util.MsgQ($"{lines.Length} 건의 자료를 SPR로 설정할까요?");
            if (dlg != DialogResult.Yes) return;

            var cn = FCOMMON.DBM.getCn();
            cn.Open();
            var cmd = new System.Data.SqlClient.SqlCommand("", cn);
            var cnt = 0;
            foreach (var item in items)
            {
                var sql = $"update Items set Storage = 'SPR' where gcode = '{FCOMMON.info.Login.gcode}' and sid='{item}'";
                cmd.CommandText = sql;
                cnt += cmd.ExecuteNonQuery();
                if (cnt % 25 == 0)
                {
                    this.Text = $"{cnt}/{items.Count}";
                    Application.DoEvents();
                }
            }
            cn.Close();
            FCOMMON.Util.MsgI($"{cnt}건의 자료가 변경 되었습니다");
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            휴가요청();
        }

        private void statusToolStripMenuItem_Click(object sender, EventArgs e)
        {


        }

        private void 프로젝트스케쥴담당자사번업데이트ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            var sql = "select idx,uidname,gcode from EETGW_ProjectsSchedule where  isnull(uidname ,'') <> ''";
            var cn = FCOMMON.DBM.getCn();
            var cnU = FCOMMON.DBM.getCn();
            cn.Open();
            cnU.Open();

            //string sql = "select " + field + " from " + table + " where idx = " + idx.ToString();
            var sqlU = "update EETGW_ProjectsSchedule set uid=@uid where idx=@idx";
            var cmdupdate = new System.Data.SqlClient.SqlCommand(sqlU, cnU);
            cmdupdate.Parameters.Add("uid", SqlDbType.VarChar);
            cmdupdate.Parameters.Add("gcode", SqlDbType.VarChar);
            cmdupdate.Parameters.Add("name", SqlDbType.VarChar);
            cmdupdate.Parameters.Add("idx", SqlDbType.Int);
            //cmdupdate.Parameters["supply"].Value = "";
            //cmdupdate.Parameters.Add("sidx", SqlDbType.Int);


            var cmd = new System.Data.SqlClient.SqlCommand(sql, cn);
            var dar = cmd.ExecuteReader();

            List<int> idxlist = new List<int>();
            while (dar.Read())
            {
                //sid 가 잇다면 해당 sid 의 suuply를 찾아서 업데이트한다.
                var sid = int.Parse(dar["idx"].ToString());
                var itemmodel = dar["uidname"].ToString().Trim();
                var itemname = dar["gcode"].ToString().Trim();

                //해당uidname 을 프로젝트 정보에서 찾는다.				
                cmdupdate.CommandText = "select isnull(id,'') from vGroupUser where gcode = @gcode and [name] = @name";
                cmdupdate.Parameters["gcode"].Value = itemname;
                cmdupdate.Parameters["name"].Value = itemmodel;
                cmdupdate.Parameters["uid"].Value = string.Empty;
                cmdupdate.Parameters["idx"].Value = -1;
                var obj_uid = cmdupdate.ExecuteScalar();
                if (obj_uid == null) continue;
                var str_uid = obj_uid.ToString();
                if (str_uid.isEmpty()) continue;

                //데이터를 업데이트한다
                cmdupdate.CommandText = "update EETGW_ProjectsSchedule set uid=@uid where idx=@idx and gcode = @gcode";
                cmdupdate.Parameters["uid"].Value = str_uid;
                cmdupdate.Parameters["idx"].Value = sid;
                var cnt = cmdupdate.ExecuteNonQuery();
                if (cnt == 1) Console.WriteLine($"update {cnt} {itemmodel} -> {str_uid}");
            }


            cmd.Dispose();
            dar.Close();
            dar.Dispose();


            cn.Close();
            cn.Dispose();
            cnU.Close();
            cnU.Dispose();

            FCOMMON.Util.MsgI("complete");
        }

        private void 그룹정보ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FCM0000.fUserGroup();
            f.ShowDialog();
        }

        private void 프로그램사용관련알림ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("프로그램이 분리되었습니다.\n\n" +
                "지금 다운로드 URL을 열까요?\n\n문의\n\n장비기술팀 : 진재훈\n자동화기술팀 : 정재희");
            if (dlg == DialogResult.Yes)
            {
                var url = "https://amkor-my.sharepoint.com/:u:/g/personal/chikyun_kim_amkor_co_kr/EX2HxdH5H9ZLqa8fyr0nD3QBQJxhdKfsfGZiJboAABBS5g?e=aaDVzZ";
                Util.RunExplorer(url);

            }
        }

        private void 일반구매ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_nrpurchase();
        }

        private void cR구매ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_crpurchase();
        }

        private void sPR구매ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_sprpurchase();
        }

        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {

            var sql = $"select * from EETGW_PurchaseCR where gcode = '{FCOMMON.info.Login.gcode}' and isnull(pumidx,-1) = -1 and isnull(sid,'') <> ''";
            var cn = FCOMMON.DBM.getCn();
            var cnU = FCOMMON.DBM.getCn();
            var cn2 = FCOMMON.DBM.getCn();
            cn.Open();
            cnU.Open();
            cn2.Open();

            //string sql = "select " + field + " from " + table + " where idx = " + idx.ToString();
            var sqlU = "update EETGW_PurchaseCR set pumidx=@pumidx where idx=@idx";
            var cmdupdate = new System.Data.SqlClient.SqlCommand(sqlU, cnU);
            cmdupdate.Parameters.Add("pumidx", SqlDbType.Int);
            cmdupdate.Parameters.Add("idx", SqlDbType.Int);
            cmdupdate.Parameters.Add("gcode", SqlDbType.VarChar);
            cmdupdate.Parameters.Add("sid", SqlDbType.VarChar);

            var cmd = new System.Data.SqlClient.SqlCommand(sql, cn);
            var dar = cmd.ExecuteReader();

            List<int> idxlist = new List<int>();
            int cnt1 = 0;
            int rec = 0;
            while (dar.Read())
            {
                rec += 1;
                //sid 가 잇다면 해당 sid 의 suuply를 찾아서 업데이트한다.
                cnt1 += 1;
                var purchaseIdx = int.Parse(dar["idx"].ToString());
                var itemsid = dar["sid"].ToString().Trim();
                var itemgcode = dar["gcode"].ToString().Trim();

                if (cnt1 % 50 == 0) Application.DoEvents();

                //해당uidname 을 프로젝트 정보에서 찾는다.				
                cmdupdate.CommandText = $"select max(idx) from Items where gcode = '{itemgcode}' and [sid] = '{itemsid}' and isnull(disable,0) = 0";
                cmdupdate.Parameters.Clear();


                var obj_pumidx = cmdupdate.ExecuteScalar();
                if (obj_pumidx == null) continue;
                var str_pumidx = obj_pumidx.ToString();
                if (str_pumidx.isEmpty())
                {
                    //자료가업으니 이것은 추가를 해야한다.
                    var sql2 = $"insert into Items(gcode,name,sid,model,unit,price,memo,wuid,wdate)" +
                        " values(@gcode,@name,@sid,@model,@unit,@price,@memo,@wuid,@wdate)";
                    var cmd2 = new System.Data.SqlClient.SqlCommand(sql2, cn2);
                    cmd2.Parameters.Add("gcode", SqlDbType.VarChar).Value = dar["gcode"];
                    cmd2.Parameters.Add("name", SqlDbType.VarChar).Value = dar["pumname"];
                    cmd2.Parameters.Add("sid", SqlDbType.VarChar).Value = dar["sid"];
                    cmd2.Parameters.Add("model", SqlDbType.VarChar).Value = dar["pumscale"];
                    cmd2.Parameters.Add("unit", SqlDbType.VarChar).Value = dar["pumunit"];
                    cmd2.Parameters.Add("price", SqlDbType.Decimal).Value = dar["pumprice"];
                    cmd2.Parameters.Add("memo", SqlDbType.VarChar).Value = dar["bigo"];
                    cmd2.Parameters.Add("wuid", SqlDbType.VarChar).Value = "dev";
                    cmd2.Parameters.Add("wdate", SqlDbType.SmallDateTime).Value = DateTime.Now;
                    var cnt2 = cmd2.ExecuteNonQuery();
                }
                else
                {
                    //데이터를 업데이트한다
                    cmdupdate.CommandText = $"update EETGW_PurchaseCR set pumidx={int.Parse(str_pumidx)} where idx={purchaseIdx}";
                    var cnt = cmdupdate.ExecuteNonQuery();
                    if (cnt == 1) Console.WriteLine($"[{rec}] update {cnt} {itemsid} -> {str_pumidx}");
                }


            }


            cmd.Dispose();
            dar.Close();
            dar.Dispose();


            cn.Close();
            cn.Dispose();
            cnU.Close();
            cnU.Dispose();
            cn2.Close();
            cn2.Dispose();

            FCOMMON.Util.MsgI("complete");
        }

        private void 품목입고ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_itemin();

        }

        private void 담당자별현황ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_projecTU_list();
        }

        //private void bwrunToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    bw_DoWork(null, null);
        //}

        //private void 휴가REMINDToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    Mail_Take_a_rest_remind();
        //}

        private void 개인별근태집계표ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var uid = FCOMMON.info.Login.nameK + "(" + FCOMMON.info.Login.no + ")";
            var f = new FBS0000.fHolyDayDataSum(DateTime.Now.ToString("yyyy-MM-dd"), uid);
            f.Show();
        }

        private void managementToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 연차현황ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "YCHAH";
            if (!ShowForm(formkey))
                AddForm(formkey, new FBS0000.fyeonchastate());
        }

        private void commonToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        //Dialog.fDashboard fdashboard = null;
        void Menu_Dashboard()
        {
            string formkey = "DASHBOARD";
            if (!ShowForm(formkey))
            {
                if (fdashboard == null || fdashboard.IsDisposed)
                    fdashboard = new Dialog.fDashboard();

                AddForm(formkey, fdashboard);
            }
        }

        private void 대쉬보드ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Menu_Dashboard();
        }

        private void toolStripMenuItem16_Click(object sender, EventArgs e)
        {
            menu_crpurchase();
        }

        private void 담당자별업무현황ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_projecT_list2();
        }
        void menu_projecT_list2()
        {
            string formkey = "PROJECTSUSER";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fProjectListUser());

        }

        private void 전자실구매승인ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "PURCHAGECONFIRMADMIN";
            if (!ShowForm(formkey))
                AddForm(formkey, new FEQ0000.fPurchaseConfirm());
        }

        private void 업무분류및형태설정ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FPJ0000.JobReport_.fJobProcessSelect("", true);
            f.Show();
        }

        private void 대체시간이월ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FBS0000.Holiday.fTimeTransfer();//.fJobProcessSelect("", true);
            f.Show();
        }

        private void 월별NRCR기준금액입력ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new FEQ0000.fMonthAmount();//.fJobProcessSelect("", true);
            f.Show();
        }

        private void webview2TestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var f = new Dialog.fWebView2Test())
                f.ShowDialog();
        }

        Dialog.fDashboard fdashboard = null;
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 0)
            {
                if (fdashboard != null)
                {
                    fdashboard.RefreshView();
                    Console.WriteLine("view update");
                }

            }
        }

        #region Chat Functions

        /// <summary>
        /// Start chat service after login
        /// </summary>
        private void StartChatService()
        {
            try
            {
                // Get user info
                string nickName = FCOMMON.info.Login.nameK ?? "Unknown";
                string employeeId = FCOMMON.info.Login.no ?? "Unknown";
                string userGroup = FCOMMON.info.Login.gcode ?? "default";

                // Initialize chat service
                //var chatServerIP = "127.0.0.1";// : "10.131.11.45";
                var chatServerIP = "10.131.11.45";
                chatService = new ChatClientService(chatServerIP, 5000);
                chatService.ConnectionStatusChanged += ChatService_ConnectionStatusChanged;
                chatService.MessageReceived += ChatService_MessageReceived;

                // Start background service
                chatService.Start(nickName, employeeId, userGroup);

                FCOMMON.Pub.log.AddI($"Chat service started: {nickName} ({employeeId}, {userGroup})");
            }
            catch (Exception ex)
            {
                FCOMMON.Pub.log.AddE($"Failed to start chat service: {ex.Message}");
            }
        }

        /// <summary>
        /// Chat connection status changed
        /// </summary>
        private void ChatService_ConnectionStatusChanged(object sender, bool isConnected)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => ChatService_ConnectionStatusChanged(sender, isConnected)));
                return;
            }

            if (isConnected)
            {
                sbChat.ForeColor = Color.Green;
                sbChat.Text = "Notice ●";
            }
            else
            {
                sbChat.ForeColor = Color.Gray;
                sbChat.Text = "Notice ○";
            }
        }

        /// <summary>
        /// Chat message received
        /// </summary>
        private void ChatService_MessageReceived(object sender, ChatMessage message)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => ChatService_MessageReceived(sender, message)));
                return;
            }

            // Track message senders (only messages directed to me)
            string myEmployeeId = chatService.EmployeeId;
            if ((message.Type == MessageType.Chat || message.Type == MessageType.Whisper) &&
                !string.IsNullOrEmpty(message.EmployeeId) &&
                message.EmployeeId != myEmployeeId &&
                message.TargetEmployeeId == myEmployeeId)
            {
                // Add or update sender
                if (!chatMessageSenders.ContainsKey(message.EmployeeId))
                {
                    chatMessageSenders[message.EmployeeId] = message.NickName ?? message.EmployeeId;
                }

                // Start blinking
                chatHasNewMessage = true;
                chatBlinkTimer.Start();
            }
        }

        /// <summary>
        /// Chat blink timer tick
        /// </summary>
        private void ChatBlinkTimer_Tick(object sender, EventArgs e)
        {
            if (!chatHasNewMessage)
            {
                chatBlinkTimer.Stop();
                sbChat.ForeColor = chatService?.IsConnected == true ? Color.Green : Color.Gray;
                return;
            }

            // Toggle color
            sbChat.ForeColor = sbChat.ForeColor == Color.Red ? Color.Green : Color.Red;
        }

        /// <summary>
        /// sbChat status label click event
        /// </summary>
        private void sbChat_Click(object sender, EventArgs e)
        {
            // Stop blinking
            chatHasNewMessage = false;
            chatBlinkTimer.Stop();
            sbChat.ForeColor = chatService?.IsConnected == true ? Color.Green : Color.Gray;

            // Show chat dialog
            if (chatService == null)
            {
                MessageBox.Show("Chat service is not running.", "Chat", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // If there are senders who sent messages, show selection dialog
            if (chatMessageSenders.Count > 0)
            {
                // Create simple selection form
                using (var selectForm = new Form())
                {
                    selectForm.Text = "Select Sender";
                    selectForm.Size = new Size(400, 300);
                    selectForm.StartPosition = FormStartPosition.CenterParent;
                    selectForm.FormBorderStyle = FormBorderStyle.FixedDialog;
                    selectForm.MaximizeBox = false;
                    selectForm.MinimizeBox = false;

                    var listBox = new ListBox
                    {
                        Dock = DockStyle.Fill,
                        Font = new Font("Malgun Gothic", 10)
                    };

                    var buttonPanel = new Panel
                    {
                        Dock = DockStyle.Bottom,
                        Height = 50
                    };

                    var btnOk = new Button
                    {
                        Text = "Open Chat",
                        DialogResult = DialogResult.OK,
                        Size = new Size(100, 30),
                        Location = new Point(140, 10)
                    };

                    var btnNew = new Button
                    {
                        Text = "New Chat",
                        DialogResult = DialogResult.Retry,
                        Size = new Size(100, 30),
                        Location = new Point(250, 10)
                    };

                    buttonPanel.Controls.Add(btnOk);
                    buttonPanel.Controls.Add(btnNew);

                    selectForm.Controls.Add(listBox);
                    selectForm.Controls.Add(buttonPanel);
                    selectForm.AcceptButton = btnOk;

                    // Populate list with senders
                    foreach (var sender2 in chatMessageSenders)
                    {
                        listBox.Items.Add(new { EmployeeId = sender2.Key, NickName = sender2.Value, Display = $"{sender2.Value} ({sender2.Key})" });
                    }
                    listBox.DisplayMember = "Display";

                    if (listBox.Items.Count > 0)
                        listBox.SelectedIndex = 0;

                    var result = selectForm.ShowDialog(this);

                    if (result == DialogResult.OK && listBox.SelectedItem != null)
                    {
                        // Open chat with selected sender
                        dynamic selected = listBox.SelectedItem;
                        var chatForm = new Dialog.fChat(chatService, selected.EmployeeId, selected.NickName);
                        chatForm.Show();

                        // Remove from senders list (chat opened)
                        chatMessageSenders.Remove(selected.EmployeeId);
                    }
                    else if (result == DialogResult.Retry)
                    {
                        // Open new chat (user will select recipient in chat window)
                        var chatForm = new Dialog.fChat(chatService);
                        chatForm.Show();
                    }
                }
            }
            else
            {
                // No senders, open new chat
                var chatForm = new Dialog.fChat(chatService);
                chatForm.Show();
            }
        }

        #endregion
    }
}
