using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using FCOMMON;

namespace Project.Web
{
    public partial class MachineBridge
    {
        /// <summary>
        /// 라이선스 목록 조회
        /// </summary>
        public string License_GetList()
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var connStr = Project.Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();

                    var cmd = new SqlCommand(@"
                        SELECT 
                            idx, gcode, expire, name, Version, MeterialNo, Supply, qty, 
                            uids, SerialNo, Remark, sdate, edate, manu, wuid, wdate
                        FROM EETGW_License WITH (nolock)
                        WHERE gcode = @gcode
                        ORDER BY expire DESC, name, sdate", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;

                    var list = new List<object>();
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            list.Add(new
                            {
                                idx = reader.GetInt32(0),
                                gcode = reader.IsDBNull(1) ? "" : reader.GetString(1),
                                expire = !reader.IsDBNull(2) && reader.GetBoolean(2),
                                name = reader.IsDBNull(3) ? "" : reader.GetString(3),
                                version = reader.IsDBNull(4) ? "" : reader.GetString(4),
                                meterialNo = reader.IsDBNull(5) ? "" : reader.GetString(5),
                                supply = reader.IsDBNull(6) ? "" : reader.GetString(6),
                                qty = reader.IsDBNull(7) ? 0 : reader.GetInt32(7),
                                uids = reader.IsDBNull(8) ? "" : reader.GetString(8),
                                serialNo = reader.IsDBNull(9) ? "" : reader.GetString(9),
                                remark = reader.IsDBNull(10) ? "" : reader.GetString(10),
                                sdate = reader.IsDBNull(11) ? "" : reader.GetString(11),
                                edate = reader.IsDBNull(12) ? "" : reader.GetString(12),
                                manu = reader.IsDBNull(13) ? "" : reader.GetString(13),
                                wuid = reader.IsDBNull(14) ? "" : reader.GetString(14),
                                wdate = reader.IsDBNull(15) ? "" : reader.GetDateTime(15).ToString("yyyy-MM-dd HH:mm:ss")
                            });
                        }
                    }

