using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Winsock_Orcas;
using System.Management;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Net;
using System.Data.SqlClient;
using System.Data;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.Drawing;
using System.Windows.Forms;

namespace Project
{
    public static class Pub
    {
        //Variable
        public static Device.Barcode barcode;

        public static UserSetting uSetting;         //user setting
        public static Setting setting;              //global setting

        public static DateTime LastInputTime = DateTime.Now;
        public static CResult Result = new CResult();
        public static DatabaseConnectionString.DatabaseInfo dbinfo = null;
        public static string WebServiceURL { get; set; }

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

            var dbAI = new dsMSSQLTableAdapters.EETGW_JobReport_AutoInputTableAdapter();//  EEEntitiesMain();
            var dbGU = new dsMSSQLTableAdapters.vGroupUserTableAdapter();// EEEntitiesMain();
            var dbHL = new dsMSSQLTableAdapters.HolidayLIstTableAdapter();
            var dbJR = new dsMSSQLTableAdapters.JobReportTableAdapter();
            var taQuery = new DSQueryTableAdapters.QueriesTableAdapter();

            var nd = DateTime.Now.ToString("yyyy-MM-dd");

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


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

            // 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));
            var rows = dbAI.GetActiveList(FCOMMON.info.Login.gcode, "A", "%", nd);

            foreach (var dr in rows)
            {
                //퇴사자 확인
                var userdata = dbGU.GetByID(FCOMMON.info.Login.gcode, dr.uid).FirstOrDefault();// db.vGroupUser.Where(t => t.id == dr.uid).FirstOrDefault();
                if (userdata != null && userdata.IsoutdateNull() == false) continue;

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

                //이데이터를 그대로 생성해준다.
                var dtjr = new dsMSSQL.JobReportDataTable();
                var newdr = dtjr.NewJobReportRow();
                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 = "진행 완료";
                newdr.tag = dr.tag;
                newdr.uid = dr.uid;
                dtjr.AddJobReportRow(newdr);
                dbJR.Update(dtjr);
            }
            dbAI.Dispose();
            dbGU.Dispose();
            dbHL.Dispose();
            dbJR.Dispose();
            taQuery.Dispose();
        }

        /// <summary>
        /// 로그인으로 업무일지를 작성하는 경우
        /// </summary>
        public static 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 nd = DateTime.Now.ToString("yyyy-MM-dd");

            var taQ = new DSQueryTableAdapters.QueriesTableAdapter();
            var exist = taQ.ExistAutoInputData(FCOMMON.info.Login.gcode, FCOMMON.info.Login.no, nd) > 0;
            //var db = new EEEntitiesMain();

