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

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


                using (var dbEnity = new EEEntitiesMain())
                {
                    var drGrpUser = dbEnity.EETGW_GroupUser.Where(t => t.uid == userdr.id & t.gcode == gCode).FirstOrDefault();
                    FCOMMON.info.Login.process = drGrpUser.Process;
                }


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

                //210221
                MakeAutoJobReport();

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

        }

        void MakeAutoJobReport()
        {
            //자동로그인 업무일지 기록 기능 추가 = 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.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 label3_Click(object sender, EventArgs e)
        {

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //var f = new Dialog.fSelectDept();
            //if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    if (cmbDept.Items.Contains(f.deptName) == false)
            //        cmbDept.Items.Add(f.deptName);
            //    cmbDept.Text = f.deptName;
            //}
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FCOMMON.Util.RunExplorer("mailto:chikyun.kim@amkor.co.kr");
        }
    }
}
