using Dapper;
using Dapper.Contrib.Extensions;
using MailKit.Security;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using MimeKit;
using Newtonsoft.Json;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using static ad_login.Controllers.ApiController;
using static DbTableClass;
using ad_login.Models;



namespace ad_login.Controllers
{
    [EnableCors("any")]
    [Route("Api")]
   
    public class ApiController : ControllerBase
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly PasswordManagementService _passwordManagement;

        DbConn dbConn = new DbConn();
        SqlConnection conn = new SqlConnection(GlobalClass.appsettings("ConnectionStrings:SQLConnectionString"));

        public ApiController(IHttpContextAccessor httpContextAccessor, IWebHostEnvironment webHostEnvironment, PasswordManagementService passwordManagement)
        {
            this._httpContextAccessor = httpContextAccessor;
            this._hostingEnvironment = webHostEnvironment;
            this._passwordManagement = passwordManagement;
        } 

        [Route("ChangeADPassword")]
        public ActionResult ChangeADPassword(IFormCollection obj) {
            result ret = new result();

            string user_name = obj["user_name"].ToString();
            string old_password = obj["old_password"].ToString();
            string new_password = obj["new_password"].ToString();

            if (new_password.Length < 6) {
                ret.ret = "no";
                ret.err_code = "0001";
                ret.message = "新密碼長度必須大於6個字元";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (old_password == new_password) {
                ret.ret = "no";
                ret.err_code = "0002";
                ret.message = "新密碼不能與舊密碼相同";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (_passwordManagement.ChangePasswordSdsP(user_name, old_password, new_password))
            {
                ret.ret = "yes";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }
            else {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "修改失敗，請確認帳號或密碼是否正確! 或者是帳號為不得更改密碼的設定!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");

            }

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }


        [EnableCors("any")]
        [Route("news_list")]
        public async Task<ActionResult> News_List(IFormCollection obj) {
            newResult ret = new newResult();

            List<news> newsList = conn.Query<news>("select * from news order by news_sn desc").ToList();

            ret.news_num = newsList.Count;

            foreach (news objNew in newsList)
            {
                newsDetial objDetial = new newsDetial(objNew);
                objDetial.news_content = objDetial.news_content.Replace("color: rgb(5, 5, 5);", "").Replace("font-family: 微軟正黑體;", "");
                ret.news_list.Add(objDetial);
            }

            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }


        [EnableCors("any")]
        [Route("esg_message")]
        public async Task<ActionResult> Esg_Message(IFormCollection obj) {
            result ret = new result();

            esgMessage objEsg = new esgMessage();

            objEsg.esgMessage_company = obj["company"].ToString();
            objEsg.esgMessage_id = obj["id"].ToString();
            objEsg.esgMessage_name = obj["name"].ToString();
            objEsg.esgMessage_email = obj["email"].ToString();
            objEsg.esgMessage_tel = obj["tel"].ToString();
            objEsg.esgMessage_department = obj["department"].ToString();
            objEsg.esgMessage_esgNeed = obj["esgNeed"].ToString();
            objEsg.esgMessage_mediaUrl = obj["mediaUrl"].ToString();
            objEsg.esgMessage_testResult = obj["result"].ToString();

            string err_msg = "";

            if (objEsg.esgMessage_company == "") {
                err_msg += "無企業名稱\n";
            }

            if (objEsg.esgMessage_name == "")
            {
                err_msg += "無聯絡人姓名\n";
            }

            if (objEsg.esgMessage_tel == "")
            {
                err_msg += "無聯絡人電話\n";
            }

            if (err_msg != "") {
                ret.ret = "no";
                ret.message = err_msg;
                ret.err_code = "0001";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string[] mediaUrl = objEsg.esgMessage_mediaUrl.Split(";");

            string htmlBody = "";

            htmlBody += "<H2>聯絡方式</H2>";
            htmlBody += "<br/>企業名稱：" + objEsg.esgMessage_company;
            htmlBody += "<br/>統一編號：" + objEsg.esgMessage_id;
            htmlBody += "<br/>聯絡人姓名：" + objEsg.esgMessage_name;
            htmlBody += "<br/>聯絡人 email：" + objEsg.esgMessage_email;
            htmlBody += "<br/>聯絡人電話：" + objEsg.esgMessage_tel;
            htmlBody += "<br/>聯絡人部門/職稱：" + objEsg.esgMessage_department;
            htmlBody += "<br/>------------------------------------------------------------------------------";
            htmlBody += "<br/>檢測結果：" + objEsg.esgMessage_testResult;
            htmlBody += "<br/>已知EGS需求：" + objEsg.esgMessage_esgNeed;
            htmlBody += "<br/>------------------------------------------------------------------------------";
            htmlBody += "<br/>企業目前主要自媒體：";

            foreach (string urlstr in mediaUrl) {
                htmlBody += "<br/><a href='" + urlstr + "' target='_blank'>" + urlstr + "</a>";
            }


            MailRequest mailRequest = new MailRequest();
            mailRequest.ToEmail = "calvin@bremen.com.tw,queenie@bremen.com.tw,sunny.lin@bremen.com.tw";
            //mailRequest.attach = arrBites;
            //mailRequest.attachName = "結果.xlsx";
            mailRequest.Body = htmlBody;
           
            mailRequest.Subject = "分眾結果通知信";

            await SendEmailAsync(mailRequest);

            DbConn dbConn = new DbConn();
            SqlConnection conn = dbConn.sqlConnection();

            conn.Insert<esgMessage>(objEsg);

            conn.Close();

            ret.ret = "yes";

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [EnableCors("any")]
        [Route("esg_mail")]
        public async Task<ActionResult> Esg_Mail(IFormCollection obj) {
            result ret = new result();

            string company = obj["company"].ToString();
            string name = obj["name"].ToString();
            string job = obj["job"].ToString();
            string needs = obj["needs"].ToString();
            string other = obj["other"].ToString();
            string target_email = obj["email"].ToString();
            string target_link = obj["link"].ToString();

            string err_msg = "";

            //if (GlobalClass.isURL(target_link) == false)
            //{
            //    err_msg += "無有效結果連結\n";
            //}

            //if (GlobalClass.isURL(target_link) == false)
            //{
            //    err_msg += "無有效結果連結\n";
            //}

            if (target_email != "")
            {
                if (GlobalClass.isEmail(target_email) == false)
                {
                    err_msg += "無有效Email\n";
                }
            }

            if (company == "")
            {
                err_msg += "無企業名稱\n";
            }

            if (name == "")
            {
                err_msg += "無聯絡人姓名\n";
            }

            if (target_link == "")
            {
                err_msg += "無檢測結果連結\n";
            }


            if (err_msg != "")
            {
                ret.ret = "no";
                ret.message = err_msg;
                ret.err_code = "0001";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }


            string ownHtml = "";
            ownHtml += "<h2>有人填寫ESG快速檢測通知信</h2>";
            ownHtml += "<br/>1.企業名稱：" + company;
            ownHtml += "<br/>2.聯絡人姓名：" + name;
            ownHtml += "<br/>3.聯絡人email：" + target_email;
            ownHtml += "<br/>4.聯絡人職稱：" + job;
            ownHtml += "<br/>5.已知ESG需求：" + needs;
            ownHtml += "<br/>  其他 >>> " + other;
            ownHtml += "<br/>6.檢測結果：<a href='" + target_link + "'>檢測結果頁</a>";

            //建立AlternativeView
            var altView2 = AlternateView.CreateAlternateViewFromString(ownHtml, null, "text/html");
            //將圖檔資源加入AlternativeView
         

            await SendEsgResultOwnAsync(altView2);

            string html = $@"";

            string fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/email_pic/email_footer.jpg");
            var res = new LinkedResource(fullPath, MediaTypeNames.Image.Jpeg);
            res.ContentId = Guid.NewGuid().ToString();

            html += "<body>";
            html += "<table align='center' border='0' cellpadding='0' cellspacing='0' role='presentation' style='border-collapse:collapse;width:100%' width='100%'>";
            html += "  <tbody>";
            html += "    <tr>";
            html += "      <td style='border-collapse:collapse'>";
            html += "        ";
            html += "        <div style='margin:0px auto;max-width:1000px'>";
            html += "          <table align='center' border='0' cellpadding='0' cellspacing='0' role='presentation' style='border-collapse:collapse;width:100%' width='100%'>";
            html += "            <tbody>";
            html += "              <tr>";
            html += "                <td style='border-collapse:collapse;direction:ltr;font-size:0px;padding:20px 0;text-align:center' align='center'>";
            html += "                  ";
            html += "                  <div class='m_-2162171852830059364mj-column-per-100' style='font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%'>";
            html += "                    <table border='0' cellpadding='0' cellspacing='0' role='presentation' style='border-collapse:collapse;vertical-align:top' width='100%' valign='top'>";
            html += "                      <tbody>";
            html += "                        <tr>";
            html += "                          <td align='center' style='border-collapse:collapse;font-size:0px;padding:10px 25px;padding-top:40px;padding-bottom:20px;word-break:break-word'>";
            html += "                            <div style=\"font-family:'Source Han Sans','Noto Sans CJK TC',sans-serif;font-size:28px;font-weight:500;letter-spacing:1px;line-height:40px;text-align:center;text-transform:uppercase;color:#163713\">您好，謝謝您填寫ESG快速檢測<br>詳細的測驗結果分析，請點擊以下連結查看：</div>";
            html += "                          </td>";
            html += "                        </tr>";
            html += "                        <tr>";
            html += "                          <td align='center' style='border-collapse:collapse;font-size:0px;padding:10px 25px;word-break:break-word'>";
            html += "                            <table border='0' cellpadding='0' cellspacing='0' role='presentation' style='border-collapse:separate;line-height:100%'>";
            html += "                              <tbody><tr>";
            html += "                                <td align='center' bgcolor='#2c5228' role='presentation' style='border-collapse:collapse;border:none;border-radius:9999px;background:#2c5228' valign='middle'>";
            html += "                                  <a href='" + target_link + "' style=\"display:inline-block;background:#2c5228;color:#ffffff;font-family:'Source Han Sans','Noto Sans CJK TC',sans-serif;font-size:28px;font-weight:normal;line-height:120%;margin:0;text-decoration:none;text-transform:none;padding:10px 25px;border-radius:9999px\" target='_blank' data-saferedirecturl='" + target_link + "'> 查看結果 </a>";
            html += "                                </td>";
            html += "                              </tr>";
            html += "                            </tbody></table>";
            html += "                          </td>";
            html += "                        </tr>";
            html += "                        <tr>";
            html += "                          <td align='center' style='border-collapse:collapse;font-size:0px;padding:0;padding-top:40px;word-break:break-word'>";
            html += "                            <table border='0' cellpadding='0' cellspacing='0' role='presentation' style='border-collapse:collapse;border-spacing:0px'>";
            html += "                              <tbody>";
            html += "                                <tr>";
            html += "                                  <td style='border-collapse:collapse;width:800px' width='800'>";
            html += "                                    <a href='" + target_link + "' target='_blank' data-saferedirecturl='https://www.google.com/url?q=" + target_link + "'>";
            html += "                                      <img alt='' height='auto' src='cid:" + res.ContentId + "' style='line-height:100%;border:0;display:block;outline:none;text-decoration:none;height:auto;width:100%;font-size:13px' width='800' class='CToWUd' data-bit='iit'>";
            html += "                                    </a>";
            html += "                                  </td>";
            html += "                                </tr>";
            html += "                              </tbody>";
            html += "                            </table>";
            html += "                          </td>";
            html += "                        </tr>";
            html += "                      </tbody>";
            html += "                    </table>";
            html += "                  </div>";
            html += "                  ";
            html += "                </td>";
            html += "              </tr>";
            html += "            </tbody>";
            html += "          </table>";
            html += "        </div>";
            html += "        ";
            html += "      </td>";
            html += "    </tr>";
            html += "  </tbody>";
            html += "</table>";
            html += "</body>";

            if (target_email != "") {
                //建立AlternativeView
                var altView = AlternateView.CreateAlternateViewFromString(html, null, "text/html");
                //將圖檔資源加入AlternativeView
                altView.LinkedResources.Add(res);

                await SendEsgResultMailAsync(altView, target_email);

                ret.ret = "yes";

                ret.message = "已寄送結果通知信至" + target_email;
            } 
            else {
                ret.ret = "yes";
                ret.message = "無Email，無法寄送結果通知信";
            }



            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        public class newResult
        {
            public string ret = "no";
            public string err_code = "0000";
            public string message = "";
            public int news_num = 0;
            public List<news> news_list = new List<news>();
        }

        public class result
        {
            public string ret = "no";
            public string err_code = "0000";
            public string message = "";

        }

        public async Task SendEsgResultOwnAsync(AlternateView altView)
        {
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host = GlobalClass.appsettings("MailServer:smtp_host");
            client.Port = int.Parse(GlobalClass.appsettings("MailServer:smtp_port"));
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential(
                GlobalClass.appsettings("MailServer:smtp_username"),
                GlobalClass.appsettings("MailServer:smtp_password")
            );

            var mail = new MailMessage();
            mail.IsBodyHtml = true;

            mail.AlternateViews.Add(altView);
            mail.To.Add("calvin@bremen.com.tw,queenie@bremen.com.tw,sunny.lin@bremen.com.tw");

            mail.From = new MailAddress(GlobalClass.appsettings("MailServer:smtp_username"), "用戶ESG快速檢測結果", System.Text.Encoding.UTF8);
            mail.Subject = "用戶ESG快速檢測結果";
            await client.SendMailAsync(mail).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Console.WriteLine("Error sending email: " + task.Exception);
                }
                else
                {
                    Console.WriteLine("Email sent successfully.");
                }
            });

            client.Dispose();
        }

        public async Task SendEsgResultMailAsync(AlternateView altView, string toEmail) {
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host = GlobalClass.appsettings("MailServer:smtp_host");
            client.Port = int.Parse(GlobalClass.appsettings("MailServer:smtp_port"));
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential(
                GlobalClass.appsettings("MailServer:smtp_username"),
                GlobalClass.appsettings("MailServer:smtp_password")
            );

            var mail = new MailMessage();
            mail.IsBodyHtml = true;

            mail.AlternateViews.Add(altView);
            mail.To.Add(toEmail);
            mail.Bcc.Add("sunny.lin@bremen.com.tw");
            mail.From = new MailAddress(GlobalClass.appsettings("MailServer:smtp_username"), "ESG快速檢測結果分析", System.Text.Encoding.UTF8);
            mail.Subject = "ESG快速檢測結果分析";
            await client.SendMailAsync(mail).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Console.WriteLine("Error sending email: " + task.Exception);
                }
                else
                {
                    Console.WriteLine("Email sent successfully.");
                }
            });

            client.Dispose();
        }

        /// <summary>
        public async Task SendEmailAsync(MailRequest mailRequest)
        {
            var email = new MimeMessage();
            email.Sender = MailboxAddress.Parse(GlobalClass.appsettings("MailServer:smtp_username"));
            email.To.Add(MailboxAddress.Parse(GlobalClass.appsettings("MailServer:smtp_username")));

            foreach (string item in mailRequest.ToEmail.Split(','))
            {
                email.Bcc.Add(MailboxAddress.Parse(item));
            }

            email.Subject = "ESG需求聯絡表通知信";

            var builder = new BodyBuilder();

            if (mailRequest.attach != null) {
                builder.Attachments.Add(mailRequest.attachName, mailRequest.attach);
            }
            
            builder.HtmlBody = mailRequest.Body;
            email.Body = builder.ToMessageBody();

            using var smtp = new MailKit.Net.Smtp.SmtpClient();
            smtp.Connect(GlobalClass.appsettings("MailServer:smtp_host"), int.Parse(GlobalClass.appsettings("MailServer:smtp_port")), SecureSocketOptions.StartTls);
            smtp.Authenticate(GlobalClass.appsettings("MailServer:smtp_username"), GlobalClass.appsettings("MailServer:smtp_password"));
            await smtp.SendAsync(email);
            smtp.Dispose();

        }

        public class MailRequest
        {
            public string ToEmail { get; set; } = "";
            public string Subject { get; set; } = "分眾結果通知信";
            public string Body { get; set; } = "";
            public byte[] attach { get; set; }
            public string attachName { get; set; } = "file.xlsx";
        }
    }
}