                    return JsonConvert.SerializeObject(new { Success = true, Data = list });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "라이선스 목록 조회 중 오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// 라이선스 추가
        /// </summary>
        public string License_Add(string name, string version, string meterialNo, string supply, 
            int qty, string uids, string serialNo, string remark, string sdate, string edate, 
            string manu, bool expire)
        {
            try
            {


                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var connStr = Project.Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();

                    var cmd = new SqlCommand(@"
                        INSERT INTO EETGW_License 
                        (gcode, expire, name, manu, Supply, qty, uids, sdate, edate, Remark, wuid, wdate, Version, SerialNo, MeterialNo)
                        VALUES 
                        (@gcode, @expire, @name, @manu, @Supply, @qty, @uids, @sdate, @edate, @Remark, @wuid, @wdate, @Version, @SerialNo, @MeterialNo);
                        SELECT SCOPE_IDENTITY();", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@expire", SqlDbType.Bit).Value = expire;
                    cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = name ?? "";
                    cmd.Parameters.Add("@manu", SqlDbType.NVarChar).Value = manu ?? "";
                    cmd.Parameters.Add("@Supply", SqlDbType.NVarChar).Value = supply ?? "";
                    cmd.Parameters.Add("@qty", SqlDbType.Int).Value = qty;
                    cmd.Parameters.Add("@uids", SqlDbType.NVarChar).Value = uids ?? "";
                    cmd.Parameters.Add("@sdate", SqlDbType.VarChar).Value = string.IsNullOrEmpty(sdate) ? DateTime.Now.ToString("yyyy-MM-dd") : sdate;
                    cmd.Parameters.Add("@edate", SqlDbType.VarChar).Value = (object)edate ?? DBNull.Value;
                    cmd.Parameters.Add("@Remark", SqlDbType.NVarChar).Value = remark ?? "";
                    cmd.Parameters.Add("@wuid", SqlDbType.VarChar).Value = info.Login.no;
                    cmd.Parameters.Add("@wdate", SqlDbType.DateTime).Value = DateTime.Now;
                    cmd.Parameters.Add("@Version", SqlDbType.NVarChar).Value = version ?? "";
                    cmd.Parameters.Add("@SerialNo", SqlDbType.NVarChar).Value = serialNo ?? "";
                    cmd.Parameters.Add("@MeterialNo", SqlDbType.NVarChar).Value = meterialNo ?? "";

                    var idx = Convert.ToInt32(cmd.ExecuteScalar());

                    return JsonConvert.SerializeObject(new { Success = true, Message = "라이선스가 추가되었습니다.", Data = new { idx } });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "라이선스 추가 중 오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// 라이선스 수정
        /// </summary>
        public string License_Update(int idx, string name, string version, string meterialNo, 
            string supply, int qty, string uids, string serialNo, string remark, string sdate, 
            string edate, string manu, bool expire)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var connStr = Project.Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();

                    var cmd = new SqlCommand(@"
                        UPDATE EETGW_License SET
                            expire = @expire, name = @name, manu = @manu, Supply = @Supply,
                            qty = @qty, uids = @uids, sdate = @sdate, edate = @edate,
                            Remark = @Remark, wuid = @wuid, wdate = @wdate,
                            Version = @Version, SerialNo = @SerialNo, MeterialNo = @MeterialNo
                        WHERE idx = @idx AND gcode = @gcode", conn);

                    cmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;
                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@expire", SqlDbType.Bit).Value = expire;
                    cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = name ?? "";
                    cmd.Parameters.Add("@manu", SqlDbType.NVarChar).Value = manu ?? "";
                    cmd.Parameters.Add("@Supply", SqlDbType.NVarChar).Value = supply ?? "";
                    cmd.Parameters.Add("@qty", SqlDbType.Int).Value = qty;
                    cmd.Parameters.Add("@uids", SqlDbType.NVarChar).Value = uids ?? "";
                    cmd.Parameters.Add("@sdate", SqlDbType.VarChar).Value = string.IsNullOrEmpty(sdate) ? DateTime.Now.ToString("yyyy-MM-dd") : sdate;
                    cmd.Parameters.Add("@edate", SqlDbType.VarChar).Value = (object)edate ?? DBNull.Value;
                    cmd.Parameters.Add("@Remark", SqlDbType.NVarChar).Value = remark ?? "";
                    cmd.Parameters.Add("@wuid", SqlDbType.VarChar).Value = info.Login.no;
                    cmd.Parameters.Add("@wdate", SqlDbType.DateTime).Value = DateTime.Now;
                    cmd.Parameters.Add("@Version", SqlDbType.NVarChar).Value = version ?? "";
                    cmd.Parameters.Add("@SerialNo", SqlDbType.NVarChar).Value = serialNo ?? "";
                    cmd.Parameters.Add("@MeterialNo", SqlDbType.NVarChar).Value = meterialNo ?? "";

                    var cnt = cmd.ExecuteNonQuery();

                    return JsonConvert.SerializeObject(new { Success = true, Message = "라이선스가 수정되었습니다.", Data = new { UpdatedCount = cnt } });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "라이선스 수정 중 오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// 라이선스 삭제
        /// </summary>
        public string License_Delete(int idx)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var connStr = Project.Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();

                    var cmd = new SqlCommand(@"
                        DELETE FROM EETGW_License 
                        WHERE idx = @idx AND gcode = @gcode", conn);

                    cmd.Parameters.Add("@idx", SqlDbType.Int).Value = idx;
                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;

                    var cnt = cmd.ExecuteNonQuery();

                    return JsonConvert.SerializeObject(new { Success = true, Message = "라이선스가 삭제되었습니다.", Data = new { DeletedCount = cnt } });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "라이선스 삭제 중 오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// 라이선스 폴더 열기
        /// </summary>
        public string License_OpenFolder(int idx)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var serverpath = DBM.getCodeSvalue("55", "01");
                if (string.IsNullOrEmpty(serverpath) || !Directory.Exists(serverpath))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "프로젝트 기본경로가 존재하지 않습니다.\\n\\n공용정보->공용코드->55-01 데이터를 설정 하시기 바랍니다." });
                }

                var folderPath = Path.Combine(serverpath, "Data", "License", idx.ToString());

                // 폴더가 없으면 생성
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                // 탐색기로 폴더 열기
                Process.Start("explorer.exe", folderPath);

                return JsonConvert.SerializeObject(new { Success = true, Message = "폴더를 열었습니다.", Data = new { Path = folderPath } });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "폴더 열기 중 오류가 발생했습니다: " + ex.Message });
            }
        }

        /// <summary>
        /// CSV로 내보내기
        /// </summary>
        public string License_ExportCSV(string filePath)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                var connStr = Project.Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();

                    var cmd = new SqlCommand(@"
                        SELECT 
                            idx, expire, name, Version, MeterialNo, Supply, qty, 
                            uids, SerialNo, Remark, sdate, edate, manu
                        FROM EETGW_License WITH (nolock)
                        WHERE gcode = @gcode
                        ORDER BY expire DESC, name, sdate", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;

                    var sb = new StringBuilder();
                    sb.AppendLine("idx,expire,name,Version,MeterialNo,Supply,qty,uids,SerialNo,Remark,sdate,edate,manu");

                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var values = new List<string>();
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                var value = reader.IsDBNull(i) ? "" : reader.GetValue(i).ToString();
                                // CSV 이스케이프 처리
                                if (value.Contains(",") || value.Contains("\"") || value.Contains("\n"))
                                {
                                    value = "\"" + value.Replace("\"", "\"\"") + "\"";
                                }
                                values.Add(value);
                            }
                            sb.AppendLine(string.Join(",", values));
                        }
                    }

                    File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);

                    return JsonConvert.SerializeObject(new { Success = true, Message = "CSV 파일이 생성되었습니다.", Data = new { Path = filePath } });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = "CSV 내보내기 중 오류가 발생했습니다: " + ex.Message });
            }
        }
    }
}
