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 : Form
    {
        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);
        }
        private void fLogin_Load(object sender, EventArgs e)
        {
            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);


            //그룹목록가져오기
            var tagrp = new dsMSSQLTableAdapters.UserGroupTableAdapter();
            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;
            //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)
        {

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

            var encpass = Pub.MakePasswordEnc(tbPW.Text.Trim());
            var ta = new dsMSSQLTableAdapters.UsersTableAdapter();
            try
            {
                var users = ta.GetIDPW(encpass, tbID.Text.Trim());
                if (users.Rows.Count != 1)
                {
                    users = ta.GetByNamePw(tbID.Text.Trim(), encpass);
                    if (users.Rows.Count != 1)
                    {
                        Util.MsgE("입력한 사용자 계정이 존재하지 않습니다");
                        tbPW.SelectAll();
                        tbPW.Focus();
                        return;
                    }
                }

                //이사용자의 부서 코드확인
                var userdr = users.Rows[0] as dsMSSQL.UsersRow;
                var taGrpUser = new dsMSSQLTableAdapters.EETGW_GroupUserTableAdapter();
                var Exist = taGrpUser.ExistCheck(gCode, userdr.id) > 0;
                if (userdr.level < 9 && Exist == false)
                {
                    Util.MsgE("입력한 사용자는 지정한 부서에 접속할 권한이 없습니다");
                    return;
                }

                if (userdr.outdate.isEmpty() == false)
                {
                    if (DateTime.TryParse(userdr.outdate, out DateTime dtout))
                    {
                        if (DateTime.Now > dtout)
                        {
                            Util.MsgE("퇴사정보로 인해 이 계정은 로그인할 수 없습니다");
                            return;
                        }
                    }
                    else
                    {
                        Util.MsgE("퇴사일자가 입력되었지만 정상 문자열이 아니라서 진행할 수 없습니다");
                        return;
                    }
                }

                FCOMMON.info.Login.no = userdr.id;
                FCOMMON.info.Login.nameK = userdr.name;
                FCOMMON.info.Login.dept = cmbDept.Text;// userdr.dept;// cmbDept.Text;
                FCOMMON.info.Login.level = userdr.level;
                FCOMMON.info.Login.email = userdr.email;
                FCOMMON.info.Login.nameE = userdr.nameE;
                FCOMMON.info.Login.hp = userdr.hp;
                FCOMMON.info.Login.tel = userdr.tel;
                FCOMMON.info.Login.title = userdr.ads_title;
                //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 + "'");
                FCOMMON.info.Login.gcode = gCode;// gcode;
                FCOMMON.info.Login.process = userdr.processs;
                FCOMMON.info.Login.permission = 0;
                FCOMMON.info.Login.gpermission = int.Parse(gperm);
                FCOMMON.info.datapath = Pub.setting.SharedDataPath;
                FCOMMON.info.ShowBuyerror = Pub.setting.Showbuyerror;   //210625

                if (FCOMMON.info.datapath.isEmpty() && gCode == "EET1P") //210524
                    FCOMMON.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) FCOMMON.info.Login.process = (userdr.id == "dev" ? "개발자" : "");
                    else FCOMMON.info.Login.process = drGrpUser.Process;
                }

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

                //210221
                MakeAutoJobReportbyLogin();

                //210613    
                MakeAutoJobReportByAuto();

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

        /// <summary>
        /// 무조건 업무일지를 자동으로 작성하는 경우
        /// </summary>
        void MakeAutoJobReportByAuto()
        {
            //누군가가 로그인하면 당일 자동 생성되어야할 유저의 데이터를 기록한다.

            var dbi = new EEEntitiesMain();
            var db = new EEEntitiesMain();
            var nd = DateTime.Now.ToShortDateString();

            //이 날짜가 휴일인지 체크한다.
            var Holyinfo = db.HolidayLIst.Where(t => t.pdate == nd).FirstOrDefault();
            if (Holyinfo != null && Holyinfo.free != null && (bool)(Holyinfo.free)) return;


            //토,일은 처리하지 않음
            if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday) return;

      
            var rows = db.EETGW_JobReport_AutoInput.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.enable==true && t.autoinput == "A" && t.pdate.CompareTo(nd) <= 0 && (string.IsNullOrEmpty(t.edate) == true || t.edate.CompareTo(nd) > 0));
            foreach (var dr in rows)
            {
                //퇴사자 확인
                var userdata = db.vGroupUser.Where(t => t.id == dr.uid).FirstOrDefault();
                if (userdata != null && string.IsNullOrEmpty(userdata.outdate) == false) continue;

      


                //오늘자 자동생성된 데이터가 있다면 처리하지 않는다
                if (db.JobReport.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate == nd && t.uid == dr.uid && t.autoinput == true).Any()) continue;

                //이데이터를 그대로 생성해준다.
                var newdr = new JobReport();
                newdr.gcode = FCOMMON.info.Login.gcode;
                newdr.wuid = dr.uid;// FCOMMON.info.Login.no;
                newdr.wdate = DateTime.Now;
                newdr.pdate = nd;
                newdr.import = false;
                newdr.hrs = dr.hrs;
                newdr.type = dr.type;//210305 누락분 추가
                newdr.ot = dr.ot;
                newdr.process = dr.process;
                newdr.projectName = dr.projectName;
                newdr.pidx = dr.pidx;
                newdr.package = dr.package;
                newdr.autoinput = true;
                newdr.description = dr.description;
                newdr.description2 = dr.description2;
                newdr.remark = dr.remark;
                newdr.requestpart = dr.requestpart;
                newdr.status = dr.status;
                newdr.tag = dr.tag;
                newdr.uid = dr.uid;
                dbi.JobReport.Add(newdr);
                dbi.SaveChanges();
            }
            dbi.Dispose();
            db.Dispose();

        }

        /// <summary>
        /// 로그인으로 업무일지를 작성하는 경우
        /// </summary>
        void MakeAutoJobReportbyLogin()
        {
            //자동로그인 업무일지 기록 기능 추가 = 210220
            //select* from EETGW_JobReport_AutoInput where gcode = 'EET1P' and pdate <= '2021-02-20' and(edate is null or edate > '2021-02-20') and autoinput = 'L'
            var db = new EEEntitiesMain();
            var nd = DateTime.Now.ToShortDateString();
            if (db.JobReport.Where(t => t.gcode == FCOMMON.info.Login.gcode &&
            t.autoinput == true &&
            t.uid == FCOMMON.info.Login.no &&
            t.pdate == nd).Any() == false)
            {
                var rows = db.EETGW_JobReport_AutoInput.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.enable == true && t.autoinput == "L" && t.uid == FCOMMON.info.Login.no && t.pdate.CompareTo(nd) <= 0 && (string.IsNullOrEmpty(t.edate) == true || t.edate.CompareTo(nd) > 0));
                foreach (var dr in rows)
                {
                    //이데이터를 그대로 생성해준다.
                    var newdr = new JobReport();
                    newdr.gcode = FCOMMON.info.Login.gcode;
                    newdr.wuid = FCOMMON.info.Login.no;
                    newdr.wdate = DateTime.Now;
                    newdr.pdate = nd;
                    newdr.import = false;
                    newdr.hrs = dr.hrs;
                    newdr.type = dr.type;//210305 누락분 추가
                    newdr.ot = dr.ot;
                    newdr.process = dr.process;
                    newdr.projectName = dr.projectName;
                    newdr.pidx = dr.pidx;
                    newdr.package = dr.package;
                    newdr.autoinput = true;
                    newdr.description = dr.description;
                    newdr.description2 = dr.description2;
                    newdr.remark = dr.remark;
                    newdr.requestpart = dr.requestpart;
                    newdr.status = dr.status;
                    newdr.tag = dr.tag;
                    newdr.uid = dr.uid;
                    db.JobReport.Add(newdr);
                }
                if (rows.Count() > 0)
                {
                    db.SaveChanges();
                    Util.MsgI($"{rows.Count()} 건의 업무일지가 자동 생성 되었습니다\n업무일지는 로그인시 최초 1회 자동 등록됩니다\n" +
                        "자동입력을 해제하려면 '업무일지-자동입력' 화면에서 내역을 변경하거나 종료일자를 설정하시기 바랍니다");
                }
            }
        }

        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 db = new EEEntitiesMain();
                db.EETGW_LoginInfo.Add(new EETGW_LoginInfo
                {
                    uid = FCOMMON.info.Login.no,
                    hostname = fullname,
                    ip = ip,
                    login = DateTime.Now,
                    wuid = FCOMMON.info.Login.no,
                    wdate = DateTime.Now
                });
                db.SaveChanges();
            }
            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");
        }
    }
}
