using NPOI.SS.UserModel;
using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Performance.Services.ExtractExcelService
{
    public class ExtractHelper
    {
        public static string GetExtractFile(int hospitalId, ref string newFilePath, string allotFilePath = "")
        {
            string originalPath = string.IsNullOrEmpty(allotFilePath)
                ? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template", "医院绩效模板.xls")
                : allotFilePath;
            var (tempPath, filePath) = CopyOriginalFile(hospitalId, originalPath);
            newFilePath = filePath;
            return tempPath;
        }

        private static (string TempPath, string FilePath) CopyOriginalFile(int hospitalId, string originalPath)
        {
            var ext = FileHelper.GetExtension(originalPath);
            var dpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files", $"{hospitalId}", "autoextract");
            FileHelper.CreateDirectory(dpath);
            string tempPath = Path.Combine(dpath, $"Template{DateTime.Now.ToString("yyyyMMddHHmmssfff")}{ext}");
            FileHelper.Copy(originalPath, tempPath);
            string filePath = Path.Combine(dpath, $"绩效提取数据{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xls");
            return (tempPath, filePath);
        }

        public static void CreateNotExistSheet(List<ex_module> modulesList, IWorkbook workbook)
        {
            SortedDictionary<string, int> pairs = new SortedDictionary<string, int>();
            for (int i = 0; i < workbook.NumberOfSheets; i++)
            {
                var sheetname = workbook.GetSheetAt(i).SheetName;
                if (!pairs.Keys.Contains(sheetname))
                    pairs.Add(workbook.GetSheetAt(i).SheetName, i);
            }

            int sheetIndex = 0;
            int newSheetCount = 0;
            foreach (var module in modulesList.Where(t => t.SheetType == (int)SheetType.Income)?.OrderBy(t => t.ModuleName))
            {
                var sheet = workbook.GetSheet(module.ModuleName);
                if (sheet == null)
                {
                    string[] keyArray = new string[] { "开单", "执行" };
                    if (keyArray.Any(key => module.ModuleName.Contains(key)))
                    {
                        var item = pairs.Where(t => t.Key.StartsWith("1.")).OrderByDescending(t => t.Key).First();
                        if (sheetIndex == 0)
                            sheetIndex = item.Value + 1;
                        var copysheet = workbook.GetSheet(item.Key);
                        var newSheet = copysheet.CopySheet(item.Key + Guid.NewGuid().ToString("N"), true);
                        workbook.SetSheetOrder(newSheet.SheetName, sheetIndex);
                        workbook.SetSheetName(sheetIndex, module.ModuleName);
                        sheetIndex++; newSheetCount++;
                    }
                }
            }

            sheetIndex = 0;
            foreach (var module in modulesList.Where(t => t.SheetType == (int)SheetType.Workload)?.OrderBy(t => t.ModuleName))
            {
                var sheet = workbook.GetSheet(module.ModuleName);
                if (sheet == null)
                {
                    string key = "工作量";
                    if (module.ModuleName.Contains(key))
                    {
                        var item = pairs.Where(t => t.Key.StartsWith("3.")).OrderByDescending(t => t.Key).First();
                        if (sheetIndex == 0)
                            sheetIndex = item.Value + newSheetCount + 1;
                        var copysheet = workbook.GetSheet(item.Key);
                        var newSheet = copysheet.CopySheet(item.Key + Guid.NewGuid().ToString("N"), true);
                        workbook.SetSheetOrder(newSheet.SheetName, sheetIndex);
                        workbook.SetSheetName(sheetIndex, module.ModuleName);
                        sheetIndex++;
                    }
                }
            }
        }

        public static void ClearSheetPartialData(ISheet sheet, PerSheetPoint point, SheetType sheetType)
        {
            if (sheet == null)
                return;

            for (int i = point.DataFirstRowNum.Value; i < sheet.LastRowNum + 1; i++)
            {
                var row = sheet.GetRow(i);
                if (row != null)
                {
                    int dataFirstCellRowNum = point.DataFirstCellNum.Value;
                    //跳过核算单元和科室
                    for (int j = dataFirstCellRowNum; j < row.LastCellNum; j++)
                    {
                        var cell = row.GetCell(j);
                        if (cell != null && (cell.CellType != CellType.Formula || sheetType == SheetType.Income))
                        {
                            cell.RemoveCellComment();
                            row.RemoveCell(cell);
                        }
                    }
                }
            }
        }
    }
}
