using FrontendWebApi.Models;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FrontendWebApi.ApiControllers
{
    public class EmergencyContactController : MyBaseApiController<EmergencyContactController>
    {
        private readonly IBackendRepository backendRepository;
        private readonly IFrontendRepository frontendRepository;

        public EmergencyContactController
        (
            IBackendRepository backendRepository,
            IFrontendRepository frontendRepository
        )
        {
            this.backendRepository = backendRepository;
            this.frontendRepository = frontendRepository;
        }

        [HttpPost]
        public async Task<ApiResult<List<KeyValueID>>> GetGroupingList(int system_parent_id)
        {
            ApiResult<List<KeyValueID>> apiResult = new ApiResult<List<KeyValueID>>();
            List<KeyValueID> keyvalue = new List<KeyValueID>();
            try
            {
                keyvalue = await backendRepository.GetAllAsync<KeyValueID>($"select id, system_key as name,system_value as value from variable where deleted = 0 and system_parent_id = {system_parent_id} and system_type = 'grouping' order by system_priority");
                apiResult.Data = keyvalue;
                apiResult.Code = "0000";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + system_parent_id);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<List<KeyValue>>> DisasterList()
        {
            ApiResult<List<KeyValue>> apiResult = new ApiResult<List<KeyValue>>();
            List<KeyValue> Variable = new List<KeyValue>();

            try
            {
                var sqlString = @$"select system_value as Value, system_key as Name from variable a where a.system_type = 'disaster' and a.deleted = 0";
                Variable = await backendRepository.GetAllAsync<KeyValue>(sqlString);

                apiResult.Code = "0000";
                apiResult.Data = Variable;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            return apiResult;
        }

        [HttpPost]
        [Route("api/EmergencyContact/EmergencyContactTable")]
        public async Task<ActionResult<ApiResult<List<EmergencyContactTable>>>> EmergencyContactTable(List<int> selectgroupidlist)
        {
            List<EmergencyContactTable> Emergency_member_tables = new List<EmergencyContactTable>();
            ApiResult<List<EmergencyContactTable>> apiResult = new ApiResult<List<EmergencyContactTable>>();
            if (!jwtlife)
            {
                apiResult.Code = "5000";
                return BadRequest(apiResult);
            }
            try
            {
                Emergency_member_tables = await backendRepository.GetAllAsync<EmergencyContactTable>($@"
                    select  v.system_key groupingName,va.system_key departmentName,* from emergency_member em left join variable v on em.grouping = v.id
                    left join (select * from variable vs where vs.system_type = 'department' and vs.deleted = 0) va on va.system_value = em.department
                    where em.grouping in @groupinglist and em.deleted = 0", new { groupinglist = selectgroupidlist });
                apiResult.Code = "0000";
                apiResult.Data = Emergency_member_tables;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            
            return Ok(apiResult);
        }

        [HttpPost]
        [Route("api/EmergencyContact/PDF")]
        public async Task<ActionResult<ApiResult<string>>> ExportPDF(export post)
        {
            //var grouping = JsonConvert.DeserializeObject<export>(post);
            ApiResult<string> apiResult = new ApiResult<string>();
            if (!jwtlife)
            {
                apiResult.Code = "5000";
                return BadRequest(apiResult);
            }
            var stream = new MemoryStream();
            try
            {
                var Emergency_member_tables = await backendRepository.GetAllAsync<EmergencyContactTable>($@"
                    select  v.system_key groupingName,va.system_key departmentName,* from emergency_member em left join variable v on em.grouping = v.id
                    left join (select * from variable vs where vs.system_type = 'department' and vs.deleted = 0) va on va.system_value = em.department
                    where em.grouping in @groupinglist and em.deleted = 0", new { groupinglist = post.groupidlist });
                using (var doc = new Document())
                {
                    using (var writer = PdfWriter.GetInstance(doc, stream))
                    {
                        writer.CloseStream = false;
                        BaseFont BaseF = BaseFont.CreateFont("C:\\Windows\\Fonts\\kaiu.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                        Font fontCh = new Font(BaseF, 14);
                        doc.Open();
                        PdfPTable table = new PdfPTable(new float[] { 1, 1, 1, 1, 1, 1 });
                        table.TotalWidth = 480f;
                        table.LockedWidth = true;
                        PdfPCell header = new PdfPCell(new Phrase(post.disaster + "-聯絡清單", fontCh));
                        header.Colspan = 6;
                        table.AddCell(header);
                        table.AddCell(new Phrase("組別", fontCh));
                        table.AddCell(new Phrase("姓名", fontCh));
                        table.AddCell(new Phrase("部門", fontCh));
                        table.AddCell(new Phrase("電話", fontCh));
                        table.AddCell(new Phrase("LINE ID", fontCh));
                        table.AddCell(new Phrase("電子信箱", fontCh));

                        foreach (var group in Emergency_member_tables)
                        {
                            table.AddCell(new Phrase(group.groupingName, fontCh));
                            table.AddCell(new Phrase(group.full_name, fontCh));
                            table.AddCell(new Phrase(group.departmentName, fontCh));
                            table.AddCell(new Phrase(group.phone, fontCh));
                            table.AddCell(new Phrase(group.lineid, fontCh));
                            table.AddCell(new Phrase(group.email, fontCh));
                        }
                        doc.Add(table);
                        doc.Close();
                    }
                }
                var time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                time = time.Replace("/", "").Replace(" ", "_").Replace(":", "");
                var bytes = stream.ToArray();
                stream.Position = 0;
                var n = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Excel", "緊急應變_聯絡清單_" + time + ".pdf");
                FileStream FS = new FileStream(n, FileMode.Create, FileAccess.Write);
                stream.WriteTo(FS);
                FS.Close();
                stream.Close();
                apiResult.Data = Path.Combine("Excel", "緊急應變_聯絡清單_" + time + ".pdf");
                apiResult.Code = "0000";
                //File(stream, "application/pdf", post.disaster + "-聯絡清單.pdf");

            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Data = exception.Message;
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return Ok(apiResult);
        }

        [HttpPost]
        [Route("api/EmergencyContact/Excel")]
        public async Task<ActionResult<ApiResult<string>>> ExportExcel(export post)
        {
            //var guid = Guid.NewGuid().ToString();
            ApiResult<string> apiResult = new ApiResult<string>();
            if (!jwtlife)
            {
                apiResult.Code = "5000";
                return BadRequest(apiResult);
            }
            var workbook = new XSSFWorkbook();
            #region excel設定
            IFont font12 = workbook.CreateFont();
            font12.FontName = "新細明體";
            font12.FontHeightInPoints = 12;
            ICellStyle style12 = workbook.CreateCellStyle();
            style12.SetFont(font12);
            style12.Alignment = HorizontalAlignment.Center;
            style12.VerticalAlignment = VerticalAlignment.Center;
            IFont font12Times = workbook.CreateFont();
            font12Times.FontName = "Times New Roman";
            font12Times.FontHeightInPoints = 12;
            IFont font18 = workbook.CreateFont();
            font18.FontName = "新細明體";
            font18.FontHeightInPoints = 18;
            font18.IsBold = true;
            ICellStyle styleTitle18 = workbook.CreateCellStyle();
            styleTitle18.SetFont(font18);
            styleTitle18.Alignment = HorizontalAlignment.Center;
            styleTitle18.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLeft12 = workbook.CreateCellStyle();
            styleLeft12.SetFont(font12);
            styleLeft12.Alignment = HorizontalAlignment.Left;
            styleLeft12.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLine12 = workbook.CreateCellStyle();
            styleLine12.SetFont(font12);
            styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            styleLine12.VerticalAlignment = VerticalAlignment.Center;
            styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            ICellStyle stylein12 = workbook.CreateCellStyle();
            stylein12.SetFont(font12Times);
            stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            stylein12.VerticalAlignment = VerticalAlignment.Center;
            stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.WrapText = true;
            #endregion
            try
            {
                var Emergency_member_tables = await backendRepository.GetAllAsync<EmergencyContactTable>($@"
                    select  v.system_key groupingName,va.system_key departmentName,* from emergency_member em left join variable v on em.grouping = v.id
                    left join (select * from variable vs where vs.system_type = 'department' and vs.deleted = 0) va on va.system_value = em.department
                    where em.grouping in @groupinglist and em.deleted = 0", new { groupinglist = post.groupidlist });
                var sheet = workbook.CreateSheet(post.disaster + "-聯絡清單");
                int RowPosition = 0;
                IRow row = sheet.CreateRow(RowPosition);
                sheet.SetColumnWidth(0, 4 * 160 * 6);
                sheet.SetColumnWidth(1, 4 * 160 * 6);
                sheet.SetColumnWidth(2, 4 * 160 * 6);
                sheet.SetColumnWidth(3, 4 * 160 * 6);
                sheet.SetColumnWidth(4, 4 * 160 * 6);
                sheet.SetColumnWidth(5, 4 * 160 * 6);
                ICell cell = row.CreateCell(0);
                cell.SetCellValue("組別");
                cell.CellStyle = styleLine12;
                cell = row.CreateCell(1);
                cell.SetCellValue("姓名");
                cell.CellStyle = styleLine12;
                cell = row.CreateCell(2);
                cell.SetCellValue("部門");
                cell.CellStyle = styleLine12;
                cell = row.CreateCell(3);
                cell.SetCellValue("電話");
                cell.CellStyle = styleLine12;
                cell = row.CreateCell(4);
                cell.SetCellValue("LINE ID");
                cell.CellStyle = styleLine12;
                cell = row.CreateCell(5);
                cell.SetCellValue("電子信箱");
                cell.CellStyle = styleLine12;
                foreach (var group in Emergency_member_tables)
                {
                    RowPosition += 1;
                    row = sheet.CreateRow(RowPosition);
                    cell = row.CreateCell(0);
                    cell.SetCellValue(group.groupingName);
                    cell.CellStyle = style12;
                    cell = row.CreateCell(1);
                    cell.SetCellValue(group.full_name);
                    cell.CellStyle = style12;
                    cell = row.CreateCell(2);
                    cell.SetCellValue(group.departmentName);
                    cell.CellStyle = style12;
                    cell = row.CreateCell(3);
                    cell.SetCellValue(group.phone);
                    cell.CellStyle = style12;
                    cell = row.CreateCell(4);
                    cell.SetCellValue(group.lineid);
                    cell.CellStyle = style12;
                    cell = row.CreateCell(5);
                    cell.SetCellValue(group.email);
                    cell.CellStyle = style12;
                }
                if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")))
                {
                    Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"));
                }
                if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Excel")))
                {
                    Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Excel"));
                }
                var time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                time = time.Replace("/", "").Replace(" ", "_").Replace(":", "");

                var n = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Excel", "緊急應變_聯絡清單_" + time + ".xlsx");
                FileStream FS = new FileStream(n, FileMode.Create, FileAccess.Write);
                workbook.Write(FS);
                FS.Close();
                
                apiResult.Data = Path.Combine("Excel", "緊急應變_聯絡清單_" + time + ".xlsx");
                apiResult.Code = "0000";

            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                //Logger.LogError("【" + controllerName + "/" + actionName + "】");
                apiResult.Data = exception.Message;
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return Ok(apiResult);
        }

        [HttpPost]
        [Route("api/EmergencyContact/Clear")]
        public async Task<ActionResult<ActionResult<string>>> Clear(string post)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            if (!jwtlife)
            {
                apiResult.Code = "5000";
                return BadRequest(apiResult);
            }
            try

            {
                if (System.IO.File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot",post)))
                {
                    System.IO.File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", post));
                    
                }
                apiResult.Code = "0000";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
            }
            return Ok(apiResult);
        }


    }
}