            if (exist == false)
            {
                var taM = new dsMSSQLTableAdapters.EETGW_JobReport_AutoInputTableAdapter();
                var rows = taM.GetActiveList(FCOMMON.info.Login.gcode, "L", FCOMMON.info.Login.no, nd);

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

                var newjob = new dsMSSQL.JobReportDataTable();
                foreach (var dr in rows)
                {
                    //이데이터를 그대로 생성해준다.
                    var newdr = newjob.NewJobReportRow();
                    newdr.gcode = FCOMMON.info.Login.gcode;
                    newdr.wuid = FCOMMON.info.Login.no;
                    newdr.wdate = DateTime.Now;
                    newdr.pdate = nd;
                    newdr.import = false;
                    if (dr.IshrsNull() == false) newdr.hrs = dr.hrs;
                    if (dr.IstypeNull() == false) newdr.type = dr.type;//210305 누락분 추가
                    if (dr.IsotNull() == false) newdr.ot = dr.ot;
                    if (dr.IsprocessNull() == false) newdr.process = dr.process;
                    if (dr.IsprojectNameNull() == false) newdr.projectName = dr.projectName;
                    if (dr.IspidxNull() == false) newdr.pidx = dr.pidx;
                    if (dr.IspackageNull() == false) newdr.package = dr.package;
                    newdr.autoinput = true;
                    if (dr.IsdescriptionNull() == false) newdr.description = dr.description;
                    if (dr.Isdescription2Null() == false) newdr.description2 = dr.description2;
                    if (dr.IsremarkNull() == false) newdr.remark = dr.remark;
                    if (dr.IsrequestpartNull() == false) newdr.requestpart = dr.requestpart;
                    if (dr.IsstatusNull() == false) newdr.status = dr.status;
                    if (dr.IstagNull() == false) newdr.tag = dr.tag;
                    if (dr.IsuidNull() == false) newdr.uid = dr.uid;
                    newjob.AddJobReportRow(newdr);
                }

                if (newjob.Count() > 0)
                {
                    var taJ = new dsMSSQLTableAdapters.JobReportTableAdapter();
                    var cnt = taJ.Update(newjob);
                    //db.SaveChanges();
                    Util.MsgI($"{cnt} 건의 업무일지가 자동 생성 되었습니다\n업무일지는 로그인시 최초 1회 자동 등록됩니다\n" +
                        "자동입력을 해제하려면 '업무일지-자동입력' 화면에서 내역을 변경하거나 종료일자를 설정하시기 바랍니다");
                }
            }
        }



        public static void init()
        {
            FCOMMON.info.Path = Util.CurrentPath;
            if (Util.isLocalApplication())
            {
                FCOMMON.info.Path = @"c:\Amkor\GroupWare\";
                if (!System.IO.Directory.Exists(FCOMMON.info.Path))
                    System.IO.Directory.CreateDirectory(FCOMMON.info.Path);
            }
            FCOMMON.info.CS = Properties.Settings.Default.gwcs;
            FCOMMON.info.mailserver = "10.101.5.150";// Properties.Settings.Default.mailserver;

            //setting
            setting = new Setting(FCOMMON.info.Path.MakeFilePath("Setting", "Setting.xml"));
            setting.Load();

            uSetting = new UserSetting(FCOMMON.info.Path.MakeFilePath("Setting", "UserSet.xml"));
            uSetting.Load();

            //log
            FCOMMON.Pub.log = new arUtil.Log();

            //clear login info
            FCOMMON.info.Login = new FCOMMON.info.sUserInfo();

            //language
            Lang.Loading(Pub.setting.Language + ".ini");
            if (WebServiceURL.isEmpty())
                WebServiceURL = "http://127.0.0.1:7979";
        }

        private static WebView2 webView21;
        public static void InitializeWebView2()
        {
            // 수동으로 WebView2 컨트롤 생성
            webView21 = new WebView2();

            // 기본 속성 설정
            webView21.CreationProperties = null;
            webView21.DefaultBackgroundColor = Color.White;
            webView21.Dock = System.Windows.Forms.DockStyle.Fill;
            webView21.Location = new Point(0, 0);
            webView21.Name = "webView21";
            webView21.Size = new Size(800, 600);
            webView21.TabIndex = 0;
            webView21.ZoomFactor = 1D;

            // 비동기 초기화
            InitializeAsync();
        }
        async private static void InitializeAsync()
        {
            try
            {
                // Fixed Version 경로 설정
                string runtimePath = System.IO.Path.Combine(Application.StartupPath, "WebView2Runtime");

                if (System.IO.Directory.Exists(runtimePath))
                {
                    var env = await CoreWebView2Environment.CreateAsync(runtimePath);
                    await webView21.EnsureCoreWebView2Async(env);

                }
                else
                {
                    // 시스템에 설치된 WebView2 사용
                    await webView21.EnsureCoreWebView2Async();
                }

                InitWebView = 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                InitWebView = 2;
            }
        }
        public static byte InitWebView = 0;

        public static string MakePasswordEnc(string data)
        {
            var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            var buffer = System.Text.Encoding.Default.GetBytes(data);
            var hashbuf = sha1.ComputeHash(buffer);
            var encpass = hashbuf.GetHexString();
            var ta = new dsMSSQLTableAdapters.UsersTableAdapter();
            encpass = encpass.Replace(" ", "");
            return encpass;
        }
        public static void SetFormStatus(ref System.Windows.Forms.Form f, string formid, Boolean read)
        {
            var fi = new System.IO.FileInfo(Util.CurrentPath + "formSetting\\" + formid + ".xml");
            if (fi.Directory.Exists == false) fi.Directory.Create();
            arUtil.XMLHelper xml = new arUtil.XMLHelper(fi.FullName);
            if (!xml.Exist())
            {
                xml.CreateFile();
                if (read) return; //읽기인데 파일이 없으므로 넘어간다.
            }
            if (read)
            {
                var leftStr = xml.get_Data("position", "left");
                var topStr = xml.get_Data("position", "top");
                int l = 0;
                int t = 0;
                if (!int.TryParse(leftStr, out l)) l = 0;
                if (!int.TryParse(topStr, out t)) t = 0;
                if (l != 0 || t != 0)
                {
                    f.Location = new System.Drawing.Point(l, t);
                }

                var wStr = xml.get_Data("size", "width");
                var hStr = xml.get_Data("size", "height");
                int w = 0;
                int h = 0;
                if (!int.TryParse(wStr, out w)) w = 0;
                if (!int.TryParse(hStr, out h)) h = 0;
                if (w != 0 || h != 0)
                {
                    f.Size = new System.Drawing.Size(w, h);
                }
            }
            else
            {
                xml.set_Data("position", "left", f.Left.ToString());
                xml.set_Data("position", "top", f.Top.ToString());
                xml.set_Data("size", "width", f.Width.ToString());
                xml.set_Data("size", "height", f.Height.ToString());
                xml.Save();
            }

        }
        public static void CheckNRegister5(string prgmName, string develop, string prgmVersion,string mcid, string remark)
        {
            if (prgmName.Length > 50) prgmName = prgmName.Substring(0, 50); //길이제한
            var task = Task.Factory.StartNew(() =>
            {
                try
                {
                    string ip = "";
                    string mac = "";
                    //      string prgmName = Application.ProductName;

                    var nif = NetworkInterface.GetAllNetworkInterfaces();
                    var host = Dns.GetHostEntry(Dns.GetHostName());
                    string fullname = System.Net.Dns.GetHostEntry("").HostName;
                    foreach (IPAddress r in host.AddressList)
                    {
                        string str = r.ToString();

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

                    string rtn = string.Empty;
                    ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled='TRUE'");
                    ManagementObjectSearcher query1 = new ManagementObjectSearcher(oq);
                    foreach (ManagementObject mo in query1.Get())
                    {
                        string[] address = (string[])mo["IPAddress"];
                        if (address[0] == ip && mo["MACAddress"] != null)
                        {
                            mac = mo["MACAddress"].ToString();
                            break;
                        }
                    }

                    if (ip == "" || mac == "")
                    {
                        return;
                    }


                    SqlConnection conn = new SqlConnection(Properties.Settings.Default.CS);// "Data Source=K4FASQL.kr.ds.amkor.com,50150;Initial Catalog=EE;Persist Security Info=True;User ID=eeadm;Password=uJnU8a8q&DJ+ug-D!" ;
                    conn.Open();
                    string ProcName = "AddPrgmUser5";
                    SqlCommand cmd = new SqlCommand(ProcName, conn);
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlParameter param = cmd.Parameters.Add("@mac", SqlDbType.NVarChar, 50);
                    param.Value = mac;

                    param = cmd.Parameters.Add("@ip", SqlDbType.NVarChar, 50);
                    param.Value = ip;

                    param = cmd.Parameters.Add("@pgrm", SqlDbType.NVarChar, 50);
                    param.Value = prgmName;

                    param = cmd.Parameters.Add("@develop", SqlDbType.NVarChar, 50);
                    param.Value = develop;

                    param = cmd.Parameters.Add("@pgver", SqlDbType.NVarChar, 50);
                    param.Value = prgmVersion;

                    param = cmd.Parameters.Add("@prgmLogin", SqlDbType.VarChar, 20);
                    param.Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    param = cmd.Parameters.Add("@account", SqlDbType.NVarChar, 50);
                    param.Value = System.Environment.UserName;

                    param = cmd.Parameters.Add("@hostname", SqlDbType.NVarChar, 100);
                    param.Value = fullname;

                    param = cmd.Parameters.Add("@mcid", SqlDbType.NVarChar, 10);
                    param.Value = mcid;

                    param = cmd.Parameters.Add("@remark", SqlDbType.NVarChar, 255);
                    param.Value = remark;

                    var cnt = cmd.ExecuteNonQuery();
                    conn.Close();
                }
                catch (Exception ex)
                {
                    FCOMMON.Pub.log.AddE(ex.Message);
                }

            });
        }
    }
}
