using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Cors;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Dapper.Contrib.Extensions;

using System.IO;
using System.Threading;
using System.Dynamic;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.XSSF;
using NPOI.XSSF.UserModel;
using NPOI.POIFS;
using NPOI.Util;
using Microsoft.Extensions.Configuration;
using Org.BouncyCastle.Ocsp;
using System.Security.Policy;
using NPOI.SS.Formula.Functions;
using static DbTableClass;
using System.Runtime.InteropServices.ObjectiveC;
using static System.Net.WebRequestMethods;
using MimeKit;
using MailKit.Net.Smtp;
using MailKit.Security;


namespace Bremen_ESG.Controllers
{
    [Route("Api")]
   
    public class ApiController : ControllerBase
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWebHostEnvironment _hostingEnvironment;

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

        [HttpPost]
        [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[] 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,poli.chen@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");
        }

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

        }

        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 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";
        }
    }
}
