using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace FCOMMON
{
    public static partial class DBM
    {
        public static SqlConnection getCn()
        {
            string cs = FCOMMON.info.CS;
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = cs;
            return cn;
        }

        public struct sItemInfo
        {
            public int idx;
            public string sid;
            public string model;
            public string supply;
            public string name;
            public string unit;
            public float scale;
            public string price;
            public int supplyidx;
            public string project;
            public int qty;
        }

        public static byte[] getImagByteArray(System.Drawing.Image img)
        {
            if (img == null || img.Width < 1 || img.Height < 1) return null;

            //이미지가 640보다 크면 조정한다.
            if (img.Width > 640)
            {
                var newrate = (640.0 / img.Width * 1.0);
                var newheight = (int)(img.Height * newrate); //높이값 다시 계산
                var newimg = new System.Drawing.Bitmap(640, newheight);
                var g = System.Drawing.Graphics.FromImage(newimg);
                g.DrawImage(img, new System.Drawing.Rectangle(0, 0, 640, newheight));
                g.Dispose();
                img = (System.Drawing.Image)(newimg.Clone());

            }
            else if (img.Height > 480)
            {
                var newrate = (480.0 / img.Height * 1.0);
                var newwidth = (int)(img.Width * newrate); //높이값 다시 계산
                var newimg = new System.Drawing.Bitmap(newwidth, 480);
                var g = System.Drawing.Graphics.FromImage(newimg);
                g.DrawImage(img, new System.Drawing.Rectangle(0, 0, newwidth, 480));
                g.Dispose();
                img = (System.Drawing.Image)(newimg.Clone());
            }



            System.IO.MemoryStream sm = new System.IO.MemoryStream();
            img.Save(sm, System.Drawing.Imaging.ImageFormat.Jpeg);
            var buffer = sm.GetBuffer();
            sm.Dispose();
            return buffer;
        }
        public static Boolean setImageData(System.Drawing.Bitmap img, string table, string field, int idx)
        {
            return setImageData((System.Drawing.Image)img, table, field, idx);
        }
        public static Boolean setImageData(System.Drawing.Image img, string table, string field, int idx)
        {
            if (img == null || img.Width < 1 || img.Height < 1) return false;

            //이미지가 640보다 크면 조정한다.
            if (img.Width > 640)
            {
                var newrate = (640.0 / img.Width * 1.0);
                var newheight = (int)(img.Height * newrate); //높이값 다시 계산
                var newimg = new System.Drawing.Bitmap(640, newheight);
                var g = System.Drawing.Graphics.FromImage(newimg);
                g.DrawImage(img, new System.Drawing.Rectangle(0, 0, 640, newheight));
                g.Dispose();
                img = (System.Drawing.Image)(newimg.Clone());

            }
            else if (img.Height > 480)
            {
                var newrate = (480.0 / img.Height * 1.0);
                var newwidth = (int)(img.Width * newrate); //높이값 다시 계산
                var newimg = new System.Drawing.Bitmap(newwidth, 480);
                var g = System.Drawing.Graphics.FromImage(newimg);
                g.DrawImage(img, new System.Drawing.Rectangle(0, 0, newwidth, 480));
                g.Dispose();
                img = (System.Drawing.Image)(newimg.Clone());
            }

            var cn = getCn();
            cn.Open();

            Boolean retval = false;
            string sql = "update  " + table + " set " + field + " = @data" + " where idx = @idx";
            var cmd = new SqlCommand(sql, cn);

            System.IO.MemoryStream sm = new System.IO.MemoryStream();
            img.Save(sm, System.Drawing.Imaging.ImageFormat.Jpeg);
            var buffer = sm.GetBuffer();
            sm.Dispose();

            cmd.Parameters.Add(new SqlParameter("idx", idx));
            cmd.Parameters.Add(new SqlParameter("data", buffer));
            try
            {
                cmd.ExecuteNonQuery();
                retval = true;
            }
            catch
            {

            }

            cn.Close();
            cn.Dispose();
            return retval;
        }


        /// <summary>
        /// 지정쿼리를 실행합니다.
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string sql)
        {
            var cn = getCn();
            cn.Open();
            var cmd = new SqlCommand(sql, cn);
            var retval = cmd.ExecuteNonQuery();
            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static int ExecuteScalarI(string sql)
        {
            var cn = getCn();
            cn.Open();
            var cmd = new SqlCommand(sql, cn);
            var retval = (int)(cmd.ExecuteScalar());
            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static string ExecuteScalar(string sql)
        {
            var cn = getCn();
            cn.Open();
            var cmd = new SqlCommand(sql, cn);
            var retval = cmd.ExecuteScalar().ToString();
            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static System.Drawing.Image GetImageData(string table, string field, int idx)
        {
            var cn = getCn();
            cn.Open();


            string sql = "select " + field + " from " + table + " where idx = " + idx.ToString();
            var cmd = new SqlCommand(sql, cn);
            var data = cmd.ExecuteScalar() as byte[];
            System.Drawing.Bitmap bmp = null;
            if (data != null)
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
                bmp = new System.Drawing.Bitmap(ms, true);
                ms.Dispose();
            }
            cn.Close();
            cn.Dispose();
            return bmp;
        }

        public static sItemInfo getLastPurchaseInfo(int idx)
        {
            var cn = getCn();
            cn.Open();

            var retval = new sItemInfo();
            retval.idx = -1;

            string sql = "select isnull(max(idx),-1) from Purchase where pumidx = " + idx.ToString();
            var cmd = new SqlCommand(sql, cn);
            int maxidx = int.Parse(cmd.ExecuteScalar().ToString());
            if (maxidx == -1) return retval;

            cmd.CommandText = "select * from Purchase where idx = " + maxidx.ToString();
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                retval.idx = (int)rdr["idx"];
                if (rdr["sid"] != DBNull.Value) retval.sid = rdr["sid"].ToString();
                if (rdr["pumscale"] != DBNull.Value) retval.model = rdr["pumscale"].ToString();
                if (rdr["supply"] != DBNull.Value) retval.supply = rdr["supply"].ToString();
                if (rdr["supplyidx"] != DBNull.Value) retval.supplyidx = int.Parse(rdr["supplyidx"].ToString());
                else retval.supplyidx = -1;

                if (rdr["pumname"] != DBNull.Value) retval.name = rdr["pumname"].ToString();
                if (rdr["pumunit"] != DBNull.Value) retval.unit = rdr["pumunit"].ToString();
                if (rdr["project"] != DBNull.Value) retval.project = rdr["project"].ToString();

                if (rdr["pumprice"] != DBNull.Value) retval.price = rdr["pumprice"].ToString();
                else retval.price = "0";

                if (rdr["pumqty"] != DBNull.Value) retval.qty = int.Parse(rdr["pumqty"].ToString());
                else retval.qty = 0;

            }

            cn.Close();
            cn.Dispose();
            return retval;
        }


        /// <summary>
        /// 서플라이정보를 찾습니다. 1개의데이터가 검색된 경우에만 사용 됩니다.
        /// </summary>
        /// <param name="nameLike"></param>
        /// <param name="idx"></param>
        /// <param name="nameK"></param>
        /// <param name="nameE"></param>
        /// <returns></returns>
        public static Boolean getFindSupply(string nameLike, out int idx, out string nameK, out string nameE)
        {
            idx = -1;
            nameE = "";
            nameK = "";

            var cn = getCn();
            cn.Open();

            string sql = "select idx,name,name2 from Customs where (name like '%SEEMAX%' or name2 like '%{0}%')";
            sql = string.Format(sql, nameLike);
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();

            int cnt = 0;
            while (rdr.Read())
            {
                idx = (int)rdr["idx"];
                if (rdr["name"] != DBNull.Value) nameK = rdr["name"].ToString();
                if (rdr["name2"] != DBNull.Value) nameE = rdr["name2"].ToString();
                cnt += 1;
            }

            cn.Close();
            cn.Dispose();
            return cnt == 1;
        }

        /// <summary>
        /// 프로젝트 주간내역을 추가합니다
        /// </summary>
        /// <param name="ProjectIdx"></param>
        /// <param name="Message"></param>
        /// <returns></returns>
        public static Boolean addProjectHistory(int ProjectIdx, string pdate, string Message,string rtf)
        {

            var cn = getCn();
            cn.Open();

            string sql =
                "insert into ProjectsHistory(pidx,pdate,remark,remark2,wuid,wdate)" +
                " values(@pidx,@pdate,@remark,@remark2,@wuid,@wdate)";

            var cmd = new SqlCommand(sql, cn);
            cmd.Parameters.Add(new SqlParameter("pidx", ProjectIdx));
            cmd.Parameters.Add(new SqlParameter("pdate", pdate));
            cmd.Parameters.Add(new SqlParameter("remark", Message));
            cmd.Parameters.Add(new SqlParameter("remark2", rtf));
            cmd.Parameters.Add(new SqlParameter("wuid", FCOMMON.info.Login.no));
            cmd.Parameters.Add(new SqlParameter("wdate", DateTime.Now));
            var cnt = cmd.ExecuteNonQuery();

            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return cnt == 1;
        }

        public static sItemInfo getItemInfo(int idx)
        {
            var cn = getCn();
            cn.Open();

            var retval = new sItemInfo();
            retval.idx = -1;

            string sql = "select * from Items where gcode='" + FCOMMON.info.Login.gcode + "' and  idx = " + idx.ToString();
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                retval.idx = (int)rdr["idx"];
                if (rdr["sid"] != DBNull.Value) retval.sid = rdr["sid"].ToString();
                if (rdr["model"] != DBNull.Value) retval.model = rdr["model"].ToString();
                if (rdr["supply"] != DBNull.Value) retval.supply = rdr["supply"].ToString();
                if (rdr["supplyidx"] != DBNull.Value) retval.supplyidx = int.Parse(rdr["supplyidx"].ToString());

                if (rdr["name"] != DBNull.Value) retval.name = rdr["name"].ToString();
                if (rdr["unit"] != DBNull.Value) retval.unit = rdr["unit"].ToString();
                if (rdr["scale"] != DBNull.Value) retval.scale = float.Parse(rdr["scale"].ToString());
                if (rdr["price"] != DBNull.Value) retval.price = rdr["price"].ToString();

            }

            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static int addItemInfo(sItemInfo info)
        {
            int retval = -1;
            var cn = getCn();
            cn.Open();

            string sql = "insert into Items" +
                " ([gcode],[cate],[sid],[model],[supply],[supplyidx],[name],[unit],[scale],[price],[wuid],[wdate])" +
                " values " +
                " (@gcode,@cate,@sid,@model,@supply,@supplyidx,@name,@unit,@scale,@price,@wuid,@wdate)";

            var cmd = new SqlCommand(sql, cn);
            cmd.Parameters.Add(new SqlParameter("@gcode", FCOMMON.info.Login.gcode));
            cmd.Parameters.Add(new SqlParameter("@cate", "etc"));
            cmd.Parameters.Add(new SqlParameter("@sid", info.sid));
            cmd.Parameters.Add(new SqlParameter("@model", info.model));
            cmd.Parameters.Add(new SqlParameter("@supply", info.supply));
            cmd.Parameters.Add(new SqlParameter("@supplyidx", info.supplyidx));
            cmd.Parameters.Add(new SqlParameter("@name", info.name));
            cmd.Parameters.Add(new SqlParameter("@unit", info.unit));
            cmd.Parameters.Add(new SqlParameter("@scale", info.scale));
            cmd.Parameters.Add(new SqlParameter("@price", info.price));
            cmd.Parameters.Add(new SqlParameter("@wuid", FCOMMON.info.Login.no));
            cmd.Parameters.Add(new SqlParameter("@wdate", DateTime.Now));

            var iCnt = cmd.ExecuteNonQuery();
            if (iCnt == 1)
            {
                cmd.CommandText = "select isnull(idx,-1) from Items where gcode=@gcode and  [sid] = @sid";
                cmd.Parameters.Clear();
                cmd.Parameters.Add(new SqlParameter("gcode", FCOMMON.info.Login.gcode));
                cmd.Parameters.Add(new SqlParameter("sid", info.sid));
                retval = (int)cmd.ExecuteScalar();
            }

            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static sItemInfo getItemInfo(string sid)
        {
            var cn = getCn();
            cn.Open();

            var retval = new sItemInfo();
            retval.idx = -1;

            string sql = "select * from Items where [gcode] = '" + FCOMMON.info.Login.gcode + "' and  [sid] = '" + sid + "'";
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                retval.idx = (int)rdr["idx"];
                if (rdr["sid"] != DBNull.Value) retval.sid = rdr["sid"].ToString();
                if (rdr["model"] != DBNull.Value) retval.model = rdr["model"].ToString();
                if (rdr["supply"] != DBNull.Value) retval.supply = rdr["supply"].ToString();
                if (rdr["supplyidx"] != DBNull.Value) retval.supplyidx = int.Parse(rdr["supplyidx"].ToString());

                if (rdr["name"] != DBNull.Value) retval.name = rdr["name"].ToString();
                if (rdr["unit"] != DBNull.Value) retval.unit = rdr["unit"].ToString();
                if (rdr["scale"] != DBNull.Value) retval.scale = float.Parse(rdr["scale"].ToString());
                if (rdr["price"] != DBNull.Value) retval.price = rdr["price"].ToString();
            }

            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static Dictionary<string, string> getUserList(int baseLevel = 1)
        {
            string where = "isnull(level,0) >= " + baseLevel.ToString();
            return getTwoColumnList("vGroupUser", "id", "name", where, "name");

        }
        public static System.Data.DataTable getUserTable(int baseLevel = 1)
        {
            var cn = getCn();
            cn.Open();

            var retval = new sItemInfo();
            retval.idx = -1;

            string sql = "select [id],[name],([name] +'(' +[id] +')') as dispName,[dept],[email],[level],[tel] " +
                " from vGroupUser " +
                " where gcode='" + FCOMMON.info.Login.gcode + "' and  [id] <> 'dev' and dept like '%" + FCOMMON.info.Login.dept.Replace("'", "''") + "%' order by [name]";
            var cmd = new SqlCommand(sql, cn);
            var da = new SqlDataAdapter(sql, cn);
            var ds = new System.Data.DataSet();
            da.Fill(ds);
            cn.Close();
            cn.Dispose();
            if (ds.Tables.Count > 0) return ds.Tables[0];
            else return null;
        }

        private static Dictionary<string, string> MakeDataTable(List<string> list)
        {
            var retval = new Dictionary<string, string>();
            foreach (var item in list)
                retval.Add(item, item);
            return retval;
        }
        private static System.Data.DataTable MakeDataTable(Dictionary<string, string> list)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("Key");
            dt.Columns.Add("Value");
            dt.Columns.Add("KeyValue");

            foreach (var item in list)
            {
                dt.Rows.Add(new string[] { item.Key, item.Value, string.Format("[{0}] {1}", item.Key, item.Value) });
            }
            dt.AcceptChanges();
            return dt;
        }

        public static Dictionary<string, string> getProjectList(string StateCode = "")
        {
            string where = "status = '{0}'";
            if (StateCode != "") where = string.Format(where, StateCode);
            else where = string.Empty;

            return getTwoColumnList("Projects", "idx", "name", where, "status,name");
        }
        public static System.Data.DataTable getProjectData(string StateCode = "")
        {
            var list = getProjectList(StateCode);
            return MakeDataTable(list);
        }
        public static Dictionary<string, string> getCodeList(string GroupCode = "99")
        {
            string where = "Grp = '{0}'";
            where = string.Format(where, GroupCode);
            return getTwoColumnList("Common", "code", "memo", where, "code");
        }
        public static string getCodeSavlue(string GroupCode, string code)
        {
            var cn = getCn();
            cn.Open();
            var sql = "select isnull(SValue,'')" +
                      " from Common" +
                      " where gcode='" + FCOMMON.info.Login.gcode + "' and  Grp = '{0}' and code = '{1}'";

            sql = string.Format(sql, GroupCode, code);
            var cmd = new SqlCommand(sql, cn);
            var data = cmd.ExecuteScalar();
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return data.ToString();
        }

        public struct sCodeData
        {
            public string code;
            public string title;
            public string svalue;
            public string grp;
        }
        public static sCodeData getCodeBySvalue(string GroupCode, string svalue)
        {
            var retval = new sCodeData();
            retval.code = string.Empty;
            retval.title = string.Empty;
            retval.svalue = string.Empty;
            retval.grp = string.Empty;

            var cn = getCn();
            cn.Open();
            var sql = "select isnull(code,''),isnull(memo,'')" +
                      " from Common" +
                      " where gcode='" + FCOMMON.info.Login.gcode + "' and  Grp = '{0}' and svalue = '{1}'";

            sql = string.Format(sql, GroupCode, svalue);
            var cmd = new SqlCommand(sql, cn);
            var da = cmd.ExecuteReader();
            while (da.Read())
            {
                retval.code = da[0].ToString();
                retval.title = da[1].ToString();
            }

            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            retval.grp = GroupCode;
            retval.svalue = svalue;
            return retval;
        }
        public static sCodeData getCodeByMemo(string GroupCode, string memo)
        {
            var retval = new sCodeData();
            retval.code = string.Empty;
            retval.title = string.Empty;
            retval.svalue = string.Empty;
            retval.grp = string.Empty;


            var cn = getCn();
            cn.Open();
            var sql = "select isnull(code,''),isnull(memo,'')" +
                      " from Common" +
                      " where gcode='" + FCOMMON.info.Login.gcode + "' and  Grp = '{0}' and memo = '{1}'";

            sql = string.Format(sql, GroupCode, memo);
            var cmd = new SqlCommand(sql, cn);
            var da = cmd.ExecuteReader();
            while (da.Read())
            {
                retval.code = da[0].ToString();
                retval.title = da[1].ToString();
            }

            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            retval.grp = GroupCode;
            retval.svalue = memo;
            return retval;
        }



        public static Boolean insertCommonCode(string GroupCode, string code, string memo, string svalue = "")
        {

            var cn = getCn();
            cn.Open();
            var sql = "insert into common(gcode,grp,code,svalue,memo,wuid,wdate)" +
                     " values(@gcode,@grp,@code,@svalue,@memo,@wuid,@wdate)";

            sql = string.Format(sql, GroupCode, memo);
            var cmd = new SqlCommand(sql, cn);
            cmd.Parameters.Add(new SqlParameter("gcode", FCOMMON.info.Login.gcode));
            cmd.Parameters.Add(new SqlParameter("grp", GroupCode));
            cmd.Parameters.Add(new SqlParameter("code", code));
            cmd.Parameters.Add(new SqlParameter("memo", memo));
            cmd.Parameters.Add(new SqlParameter("svalue", svalue));
            cmd.Parameters.Add(new SqlParameter("wuid", FCOMMON.info.Login.no));
            cmd.Parameters.Add(new SqlParameter("wdate", DateTime.Now));
            var da = cmd.ExecuteNonQuery();

            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return da > 0;
        }

        public static sCodeData getCodeByCode(string GroupCode, string code)
        {
            var retval = new sCodeData();
            retval.code = string.Empty;
            retval.title = string.Empty;
            retval.svalue = string.Empty;
            retval.grp = string.Empty;

            var cn = getCn();
            cn.Open();
            var sql = "select isnull(code,''),isnull(memo,'')" +
                      " from Common" +
                      " where gcode='" + FCOMMON.info.Login.gcode + "' and  Grp = '{0}' and code = '{1}'";

            sql = string.Format(sql, GroupCode, code);
            var cmd = new SqlCommand(sql, cn);
            var da = cmd.ExecuteReader();
            while (da.Read())
            {
                retval.code = da[0].ToString();
                retval.title = da[1].ToString();
            }

            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            retval.grp = GroupCode;
            retval.svalue = code;
            return retval;
        }

        /// <summary>
        /// 지정된 프로젝트의 마지막 업무일지 데이터를 반환함 
        /// </summary>
        /// <param name="projectIdx"></param>
        /// <returns></returns>
        public static System.Data.DataTable getLastJobReportData(string uid, int projectIdx)
        {
            var cn = getCn();
            cn.Open();
            var sql = "select top 1 * from JobReport" +
                " where gcode ='" + FCOMMON.info.Login.gcode + "' and  isnull(pidx,-1)=" + projectIdx.ToString() +
                " and uid ='" + uid + "'" +
                " order by pdate desc, idx desc";
            var da = new SqlDataAdapter(sql, cn);
            var ds = new System.Data.DataSet();
            da.Fill(ds);
            cn.Close();
            if (ds.Tables.Count > 0) return ds.Tables[0];
            else return null;
        }
        public static System.Data.DataTable getLastJobReportDatabyProjectName(string uid, string prjName)
        {
            var cn = getCn();
            cn.Open();
            var sql = "select top 1 * from JobReport" +
                " where gcode='" + FCOMMON.info.Login.gcode + "' and isnull(projectName,'') like '" + prjName + "'" +
                " and uid ='" + uid + "'" +
                " order by pdate desc, idx desc";
            var da = new SqlDataAdapter(sql, cn);
            var ds = new System.Data.DataSet();
            da.Fill(ds);
            cn.Close();
            if (ds.Tables.Count > 0) return ds.Tables[0];
            else return null;
        }
        public static System.Data.DataTable getLastJobReportData(string uid, string type)
        {
            var cn = getCn();
            cn.Open();
            var sql = "select top 1 * from JobReport" +
                " where gcode = '" + FCOMMON.info.Login.gcode + "' and  isnull([type],'')='" + type + "'" +
                " and uid ='" + uid + "'" +
                " order by pdate desc, idx desc";
            var da = new SqlDataAdapter(sql, cn);
            var ds = new System.Data.DataSet();
            da.Fill(ds);
            cn.Close();
            if (ds.Tables.Count > 0) return ds.Tables[0];
            else return null;
        }

        public static System.Data.DataTable getProcessList()
        {

            System.Data.DataTable retval = new System.Data.DataTable();
            retval.Columns.Add("Code");
            retval.Columns.Add("Value");

            var cn = getCn();
            cn.Open();
            var sql = "select isnull(processs,'') as process" +
                        " from Users" +
                        " where processs is not null and gcode='{0}'" +
                        " group by processs" +
                        " order by process";

            sql = string.Format(sql, FCOMMON.info.Login.gcode);
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            var cnt = 0;
            while (rdr.Read())
            {
                retval.Rows.Add(new string[] { cnt.ToString(), rdr[0].ToString() });
                cnt += 1;
            }
            rdr.Close();
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return retval;
        }



        public static System.Data.DataTable getUserProjectList(string userName)
        {

            System.Data.DataTable retval = new System.Data.DataTable();
            retval.Columns.Add("Code");
            retval.Columns.Add("Value");

            var cn = getCn();
            cn.Open();
            var sql = "select idx, '[' + cast(idx as varchar) + '] ' + isnull(name,''),pdate  from Projects" +
                " where gcode='{0}'" +
                " and  (isnull(userManager,'') like '%{1}%'" +
                " or  isnull(userMain,'') like '%{1}%'" +
                " or  isnull(usersub,'') like '%{1}%')" +
                " order by pdate desc,name";
            sql = string.Format(sql, FCOMMON.info.Login.gcode, userName);
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                retval.Rows.Add(new string[] { rdr[0].ToString(), rdr[1].ToString() });
            }
            rdr.Close();
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return retval;
        }


        public static System.Data.DataTable getCodeTable(string GroupCode = "99",string sort="memo")
        {

            System.Data.DataTable retval = new System.Data.DataTable();
            retval.Columns.Add("Code");
            retval.Columns.Add("Value");
            retval.Columns.Add("SValue");

            var cn = getCn();
            cn.Open();
            var sql = "select isnull(code,''),isnull(memo ,''),isnull(svalue,'')" +
                " from common" +
                " where gcode='" + FCOMMON.info.Login.gcode + "' and grp = '" + GroupCode + "'" +
                " and isnull(code,'') <> ''" +
                " order by isnull("+ sort + ",'')";
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                retval.Rows.Add(new string[] { rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString() });
            }
            rdr.Close();
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static Dictionary<string, string> getTwoColumnList(string table, string col1, string col2, string where = "", string order = "")
        {
            Dictionary<string, string> retval = new Dictionary<string, string>();
            var cn = getCn();
            cn.Open();
            var sql = "select isnull({1},''),isnull({2},'')" +
                " from {0} " +
                " where gcode = '" + FCOMMON.info.Login.gcode + "' ";
            if (where != "") sql += " and " + where;
            if (order != "") sql += " order by " + order;
            sql = string.Format(sql, table, col1, col2);
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                retval.Add(rdr[0].ToString(), rdr[1].ToString());
            }
            rdr.Close();
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static List<string> getPlaceList(string gcode)
        {
            var retval = new List<string>();
            var cn = getCn();
            cn.Open();
            var sql = "select isnull(place,'')" +
                " from Inventory " +
                " where gcode = '{0}'" +
                " order by place";
            sql = string.Format(sql, gcode);
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                retval.Add(rdr[0].ToString());
            }
            rdr.Close();
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return retval;
        }
        public static Dictionary<string, string> getGroupTable(string GroupColumn, string table, string where = "", Boolean desc = false)
        {
            var list = getGroupList(GroupColumn, table, where, desc);
            return MakeDataTable(list);
        }

        /// <summary>
        /// 데이터중 첫번째 자료를 반환 합니다.
        /// </summary>
        /// <param name="column"></param>
        /// <param name="table"></param>
        /// <param name="where"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public static String getFirstValue(string column, string table, string where = "", string order = "")
        {
            string retval = string.Empty;
            var cn = getCn();
            cn.Open();
            var sql = "select {0} " +
                " from {1} " +
                " where gcode='" + FCOMMON.info.Login.gcode + "' and isnull({0},'') != '' ";

            if (where != "") sql += " and " + where;
            if (order != "") sql += " order by " + order;

            sql = string.Format(sql, "[" + column + "]", table);
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                if (rdr[0] != null) retval = rdr[0].ToString();
            }
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return retval;
        }


        /// <summary>
        /// 지정된 사용자/월의 전체 근무시간 초과시간을 반환함
        /// </summary>
        /// <param name="uid">사용자번호</param>
        /// <param name="yymm">지정월(2019-05)</param>
        /// <param name="work">근무시간</param>
        /// <param name="total">최대근무시간(근무일수*8)</param>
        /// <param name="ot">초과근무시간</param>
        public static void getWorkTime(string uid, string yymm, out float work, out int total, out float ot)
        {
            work = 0;
            total = 0;
            ot = 0;
            string retval = string.Empty;
            var cn = getCn();

            try
            {

                cn.Open();
                var sql = "select isnull(sum(hrs),0) as hrs,isnull(sum(ot),0) as ot,dbo.getWorkDayCount('{1}') as workday" +
                    " from JobReport" +
                    " where gcode='" + FCOMMON.info.Login.gcode + "' and uid = '{0}' and substring(pdate,1,7) = '{1}'";

                sql = string.Format(sql, uid, yymm);
                var cmd = new SqlCommand(sql, cn);
                var rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    work = float.Parse(rdr[0].ToString());
                    ot = float.Parse(rdr[1].ToString());
                    total = int.Parse(rdr[2].ToString()) * 8;
                }
                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }
            catch
            {
                work = 0;
                total = 0;
                ot = 0;
            }
            finally
            {
                if (cn != null) cn.Dispose();
            }
        }


        public static int addItem(string pumname, string sid, string model, decimal price, string supply, int supplyidx = -1, byte[] pic = null)
        {

            var cn = getCn();
            cn.Open();

            int retval = -1;
            var cmd2 = new SqlCommand("", cn);

            cmd2.CommandText = string.Format("select count(*) from Items " +
                " where  ISNULL(REPLACE(name, ' ', '') + REPLACE(model, ' ', ''), '') = '{0}'", pumname.Replace(" ", "").Replace("'", "''") + model.Replace(" ", "").Replace("'", "''"));
            var cnt = int.Parse(cmd2.ExecuteScalar().ToString());
            if (cnt == 0)
            {
                DateTime wdate = DateTime.Now;

                if (pic == null)
                {
                    cmd2.CommandText = "insert into items(gcode,cate,name,sid,model,scale,unit,supply,supplyidx,price,wuid,wdate)" +
                       "values(@gcode,@cate,@name,@sid,@model,@scale,@unit,@supply,@supplyidx,@price,@wuid,@wdate)";
                }
                else
                {
                    cmd2.CommandText = "insert into items(gcode,cate,name,sid,model,scale,unit,supply,supplyidx,price,image,wuid,wdate)" +
                       "values(@gcode,@cate,@name,@sid,@model,@scale,@unit,@supply,@supplyidx,@price,@image,@wuid,@wdate)";
                }

                cmd2.Parameters.Clear();
                cmd2.Parameters.Add(new SqlParameter("gcode", FCOMMON.info.Login.gcode));
                cmd2.Parameters.Add(new SqlParameter("cate", "--"));
                cmd2.Parameters.Add(new SqlParameter("name", pumname.Trim()));
                cmd2.Parameters.Add(new SqlParameter("sid", sid.Trim()));
                cmd2.Parameters.Add(new SqlParameter("model", model.Trim()));
                cmd2.Parameters.Add(new SqlParameter("scale", 1.0));
                cmd2.Parameters.Add(new SqlParameter("unit", "EA"));
                cmd2.Parameters.Add(new SqlParameter("supply", supply));
                if (pic != null) cmd2.Parameters.Add(new SqlParameter("image", pic));
                cmd2.Parameters.Add(new SqlParameter("supplyidx", supplyidx));
                cmd2.Parameters.Add(new SqlParameter("price", price));
                cmd2.Parameters.Add(new SqlParameter("wuid", FCOMMON.info.Login.no));
                cmd2.Parameters.Add(new SqlParameter("wdate", wdate));
                retval += cmd2.ExecuteNonQuery();

                //추가된 데이터를 찾아서 다시 검색한다.
                //if (retval == 0)
                //{
                //    cmd2.CommandText = "select idx from Items where gcode=@gcode and  name = @name and sid = @sid and model = @model and wuid = @wuid and wdate = @wdate";
                //    retval = int.Parse(cmd2.ExecuteScalar().ToString());
                //}
                //else retval = -1;
            }

            //{
            cmd2.CommandText = string.Format("select min(idx) from Items where gcode='" + FCOMMON.info.Login.gcode + "' and  ISNULL(REPLACE(name, ' ', '') + REPLACE(model, ' ', ''), '') = '{0}'", pumname.Replace(" ", "").Replace("'", "''") + model.Replace(" ", "").Replace("'", "''"));
            var itemdata = cmd2.ExecuteScalar();
            if (itemdata == DBNull.Value || itemdata == null)
            {
                retval = -1;
            }
            else
            {
                var strItem = itemdata.ToString();
                if (strItem == "") retval = -1;
                else retval = int.Parse(strItem);
            }

            //}
            cmd2.Dispose();
            cn.Close();
            cn.Dispose();
            return retval;
        }

        public static Boolean UpdateItemSID(int itemIdx, string sid)
        {
            var cn = getCn();
            cn.Open();

            int retval = 0;
            var cmd2 = new SqlCommand("", cn);

            cmd2.CommandText = string.Format("update Items set sid=@sid where idx=@idx");

            cmd2.Parameters.Clear();
            cmd2.Parameters.Add(new SqlParameter("idx", itemIdx));
            cmd2.Parameters.Add(new SqlParameter("sid", sid));
            retval = cmd2.ExecuteNonQuery();
            cmd2.Dispose();
            cn.Close();
            cn.Dispose();
            return retval != 0;
        }

        public static List<String> getGroupList(string GroupColumn, string table, string where = "", Boolean desc = false, Boolean useColumncover = true)
        {
            List<string> retval = new List<string>();
            var cn = getCn();
            cn.Open();
            var sql = "select {0} " +
                " from {1} " +
                " where gcode='" + FCOMMON.info.Login.gcode + "' and isnull({0},'') != '' ";

            if (table.ToUpper() == "USERS")
                sql = "select {0} " +
                " from {1} " +
                " where isnull({0},'') != '' ";


            if (where != "") sql += " and " + where;

            sql += " group by {0} " +
                   " order by {0} ";
            if (desc) sql += " desc";

            if (useColumncover)
                sql = string.Format(sql, "[" + GroupColumn + "]", table);
            else
                sql = string.Format(sql, GroupColumn, table);
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                retval.Add(rdr[0].ToString());
            }
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return retval;
        }

        public static String getPathKJ(string dept)
        {
            var cn = getCn();
            cn.Open();
            var sql = "select max(isnull(path_kj,'')) " +
                " from UserGroup " +
                " where dept = '" + dept + "'";

            sql = string.Format(sql);
            var cmd = new SqlCommand(sql, cn);
            var rdr = cmd.ExecuteScalar();
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            if (rdr == null) return string.Empty;
            else return rdr.ToString();
        }
        public static Boolean setPathKJ(string dept, string path)
        {
            var cn = getCn();
            cn.Open();
            var sql = "update UserGroup set path_kj=@path" +
                " where dept = @dept";

            sql = string.Format(sql);
            var cmd = new SqlCommand(sql, cn);
            cmd.Parameters.Add(new SqlParameter("path", path));
            cmd.Parameters.Add(new SqlParameter("dept", dept));
            var rdr = cmd.ExecuteNonQuery();
            cmd.Dispose();
            cn.Close();
            cn.Dispose();
            return rdr > 0;
        }

        public static List<String> getDateList(string table, string where = "", Boolean desc = false)
        {
            return getGroupList("pdate", table, where, desc);
        }

        public static int UpdateItemIndexbySID()
        {
            int retval = 0;
            var cn1 = getCn();
            cn1.Open();

            var cn2 = getCn();
            cn2.Open();

            var sql = "select idx, " +
                        " isnull(pumname,'') as pumname, " +
                        " isnull([sid],'') as [sid], " +
                        " isnull(pumscale,'') as pummodel, " +
                        " isnull(pumunit,'EA') as pumunit, " +
                        " isnull(pumprice,0) as pumprice, " +
                        " isnull(supply,'') as supply, " +
                        " isnull(supplyidx,-1) as supplyidx" +
                        " from purchase " +
                        " where  gcode='" + FCOMMON.info.Login.gcode + "' and  isnull(sid,'') <> '' and " +
                        " isnull(sid,'') <> '신규'" +
                        " and isnull(pumidx,-1) = -1 " +
                        " and len(sid) = 9" +
                        " and isnull(pumname,'') <> ''";

            var cmd2 = new SqlCommand("", cn2);
            var cmd = new SqlCommand(sql, cn1);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                var pumname = rdr["pumname"].ToString();
                var pummodel = rdr["pummodel"].ToString();
                var pumunit = rdr["pumunit"].ToString();
                var pumprice = decimal.Parse(rdr["pumprice"].ToString());
                var supply = rdr["supply"].ToString();
                var supplyidx = int.Parse(rdr["supplyidx"].ToString());

                var sid = rdr["sid"].ToString();
                var idx = int.Parse(rdr["idx"].ToString());

                //아이템정보에서 이 sid 가 1개 존재한다면 그것에 연결한다.
                var sql2 = "select isnull(idx,-1) from Items where gcode='" + FCOMMON.info.Login.gcode + "' and [sid] = '" + sid + "'";
                cmd2.CommandText = sql2;

                var itemdata = cmd2.ExecuteScalar();
                if (itemdata != null && itemdata.ToString() != "-1")
                {
                    cmd2.CommandText = "update purchase set pumidx = " + itemdata.ToString() +
                        " where gcode='" + FCOMMON.info.Login.gcode + "' and idx=" + idx.ToString();
                    retval += cmd2.ExecuteNonQuery();
                }
                else
                {
                    cmd2.CommandText = "insert into items(gcode,cate,name,sid,model,scale,unit,supply,supplyidx,price,wuid,wdate)" +
                        "values(@gcode,@cate,@name,@sid,@model,@scale,@unit,@supply,@supplyidx,@price,@wuid,@wdate)";
                    cmd2.Parameters.Clear();
                    cmd2.Parameters.Add(new SqlParameter("gcode", FCOMMON.info.Login.gcode));
                    cmd2.Parameters.Add(new SqlParameter("cate", "--"));
                    cmd2.Parameters.Add(new SqlParameter("name", pumname));
                    cmd2.Parameters.Add(new SqlParameter("sid", sid));
                    cmd2.Parameters.Add(new SqlParameter("model", pummodel));
                    cmd2.Parameters.Add(new SqlParameter("scale", 1.0));
                    cmd2.Parameters.Add(new SqlParameter("unit", pumunit));
                    cmd2.Parameters.Add(new SqlParameter("supply", supply));
                    cmd2.Parameters.Add(new SqlParameter("supplyidx", supplyidx));
                    cmd2.Parameters.Add(new SqlParameter("price", pumprice));
                    cmd2.Parameters.Add(new SqlParameter("wuid", "dev"));
                    cmd2.Parameters.Add(new SqlParameter("wdate", DateTime.Now));
                    retval += cmd2.ExecuteNonQuery();
                }


            }
            cmd2.Dispose();
            cmd.Dispose();
            cn1.Close();
            cn1.Dispose();

            cn2.Close();
            cn2.Dispose();
            return retval;
        }
    }
}
