using arTCPService.Server;
using Microsoft.Owin.Hosting;
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 StackExchange.Redis;

namespace Project
{
    public partial class fMain : Form
    {
        string SearchKey = string.Empty;
        arTCPService.Server.Server server;

        public fMain()
        {
            InitializeComponent();
            server = new Server();
            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;
            this.server.ClientConnected += Server_ClientConnected;
        }

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

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

            ////close redis
            //if (this.redisConnection != null && this.redisConnection.IsConnected && this.db != null)
            //{
            //    this.redisConnection.Close();
            //    this.redisConnection.Dispose();
            //}

            Pub.log.Add("Program Close");
            Pub.log.Flush();
            bBW = false;    //backgroundWorker
            if (bw.IsBusy) bw.CancelAsync();
        }

        //ConnectionMultiplexer redisConnection;
        //IDatabase db;

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

            setToolbar();


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

            Pub.barcode = new Device.Barcode();
            if (!Pub.setting.Barcode.isEmpty()) Pub.barcode.PortName = Pub.setting.Barcode;
            Pub.barcode.ReceiveData += barcode_ReceiveData;

            FCOMMON.info.camIndex = Pub.setting.CamIndex;
            UpdateControls();

            tmDisplay.Start();  //display timer

            Func_Login();

            if(Pub.setting.SharedDataPath.isEmpty() && FCOMMON.info.Login.gcode == "EET1P") //210524
            {
                FCOMMON.info.datapath = @"\\k4fs3201n\k4bpartcenter$";
                Pub.setting.SharedDataPath = FCOMMON.info.datapath;
                Pub.setting.Save();
            }
                

            Update_Site();
            bw.RunWorkerAsync(); //background worker
            UpdateControls();

            //사용기록추적
            Pub.CheckNRegister3(Application.ProductName, "chi", Application.ProductVersion);

            // Start OWIN host
            try
            {
                WebApp.Start<OWIN.Startup>(url: "http://127.0.0.1:9000");
                Console.WriteLine("start webapp");
                Pub.log.AddI("웹지원 서버 준비 완료");
            }
            catch (Exception ex)
            {
                //Util.MsgE("Web Interface Error\r\n" + ex.Message)/;
                Console.WriteLine(ex.Message);
                Pub.log.AddE("웹지원오류" + ex.Message);
            }


            ////서버ON
            //try
            //{
            //    this.server.Start(7979);//기본 79포트로 설정한다
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}

        }
        void Update_Site()
        {
            //즐겨찾기 없데이트 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()
        {
            Dialog.fLogin flogIn = new Dialog.fLogin();
            if (flogIn.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                Application.ExitThread();

            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);
            this.mn_docu.Visible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_docu);
            //this.mn_logdata.Visible = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.menu_logdata);

            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);
            Pub.log.Add("Program Start");

            Func_RunStartForm();
        }
        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);


            // Menu_Note();

            //시작폼 확인
            if (Pub.setting.startForm == eFormList.NR구매관리 && menu_purchaseVisible == true)
            {
                menu_nrpurchase();
            }
            else if (Pub.setting.startForm == eFormList.업무일지 && menu_dailyhistoryVisible == true)
            {
                menu_work_report();
            }
            else if (Pub.setting.startForm == eFormList.프로젝트관리 && menu_projectVisible == true)
            {
                menu_projecT_list();
            }
            else if (Pub.setting.startForm == eFormList.재고관리 && menu_jagoVisible == true)
            {
                Menu_Inventory();
            }
            else if (Pub.setting.startForm == eFormList.재고현황 && menu_jagoVisible == true)
            {
                Menu_InventoryList();
            }
            else if (Pub.setting.startForm == eFormList.근태입력)
            {
                Menu_WorkTable();
            }

        }
        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
            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;
                Pub.setting.Save();
                Pub.log.AddI("Setting Save");
                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;
        }

        #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_eboard()
        {
            string formkey = "WORKEBOARD";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fEboardList());
        }
        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))
                AddForm(formkey, new FPJ0000.fJobReport());

        }
        void menu_save_cost()
        {
            string formkey = "SAVECOST";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fSaveCostList());
        }

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

        }

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


        private void requestITemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "ITEMREQUEST";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fRequestItem());

        }

        void menu_nrpurchase()
        {
            string formkey = "PUCHASE";
            if (!ShowForm(formkey))
                AddForm(formkey, new FEQ0000.fPurchase());
        }

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

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

            Func_Login();
        }

        private void 메일전송ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (FCOMMON.info.Login.level < 10)
            {
                FCOMMON.Util.MsgE("테스트 기능이므로 개발자만 사용가능 합니다.");
                return;
            }
            FCM0000.fSendMail f = new FCM0000.fSendMail();
            //f.MdiParent = this;
            f.Show();
        }

        private void 업무일지ToolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void 패치내역ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FCM0000.fPatchList f = new FCM0000.fPatchList();
            f.Show();
        }

        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.fUserGroup();
            f.ShowDialog();
        }

        private void 권한설정ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (FCOMMON.info.Login.level < 5)
            {
                FCOMMON.Util.MsgE("관리자 이상 사용가능한 메뉴 입니다.");
                return;
            }

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

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

     
        void Menu_InventoryList()
        {
            string formkey = "INVENTORYLIST";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.fInventoryJagoList());
        }
        void Menu_Note()
        {
            string formkey = "NOTELIST";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.Note.fNote());
        }
        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 sMTRepairLogToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

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

        private void 메일전송ToolStripMenuItem1_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)
        {
            string formkey = "MAILLIST";
            if (!ShowForm(formkey))
                AddForm(formkey, new FCM0000.Mail.fMailList());
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {

            var f = new FBS0000.fHolyday_Add();
            f.TopMost = true;
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //RefreshData();
            }
        }

        private void pMP데이터베이스업데이트ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new Dialog.PMPUpdate();
            f.ShowDialog();
        }

        private void pMP현황ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "PMPDB";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPM0000.fSPMaster());

        }

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

        private void 메모장ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Menu_Note();
        }


        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 toolStripButton4_Click_1(object sender, EventArgs e)
        {
            string formkey = "PMPDB";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPM0000.fSPMaster());
        }

        private void 휴가관리ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        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_save_cost();
        }

        private void 목록ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_projecT_list();
        }
        void menu_projectPartStatus_list()
        {
            string formkey = "PROJECTPARTST";
            if (!ShowForm(formkey))
                AddForm(formkey, new FPJ0000.fPartBuyStatus());

        }
        private void 구매진행현황ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_projectPartStatus_list();
        }

        private void toolStripButton1_Click_2(object sender, EventArgs e)
        {
            menu_projectPartStatus_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)
        {
            //업무현황 전자실
            menu_work_eboard();
        }


        private void 품목검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var url = "http://localhost:9000/item/find";
            Util.RunExplorer(url);
            //var f = new Dialog.fWebView("http://localhost:9000/item/find");
            //f.Show();
        }

        private void accessDBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new Dialog.AccessDB();
            f.ShowDialog();
        }

      
        private void aLLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string formkey = "EQALL";
            if (!ShowForm(formkey))
                AddForm(formkey, new FEQ0000.fEquipment(FEQ0000.fEquipment.eTabletype.ALL), "ALL");
        }

        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 = "EDLIST";
            if (!ShowForm(formkey))
                AddForm(formkey, new FED0000.fEdulist());
        }

        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)
        {
           
            Util.RunExplorer("http://127.0.0.1:9000/Manual");
        }

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

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
