using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using Performance.DtoModels;
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Performance.Services.ExtractExcelService.SheetDataWrite
{
    public class OtherIncomeDataWrite : ISheetDataWrite
    {
        private readonly ILogger logger;

        public OtherIncomeDataWrite(ILogger logger)
        {
            this.logger = logger;
        }

        public void WriteCollectData(ISheet sheet, PerSheetPoint point, SheetType sheetType, ExcelStyle style, List<collect_data> collects, Dictionary<ExDataDict, object> exdict = null)
        {
            if (collects == null || !collects.Any(t => !string.IsNullOrEmpty(t.TypeName))) return;

            var columns = collects.Where(t => !string.IsNullOrEmpty(t.TypeName)).Select(t => t.TypeName).Distinct().OrderBy(t => t).ToList();

            var headers = columns.Select(t => new ExcelHeader
            {
                ColumnName = t.Trim(),
                DoctorFactor = 0,
                NurseFactor = 0,
                TechnicianFactor = 0
            }).ToList();

            WriteDataHelper.WriteSheetHeader(sheet, point, sheetType, style, headers);
            WriteDataHelper.WriteCollectData(sheet, point, sheetType, style, columns, collects);
        }

        public void WriteSheetData(ISheet sheet, PerSheetPoint point, SheetType sheetType, ExcelStyle style, object data, Dictionary<ExDataDict, object> exdict = null)
        {
            var modules = exdict[ExDataDict.ExModule] as List<ex_module>;
            var module = modules?.FirstOrDefault(t => t.SheetType == (int)sheetType && t.ModuleName.NoBlank() == sheet.SheetName.NoBlank());
            if (module == null) return;

            var items = exdict[ExDataDict.ExItem] as List<ex_item>;
            var modelItems = items?.Where(t => t.ModuleId == module.Id);
            if (modelItems == null || !modelItems.Any()) return;

            var headers = modelItems.Select(t => new ExcelHeader
            {
                ColumnName = t.ItemName,
                DoctorFactor = t.FactorValue1 ?? 0,
                NurseFactor = t.FactorValue2 ?? 0,
                TechnicianFactor = t.FactorValue3 ?? 0
            }).ToList();

            WriteDataHelper.WriteSheetHeader(sheet, point, sheetType, style, headers);
            if (data is List<ExtractTransDto> extractDto && extractDto.Any())
            {
                var columns = headers.Select(t => t.ColumnName).ToList();
                WriteDataHelper.ClearSheetFormula(sheet, point, sheetType, style, columns, extractDto);
                WriteDataHelper.WriteSheetData(sheet, point, sheetType, style, columns, extractDto);
            }
        }
    }
}
