using FCOMMON;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;

namespace Project.Dialog
{
    public partial class fLogin : fBase
    {
        public fLogin()
        {
            InitializeComponent();
            this.tbID.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Enter) tbPW.Focus(); };
            this.tbPW.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Enter) btLogin.PerformClick(); };
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
            this.Text = string.Format("사용자 확인(v{0})", Application.ProductVersion);

            var lv = this.listView1.Items.Add("[25-04-06] 데이터베이스 이전 작업 완료 (버그신고:chikyun.kim@amkor.co.kr)");
            lv.Tag = "기존 데이터베이스 삭제 예정으로 인한 신규 데이터베이스 업데이트 작업 완료\n일부 기능에 문제가 발생할 수 있습니다. 문제 발생시에는 chikyun.kim@amkor.co.kr 로 문의 주세요";

            
        }
        private void fLogin_Load(object sender, EventArgs e)
        {
            //EnsureVisibleAndUsableSize();
            var list = Pub.setting.lastid.Split(';');
            foreach (var item in list)
                if (item != "") tbID.Items.Add(item);
            if (tbID.Items.Count > 0) tbID.SelectedIndex = 0;



            //S1 사용자 그룹목록 확인
            //var tas1 = new S1ACCESS300Entities();
            //var deptlist = tas1.VIEW_CARD_PERSON
            //    .Where(t => t.CardStatusID == 0 && string.IsNullOrEmpty(t.CardUser2) == false)
            //    .GroupBy(t => t.PersonUser2)
            //    .OrderBy(t => t.Key)
            //    .ToList();

            //this.cmbDept.Items.Clear();
            //foreach (var dept in deptlist)
            //    cmbDept.Items.Add(dept);


            //그룹목록가져오기
            //Util.MsgE(Properties.Settings.Default.CS);
            var tagrp = new dsMSSQLTableAdapters.UserGroupTableAdapter();
            //Util.MsgE(tagrp.Connection.ConnectionString);
            var grplist = tagrp.GetData();
            this.cmbDept.DataSource = grplist;
            this.cmbDept.DisplayMember = "dept";
            this.cmbDept.ValueMember = "gcode";

            //마지막으로사용한 부서이름
            if (Pub.setting.lastdpt.isEmpty()) this.cmbDept.SelectedIndex = -1;
            else this.cmbDept.Text = Pub.setting.lastdpt;
            if (cmbDept.SelectedIndex == -1 && Pub.setting.lastgcode.isEmpty() == false)
            {
                var dr = grplist.Where(t => t.gcode.Equals(Pub.setting.lastgcode)).FirstOrDefault();
                if (dr != null) cmbDept.Text = dr.dept;
            }
            //foreach (var item in dlist)
            //    if (item != "") this.cmbDept.Items.Add(item);
            //if (cmbDept.Items.Count > 0) cmbDept.SelectedIndex = 0;

            this.Show();
            Application.DoEvents();

            if (this.tbID.Text.isEmpty() == false) tbPW.Focus();
            else tbID.Focus();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;

            //if(tbID.Text != "dev" && (dt.ToString("yyyy-MM-dd") == "2025-04-05" ||
            //    dt.ToString("yyyy-MM-dd") == "2025-04-06"))
            //{
            //    Util.MsgE("4월 5일~6일은 데이터베이스 마이그레이션 기간이므로 프로그램 사용이 중단 됩니다\n문의 010-9155-9051 (EEDP:김치균)");
            //    return;
            //}
            if (this.tbID.Text.isEmpty())
            {
                tbID.Focus();
                return;
            }
            if (this.tbPW.Text.isEmpty())
            {
                tbPW.Focus();
                return;
            }
            if (cmbDept.SelectedIndex < 0)
            {
                FCOMMON.Util.MsgE("소속 부서를 선택하세요");
                cmbDept.Focus();
                return;
            }

            List<string> idlist = new List<string>();
            idlist.Add(tbID.Text.Trim());
            foreach (var item in this.tbID.Items)
                if (idlist.Contains(item) == false) idlist.Add(item.ToString());

            //List<string> deptlist = new List<string>();
            //deptlist.Add(cmbDept.Text.Trim());
            //foreach (var item in this.cmbDept.Items)
            //    if (deptlist.Contains(item) == false) deptlist.Add(item.ToString());

            //180605
            var vuserlist = "";
            foreach (var item in idlist)
                vuserlist += ";" + item;

            //var vdeptlist = "";
            //foreach(var item in deptlist)
            //    vdeptlist += ";" + item;

            var gCode = this.cmbDept.SelectedValue.ToString();// as dsMSSQL.UserGroupRow;

            Pub.setting.lastid = vuserlist;// tbID.Text.Trim();
            Pub.setting.lastdpt = cmbDept.Text; //부서저장 201006
            Pub.setting.lastgcode = gCode;
            Pub.setting.Save();

            var encpass = Pub.MakePasswordEnc(tbPW.Text.Trim());
            var id = tbID.Text.Trim();
            //var ta = new dsMSSQLTableAdapters.QueriesTableAdapter();//.UsersTableAdapter();
            try
            {
                if (id.ToUpper().Equals("DEV") == false)
                {
                    var taGrpUser = new dsMSSQLTableAdapters.EETGW_GroupUserTableAdapter();
                    var drGrpUser = taGrpUser.GetbyID(gCode, id).FirstOrDefault();
                    if (drGrpUser == null)
                    {
                        Util.MsgE($"입력한 사용자 계정이 존재하지 않습니다\n\n담당부서명:{cmbDept.Text}\n부서코드:{gCode}\n\n접속 부서를 확인하시고 관리자 문의 하세요");
                        tbPW.SelectAll();
                        tbPW.Focus();
                        return;
                    }
                    else if (drGrpUser.level == 0)
                    {
                        Util.MsgE($"해당 계정이 활성화되지 않았습니다\n계정 담당자 문의하세요");
                        tbPW.SelectAll();
                        tbPW.Focus();
                        return;
                    }

                    //사용자테이블에서 암호를 확인합니다.
                    var taUser = new dsMSSQLTableAdapters.UsersTableAdapter();
                    var drUser = taUser.GetID(id).FirstOrDefault();
                    if (drUser == null)
                    {
                        Util.MsgE($"입력한 사용자 계정이 존재하지 않습니다\n\n담당부서명:{cmbDept.Text}\n부서코드:{gCode}\n\n접속 부서를 확인하시고 관리자 문의 하세요");
                        tbPW.SelectAll();
                        tbPW.Focus();
                        return;
                    }
                    else if (drUser.password.Equals(encpass) == false)
                    {
                        Util.MsgE($"암호가 일치하지 않습니다.\n암호를 분실했을 경우에는 계정담당자에 초기화를 요청 하세요");
                        tbPW.SelectAll();
                        tbPW.Focus();
                        return;
                    }

                    //이사용자의 부서 코드확인
                    //var taUser = new dsMSSQLTableAdapters.vGroupUserTableAdapter();
                    //var userdr = taUser.GetByID(userGcode, id).Rows[0] as dsMSSQL.vGroupUserRow;

                    var MaxVerstion = FCOMMON.DBM.GetMaxVersion();
                    if (MaxVerstion.isEmpty() == false)
                    {
                        var curversion = Application.ProductVersion;
                        var verchk = curversion.CompareTo(MaxVerstion);
                        if (verchk < 0)
                        {
                            //내버젼이 낮다
                            Util.MsgE("현재 구 버젼을 사용하고 있습니다.\n업데이트를 진행 하고 사용하시기 바랍니다");
                        }
                    }

                    info.Login.no = drUser.id;
                    info.Login.nameK = drUser.name;
                    info.Login.dept = cmbDept.Text;// userdr.dept;// cmbDept.Text;
                    info.Login.level = drGrpUser.level;
                    info.Login.email = drUser.email;
                    info.Login.nameE = drUser.nameE;
                    info.Login.hp = drUser.hp;
                    info.Login.tel = drUser.tel;
                    info.Login.title = drUser.dept + "(" + drUser.grade + ")";
                    info.NotShowJobReportview = Pub.setting.NotShowJobreportPRewView;
                    //var gcode = FCOMMON.DBM.ExecuteScalar("select isnull(gcode,'NOGCODE') from UserGroup where dept ='" + cmbDept.Text + "'");
                    var gperm = FCOMMON.DBM.ExecuteScalar("select isnull(permission,0) from UserGroup where dept ='" + cmbDept.Text + "'");
                    info.Login.gcode = gCode;// gcode;
                    info.Login.process = drUser.id == "dev" ? "개발자" : drGrpUser.Process;
                    info.Login.permission = 0;
                    info.Login.gpermission = int.Parse(gperm);
                    //info.datapath = Pub.setting.SharedDataPath;
                    info.ShowBuyerror = Pub.setting.Showbuyerror;   //210625



                }
                else
                {
                    if (tbPW.Text.Equals("123") == false)
                    {
                        return;
                    }
                    info.Login.no = "dev";
                    info.Login.nameK = "개발자";
                    info.Login.dept = cmbDept.Text;// userdr.dept;// cmbDept.Text;
                    info.Login.level = 10;
                    info.Login.email = "";
                    info.Login.nameE = "DEVELOPER";
                    info.Login.hp = "";
                    info.Login.tel = "";
                    info.Login.title = "업무일지 개발자";
                    info.NotShowJobReportview = Pub.setting.NotShowJobreportPRewView;
                    //var gcode = FCOMMON.DBM.ExecuteScalar("select isnull(gcode,'NOGCODE') from UserGroup where dept ='" + cmbDept.Text + "'");
                    var gperm = FCOMMON.DBM.ExecuteScalar("select isnull(permission,0) from UserGroup where dept ='" + cmbDept.Text + "'");
                    info.Login.gcode = gCode;
                    info.Login.process = "개발자";
                    info.Login.permission = 0;
                    info.Login.gpermission = int.Parse(gperm);
                    //var datapath = FCOMMON.DBM.getCodeSavlue("55", "01");
                    //info.datapath = datapath;// Pub.setting.SharedDataPath;
                    info.ShowBuyerror = Pub.setting.Showbuyerror;   //210625
                }

                //if (info.datapath.isEmpty() && gCode == "EET1P") //210524
                //    info.datapath = @"\\k4fs3201n\k4bpartcenter$";
                //using (var dbEnity = new EEEntitiesMain())
                //{
                //	var drGrpUser = dbEnity.EETGW_GroupUser.Where(t => t.uid == userdr.id & t.gcode == gCode).FirstOrDefault();
                //	if (drGrpUser == null) info.Login.process = (userdr.id == "dev" ? "개발자" : "");
                //	else info.Login.process = drGrpUser.Process;
                //}

                //로그인정보 기록
                AddLoginInfo();

                //210221
                Pub.MakeAutoJobReportbyLogin();

                //210613    
                Pub.MakeAutoJobReportByAuto();

                DialogResult = DialogResult.OK;
                info.Login.loginusetime = (DateTime.Now - dt).TotalMilliseconds;
            }
            catch (Exception ex)
            {
                Util.MsgE("데이터베이스 조회 실패 다음 오류 메세지를 참고하세요.\n\n" + ex.Message + "\n\n증상이 동일 할 경우 서버가 접속가능한지 먼저 확인하세요");
                DialogResult = System.Windows.Forms.DialogResult.Cancel;
            }
        }

        void AddLoginInfo()
        {
            string ip = string.Empty;
            string hostname = Dns.GetHostName();
            string fullname = System.Net.Dns.GetHostEntry("").HostName;

            var nif = NetworkInterface.GetAllNetworkInterfaces();
            var host = Dns.GetHostEntry(hostname);
            foreach (IPAddress r in host.AddressList)
            {
                string str = r.ToString();

                if (str != "" && str.Substring(0, 3) == "10.")
                {
                    ip = str;
                    break;
                }
            }

            if (ip == "" || hostname == "") return;

            try
            {
                var ta = new dsMSSQLTableAdapters.EETGW_LoginInfoTableAdapter();
                ta.Insert(info.Login.no, DateTime.Now, ip, fullname, info.Login.no, DateTime.Now);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
                Console.WriteLine(ex.Message);
            }
        }
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FCOMMON.Util.RunExplorer("mailto:chikyun.kim@amkor.co.kr");
        }

        private void cmbDept_SelectedIndexChanged(object sender, EventArgs e)
        {
            //부서명이 변경되었다
            label4.Text = "문의) 정보없음(?)";
            var sel = cmbDept.SelectedItem as DataRowView;
            if (sel == null) return;
            var dr = sel.Row as dsMSSQL.UserGroupRow;
            if (dr == null) return;

            var admin = dr.managerinfo;
            if (string.IsNullOrEmpty(admin))
                admin = "--";

            var dev = dr.devinfo;
            if (string.IsNullOrEmpty(dev))
                dev = "chikyun.kim@amkor.co.kr(T8567)";

            label4.Text = $"문의) 관리:{admin},개발:{dev}";

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //if (System.Diagnostics.Debugger.IsAttached == false)
            //{
            //    Util.MsgE("이 기능은 준비중 입니다");
            //    return;
            //}

            var gCode = this.cmbDept.SelectedValue.ToString();// as dsMSSQL.UserGroupRow;
            info.Login.gcode = gCode;
            info.Login.no = "new";
            info.Login.dept = this.cmbDept.Text;

            var dlg = FCOMMON.Util.MsgQ($"현재 선택된 그룹[{this.cmbDept.Text}]의 사용자를 추가할까요?\n" +
          "추가된 사용자는 담당자로부터 승인 완료되어야 접속이 가능 합니다\n" +
          "사용자 추가 후 그룹담당자에게 문의 하시기 바랍니다");
            if (dlg != DialogResult.Yes) return;
            var f = new _Common.fAddNewUser(cmbDept.Text, string.Empty, 0);//.fUserInfo();
            dlg = f.ShowDialog();
            if (dlg == DialogResult.OK)
            {
                tbID.Text = f.tbId.Text.Trim();
            }
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var lv = this.listView1.FocusedItem;
            if (lv == null) return;
            if (lv.Tag == null) return;
            var msg = lv.Tag.ToString();
            Util.MsgI(msg);

        }
    }
}
