using NPOI.SS.UserModel;
using NPOI.SS.Util;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace Performance.Services
{
    public class PerSheetDataReadSpecialUnit : IPerSheetDataRead
    {
        public PerSheetPoint Point => new PerSheetPoint
        {
            HeaderFirstRowNum = 1,
            HeaderLastRowNum = 1,
            HeaderFirstCellNum = 0,
            DataFirstRowNum = 2,
        };

        public List<IPerData> ReadData(ISheet sheet, List<PerHeader> perHeader)
        {
            List<IPerData> dataList = new List<IPerData>();
            string[] headers = new string[]
            {
                "量化指标",
                "数量",
                "量化指标绩效分值",
                "科室",
                "人数",
                //"考核得分率",
                //"其他绩效",
                //"医院奖罚",
                //"调节系数",
            };
            foreach (var item in headers)
            {
                if (!perHeader.Any(p => p.CellValue == item))
                    throw new NullReferenceException($"sheet '{sheet.SheetName}'中列'{item}'为空");
            }
            // 特殊科室多科室聚合，合并时保留科室名称
            string lastAccount = "";
            for (int r = Point.DataFirstRowNum.Value; r < sheet.LastRowNum + 1; r++)
            {
                var row = sheet.GetRow(r);
                if (row == null) continue;

                PerDataSpecialUnit specialUnit = new PerDataSpecialUnit
                {
                    RowNumber = r,
                };
                int point;
                if (NopiSevice.TryGetPoint(perHeader, "量化指标", out point))
                    specialUnit.QuantitativeIndicators = row.GetCell(point).GetValue();
                if (NopiSevice.TryGetPoint(perHeader, "数量", out point))
                    specialUnit.Quantity = ConvertHelper.To<decimal?>(row.GetCell(point).GetValue());
                if (NopiSevice.TryGetPoint(perHeader, "量化指标绩效分值", out point))
                    specialUnit.QuantitativeIndicatorsValue = ConvertHelper.To<decimal?>(row.GetCell(point).GetValue());
                if (NopiSevice.TryGetPoint(perHeader, "人数", out point))
                    specialUnit.Number = ConvertHelper.To<decimal?>(row.GetCell(point).GetValue());
                if (NopiSevice.TryGetPoint(perHeader, "实发绩效", out point))
                    specialUnit.RealGiveFee = ConvertHelper.To<decimal?>(row.GetCell(point).GetValue());

                ICell cell = null;
                if (NopiSevice.TryGetPoint(perHeader, "科室", out int kspoint))
                    cell = row.GetCell(kspoint);

                if (cell == null) continue;

                var accountingUnit = cell.GetValue();
                if (cell != null && IsMergeCell(cell, out Point start, out Point end) && r != start.X)
                {
                    row = sheet.GetRow(start.X);
                    cell = row.GetCell(kspoint);
                    accountingUnit = cell.GetValue();
                }
                if (string.IsNullOrEmpty(accountingUnit))
                    accountingUnit = lastAccount;
                //相同科室只取以下项目第一次出现的值
                //if (accountingUnit != lastAccount)
                //{

                specialUnit.AccountingUnit = accountingUnit;
                specialUnit.Department = accountingUnit;
                //specialUnit.ScoringAverage = ConvertHelper.To<decimal?>(row.GetCell(perHeader.FirstOrDefault(p => p.CellValue == "考核得分率").PointCell)?.NumericCellValue);
                //specialUnit.OtherPerfor = ConvertHelper.To<decimal?>(row.GetCell(perHeader.FirstOrDefault(p => p.CellValue == "其他绩效").PointCell)?.NumericCellValue);
                //specialUnit.Punishment = ConvertHelper.To<decimal?>(row.GetCell(perHeader.FirstOrDefault(p => p.CellValue == "医院奖罚").PointCell)?.NumericCellValue);
                //specialUnit.Adjust = ConvertHelper.To<decimal?>(row.GetCell(perHeader.FirstOrDefault(p => p.CellValue == "调节系数").PointCell)?.NumericCellValue);
                //}
                if (!string.IsNullOrEmpty(specialUnit.QuantitativeIndicators) && specialUnit.QuantitativeIndicatorsValue != null)
                    dataList.Add(specialUnit);
                //合并单元格科室名称补全
                lastAccount = specialUnit.AccountingUnit;
            }

            return dataList;
        }

        public static bool IsMergeCell(ICell cell, out Point start, out Point end)
        {
            return IsMergeCell(cell.Sheet, cell.RowIndex, cell.ColumnIndex, out start, out end);
        }


        /// <summary>
        /// 获取当前单元格所在的合并单元格的位置
        /// </summary>
        /// <param name="sheet">sheet表单</param>
        /// <param name="rowIndex">行索引 0开始</param>
        /// <param name="colIndex">列索引 0开始</param>
        /// <param name="start">合并单元格左上角坐标</param>
        /// <param name="end">合并单元格右下角坐标</param>
        /// <returns>返回false表示非合并单元格</returns>
        private static bool IsMergeCell(ISheet sheet, int rowIndex, int colIndex, out Point start, out Point end)
        {
            bool result = false;
            start = new Point(0, 0);
            end = new Point(0, 0);
            if ((rowIndex < 0) || (colIndex < 0)) return result;
            int regionsCount = sheet.NumMergedRegions;
            for (int i = 0; i < regionsCount; i++)
            {
                CellRangeAddress range = sheet.GetMergedRegion(i);
                //sheet.IsMergedRegion(range); 
                if (rowIndex >= range.FirstRow && rowIndex <= range.LastRow && colIndex >= range.FirstColumn && colIndex <= range.LastColumn)
                {
                    start = new Point(range.FirstRow, range.FirstColumn);
                    end = new Point(range.LastRow, range.LastColumn);
                    result = true;
                    break;
                }
            }
            return result;
        }
    }
}
