using BMA.EHR.Application.Repositories.Reports;
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Annotations;
using Telerik.Reporting;
using Telerik.Reporting.Processing;
using BMA.EHR.Application.Repositories;

namespace BMA.EHR.Report.Service.Controllers
{
    [Route("api/v{version:apiVersion}/report/insignia")]
    [ApiVersion("2.0")]
    [ApiController]
    [Produces("application/json")]
    [Authorize]
    [SwaggerTag("API รายงานระบบเครื่องราชอิสริยาภรณ์")]
    public class InsigniaReportController : BaseController
    {
        #region " Fields "

        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IConfiguration _configuration;
        private readonly InsigniaReportRepository _repository;
        private readonly GenericReportGenerator _reportGenerator;
        private readonly PermissionRepository _permission;

        #endregion

        #region " Constuctor and Destructor "

        public InsigniaReportController(IWebHostEnvironment hostingEnvironment, IConfiguration configuration, InsigniaReportRepository repository, GenericReportGenerator reportGenerator, PermissionRepository permission)
        {

            _hostingEnvironment = hostingEnvironment;
            _configuration = configuration;
            _repository = repository;
            _reportGenerator = reportGenerator;
            _permission = permission;
        }

        #endregion

        #region " Methods "

        #region 39-แบบ ขร1 บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ ข้าราชการ ชั้นสายสะพาย
        /// <summary>
        /// 39-แบบ ขร1 บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ ข้าราชการ ชั้นสายสะพาย
        /// </summary>
        /// <param name="id">id </param>
        /// <param name="exportType">pdf, docx หรือ xlsx</param>
        /// <returns></returns>
        /// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
        /// <response code="401">ไม่ได้ Login เข้าระบบ</response>
        /// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
        [HttpGet("39/{exportType}/{id}")]
        public async Task<ActionResult<ResponseObject>> GetInsignia39ConvertReportAsync(Guid id, string exportType = "pdf")
        {
            try
            {
                var data = await _repository.GetKhr1Report(id);
                var total = await _repository.GetKhr1TotalReport(id);
                var YearInsignalPeriod = await _repository.GetYearInsigniaPeriod(id);
                var TwoYearInsignalPeriod = await _repository.Get2YearInsigniaPeriod(id);
                var Date = await _repository.GetDateInsigniaPeriod(id);
                var mimeType = "";
                switch (exportType.Trim().ToLower())
                {
                    case "pdf": mimeType = "application/pdf"; break;
                    case "docx": mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
                    case "xlsx": mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
                }

                var rptFile = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"39-แบบ ขร1 บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ ข้าราชการ ชั้นสายสะพาย.trdp");

                ReportPackager reportPacker = new ReportPackager();
                Telerik.Reporting.Report? report = null;
                using (var sourceStream = System.IO.File.OpenRead(rptFile))
                {
                    report = (Telerik.Reporting.Report)reportPacker.UnpackageDocument(sourceStream);
                }

                report.ReportParameters["YearInsigniaPeriod"].Value = YearInsignalPeriod;
                report.ReportParameters["TwoYearInsignalPeriod"].Value = TwoYearInsignalPeriod;
                report.ReportParameters["EndDate"].Value = Date.GetType().GetProperty("EndDate").GetValue(Date);

                var _Khr1List = new List<dynamic>();
                foreach (var _data in data)
                {
                    _Khr1List.Add(new
                    {
                        //RowNo = _data.GetType().GetProperty("RowNo").GetValue(_data),
                        RowNo = _Khr1List.Count + 1,
                        DepartmentName = _data.GetType().GetProperty("DepartmentName").GetValue(_data),
                        G1Male = _data.GetType().GetProperty("G1Male").GetValue(_data),
                        G1Female = _data.GetType().GetProperty("G1Female").GetValue(_data),
                        G2Male = _data.GetType().GetProperty("G2Male").GetValue(_data),
                        G2Female = _data.GetType().GetProperty("G2Female").GetValue(_data),
                        G3Male = _data.GetType().GetProperty("G3Male").GetValue(_data),
                        G3Female = _data.GetType().GetProperty("G3Female").GetValue(_data),
                        G4Male = _data.GetType().GetProperty("G4Male").GetValue(_data),
                        G4Female = _data.GetType().GetProperty("G4Female").GetValue(_data),
                        G5Male = _data.GetType().GetProperty("G5Male").GetValue(_data),
                        G5Female = _data.GetType().GetProperty("G5Female").GetValue(_data),
                        Remark = _data.GetType().GetProperty("Remark").GetValue(_data),
                    });
                }
                var tbl = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table1"];
                tbl.DataSource = _Khr1List;
                var tbl2 = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table2"];
                tbl2.DataSource = total;

                System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();
                InstanceReportSource instanceReportSource = new InstanceReportSource()
                {
                    ReportDocument = report,
                };
                ReportProcessor reportProcessor = new ReportProcessor(_configuration);
                RenderingResult result = reportProcessor.RenderReport($"{exportType}", instanceReportSource, deviceInfo);
                return File(result.DocumentBytes, mimeType, $"แบบ ขร1.{exportType.Trim().ToLower()}");
            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 40-แบบ ขร2 บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ ข้าราชการ ชั้นต่ำกว่าสายสะพาย	
        /// <summary>
        /// 40-แบบ ขร2 บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ ข้าราชการ ชั้นต่ำกว่าสายสะพาย	
        /// </summary>
        /// <param name="id">id </param>
        /// <param name="exportType">pdf, docx หรือ xlsx</param>
        /// <returns></returns>
        /// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
        /// <response code="401">ไม่ได้ Login เข้าระบบ</response>
        /// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
        [HttpGet("40/{exportType}/{id}")]
        public async Task<ActionResult<ResponseObject>> GetInsignia40ConvertReportAsync(Guid id, string exportType = "pdf")
        {
            try
            {
                var data = await _repository.GetKhr2Report(id);
                var total = await _repository.GetKhr2TotalReport(id);
                var YearInsignalPeriod = await _repository.GetYearInsigniaPeriod(id);
                var TwoYearInsignalPeriod = await _repository.Get2YearInsigniaPeriod(id);
                var Date = await _repository.GetDateInsigniaPeriod(id);
                var mimeType = "";
                switch (exportType.Trim().ToLower())
                {
                    case "pdf": mimeType = "application/pdf"; break;
                    case "docx": mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
                    case "xlsx": mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
                }

                var rptFile = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"40-แบบ ขร2 บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ ข้าราชการ ชั้นต่ำกว่าสายสะพาย.trdp");
                ReportPackager reportPacker = new ReportPackager();
                Telerik.Reporting.Report? report = null;
                using (var sourceStream = System.IO.File.OpenRead(rptFile))
                {
                    report = (Telerik.Reporting.Report)reportPacker.UnpackageDocument(sourceStream);
                }

                report.ReportParameters["YearInsigniaPeriod"].Value = YearInsignalPeriod;
                report.ReportParameters["TwoYearInsignalPeriod"].Value = TwoYearInsignalPeriod;
                report.ReportParameters["EndDate"].Value = Date.GetType().GetProperty("EndDate").GetValue(Date);

                var _Khr2List = new List<dynamic>();
                foreach (var _data in data)
                {
                    _Khr2List.Add(new
                    {
                        RowNo = _Khr2List.Count + 1,
                        DepartmentName = _data.GetType().GetProperty("DepartmentName").GetValue(_data),
                        G1Male = _data.GetType().GetProperty("G1Male").GetValue(_data),
                        G1Female = _data.GetType().GetProperty("G1Female").GetValue(_data),
                        G2Male = _data.GetType().GetProperty("G2Male").GetValue(_data),
                        G2Female = _data.GetType().GetProperty("G2Female").GetValue(_data),
                        G3Male = _data.GetType().GetProperty("G3Male").GetValue(_data),
                        G3Female = _data.GetType().GetProperty("G3Female").GetValue(_data),
                        G4Male = _data.GetType().GetProperty("G4Male").GetValue(_data),
                        G4Female = _data.GetType().GetProperty("G4Female").GetValue(_data),
                        G5Male = _data.GetType().GetProperty("G5Male").GetValue(_data),
                        G5Female = _data.GetType().GetProperty("G5Female").GetValue(_data),
                        G6Male = _data.GetType().GetProperty("G6Male").GetValue(_data),
                        G6Female = _data.GetType().GetProperty("G6Female").GetValue(_data),
                        G7Male = _data.GetType().GetProperty("G7Male").GetValue(_data),
                        G7Female = _data.GetType().GetProperty("G7Female").GetValue(_data),
                        G8Male = _data.GetType().GetProperty("G8Male").GetValue(_data),
                        G8Female = _data.GetType().GetProperty("G8Female").GetValue(_data),
                        G9Male = _data.GetType().GetProperty("G9Male").GetValue(_data),
                        G9Female = _data.GetType().GetProperty("G9Female").GetValue(_data),
                        Remark = _data.GetType().GetProperty("Remark").GetValue(_data),
                    });
                }
                var tbl1 = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table1"];
                tbl1.DataSource = _Khr2List;
                var tbl2 = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table2"];
                tbl2.DataSource = total;

                System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();
                InstanceReportSource instanceReportSource = new InstanceReportSource()
                {
                    ReportDocument = report,
                };
                ReportProcessor reportProcessor = new ReportProcessor(_configuration);
                RenderingResult result = reportProcessor.RenderReport($"{exportType}", instanceReportSource, deviceInfo);
                return File(result.DocumentBytes, mimeType, $"แบบ ขร2.{exportType.Trim().ToLower()}");
            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 41-แบบ ขร3 บัญชีรายชื่อข้าราชการผู้ขอพระราชทานเครื่องราชฯ
        /// <summary>
        /// 41-แบบ ขร3 บัญชีรายชื่อข้าราชการผู้ขอพระราชทานเครื่องราชฯ
        /// </summary>
        /// <param name="id">id </param>
        /// <param name="exportType">pdf, docx หรือ xlsx</param>
        /// <returns></returns>
        /// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
        /// <response code="401">ไม่ได้ Login เข้าระบบ</response>
        /// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
        [HttpGet("41/{exportType}/{id}")]
        public async Task<ActionResult<ResponseObject>> GetInsignia41ConvertReportAsync(Guid id, string exportType = "pdf")
        {
            try
            {
                var data = await _repository.GetKhr3Report(id);
                var YearInsignalPeriod = await _repository.GetYearInsigniaPeriod(id);
                var TwoYearInsignalPeriod = await _repository.Get2YearInsigniaPeriod(id);
                var Date = await _repository.GetDateInsigniaPeriod(id);
                var mimeType = "";
                switch (exportType.Trim().ToLower())
                {
                    case "pdf": mimeType = "application/pdf"; break;
                    case "docx": mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
                    case "xlsx": mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
                }
                var rptFile = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"41-แบบ ขร3 บัญชีรายชื่อข้าราชการผู้ขอพระราชทานเครื่องราชฯ.trdp");
                ReportPackager reportPacker = new ReportPackager();
                Telerik.Reporting.Report? report = null;



                using (var sourceStream = System.IO.File.OpenRead(rptFile))
                {
                    report = (Telerik.Reporting.Report)reportPacker.UnpackageDocument(sourceStream);
                }

                report.ReportParameters["YearInsigniaPeriod"].Value = YearInsignalPeriod;
                report.ReportParameters["TwoYearInsignalPeriod"].Value = TwoYearInsignalPeriod;
                report.ReportParameters["EndDate"].Value = Date.GetType().GetProperty("EndDate").GetValue(Date);
                //int count = ((IEnumerable<object>)data).Count();
                //int counter = 0;
                //var _Khr3LeftList = new List<dynamic>();
                //var _Khr3RightList = new List<dynamic>();
                //foreach(var _data in data)
                //{
                //    _Khr3LeftList.Add(new
                //    {
                //        RowNo = _Khr3LeftList.Count +1,
                //        FullName = _data.GetType().GetProperty("FullName").GetValue(_data),
                //        OCName = _data.GetType().GetProperty("OCName").GetValue(_data),
                //        InsigniaName = _data.GetType().GetProperty("InsigniaName").GetValue(_data),

                //    });
                //}
                //var tbl1 = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table1"];
                //tbl1.DataSource = _Khr3LeftList;

                //var tbl2 = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table2"];
                //tbl2.DataSource = _Khr3RightList;

                report.DataSource = data;

                System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();
                InstanceReportSource instanceReportSource = new InstanceReportSource()
                {
                    ReportDocument = report,
                };
                ReportProcessor reportProcessor = new ReportProcessor(_configuration);
                RenderingResult result = reportProcessor.RenderReport($"{exportType}", instanceReportSource, deviceInfo);

                return File(result.DocumentBytes, mimeType, $"แบบ ขร3.{exportType.Trim().ToLower()}");
            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 42-แบบ ขร4 บัญชีแสดงคุณสมบัติของข้าราชการซึ่งเสนอขอเครื่องราชฯ
        /// <summary>
        /// 42-แบบ ขร4 บัญชีแสดงคุณสมบัติของข้าราชการซึ่งเสนอขอเครื่องราชฯ
        /// </summary>
        /// <param name="id">id </param>
        /// <param name="exportType">pdf, docx หรือ xlsx</param>
        /// <returns></returns>
        /// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
        /// <response code="401">ไม่ได้ Login เข้าระบบ</response>
        /// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
        [HttpGet("42/{exportType}/{id}")]
        public async Task<ActionResult<ResponseObject>> GetInsignia42ConvertReportAsync(Guid id, string exportType = "pdf")
        {
            try
            {
                var data = await _repository.GetKhr4Report(id);
                var YearInsignalPeriod = await _repository.GetYearInsigniaPeriod(id);
                var TwoYearInsignalPeriod = await _repository.Get2YearInsigniaPeriod(id);
                var mimeType = "";
                switch (exportType.Trim().ToLower())
                {
                    case "pdf": mimeType = "application/pdf"; break;
                    case "docx": mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
                    case "xlsx": mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
                }

                var rptFile = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"42-แบบ ขร4 บัญชีแสดงคุณสมบัติของข้าราชการซึ่งเสนอขอเครื่องราชฯ.trdp");
                ReportPackager reportPacker = new ReportPackager();
                Telerik.Reporting.Report? report = null;
                using (var sourceStream = System.IO.File.OpenRead(rptFile))
                {
                    report = (Telerik.Reporting.Report)reportPacker.UnpackageDocument(sourceStream);
                }
                report.ReportParameters["YearInsigniaPeriod"].Value = YearInsignalPeriod;
                report.ReportParameters["TwoYearInsignalPeriod"].Value = TwoYearInsignalPeriod;

                var tbl1 = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table1"];
                var _Khr4List = new List<dynamic>();
                foreach (var _data in data)
                {
                    _Khr4List.Add(new
                    {
                        RowNo = _Khr4List.Count + 1,
                        FullName = _data.GetType().GetProperty("FullName").GetValue(_data),
                        CitizenId = _data.GetType().GetProperty("CitizenId").GetValue(_data),
                        Type = _data.GetType().GetProperty("Type").GetValue(_data),
                        Level = _data.GetType().GetProperty("Level").GetValue(_data),
                        DateStart = _data.GetType().GetProperty("DateStart").GetValue(_data),
                        SalaryAmount = _data.GetType().GetProperty("SalaryAmount").GetValue(_data),
                        Position = _data.GetType().GetProperty("Position").GetValue(_data),
                        InsigniaRecv = _data.GetType().GetProperty("InsigniaRecv").GetValue(_data),
                        InsigniaRecvDate = _data.GetType().GetProperty("InsigniaRecvDate").GetValue(_data),
                        InsigniaRequest = _data.GetType().GetProperty("InsigniaRequest").GetValue(_data),
                        Remark = _data.GetType().GetProperty("Remark").GetValue(_data),
                    });
                }
                tbl1.DataSource = _Khr4List;

                System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();
                InstanceReportSource instanceReportSource = new InstanceReportSource()
                {
                    ReportDocument = report,
                };
                ReportProcessor reportProcessor = new ReportProcessor(_configuration);
                RenderingResult result = reportProcessor.RenderReport($"{exportType}", instanceReportSource, deviceInfo);
                return File(result.DocumentBytes, mimeType, $"แบบ ขร4.{exportType.Trim().ToLower()}");

            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 43-บัญชีระดับผลการประเมินผลการปฏิบัติราชการในรอบ 5 ปี
        /// <summary>
        /// 43-บัญชีระดับผลการประเมินผลการปฏิบัติราชการในรอบ 5 ปี
        /// </summary>
        /// <param name="id">id </param>
        /// <param name="exportType">pdf, docx หรือ xlsx</param>
        /// <returns></returns>
        /// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
        /// <response code="401">ไม่ได้ Login เข้าระบบ</response>
        /// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
        [HttpGet("43/{exportType}/{id}")]
        public async Task<ActionResult<ResponseObject>> GetInsignia43ConvertReportAsync(Guid id, string exportType = "pdf")
        {
            try
            {
                var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(id.ToString(), "SYS_INSIGNIA_REPORT");
                if (getWorkflow == false)
                {
                    var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_INSIGNIA_REPORT");
                    var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
                    if (jsonData["status"]?.ToString() != "200")
                    {
                        return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
                    }
                }
                var mimeType = "";
                switch (exportType.Trim().ToLower())
                {
                    case "pdf": mimeType = "application/pdf"; break;
                    case "docx": mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
                    case "xlsx": mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
                }

                var rptFile = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"43-บัญชีระดับผลการประเมินผลการปฏิบัติราชการในรอบ 5 ปี.trdp");
                var contentData = _reportGenerator.GenerateReport(rptFile, exportType);

                return File(contentData, mimeType, $"insignia.{exportType.Trim().ToLower()}");

            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 44-บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ
        /// <summary>
        /// 44-บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ
        /// </summary>
        /// <param name="id">id </param>
        /// <param name="exportType">pdf, docx หรือ xlsx</param>
        /// <returns></returns>
        /// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
        /// <response code="401">ไม่ได้ Login เข้าระบบ</response>
        /// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
        [HttpGet("44/{exportType}/{id}")]
        public async Task<ActionResult<ResponseObject>> GetInsignia44ConvertReportAsync(Guid id, string exportType = "pdf")
        {
            try
            {
                var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(id.ToString(), "SYS_INSIGNIA_REPORT");
                if (getWorkflow == false)
                {
                    var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_INSIGNIA_REPORT");
                    var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
                    if (jsonData["status"]?.ToString() != "200")
                    {
                        return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
                    }
                }
                var data = await _repository.GetSummaryCoinReport(id);
                var SummaryTotal = await _repository.GetSummaryTotalCoinReport(id);
                var YearInsignalPeriod = await _repository.GetYearInsigniaPeriod(id);
                var mimeType = "";
                switch (exportType.Trim().ToLower())
                {
                    case "pdf": mimeType = "application/pdf"; break;
                    case "docx": mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
                    case "xlsx": mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
                }

                var rptFile = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"44-บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ.trdp");
                ReportPackager reportPacker = new ReportPackager();
                Telerik.Reporting.Report? report = null;
                using (var sourceStream = System.IO.File.OpenRead(rptFile))
                {
                    report = (Telerik.Reporting.Report)reportPacker.UnpackageDocument(sourceStream);
                }
                report.ReportParameters["YearInsigniaPeriod"].Value = YearInsignalPeriod;

                var tbl1 = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table1"];
                var _Khr6List = new List<dynamic>();
                foreach (var _data in data)
                {
                    _Khr6List.Add(new
                    {
                        RowNo = (_Khr6List.Count + 1).ToString().ToThaiNumber(),
                        DepartmentName = _data.GetType().GetProperty("DepartmentName").GetValue(_data),
                        InsigniaInitial = _data.GetType().GetProperty("InsigniaInitial").GetValue(_data),
                        G1Male = _data.GetType().GetProperty("G1Male").GetValue(_data),
                        G1Female = _data.GetType().GetProperty("G1Female").GetValue(_data),
                        G2Male = _data.GetType().GetProperty("G2Male").GetValue(_data),
                        G2Female = _data.GetType().GetProperty("G2Female").GetValue(_data),
                        Remark = _data.GetType().GetProperty("Remark").GetValue(_data),
                    });
                }
                tbl1.DataSource = _Khr6List;

                var tbl2 = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["table2"];
                tbl2.DataSource = SummaryTotal;
                System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();
                InstanceReportSource instanceReportSource = new InstanceReportSource()
                {
                    ReportDocument = report,
                };
                ReportProcessor reportProcessor = new ReportProcessor(_configuration);
                RenderingResult result = reportProcessor.RenderReport($"{exportType}", instanceReportSource, deviceInfo);
                return File(result.DocumentBytes, mimeType, $"บัญชีแสดงจำนวนชั้นตราเครื่องราชฯ{exportType.Trim().ToLower()}");

            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 45-บัญชีแสดงรายชื่อผู้ขอพระราชทานเหรียญจักรพรรดิมาลา
        /// <summary>
        /// 45-บัญชีแสดงรายชื่อผู้ขอพระราชทานเหรียญจักรพรรดิมาลา
        /// </summary>
        /// <param name="id">id </param>
        /// <param name="exportType">pdf, docx หรือ xlsx</param>
        /// <returns></returns>
        /// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
        /// <response code="401">ไม่ได้ Login เข้าระบบ</response>
        /// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
        [HttpGet("45/{exportType}/{id}")]
        public async Task<ActionResult<ResponseObject>> GetInsignia45ConvertReportAsync(Guid id, string exportType = "pdf")
        {
            try
            {
                var getWorkflow = await _permission.GetPermissionAPIWorkflowAsync(id.ToString(), "SYS_INSIGNIA_REPORT");
                if (getWorkflow == false)
                {
                    var getPermission = await _permission.GetPermissionAPIAsync("GET", "SYS_INSIGNIA_REPORT");
                    var jsonData = JsonConvert.DeserializeObject<JObject>(getPermission);
                    if (jsonData["status"]?.ToString() != "200")
                    {
                        return Error(jsonData["message"]?.ToString(), StatusCodes.Status403Forbidden);
                    }
                }

                //Guid ids = Guid.Parse(id);  
                var data = await _repository.GetCoinReport(id);
                var YearInsignalPeriod = await _repository.GetYearInsigniaPeriod(id);
                var mimeType = "";
                switch (exportType.Trim().ToLower())
                {
                    case "pdf": mimeType = "application/pdf"; break;
                    case "docx": mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
                    case "xlsx": mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
                }
                var rptFile = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"45-บัญชีแสดงรายชื่อผู้ขอพระราชทานเหรียญจักรพรรดิมาลา-1.trdp");
                var rptFile2 = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"45-บัญชีแสดงรายชื่อผู้ขอพระราชทานเหรียญจักรพรรดิมาลา-2.trdp");

                ReportPackager reportPacker = new ReportPackager();
                Telerik.Reporting.Report? report = null;
                Telerik.Reporting.Report? report2 = null;

                using (var sourceStream = System.IO.File.OpenRead(rptFile))
                using (var sourceStream2 = System.IO.File.OpenRead(rptFile2))
                {
                    report = (Telerik.Reporting.Report)reportPacker.UnpackageDocument(sourceStream);
                    report2 = (Telerik.Reporting.Report)reportPacker.UnpackageDocument(sourceStream2);
                }
                var OCName = string.Empty;
                report.ReportParameters["YearInsignalPeriod"].Value = YearInsignalPeriod;
                report.ReportParameters["OCName"].Value = OCName;

                var dataList = new List<dynamic>(data);
                var detailList = new List<dynamic>();
                var check = 0;
                var status = false;

                for (int i = 0; i < dataList.Count; i++)
                {
                    check++;
                    var gender = dataList[i].GetType().GetProperty("Gender").GetValue(dataList[i]);
                    detailList.Add(new
                    {
                        status = status,
                        row = detailList.Count + 1,
                        //Number = (detailList.Count + 1).ToString().ToThaiNumber(),
                        InsigniaName = dataList[i].GetType().GetProperty("InsigniaName").GetValue(dataList[i]),
                        FullName = dataList[i].GetType().GetProperty("FullName").GetValue(dataList[i]),
                        InsigniaInitial = dataList[i].GetType().GetProperty("InsigniaInitial").GetValue(dataList[i]),
                        Male = gender == "ชาย" ? 1 : 0,
                        Female = gender == "หญิง" ? 1 : 0,
                    });

                    if (check == 25)
                    {
                        status = true;
                    }
                    else if (check == 50)
                    {
                        status = false;
                        check = 0;
                    }
                }

                if (detailList.Count > 0)
                {
                    var left = detailList.Where(x => x.status == false);
                    var right = detailList.Where(x => x.status == true);
                    var mergeList = new List<object>();
                    var InsigniaName = string.Empty;
                    var range = string.Empty;
                    var male = 0;
                    var female = 0;
                    var start = 0;
                    var stop = 0;
                    var colLeft = 0;
                    var colRight = 0;
                    for (int i = 0; i < detailList.Count / 2; i++)
                    {
                        if (InsigniaName != (string)left.ElementAt(i).GetType().GetProperty("InsigniaName").GetValue(left.ElementAt(i)))
                        {
                            InsigniaName = (string)left.ElementAt(i).GetType().GetProperty("InsigniaName").GetValue(left.ElementAt(i));
                            male = left.Count(x => x.Male == 1 && x.InsigniaName == InsigniaName) + right.Count(x => x.Male == 1 && x.InsigniaName == InsigniaName);
                            female = left.Count(x => x.Female == 1 && x.InsigniaName == InsigniaName) + right.Count(x => x.Female == 1 && x.InsigniaName == InsigniaName);
                            //find coin group range
                            var countGroup = detailList.Count(x => x.InsigniaName == InsigniaName);
                            var countGroupTemp = detailList.Count(x => x.InsigniaName == InsigniaName && x.FullName == "");
                            start = i == 0 ? (mergeList.Count + 1) : (stop + 1);
                            stop = i == 0 ? (mergeList.Count) + (countGroup - countGroupTemp) : (countGroup - countGroupTemp) == 1 ? start : start + (countGroup - countGroupTemp);
                            range = countGroup - countGroupTemp != 1 ? $"{start} - {stop}" : $"{start}";
                            //set column left and right when start
                            colLeft = start;
                            colRight = start + 25;
                        }
                        mergeList.Add(new
                        {
                            row = mergeList.Count + 1,
                            //RowLeft = left.ElementAt(i).GetType().GetProperty("Number").GetValue(left.ElementAt(i)),
                            ColLeft = colLeft.ToString().ToThaiNumber(),
                            NameLeft = left.ElementAt(i).GetType().GetProperty("FullName").GetValue(left.ElementAt(i)),
                            //RowRight = right.ElementAt(i).GetType().GetProperty("Number").GetValue(right.ElementAt(i)),
                            ColRight = colRight.ToString().ToThaiNumber(),
                            NameRight = right.ElementAt(i).GetType().GetProperty("FullName").GetValue(right.ElementAt(i)),
                            InsigniaInitial = left.ElementAt(i).GetType().GetProperty("InsigniaInitial").GetValue(left.ElementAt(i)),
                            InsigniaName = left.ElementAt(i).GetType().GetProperty("InsigniaName").GetValue(left.ElementAt(i)),
                            Range = range.ToThaiNumber(),
                            Male = male.ToString().ToThaiNumber(),
                            Female = female.ToString().ToThaiNumber(),
                        });
                        if (mergeList.Count % 25 == 0)
                        {
                            //set column when new page
                            colLeft = colRight;
                            colRight = colLeft + 25;
                        }
                        colLeft++;
                        colRight++;
                    }
                    report.DataSource = mergeList;
                }

                var reportBook = new ReportBook();
                reportBook.Reports.Add(report);
                reportBook.Reports.Add(report2);
                System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();
                InstanceReportSource instanceReportSource = new InstanceReportSource()
                {
                    ReportDocument = reportBook,
                };
                ReportProcessor reportProcessor = new ReportProcessor(_configuration);
                RenderingResult result = reportProcessor.RenderReport($"{exportType}", instanceReportSource, deviceInfo);
                return File(result.DocumentBytes, mimeType, $"บัญชีแสดงรายชื่อผู้ขอพระราชทานเหรียญจักรพรรดิมาลา.{exportType.Trim().ToLower()}");

            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 46-ประวัติสำหรับการเสนอขอพระราชทานเหรียญจักรพรรดิมาลา
        /// <summary>
        /// 46-ประวัติสำหรับการเสนอขอพระราชทานเหรียญจักรพรรดิมาลา
        /// </summary>
        /// <param name="id">id </param>
        /// <param name="exportType">pdf, docx หรือ xlsx</param>
        /// <returns></returns>
        /// <response code="200">เมื่อทำการอ่านข้อมูลจาก Relational Database สำเร็จ</response>
        /// <response code="401">ไม่ได้ Login เข้าระบบ</response>
        /// <response code="500">เมื่อเกิดข้อผิดพลาดในการทำงาน</response>
        [HttpGet("46/{exportType}/{id}")]
        public async Task<ActionResult<ResponseObject>> GetInsignia46ConvertReportAsync(Guid id, string exportType = "pdf")
        {
            try
            {
                var profile = await _repository.GetProfileInsignia(id);
                var data = await _repository.GetHistorySalaryReport(id);
                var mimeType = "";
                switch (exportType.Trim().ToLower())
                {
                    case "pdf": mimeType = "application/pdf"; break;
                    case "docx": mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break;
                    case "xlsx": mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break;
                }

                var rptFile = System.IO.Path.Combine(_hostingEnvironment.ContentRootPath, "Reports", $"46-ประวัติสำหรับการเสนอขอพระราชทานเหรียญจักรพรรดิมาลา.trdp");
                ReportPackager reportPacker = new ReportPackager();
                Telerik.Reporting.Report? report = null;
                using (var sourceStream = System.IO.File.OpenRead(rptFile))
                {
                    report = (Telerik.Reporting.Report)reportPacker.UnpackageDocument(sourceStream);
                }

                report.ReportParameters["FullName"].Value = profile.GetType().GetProperty("FullName").GetValue(profile);
                report.ReportParameters["Position"].Value = profile.GetType().GetProperty("Position").GetValue(profile);
                report.ReportParameters["OCName"].Value = profile.GetType().GetProperty("OCName").GetValue(profile);
                report.ReportParameters["BirthDate"].Value = profile.GetType().GetProperty("BirthDate").GetValue(profile);
                report.ReportParameters["DateAppoint"].Value = profile.GetType().GetProperty("DateAppoint").GetValue(profile);

                var historysalary = new List<dynamic>();
                foreach (var _data in data)
                {
                    historysalary.Add(new
                    {
                        DateTh = _data.GetType().GetProperty("DateTh").GetValue(_data),
                        Position = _data.GetType().GetProperty("Position").GetValue(_data),
                        OCName = _data.GetType().GetProperty("OCName").GetValue(_data),
                        Age = _data.GetType().GetProperty("Age").GetValue(_data),
                        Amount = _data.GetType().GetProperty("Amount").GetValue(_data),
                        Remark = _data.GetType().GetProperty("Remark").GetValue(_data),
                    });
                }
                var tbl1 = (Telerik.Reporting.Table)report.Items["detailsection1"].Items["table1"];
                tbl1.DataSource = historysalary;

                System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable();
                InstanceReportSource instanceReportSource = new InstanceReportSource()
                {
                    ReportDocument = report,
                };
                ReportProcessor reportProcessor = new ReportProcessor(_configuration);
                RenderingResult result = reportProcessor.RenderReport($"{exportType}", instanceReportSource, deviceInfo);
                return File(result.DocumentBytes, mimeType, $"ประวัติสำหรับการเสนอขอพระราชทานเหรียญจักรพรรดิมาลา.{exportType.Trim().ToLower()}");

            }
            catch
            {
                throw;
            }
        }
        #endregion

        #endregion
    }
}
