using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using FCOMMON;
using NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;

namespace Project.Web
{
    public partial class MachineBridge
    {
        /// <summary>
        /// 메일 발신 내역 조회
        /// </summary>
        public string Mail_GetList(string startDate, string endDate, string searchKey)
        {
            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, subject, body, fromlist, tolist, cc AS cclist, bcc AS bcclist, project, cate, pdate
                        FROM MailData WITH (nolock)
                        WHERE gcode = @gcode 
                          AND (pdate BETWEEN @startDate AND @endDate)
                          AND (ISNULL(subject,'') LIKE @search OR ISNULL(fromlist,'') LIKE @search OR ISNULL(tolist,'') LIKE @search OR ISNULL(cate,'') LIKE @search)
                        ORDER BY pdate DESC", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@startDate", SqlDbType.VarChar).Value = startDate;
                    cmd.Parameters.Add("@endDate", SqlDbType.VarChar).Value = endDate;
                    cmd.Parameters.Add("@search", SqlDbType.NVarChar).Value = $"%{searchKey}%";

                    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),
                                uid = "",  // uid 컬럼 없음
                                subject = reader.IsDBNull(2) ? "" : reader.GetString(2),
                                htmlbody = reader.IsDBNull(3) ? "" : reader.GetString(3),  // body를 htmlbody로 반환
                                fromlist = reader.IsDBNull(4) ? "" : reader.GetString(4),
                                tolist = reader.IsDBNull(5) ? "" : reader.GetString(5),
                                cclist = reader.IsDBNull(6) ? "" : reader.GetString(6),
                                bcclist = reader.IsDBNull(7) ? "" : reader.GetString(7),
                                project = reader.IsDBNull(8) ? "" : reader.GetInt32(8).ToString(),
                                cate = reader.IsDBNull(9) ? "" : reader.GetString(9),
                                wdate = reader.IsDBNull(10) ? "" : reader.GetString(10)  // pdate를 wdate로 반환 (프론트엔드 호환)
                            });
                        }
                    }

                    return JsonConvert.SerializeObject(new { Success = true, Data = list });
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 메일 데이터 추가 (발송 대기열)
        /// </summary>
        public string Mail_AddData(string cate, string subject, string fromlist, string tolist, string cc, string bcc, string body)
        {
            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 MailData 
                        (gcode, cate, pdate, subject, fromlist, tolist, cc, bcc, body, SendOK, wuid, wdate)
                        VALUES 
                        (@gcode, @cate, @pdate, @subject, @fromlist, @tolist, @cc, @bcc, @body, 0, @wuid, GETDATE())", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@cate", SqlDbType.VarChar).Value = cate ?? "";
                    cmd.Parameters.Add("@pdate", SqlDbType.VarChar).Value = DateTime.Now.ToString("yyyy-MM-dd");
                    cmd.Parameters.Add("@subject", SqlDbType.VarChar).Value = subject ?? "";
                    cmd.Parameters.Add("@fromlist", SqlDbType.VarChar).Value = fromlist ?? "";
                    cmd.Parameters.Add("@tolist", SqlDbType.VarChar).Value = tolist ?? "";
                    cmd.Parameters.Add("@cc", SqlDbType.VarChar).Value = cc ?? "";
                    cmd.Parameters.Add("@bcc", SqlDbType.VarChar).Value = bcc ?? "";
                    cmd.Parameters.Add("@body", SqlDbType.VarChar).Value = body ?? "";
                    cmd.Parameters.Add("@wuid", SqlDbType.VarChar).Value = info.Login.no;

                    int affected = cmd.ExecuteNonQuery();

                    if (affected > 0)
                    {
                        return JsonConvert.SerializeObject(new { Success = true, Message = "메일이 발송 대기열에 추가되었습니다." });
                    }
                    else
                    {
                        return JsonConvert.SerializeObject(new { Success = false, Message = "메일 등록에 실패했습니다." });
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 메일 직접 발송 (SMTP)
        /// </summary>
        public string Mail_SendDirect(string cate, string subject, string fromlist, string tolist, string cc, string bcc, string body)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                // SMTP 직접 발송
                var mailserver = info.mailserver ?? "scwa.amkor.co.kr";
                var mc = new System.Net.Mail.SmtpClient(mailserver);
                var msg = new System.Net.Mail.MailMessage(
                    string.IsNullOrEmpty(fromlist) ? "gw@amkor.co.kr" : fromlist,
                    tolist,
                    subject,
                    body
                );

                if (!string.IsNullOrEmpty(bcc)) msg.Bcc.Add(bcc);
                if (!string.IsNullOrEmpty(cc)) msg.CC.Add(cc);
                msg.IsBodyHtml = true;

                mc.Send(msg);

                // 발송 성공 시 MailData에도 저장 (SendOK=1)
                var connStr = Project.Properties.Settings.Default.CS;
                using (var conn = new SqlConnection(connStr))
                {
                    conn.Open();

                    var cmd = new SqlCommand(@"
                        INSERT INTO MailData 
                        (gcode, cate, pdate, subject, fromlist, tolist, cc, bcc, body, SendOK, SendMsg, wuid, wdate, suid, sdate)
                        VALUES 
                        (@gcode, @cate, @pdate, @subject, @fromlist, @tolist, @cc, @bcc, @body, 1, @SendMsg, @wuid, GETDATE(), @wuid, GETDATE())", conn);

                    cmd.Parameters.Add("@gcode", SqlDbType.VarChar).Value = info.Login.gcode;
                    cmd.Parameters.Add("@cate", SqlDbType.VarChar).Value = cate ?? "";
                    cmd.Parameters.Add("@pdate", SqlDbType.VarChar).Value = DateTime.Now.ToString("yyyy-MM-dd");
                    cmd.Parameters.Add("@subject", SqlDbType.VarChar).Value = subject ?? "";
                    cmd.Parameters.Add("@fromlist", SqlDbType.VarChar).Value = string.IsNullOrEmpty(fromlist) ? "gw@amkor.co.kr" : fromlist;
                    cmd.Parameters.Add("@tolist", SqlDbType.VarChar).Value = tolist ?? "";
                    cmd.Parameters.Add("@cc", SqlDbType.VarChar).Value = cc ?? "";
                    cmd.Parameters.Add("@bcc", SqlDbType.VarChar).Value = bcc ?? "";
                    cmd.Parameters.Add("@body", SqlDbType.VarChar).Value = body ?? "";
                    cmd.Parameters.Add("@SendMsg", SqlDbType.VarChar).Value = "Direct Send";
                    cmd.Parameters.Add("@wuid", SqlDbType.VarChar).Value = info.Login.no;

                    cmd.ExecuteNonQuery();
                }

                return JsonConvert.SerializeObject(new { Success = true, Message = "메일이 발송되었습니다." });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = $"메일 발송 실패: {ex.Message}" });
            }
        }

        /// <summary>
        /// Outlook으로 메일 미리보기/발송
        /// </summary>
        public string Mail_SendOutlook(string subject, string _tolist, string cc, string bcc, string body)
        {
            try
            {
                if (string.IsNullOrEmpty(info.Login.no) || string.IsNullOrEmpty(info.Login.gcode))
                {
                    return JsonConvert.SerializeObject(new { Success = false, Message = "로그인이 필요합니다." });
                }

                // Outlook COM 객체 생성
                var tolist = new string[] { "Chikyun.kim@amkor.co.kr" }; //dr.tolist.Split(',');
                Outlook.Application outlookApplication = new Outlook.Application();

                foreach (var to in tolist)
                {
                    if (to.isEmpty()) continue;
                    var newMail = outlookApplication.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
                    newMail.Display();
                    newMail.Subject = subject.Trim(); // dr.title;
                    newMail.To = to;
                    newMail.CC = cc;
                    newMail.BCC = bcc;
                    // newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                    newMail.HTMLBody = body
                         .Replace("{USER}", FCOMMON.info.Login.nameK)
                         .Replace("{EUSER}", FCOMMON.info.Login.nameE)
                         .Replace("{EMAIL}", FCOMMON.info.Login.email)
                         .Replace("%7BEMAIL%7D", FCOMMON.info.Login.email)
                         .Replace("{HP}", FCOMMON.info.Login.hp)
                         .Replace("{TEL}", FCOMMON.info.Login.tel)
                         .Replace("{ITEM}", subject) + newMail.HTMLBody;
                }

                return JsonConvert.SerializeObject(new { Success = true, Message = "Outlook 메일 창이 열렸습니다." });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Success = false, Message = $"Outlook 실행 실패: {ex.Message}" });
            }
        }
    }
}
