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

namespace BMA.EHR.Report.Service.Controllers
{
    [Route("api/v{version:apiVersion}/report/candidate")]
    [ApiVersion("2.0")]
    [ApiController]
    [Produces("application/json")]
    [Authorize]
    [SwaggerTag("API รายงานระบบสอบคัดเลือก")]
    public class CandidateReportController : BaseController
    {
        private readonly CandidateReportRepository _service;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IConfiguration _configuration;
        private readonly MinIOExamService _minIOExamService;

        public CandidateReportController(CandidateReportRepository service, IWebHostEnvironment hostingEnvironment,
                                MinIOExamService minIOExamService, IConfiguration configuration)
        {
            _service = service;
            _hostingEnvironment = hostingEnvironment;
            _configuration = configuration;
            _minIOExamService = minIOExamService;
        }

        #region ใบสมัคร
        /// <summary>
        /// ใบสมัคร
        /// </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("{exportType}/{Id}")]
        [AllowAnonymous]
        public async Task<ActionResult<ResponseObject>> GetExamCandidate([FromRoute] Guid Id, string exportType = "pdf")
        {
            var candidate = await _service.GetExamCandidateAsync(Id);
            var careers = await _service.GetExamCareerCandidateAsync(Id);
            var avatar = await _service.GetExamAvatarCandidateAsync(Id);
            if (candidate != null)
            {
                //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", $"ผลสอบคัดเลือกรายบุคคล.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.DataSource = candidate;

                //var tblData = (Telerik.Reporting.Table)report.Items["detailSection1"].Items["tblData"];
                //tblData.DataSource = careers;

                //Console.WriteLine("000000");
                //if (avatar != Guid.Parse("00000000-0000-0000-0000-000000000000"))
                //{
                //    try
                //    {
                //        // Get avatar Image
                var picContent = avatar == null ? null : await _minIOExamService.ImagesPath(avatar);
                //var pictureBox = (Telerik.Reporting.PictureBox)report.Items["detailSection1"].Items["picAvatar"];
                //pictureBox.Value = Image.FromStream(new MemoryStream(picContent.FileContent));
                //    }
                //    catch { }
                //}

                //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()}");
                var mapData = new
                {
                    Id = candidate.GetType().GetProperty("Id").GetValue(candidate),
                    AvatarId = candidate.GetType().GetProperty("AvatarId").GetValue(candidate),
                    PeriodExamName = candidate.GetType().GetProperty("PeriodExamName").GetValue(candidate),
                    PeriodExamRound = candidate.GetType().GetProperty("PeriodExamRound").GetValue(candidate),
                    PeriodExamYear = candidate.GetType().GetProperty("PeriodExamYear").GetValue(candidate),
                    PositionName = candidate.GetType().GetProperty("PositionName").GetValue(candidate),
                    PositionLevelName = candidate.GetType().GetProperty("PositionLevelName").GetValue(candidate),
                    FullName = candidate.GetType().GetProperty("FullName").GetValue(candidate),
                    Nationality = candidate.GetType().GetProperty("Nationality").GetValue(candidate),
                    Religion = candidate.GetType().GetProperty("Religion").GetValue(candidate),
                    CitizenId = candidate.GetType().GetProperty("CitizenId").GetValue(candidate),
                    DateOfBirth = candidate.GetType().GetProperty("DateOfBirth").GetValue(candidate),
                    Age = candidate.GetType().GetProperty("Age").GetValue(candidate),
                    EducationLevelExamName = candidate.GetType().GetProperty("EducationLevelExamName").GetValue(candidate),
                    EducationName = candidate.GetType().GetProperty("EducationName").GetValue(candidate),
                    EducationMajor = candidate.GetType().GetProperty("EducationMajor").GetValue(candidate),
                    EducationLocation = candidate.GetType().GetProperty("EducationLocation").GetValue(candidate),
                    EducationEndDate = candidate.GetType().GetProperty("EducationEndDate").GetValue(candidate),
                    EducationScores = candidate.GetType().GetProperty("EducationScores").GetValue(candidate),
                    EducationType = candidate.GetType().GetProperty("EducationType").GetValue(candidate),
                    EducationLevelHighName = candidate.GetType().GetProperty("EducationLevelHighName").GetValue(candidate),
                    ExamIdenNumber = candidate.GetType().GetProperty("ExamIdenNumber").GetValue(candidate),
                    OccupationPositionType = candidate.GetType().GetProperty("OccupationPositionType").GetValue(candidate),
                    OccupationPosition = candidate.GetType().GetProperty("OccupationPosition").GetValue(candidate),
                    OccupationSalary = candidate.GetType().GetProperty("OccupationSalary").GetValue(candidate),
                    OccupationGroup = candidate.GetType().GetProperty("OccupationGroup").GetValue(candidate),
                    OccupationPile = candidate.GetType().GetProperty("OccupationPile").GetValue(candidate),
                    OccupationOrg = candidate.GetType().GetProperty("OccupationOrg").GetValue(candidate),
                    OccupationTelephone = candidate.GetType().GetProperty("OccupationTelephone").GetValue(candidate),
                    CareersTotal = candidate.GetType().GetProperty("CareersTotal").GetValue(candidate),
                    RegistAddress = candidate.GetType().GetProperty("RegistAddress").GetValue(candidate),
                    RegistProvinceName = candidate.GetType().GetProperty("RegistProvinceName").GetValue(candidate),
                    RegistDistrictName = candidate.GetType().GetProperty("RegistDistrictName").GetValue(candidate),
                    RegistSubDistrictName = candidate.GetType().GetProperty("RegistSubDistrictName").GetValue(candidate),
                    RegistZipCode = candidate.GetType().GetProperty("RegistZipCode").GetValue(candidate),
                    CurrentAddress = candidate.GetType().GetProperty("CurrentAddress").GetValue(candidate),
                    CurrentProvinceName = candidate.GetType().GetProperty("CurrentProvinceName").GetValue(candidate),
                    CurrentDistrictName = candidate.GetType().GetProperty("CurrentDistrictName").GetValue(candidate),
                    CurrentSubDistrictName = candidate.GetType().GetProperty("CurrentSubDistrictName").GetValue(candidate),
                    CurrentZipCode = candidate.GetType().GetProperty("CurrentZipCode").GetValue(candidate),
                    Telephone = candidate.GetType().GetProperty("Telephone").GetValue(candidate),
                    Email = candidate.GetType().GetProperty("Email").GetValue(candidate),
                    ContactFullName = candidate.GetType().GetProperty("ContactFullName").GetValue(candidate),
                    ContactRelations = candidate.GetType().GetProperty("ContactRelations").GetValue(candidate),
                    ContactTel = candidate.GetType().GetProperty("ContactTel").GetValue(candidate),
                    RegisterDate = candidate.GetType().GetProperty("RegisterDate").GetValue(candidate),
                    Url = picContent ?? "https://bma-ehr.frappet.synology.me/assets/avatar_user-89f22423.jpg",
                    Careers = careers,
                };

                var data = new {
                    template = "ผลสอบคัดเลือกรายบุคคล",
                    reportName = "docx-report",
                    data = mapData
                };
                return Success(data);
            }
            else
            {
                return NotFound();
            }
        }
        #endregion
    }
}