using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;

namespace Tiobon.Core.Services;

/// <summary>
/// 年度人力配置 (服务)
/// </summary>
public class Ghrh_YearHumanSettingsServices : BaseServices<Ghrh_YearHumanSettings, Ghrh_YearHumanSettingsDto, InsertGhrh_YearHumanSettingsInput, EditGhrh_YearHumanSettingsInput>, IGhrh_YearHumanSettingsServices
{
    private readonly IBaseRepository<Ghrh_YearHumanSettings> _dal;
    private readonly ICommonServices _commonServices;
    public Ghrh_YearHumanSettingsServices(ICaching caching, IBaseRepository<Ghrh_YearHumanSettings> dal, ICommonServices commonServices)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
        _commonServices = commonServices;
    }

    #region 字典映射、全称、单位转换等
    /// <summary>
    /// 字典映射、全称、单位转换等
    /// </summary>
    /// <param name="view"></param>
    private async Task SetLabel(Ghrh_YearHumanSettingsDto data)
    {
        if (data != null)
        {
            data.M1_F = data.M1 + (data.M1_A ?? 0);
            data.M2_F = data.M2 + (data.M2_A ?? 0);
            data.M3_F = data.M3 + (data.M3_A ?? 0);
            data.M4_F = data.M4 + (data.M4_A ?? 0);
            data.M5_F = data.M5 + (data.M5_A ?? 0);
            data.M6_F = data.M6 + (data.M6_A ?? 0);
            data.M7_F = data.M7 + (data.M7_A ?? 0);
            data.M8_F = data.M8 + (data.M8_A ?? 0);
            data.M9_F = data.M9 + (data.M9_A ?? 0);
            data.M10_F = data.M10 + (data.M10_A ?? 0);
            data.M11_F = data.M11 + (data.M11_A ?? 0);
            data.M12_F = data.M12 + (data.M12_A ?? 0);
        }
    }
    #endregion

    public override async Task<long> Add(InsertGhrh_YearHumanSettingsInput entity)
    {
        entity.WorkState = 1;

        if (await Db.Queryable<Ghrh_YearHumanSettings>()
            .WhereIF(entity.GradeId.IsNotEmptyOrNull(), x => x.GradeId == entity.GradeId)
            .WhereIF(entity.JobId.IsNotEmptyOrNull(), x => x.JobId == entity.JobId)
            .AnyAsync(x => x.Year == entity.Year && x.DeptId == entity.DeptId && x.TitleId == entity.TitleId))
            throw new Exception($" {entity.Year}年度，已存在相同数据！");

        var result = await base.Add(entity);

        return result;
    }

    public override async Task<bool> Update(long Id, EditGhrh_YearHumanSettingsInput entity)
    {
        entity.WorkState = 1;

        if (await Db.Queryable<Ghrh_YearHumanSettings>()
            .WhereIF(entity.GradeId.IsNotEmptyOrNull(), x => x.GradeId == entity.GradeId)
            .WhereIF(entity.JobId.IsNotEmptyOrNull(), x => x.JobId == entity.JobId)
            .AnyAsync(x => x.Year == entity.Year && x.DeptId == entity.DeptId && x.TitleId == entity.TitleId && x.Id != Id))
            throw new Exception($" {entity.Year}年度，已存在相同数据！");

        var result = await base.Update(Id, entity);

        return result;
    }

    public override async Task<ServicePageResult<Ghrh_YearHumanSettingsDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {
        var result = await base.QueryFilterPage(filter, $"WorkState = 1 AND dbo.[FUserDeptPriv] ({App.User.ID}, DeptId, getdate())=1", IsEnable);
        var entitys = result.result.DT_TableDataT1;
        int? year = null;
        if (filter.jsonParam != null)
            foreach (JProperty jProperty in filter.jsonParam.Properties())
            {
                var name = jProperty.Name;
                var value = jProperty.Value.ToString();
                if (name == "Year")
                {

                    var jsonParam = JsonHelper.JsonToObj<JsonParam>(value);
                    year = jsonParam.columnValue.ObjToInt();

                }
            }

        var deptIds = entitys.Where(x => x.DeptId != null).Select(x => x.DeptId).ToList();
        var titleIds = entitys.Where(x => x.TitleId != null).Select(x => x.TitleId).ToList();
        var gradeIds = entitys.Where(x => x.GradeId != null).Select(x => x.GradeId).ToList();
        var jobIds = entitys.Where(x => x.JobId != null).Select(x => x.JobId).ToList();

        if (deptIds.Any())
        {
            var depts = await Db.Queryable<Ghro_Dept>().Where(x => deptIds.Contains(x.DeptID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.DeptName = depts.FirstOrDefault(o => rule.DeptId == o.DeptID)?.DeptName;
            });
        }

        if (titleIds.Any())
        {
            var titles = await Db.Queryable<Ghra_Title>().Where(x => titleIds.Contains(x.TitleID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.TitleName = titles.FirstOrDefault(o => rule.TitleId == o.TitleID)?.TitleName;
            });
        }

        if (gradeIds.Any())
        {
            var grades = await Db.Queryable<Ghra_Grade>().Where(x => gradeIds.Contains(x.GradeID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.GradeName = grades.FirstOrDefault(o => rule.GradeId == o.GradeID)?.GradeName;
            });
        }

        if (jobIds.Any())
        {
            var jobs = await Db.Queryable<Ghra_Job>().Where(x => jobIds.Contains(x.JobID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.JobName = jobs.FirstOrDefault(o => rule.JobId == o.JobID)?.JobName;
            });
        }
        entitys.ForEach(async x =>
        {
            await SetLabel(x);
        });

        result.result.DT_TableDataT1 = entitys;
        ModuleParam param = new ModuleParam()
        {
            langId = filter.langId,
            menuName = filter.menuName
        };
        var module = await _commonServices.GetModuleInfoAsync(param);
        result.result.JM_TableColumnT1 = module.Data.JM_TableColumnT1;

        var yearField = module.Data.JM_TableColumnT1.TableColumn.Where(x => x.field == "Year").SingleOrDefault();
        if (year != yearField?.searchColumnDefaultValue.ObjToInt())
        {

            result.result.JM_TableColumnT1.TableColumn?.ForEach(x =>
            {
                if (x.GroupName == "预算编制数")
                {

                    int month = x.field.Replace("M", null).Replace("_F", null).ObjToInt();
                    x.label = year + "-" + (month < 10 ? "0" + month : month);
                    if (month == 12)
                        year++;
                }
            });
        }
        return result;
    }

    public override async Task<ServiceFormResult<Ghrh_YearHumanSettingsDto>> QueryForm(QueryForm body)
    {

        var result = await base.QueryForm(body);
        var config = await Db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_Year_Human_Start_Month").FirstAsync();

        var data = result.result.DT_TableDataT1[0];
        data.StartMonth = config != null ? config.ConfigValue.ObjToInt() : 1;

        await SetLabel(data);
        result.result.DT_TableDataT1[0] = data;
        return result;

    }

    public override async Task<Ghrh_YearHumanSettingsDto> QueryById(object objId)
    {
        var entity = await base.QueryById(objId);

        await SetLabel(entity);

        return entity;
    }

    public async Task<ServiceResult<List<FlowTableColumn>>> QueryApplyColumn(int curentYear, int langId)
    {
        int flowId = await Db.Ado.GetIntAsync("Select FlowID from Ghrw_Flow where FlowNo='F_ESS_RecruitYearManpowerApply'");
        var param = new FlowParam() { doType = "Insert", jsonParam = new FlowJsonParam() { FlowID = flowId }, menuName = "F_ESS_RecruitYearManpowerApply", langId = langId, userId = App.User.ID };

        var flowReturn = await _commonServices.GetFlowInfoAsync(param);
        var config = await Db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_Year_Human_Start_Month").FirstAsync();

        var startMonth = config != null ? config.ConfigValue.ObjToInt() : 1;

        #region 处理起始月 
        var months = new List<string>();
        List<int> numbers = new();
        for (int i = 1; i <= 12; i++)
        {
            if (i < 10)
                months.Add("0" + i);
            else
                months.Add(i.ObjToString());
            numbers.Add(i);
        }
        // 指定要打头的数字
        int startNumber = startMonth;
        var sort = flowReturn.result.JM_TableColumnT1.TableColumn.Where(x => x.field == "M1").SingleOrDefault()?.rowNum ?? 5;
        // 创建一个新的列表用于存储重新排序后的结果
        List<int> reorderedNumbers = new();
        flowReturn.result.JM_TableColumnT1.TableColumn?.ForEach(x =>
        {
            if (months.Where(o => o == x.label).Any())
                x.GroupName = "预算编制数";

        });

        // 找到指定数字的索引
        int index1 = numbers.IndexOf(startNumber);
        if (index1 != -1)
        {
            // 从指定数字开始，按照循环顺序添加数字
            for (int i = 0; i < numbers.Count; i++)
            {
                int currentIndex = (index1 + i) % numbers.Count;
                reorderedNumbers.Add(numbers[currentIndex]);
            }

            foreach (var num in reorderedNumbers)
            {
                flowReturn.result.JM_TableColumnT1.TableColumn?.ForEach(x =>
                {
                    if (x.field.Replace("M", null).ObjToInt() == num)
                    {
                        x.rowNum = sort;
                        x.label = curentYear + "-" + x.field.Replace("M", null);
                    }
                });
                if (num == 12)
                    curentYear++;
                sort++;
            }
        }
        flowReturn.result.JM_TableColumnT1.TableColumn = flowReturn.result.JM_TableColumnT1.TableColumn.OrderBy(x => x.rowNum).ToList();
        #endregion

        flowReturn.result.JM_TableColumnT1.TableColumn.ForEach(x =>
        {
            if (x.field == "DeptId")
                x.field = "DeptName";
            else if (x.field == "TitleId")
                x.field = "TitleName";
            else if (x.field == "JobId")
                x.field = "JobName";
            else if (x.field == "GradeId")
                x.field = "GradeName";
        });

        return ServiceResult<List<FlowTableColumn>>.OprateSuccess("查询成功！", flowReturn.result.JM_TableColumnT1.TableColumn);

    }



    #region Excel导入
    public override async Task<ServiceResult<ExcelData>> ImportExcel(IFormFile file, string menuName = null, long? MasterId = null)
    {
        var data = new ExcelData();
        long id = SnowFlakeSingle.instance.getID();
        var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
        var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}import{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}";
        if (!Directory.Exists(physicsPath + path))
            Directory.CreateDirectory(physicsPath + path);

        var filepath = physicsPath + path + file.FileName;
        using (var stream = File.Create(filepath))
        {
            await file.CopyToAsync(stream);
        }
        string extension = Path.GetExtension(filepath);

        bool isExistError = false;
        var id1 = SnowFlakeSingle.instance.getID();
        string errorFileName = path + SnowFlakeSingle.instance.getID() + extension;
        try
        {
            DataTable dt = NPOIHelper.ImportExcel(filepath, "年度人力配置");
            if (dt.Columns["Comments"] == null)
                dt.Columns.Add("Comments", typeof(string));

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var comments = new List<string>();

                if (!dt.Columns.Contains("年度"))
                {
                    comments.Add("未查询到【年度】列！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }
                if (!dt.Columns.Contains("部门"))
                {
                    comments.Add("未查询到【部门】列！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }

                if (!dt.Columns.Contains("岗位"))
                {
                    comments.Add("未查询到【岗位】列！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }


                if (!dt.Columns.Contains("职称"))
                {
                    comments.Add("未查询到【职称】列！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }
                if (!dt.Columns.Contains("职等"))
                {
                    comments.Add("未查询到【职等】列！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }

                for (int j = 1; j <= 12; j++)
                {
                    if (!dt.Columns.Contains(j + "月"))
                    {
                        comments.Add($"未查询到【{j}月】列！");
                        data.ErrorCount++;
                        dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                        isExistError = true;
                        continue;
                    }
                }

                var year = dt.Rows[i]["年度"].ToString();
                var deptName = dt.Rows[i]["部门"].ToString();
                var titleName = dt.Rows[i]["岗位"].ToString();
                var jobName = dt.Rows[i]["职称"].ToString();
                var gradeName = dt.Rows[i]["职等"].ToString();

                var dept = await Db.Queryable<Ghro_Dept>().Where(x => x.DeptName == deptName).FirstAsync();
                if (dept == null)
                {
                    comments.Add($"无效的部门名称！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }
                var title = await Db.Queryable<Ghra_Title>().Where(x => x.TitleName == titleName).FirstAsync();
                if (title == null)
                {
                    comments.Add($"无效的岗位名称！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }

                var job = await Db.Queryable<Ghra_Job>().Where(x => x.JobName == jobName).FirstAsync();
                if (job == null)
                {
                    comments.Add($"无效的职称名称！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }

                var grade = await Db.Queryable<Ghra_Grade>().Where(x => x.GradeName == gradeName).FirstAsync();
                if (grade == null)
                {
                    comments.Add($"无效的职等名称！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }

                if (1 == 1)
                {
                    var dict = new Dictionary<string, object>
                    {
                        { "Id", SnowFlakeSingle.Instance.NextId() },
                        { "CreateBy", App.User.ID },
                        { "CreateTime", DateTime.Now },
                        { "WorkState", 1 },
                        { "Year", year },
                        { "DeptId", dept.DeptID },
                        { "TitleId", title.TitleID },
                        { "GradeId", grade.GradeID },
                        { "JobId", job.JobID }
                    };
                    for (int j = 1; j <= 12; j++)
                        dict.Add("M" + j, dt.Rows[i][j + "月"].ToString());
                    await Db.Insertable(dict).AS("Ghrh_YearHumanSettings").ExecuteCommandAsync();
                    if (comments.Any())
                    {
                        data.ErrorCount++;
                        dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                        isExistError = true;
                        continue;
                    }
                    else
                    {
                        data.SuccessCount++;
                    }
                }
                else
                {
                    dt.Rows[i]["Comments"] = "试题在系统中已存在！";
                    data.ErrorCount++;
                    isExistError = true;
                    continue;
                }

            }

            if (isExistError)
            {
                NPOIHelper.ExportExcel(dt, null, "年度人力配置", physicsPath + errorFileName);
                data.filePath = "/Advanced" + errorFileName;
            }
        }
        catch (Exception)
        {
        }
        return ServiceResult<ExcelData>.OprateSuccess("导入成功！", data);
    }

    public override async Task<ServiceResult<string>> DownloadExcel(string menuName)
    {
        var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
        var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}ExcelTemplate{Path.DirectorySeparatorChar}"}";
        if (!Directory.Exists(physicsPath + path))
            Directory.CreateDirectory(physicsPath + path);

        Type entityType = typeof(Ghrh_YearHumanSettings);
        var fileName = entityType.GetEntityTableName() + ".xlsx";
        //physicsPath = physicsPath + path + fileName;

        IWorkbook hssfworkbook;
        ISheet sheet;
        using (FileStream file = new FileStream(physicsPath + path + fileName, FileMode.Open, FileAccess.Read))
        {
            //hssfworkbook = new HSSFWorkbook(file);
            //hssfworkbook = new XSSFWorkbook(file);
            hssfworkbook = WorkbookFactory.Create(file);
        }
        ISheet sheet2 = hssfworkbook.CreateSheet("下拉数据");

        var newFileName = Guid.NewGuid() + ".xlsx";
        int listColIndex = 0;
        //string sql = @"select 'Course' field, Id id, CourseNo no, CourseName name from Ghre_Course where IsEnable=1 and Status='Released'";
        //var dataSourceLists = await Db.Ado.SqlQueryAsync<DataSourceList>(sql);
        //if (dataSourceLists.Any())
        //{
        //    var types = new List<string>
        //    {
        //    "学习记录"
        //    };

        //    types.ForEach(sheetName =>
        //    {
        //        int sheetIndex = hssfworkbook.GetSheetIndex(sheetName);
        //        if (sheetIndex >= 0)
        //        {
        //            sheet = hssfworkbook.GetSheetAt(sheetIndex);

        //            SetCellDropdownList(sheet, 0, 0, dataSourceLists.Select(x => x.name).ToArray());
        //        }

        //    });
        //    MemoryStream ms;
        //    using (ms = new MemoryStream())
        //    {
        //        hssfworkbook.Write(ms);
        //        ms.Flush();
        //        hssfworkbook.Dispose();
        //        //ms.Position = 0;
        //        //return ms;
        //    }
        //    using (FileStream fs = new FileStream(physicsPath + path + newFileName, FileMode.Create, FileAccess.Write))
        //    {
        //        byte[] data = ms.ToArray();
        //        fs.Write(data, 0, data.Length);
        //        fs.Flush();
        //    }

        //}

        var physicsPath1 = physicsPath + path + fileName;
        //if (dataSourceLists.Any())
        //    physicsPath1 = physicsPath + path + newFileName;
        var result = ServiceResult<string>.OprateSuccess("年度人力配置_" + DateTimeHelper.ConvertToSecondString1(DateTime.Now) + ".xlsx", physicsPath1);
        return result;
    }

    public static void SetCellDropdownList(ISheet sheet, int firstcol, int lastcol, string[] vals)
    {

        //設置生成下拉框的行和列
        var cellRegions = new CellRangeAddressList(1, 65535, firstcol, lastcol);
        IDataValidation validation = null;

        if (sheet.GetType().Name.Contains("XSSF")) // .xlsx
        {
            XSSFDataValidationHelper helper = new XSSFDataValidationHelper((XSSFSheet)sheet);//获得一个数据验证Helper  
                                                                                             //IDataValidation
            validation = helper.CreateValidation(
            helper.CreateExplicitListConstraint(vals), cellRegions);//创建约束
        }
        else // HSSF .xls
        {
            //設置 下拉框內容
            DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(vals);
            validation = new HSSFDataValidation(cellRegions, constraint);


            /*綁定下拉框和作用區域，並設置錯誤提示信息
            HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint);
            dataValidate.CreateErrorBox("輸入不合法", "請輸入或選擇下拉列表中的值。");
            dataValidate.ShowPromptBox = true;
*/
        }

        validation.CreateErrorBox("输入不合法", "请输入或选择下拉列表中的值。");
        validation.ShowPromptBox = true;

        sheet.AddValidationData(validation);
    }

    #endregion

    #region Excel导出
    public override async Task<ServiceResult<ExcelData>> ExportExcel(QueryExport body)
    {
        QueryBody filter = new QueryBody();
        filter.pageNum = 1;
        filter.pageSize = 1000000;
        filter.jsonParam = body.jsonParam;
        filter.langId = body.langId;
        filter.menuName = body.menuName;

        var condition = "1=1";
        if (body.exportSet.SelectRowKeys != null && body.exportSet.SelectRowKeys.Any())
            condition += $" AND Id IN({string.Join(",", body.exportSet.SelectRowKeys)})";

        var data = await QueryFilterPage(filter, condition, true);

        var columns = data.result.JM_TableColumnT1.TableColumn;

        var fieldDescs = new Dictionary<string, string>();
        if (body.exportSet.ExFields.Any())
            body.exportSet.ExFields.ForEach(x =>
            {
                if (columns.Any(o => o.field == x))
                    fieldDescs.Add(x, columns.FirstOrDefault(o => o.field == x)?.label);
            });
        else
            fieldDescs = columns.ToDictionary(item => item.field, item => item.label);
        var dt = ToDataTable(data.result.DT_TableDataT1, fieldDescs, null);
        // 获取所有列名
        var dtColumns = dt.Columns;

        var id = SnowFlakeSingle.instance.getID();
        var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
        var path = $"{$"/files/export/{id}/"}";
        if (!Directory.Exists(physicsPath + path))
            Directory.CreateDirectory(physicsPath + path);

        path = path + body.exportSet.TitleName + ".xlsx";
        NPOIHelper.ExportExcel(dt, body.exportSet.TitleName, "年度人力配置", physicsPath + path);

        var result = new ExcelData();
        result.filePath = "/Advanced" + path;
        result.fileName = body.exportSet.TitleName + ".xlsx";
        return ServiceResult<ExcelData>.OprateSuccess("导出成功", result);
    }
    #endregion
}