using NPOI.SS.UserModel;
using NPOI.SS.Util;
using static Tiobon.Core.Model.Consts;

namespace Tiobon.Core.Services;

/// <summary>
/// 培训计划 (服务)
/// </summary>
public class Ghre_PlanServices : BaseServices<Ghre_Plan, Ghre_PlanDto, InsertGhre_PlanInput, EditGhre_PlanInput>, IGhre_PlanServices
{
    private readonly IBaseRepository<Ghre_Plan> _dal;
    private readonly ICommonServices _commonServices;
    public Ghre_PlanServices(ICaching caching, IBaseRepository<Ghre_Plan> dal, ICommonServices commonServices)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
        _commonServices = commonServices;
    }
    public override async Task<ServicePageResult<Ghre_PlanDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {
        var result = await base.QueryFilterPage(filter, condition, IsEnable);

        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 DT_TableDataT1 = result.result.DT_TableDataT1;

        var deptIds = DT_TableDataT1.Select(x => x.DeptId).Distinct().ToList();
        var courseIds = DT_TableDataT1.Select(x => x.CourseId).Distinct().ToList();
        var schoolIds = DT_TableDataT1.Select(x => x.SchoolId).Distinct().ToList();
        var staffIds = new List<int>();
        for (int i = 0; i < DT_TableDataT1.Count; i++)
        {
            if (DT_TableDataT1[i].StaffIds.IsNotEmptyOrNull())
                staffIds.AddRange(JsonHelper.JsonToObj<List<int>>(DT_TableDataT1[i].StaffIds));
            DT_TableDataT1[i].TrainCategory = await GetParaLabel("TrainingCategory", DT_TableDataT1[i].TrainCategory);
            if (DT_TableDataT1[i].Month.IsNotEmptyOrNull())
                DT_TableDataT1[i].Months = JsonHelper.JsonToObj<List<string>>(DT_TableDataT1[i].Month);
            //DT_TableDataT1[i].Month = await GetParaLabel("MonthSelect", DT_TableDataT1[i].Month);
            DT_TableDataT1[i].InOrOut = await GetParaLabel("CourseInOrOut", DT_TableDataT1[i].InOrOut);

            if (DT_TableDataT1[i].Months.Any())
                DT_TableDataT1[i].Months.ForEach(x =>
                {
                    if (x.ObjToInt() == 1) DT_TableDataT1[i].M1 = "✔";
                    else if (x.ObjToInt() == 2) DT_TableDataT1[i].M2 = "✔";
                    else if (x.ObjToInt() == 3) DT_TableDataT1[i].M3 = "✔";
                    else if (x.ObjToInt() == 4) DT_TableDataT1[i].M4 = "✔";
                    else if (x.ObjToInt() == 5) DT_TableDataT1[i].M5 = "✔";
                    else if (x.ObjToInt() == 6) DT_TableDataT1[i].M6 = "✔";
                    else if (x.ObjToInt() == 7) DT_TableDataT1[i].M7 = "✔";
                    else if (x.ObjToInt() == 8) DT_TableDataT1[i].M8 = "✔";
                    else if (x.ObjToInt() == 9) DT_TableDataT1[i].M9 = "✔";
                    else if (x.ObjToInt() == 10) DT_TableDataT1[i].M10 = "✔";
                    else if (x.ObjToInt() == 11) DT_TableDataT1[i].M11 = "✔";
                    else if (x.ObjToInt() == 12) DT_TableDataT1[i].M12 = "✔";
                });
        }
        staffIds = staffIds.Distinct().ToList();
        var staffs = await Db.Queryable<Ghra_Staff>().Where(x => staffIds.Contains(x.StaffID)).ToListAsync();
        var depts = await Db.Queryable<Ghro_Dept>().Where(x => deptIds.Contains(x.DeptID)).ToListAsync();
        var courses = await Db.Queryable<Ghre_Course>().Where(x => courseIds.Contains(x.Id)).ToListAsync();
        var schools = await Db.Queryable<Ghre_School>().Where(x => schoolIds.Contains(x.Id)).ToListAsync();


        for (int i = 0; i < DT_TableDataT1.Count; i++)
        {
            if (DT_TableDataT1[i].StaffIds.IsNotEmptyOrNull())
            {
                var staffIds1 = JsonHelper.JsonToObj<List<int>>(DT_TableDataT1[i].StaffIds);
                if (staffIds1.Any())
                    DT_TableDataT1[i].StaffNames = string.Join("、", staffs.Where(x => staffIds1.Contains(x.StaffID)).Select(x => x.StaffName));
            }

            if (DT_TableDataT1[i].CourseId.IsNotEmptyOrNull() && DT_TableDataT1[i].CourseName.IsNullOrEmpty())
                DT_TableDataT1[i].CourseName = courses.Where(x => x.Id == DT_TableDataT1[i].CourseId).Select(x => x.CourseName).FirstOrDefault();
            if (DT_TableDataT1[i].DeptId.IsNotEmptyOrNull())
            {
                DT_TableDataT1[i].DeptName = depts.Where(x => x.DeptID == DT_TableDataT1[i].DeptId).Select(x => x.DeptName).FirstOrDefault();
                DT_TableDataT1[i].DeptNo = depts.Where(x => x.DeptID == DT_TableDataT1[i].DeptId).Select(x => x.DeptNo).FirstOrDefault();

            }
            if (DT_TableDataT1[i].SchoolId.IsNotEmptyOrNull())
                DT_TableDataT1[i].SchoolName = schools.Where(x => x.Id == DT_TableDataT1[i].SchoolId).Select(x => x.SchoolName).FirstOrDefault();

            if (DT_TableDataT1[i].TrainNum != null && DT_TableDataT1[i].TrainDays != null)
                DT_TableDataT1[i].TotalDays = DT_TableDataT1[i].TrainNum * DT_TableDataT1[i].TrainDays;
            DT_TableDataT1[i].BuiltInLabel = DT_TableDataT1[i].BuiltIn == 1 ? "是" : "否";
        }

        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<long> Add(InsertGhre_PlanInput entity)
    {
        if (entity.StaffId != null)
            entity.StaffIds = JsonHelper.ObjToJson(entity.StaffId.OrderBy(n => n).ToList());
        if (entity.StaffId.IsNotEmptyOrNull() && entity.StaffId.Count > 0)
            entity.TrainNum = entity.StaffId.Count;
        if (entity.Months != null)
            entity.Month = JsonHelper.ObjToJson(entity.Months.OrderBy(n => n).ToList());
        var result = await base.Add(entity);

        return result;
    }

    public override async Task<bool> Update(long Id, EditGhre_PlanInput editModel)
    {
        if (editModel.StaffId != null)
            editModel.StaffIds = JsonHelper.ObjToJson(editModel.StaffId);

        if (editModel.StaffId.IsNotEmptyOrNull() && editModel.StaffId.Count > 0)
            editModel.TrainNum = editModel.StaffId.Count;
        if (editModel.Months != null)
            editModel.Month = JsonHelper.ObjToJson(editModel.Months.OrderBy(n => n).ToList());

        var result = await base.Update(Id, editModel, null, ["Status"]);
        return result;
    }

    public override async Task<ServiceFormResult<Ghre_PlanDto>> QueryForm(QueryForm body)
    {
        var result = await base.QueryForm(body);

        string StaffIds = result.result.DT_TableDataT1[0].StaffIds;
        string Month = result.result.DT_TableDataT1[0].Month;
        if (!string.IsNullOrWhiteSpace(StaffIds))
            result.result.DT_TableDataT1[0].StaffId = JsonConvert.DeserializeObject<List<int>>(StaffIds);

        if (!string.IsNullOrWhiteSpace(Month))
            result.result.DT_TableDataT1[0].Months = JsonConvert.DeserializeObject<List<string>>(Month);
        if (result.result.DT_TableDataT1[0].TrainNum != null && result.result.DT_TableDataT1[0].TrainDays != null)
            result.result.DT_TableDataT1[0].TotalDays = result.result.DT_TableDataT1[0].TrainNum * result.result.DT_TableDataT1[0].TrainDays;
        return result;
    }
    public async Task<ServiceResult<long>> InsertByStatus(InsertGhre_PlanInput insertModel, string status)
    {
        if (insertModel.StaffId != null)
            insertModel.StaffIds = JsonHelper.ObjToJson(insertModel.StaffId);
        var data = ServiceResult<long>.OprateSuccess("新增成功", 0);
        insertModel.Status = status;
        var id = await Add(insertModel);

        data.Success = id > 0;
        if (data.Success)
            data.Data = id;
        else
            return ServiceResult<long>.OprateFailed("失败！");

        return data;
    }

    public async Task<ServiceResult> UpdateStatus(InsertGhre_PlanInput input, string status)
    {

        HttpRequest request = UserContext.Context.Request;
        var api = request.Path.ObjToString().TrimEnd('/').ToLower();
        var ip = GetUserIp(UserContext.Context);

        var entities = new List<Ghre_Plan>();
        foreach (var id in input.Ids)
        {
            if (!BaseDal.Any(id))
                continue;

            var entity = await BaseDal.QueryById(id);


            switch (status)
            {
                case DIC_REQUEST_STATUS.Active:
                    entity.AgreeReason = input.Reason;
                    entity.AgreeTime = DateTime.Now;
                    entity.AgreeUserId = App.User.ID;
                    break;
                case DIC_REQUEST_STATUS.Temporary:
                    entity.RefuseReason = input.Reason;
                    entity.RefuseTime = DateTime.Now;
                    entity.RefuseUserId = App.User.ID;
                    break;
            }

            entity.UpdateIP = ip;
            entity.UpdateProg = api;
            entity.Status = status;
            entities.Add(entity);
        }

        var result = await BaseDal.Update(entities);
        return ServiceResult.OprateSuccess("执行成功！");

    }


    public async Task<ServicePageResult<UshioPlanReport>> QueryUshioPlan(QueryBody filter)
    {
        var result = await QueryFilterPage(filter, "", true);

        var inPlanIds = result.result.DT_TableDataT1.Where(x => x.InOrOut == "In").Select(x => x.Id).ToList();
        var outPlanIds = result.result.DT_TableDataT1.Where(x => x.InOrOut == "Out").Select(x => x.Id).ToList();

        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 studyRecordGroup1 = await Db.SqlQueryable<Ghre_StudyRecordDto>("select * from Ghre_StudyRecord_V")
            .Where(m =>
           inPlanIds.Contains(m.PlanId.Value) && m.PlanId != null && (
           m.CourseType == "ManualInsert" ||
            (m.BeginTime != null && m.EndTime != null && m.ExamId == null) ||
            (m.BeginTime != null && m.EndTime != null && m.ExamId != null && m.IsRequireStudy == true && m.IsPass == true)
            ))
            .Select(q => new { q.Id, q.PlanId, ExamDate = q.ExamDate1 ?? q.EndTime })
            .GroupBy(q => new { q.Id, q.PlanId, q.ExamDate })
            .Select(m => new { m.PlanId, ExamDate = m.ExamDate.Value, Count = SqlFunc.AggregateCount(m.Id) })
            .ToListAsync();
        studyRecordGroup1 = studyRecordGroup1.Where(x => x.ExamDate.Year == year).ToList();
        var data = Mapper.Map(result.result.DT_TableDataT1).ToANew<List<UshioPlanReport>>();


        data.ForEach(async d =>
        {
            int year = d.Year.Value;
            if (d.InOrOut == "In")
            {
                d.M1_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 1).Sum(x => x.Count);
                d.M2_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 2).Sum(x => x.Count);
                d.M3_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 3).Sum(x => x.Count);
                d.M4_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 4).Sum(x => x.Count);
                d.M5_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 5).Sum(x => x.Count);
                d.M6_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 6).Sum(x => x.Count);
                d.M7_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 7).Sum(x => x.Count);
                d.M8_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 8).Sum(x => x.Count);
                d.M9_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 9).Sum(x => x.Count);
                d.M10_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 10).Sum(x => x.Count);
                d.M11_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 11).Sum(x => x.Count);
                d.M12_Count = studyRecordGroup1.Where(x => x.PlanId == d.Id && x.ExamDate.Year == year && x.ExamDate.Month == 12).Sum(x => x.Count);
            }
            else
            {

                if (await QueryCompanyCode() == "Ushio")
                {
                    var sql = $"select TrainDays,BeginDate,EndDate from [120.26.205.42].[GhrUshio].[dbo].Ushio_ExternalTrainApply where TrainNeeds like '%{d.Id}%'";

                    var applys = await DbAccess.QueryListAsync<Ushio_ExternalTrainApply>(sql);

                    d.M1_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 1).Sum(x => x.TrainDays);
                    d.M2_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 2).Sum(x => x.TrainDays);
                    d.M3_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 3).Sum(x => x.TrainDays);
                    d.M4_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 4).Sum(x => x.TrainDays);
                    d.M5_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 5).Sum(x => x.TrainDays);
                    d.M6_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 6).Sum(x => x.TrainDays);
                    d.M7_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 7).Sum(x => x.TrainDays);
                    d.M8_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 8).Sum(x => x.TrainDays);
                    d.M9_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 9).Sum(x => x.TrainDays);
                    d.M10_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 10).Sum(x => x.TrainDays);
                    d.M11_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 11).Sum(x => x.TrainDays);
                    d.M12_Count = applys.Where(x => x.BeginDate.Year == year && x.BeginDate.Month == 12).Sum(x => x.TrainDays);
                }
            }



            if (d.M1_Count > 0 && d.TrainNum > 0)
                d.M1_CompletionRate = d.M1_Count / d.TrainNum;

            if (d.M2_Count > 0 && d.TrainNum > 0)
                d.M2_CompletionRate = d.M2_Count / d.TrainNum;

            if (d.M3_Count > 0 && d.TrainNum > 0)
                d.M3_CompletionRate = d.M3_Count / d.TrainNum;

            if (d.M4_Count > 0 && d.TrainNum > 0)
                d.M4_CompletionRate = d.M4_Count / d.TrainNum;

            if (d.M5_Count > 0 && d.TrainNum > 0)
                d.M5_CompletionRate = d.M5_Count / d.TrainNum;

            if (d.M6_Count > 0 && d.TrainNum > 0)
                d.M6_CompletionRate = d.M6_Count / d.TrainNum;

            if (d.M7_Count > 0 && d.TrainNum > 0)
                d.M7_CompletionRate = d.M7_Count / d.TrainNum;

            if (d.M8_Count > 0 && d.TrainNum > 0)
                d.M8_CompletionRate = d.M8_Count / d.TrainNum;

            if (d.M9_Count > 0 && d.TrainNum > 0)
                d.M9_CompletionRate = d.M9_Count / d.TrainNum;

            if (d.M10_Count > 0 && d.TrainNum > 0)
                d.M10_CompletionRate = d.M10_Count / d.TrainNum;

            if (d.M11_Count > 0 && d.TrainNum > 0)
                d.M11_CompletionRate = d.M11_Count / d.TrainNum;

            if (d.M12_Count > 0 && d.TrainNum > 0)
                d.M12_CompletionRate = d.M12_Count / d.TrainNum;


        });

        ModuleParam param = new ModuleParam()
        {
            langId = filter.langId,
            menuName = filter.menuName
        };
        var module = await _commonServices.GetModuleInfoAsync(param);
        var result1 = new ServicePageResult<UshioPlanReport>(filter.pageNum, result.result.DT_TablePageInfoT1.TotalCount, filter.pageSize, data);
        result1.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())
        {

            result1.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 result1;


    }


    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(Ghre_Course);
        var fileName = "F_TrainPlan.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;
        var items = await GetParaList("TrainingCategory");
        //var depts = await Db.Queryable<Ghro_Dept>().Select(x => new
        //{
        //    x.DeptID,
        //    x.DeptName
        //}).ToListAsync();

        //var courses = await Db.Queryable<Ghre_Course>().Select(x => new
        //{
        //    x.Id,
        //    x.CourseName
        //}).ToListAsync();

        var schools = await Db.Queryable<Ghre_School>().Select(x => new
        {
            x.Id,
            x.SchoolName
        }).ToListAsync();

        int sheetIndex = hssfworkbook.GetSheetIndex("培训计划");
        if (sheetIndex >= 0)
        {
            sheet = hssfworkbook.GetSheetAt(sheetIndex);

            //设置数据源的值
            IDataValidationConstraint dvConstraint1 = sheet.GetDataValidationHelper().CreateExplicitListConstraint(items.Select(x => x.ParaDetailName).ToArray());
            //设置编辑的区域
            IDataValidation dataValidation1 = sheet.GetDataValidationHelper().CreateValidation(dvConstraint1, new CellRangeAddressList(1, 65535, 2, 2));
            sheet.AddValidationData(dataValidation1);

            //dvConstraint1 = sheet.GetDataValidationHelper().CreateExplicitListConstraint(depts.Select(x => x.DeptName).ToArray());
            ////设置编辑的区域
            //dataValidation1 = sheet.GetDataValidationHelper().CreateValidation(dvConstraint1, new CellRangeAddressList(1, 65535, 1, 1));
            //sheet.AddValidationData(dataValidation1);

            //dvConstraint1 = sheet.GetDataValidationHelper().CreateExplicitListConstraint(courses.Select(x => x.CourseName).ToArray());
            ////设置编辑的区域
            //dataValidation1 = sheet.GetDataValidationHelper().CreateValidation(dvConstraint1, new CellRangeAddressList(1, 65535, 3, 3));
            //sheet.AddValidationData(dataValidation1);

            dvConstraint1 = sheet.GetDataValidationHelper().CreateExplicitListConstraint(schools.Select(x => x.SchoolName).ToArray());
            //设置编辑的区域
            dataValidation1 = sheet.GetDataValidationHelper().CreateValidation(dvConstraint1, new CellRangeAddressList(1, 65535, 5, 5));
            sheet.AddValidationData(dataValidation1);
        }
        //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 + newFileName;
        if (menuName == "F_TrainPlan_Temporary" || menuName == "F_UshioTrainPlan_Temporary")
            return ServiceResult<string>.OprateSuccess("计划暂存_" + DateTimeHelper.ConvertToSecondString1(DateTime.Now) + ".xlsx", physicsPath1);
        else
            return ServiceResult<string>.OprateSuccess("计划维护_" + DateTimeHelper.ConvertToSecondString1(DateTime.Now) + ".xlsx", physicsPath1);

    }

    #region Excel导入

    public async Task<(List<Dictionary<string, object>>, int)> ValidImportExcel(ISqlSugarClient Db, List<QueryExportColumn> columns, DataTable dt)
    {
        var CompanyCode = await QueryCompanyCode();
        Type entityType = typeof(Ghre_Plan);
        var properties = entityType.GetGenericProperties();
        int ErrorCount = 0;
        var dictList = new List<Dictionary<string, object>>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            var dict = ReportHelper.GetDefaultDict();
            var comments = new List<string>();
            for (int j = 0; j < columns.Count; j++)
            {
                var x = columns[j];
                if (!dt.Columns.Contains(x.label))
                    comments.Add("未查询到【" + x.label + "】列！");
                else
                {
                    var value = dt.Rows[i][x.label].ToString();

                    if (x.required == "true" && value.IsNullOrEmpty())
                    {
                        comments.Add(x.label + "不能为空！");
                        dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    }

                    if (x.dataSourceType.IsNullOrEmpty() && value.IsNotEmptyOrNull())
                    {
                        if (x.dataType == "int" || x.dataType == "decimal")
                        {
                            try
                            {
                                Convert.ToDecimal(value);
                            }
                            catch (Exception)
                            {
                                comments.Add(x.label + "无效的数字类型！");
                            }
                        }
                        else if (x.dataType == "date")
                        {
                            try
                            {
                                Convert.ToDateTime(value);
                            }
                            catch (Exception)
                            {
                                comments.Add(x.label + "无效的日期类型！");
                            }
                        }
                    }

                    if (value.IsNotEmptyOrNull())
                    {
                        if (x.field == "StaffId")
                        {
                            value = value.Replace("，", ",");
                            value = value.Replace("；", ",");
                            value = value.Replace(";", ",");
                            var value1 = value.Split(',').ToList();
                            var ids = await Db.Queryable<Ghra_Staff>().Where(o => value1.Contains(o.StaffName) || value1.Contains(o.StaffNo) || value1.Contains(o.StaffEname)).Select(x => x.StaffID).ToListAsync();
                            dict.Add("StaffIds", JsonHelper.ObjToJson(ids));
                        }
                        else if (x.field == "CourseId")
                        {
                            var ids = await Db.Queryable<Ghre_Course>().Where(o => o.CourseNo == value || o.CourseName == value).Select(x => x.Id).FirstAsync();
                            dict.Add("CourseId", ids);
                        }
                        else if (x.field == "SchoolId")
                        {
                            var ids = await Db.Queryable<Ghre_School>().Where(o => o.SchoolNo == value || o.SchoolName == value).Select(x => x.Id).FirstAsync();
                            dict.Add("SchoolId", ids);
                        }
                        else if (x.field == "Months")
                        {
                            value = value.Replace("，", ",");
                            value = value.Replace("；", ",");
                            value = value.Replace(";", ",");
                            var value1 = value.Split(',').ToList();

                            var value2 = new List<string>();

                            value1.ForEach(x =>
                            {
                                try
                                {
                                    if (Convert.ToInt16(x) >= 1 && Convert.ToInt16(x) <= 12)
                                        value2.Add(Convert.ToInt16(x).ObjToString());
                                }
                                catch (Exception)
                                {
                                }
                            });


                            dict.Add("Month", JsonHelper.ObjToJson(value2));
                        }
                        else
                        {
                            if (x.elementType == "Switch")
                                value = value == "是" ? "true" : "false";
                            if (x.dataSourceId.IsNotEmptyOrNull() && x.dataSourceType.IsNotEmptyOrNull() && !x.dataSource.StartsWith("OrgTreeWith")
                             && !x.dataSource.StartsWith("StaffWith"))
                            {

                                if (x.dataSourceType == "CommonList")
                                {
                                    var commonSql = await Db.Queryable<Ghrs_ListCommonSql>().Where(o => o.ListCommonSqlId == x.dataSourceId).FirstAsync();

                                    if (commonSql != null)
                                    {
                                        string sql = @$"SELECT [value]
                                FROM ({commonSql.SelectSql}) A
                                WHERE label = '{value}'";
                                        sql = sql.Replace("{@LangID}", "1");
                                        sql = sql.Replace("{@UserID}", App.User.ID.ObjToString());
                                        sql = sql.Replace("{@KeyWords}", null);
                                        var id2 = await Db.Ado.GetLongAsync(sql);
                                        if (properties.Any(o => o.Name == x.field))
                                            dict.Add(x.field, id2);
                                    }
                                }
                                else if (x.dataSourceType == "ParaDetailNo")
                                {
                                    var sql = @$"SELECT ParaDetailNo
                                FROM Ghrs_ParaDetail
                                WHERE     ParaMasterId IN (SELECT ParaMasterId
                                                           FROM Ghrs_ParaMaster
                                                           WHERE ParaMasterId = {x.dataSourceId.ObjToInt()})
                                      AND IsEnable = 1
                                      AND ParaDetailName = '{value}'";
                                    var id2 = await Db.Ado.GetStringAsync(sql);

                                    if (properties.Any(o => o.Name == x.field))
                                        dict.Add(x.field, id2);
                                }
                            }
                            else if (x.dataSource == "OrgTreeWithPriv" || x.dataSource == "OrgTreeWithoutPriv")
                            {
                                string sql = @$"SELECT DeptID FROM Ghro_Dept WHERE DeptNo = '{value}'";
                                var id2 = await Db.Ado.GetLongAsync(sql);
                                if (properties.Any(o => o.Name == x.field))
                                    dict.Add(x.field, id2);
                            }
                            else if (x.dataSource == "StaffWithoutPriv")
                            {
                                string sql = @$"SELECT StaffID FROM Ghra_Staff WHERE StaffName = '{value}' OR StaffNo = '{value}' OR StaffEname = '{value}'";
                                var id2 = await Db.Ado.GetLongAsync(sql);
                                if (properties.Any(o => o.Name == x.field))
                                    dict.Add(x.field, id2);
                            }
                            else
                            {
                                if (properties.Any(o => o.Name == x.field))
                                    dict.Add(x.field, value);

                            }
                        }
                    }
                    else
                        dict.Add(x.field, null);
                }
            }
            if (comments.Any())
            {
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                ErrorCount++;
                continue;
            }
            else
                dictList.Add(dict);
        }

        return (dictList, ErrorCount);
    }
    public override async Task<ServiceResult<ExcelData>> ImportExcel(IFormFile file, string menuName = null, long? MasterId = null)
    {
        var data = new ExcelData();
        var (path, filepath) = await ReportHelper.GetImportFilePath(file, menuName);
        var id1 = SnowFlakeSingle.instance.getID();
        string errorFileName = path + SnowFlakeSingle.instance.getID() + FileHelper.GetPostfixStr(filepath);

        var dt = ReportHelper.ReadImportExcel(filepath, "培训计划");
        var columns = await QueryExportColumn(menuName);
        columns = columns.Where(x => x.label != "系统内置").ToList();
        var (dictList, errorCount) = await ValidImportExcel(Db, columns, dt);
        Type entityType = typeof(Ghre_Plan);
        var properties = entityType.GetGenericProperties();
        if (errorCount > 0)
        {
            NPOIHelper.ExportExcel(dt, null, "导入数据", FileHelper.GetPhysicsPath() + errorFileName);
            data.filePath = "/Advanced" + errorFileName;
            data.ErrorCount = errorCount;
        }
        else
        {
            dictList.ForEach(x =>
            {
                if (menuName == "F_TrainPlan_Wait" || menuName == "F_UshioTrainPlan_Wait")
                    x.Add("Status", "Wait");
                else if (menuName == "F_TrainPlan_Temporary" || menuName == "F_UshioTrainPlan_Temporary")
                    x.Add("Status", "Temporary");
            });
            await Db.Insertable(dictList).AS(entityType.GetEntityTableName()).ExecuteCommandAsync();

            data.SuccessCount = dictList.Count;
        }

        return ServiceResult<ExcelData>.OprateSuccess("导入成功！", data);
    }
    #endregion

    #region 培训计划达成率

    public async Task<ServicePageResult<CompletionRateBLT>> QueryCompletionRateBLT(QueryBody filter)
    {

        var data = new List<CompletionRateBLT>();
        int totalCount = 0;
        bool isFirst = true;
        DateTime? startTime = null, endTime = null;
        string seachType = string.Empty;
        int? deptId_40 = null, deptId_30 = null, deptId_20 = null;
        int? deptId = null;
        if (filter.jsonParam != null)
            foreach (JProperty jProperty in filter.jsonParam.Properties())
            {
                isFirst = false;
                var name = jProperty.Name;
                var value = jProperty.Value.ToString();
                if (name == "page" || name == "pageSize")
                    continue;

                if (name == "Month")
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);
                    var ids1 = JsonHelper.JsonToObj<List<DateTime>>(jsonParam.columnValue.ToString());
                    startTime = ids1[0];
                    endTime = ids1[1];
                    continue;
                }

                if (name == "SeachType")
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);
                    seachType = jsonParam.columnValue.ToString();
                    continue;
                }
                if (name == "DeptId_40")
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);
                    deptId_40 = jsonParam.columnValue.ObjToInt();
                    continue;
                }
                if (name == "DeptId_30")
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);
                    deptId_30 = jsonParam.columnValue.ObjToInt();
                    continue;
                }
                if (name == "DeptId_20")
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);
                    deptId_20 = jsonParam.columnValue.ObjToInt();
                    continue;
                }
            }

        if (isFirst) return new ServicePageResult<CompletionRateBLT>(filter.pageNum, totalCount, filter.pageSize, data);


        filter.pageSize = 10000;
        if (startTime.IsNullOrEmpty())
            throw new Exception("请先选择月份！");
        if (seachType.IsNullOrEmpty())
            throw new Exception("请先选择查询类别！");
        if (!(deptId_40.IsNotEmptyOrNull() || deptId_30.IsNotEmptyOrNull() || deptId_20.IsNotEmptyOrNull()))
            throw new Exception("请先选择部门！");
        var aaa = 0;
        if (deptId_40.IsNotEmptyOrNull())
        {
            aaa++;
            deptId = deptId_40;
        }
        if (deptId_30.IsNotEmptyOrNull())
        {
            aaa++;
            deptId = deptId_30;
        }
        if (deptId_20.IsNotEmptyOrNull())
        {
            aaa++;
            deptId = deptId_20;
        }

        if (aaa > 1)
            throw new Exception("部门层架筛选条件不可组合使用！");

        var deptName = await Db.Queryable<Ghro_Dept>().Where(x => x.DeptID == deptId).Select(x => x.DeptName).FirstAsync();

        var deptName1 = await Db.Ado.GetStringAsync(@$"SELECT GHR30.dbo.[FO_DeptInfo] ( 
    {deptId},
    getdate (),
    1,
    'DeptFullPateName');");

        if (seachType == "Month")
        {
            for (DateTime? dt = startTime; dt <= endTime; dt = dt.Value.AddMonths(1))
            {
                string formatted = dt.Value.ToString("yyyy-MM");
                int submitCount = 0;
                var courseCount = await Db.Queryable<Ghre_Plan>()
                    .Where(x => x.Year == dt.Value.Year && x.DeptId == deptId && x.Month.Contains($"\"{dt.Value.Month}\""))
                    .CountAsync();

                if (courseCount > 0)
                {
                    var planIds = await Db.Queryable<Ghre_Plan>()
                       .Where(x => x.Year == dt.Value.Year && x.DeptId == deptId && x.Month.Contains($"\"{dt.Value.Month}\""))
                       .Select(x => x.Id).ToListAsync();

                    for (int i = 0; i < planIds.Count; i++)
                    {
                        var submitCount1 = await Db.Queryable<Ghre_TrainFeeApplyOrder_Boltone>()
                            .Where(x => x.PlanId != null && x.PlanId.Contains(planIds[i].ObjToString())).CountAsync();
                        submitCount = submitCount + submitCount1;
                    }
                }
                data.Add(new CompletionRateBLT
                {
                    Month = formatted,
                    SubmitCount = submitCount,
                    CourseCount = courseCount
                });
            }
        }
        else
        {
            int submitCount = 0;
            var courseCount = 0;
            for (DateTime? dt = startTime; dt <= endTime; dt = dt.Value.AddMonths(1))
            {
                string formatted = dt.Value.ToString("yyyy-MM");
                var courseCount1 = await Db.Queryable<Ghre_Plan>()
                    .Where(x => x.Year == dt.Value.Year && x.DeptId == deptId && x.Month.Contains($"\"{dt.Value.Month}\""))
                    .CountAsync();
                courseCount = courseCount + courseCount1;

                if (courseCount > 0)
                {
                    var planIds = await Db.Queryable<Ghre_Plan>()
                        .Where(x => x.Year == dt.Value.Year && x.DeptId == deptId && x.Month.Contains($"\"{dt.Value.Month}\""))
                        .Select(x => x.Id).ToListAsync();

                    for (int i = 0; i < planIds.Count; i++)
                    {
                        var submitCount1 = await Db.Queryable<Ghre_TrainFeeApplyOrder_Boltone>()
                            .Where(x => x.PlanId != null && x.PlanId.Contains(planIds[i].ObjToString())).CountAsync();
                        submitCount = submitCount + submitCount1;
                    }
                }
            }
            data.Add(new CompletionRateBLT
            {
                Month = $"{startTime.Value.ToString("yyyy-MM")}~{endTime.Value.ToString("yyyy-MM")}",
                SubmitCount = submitCount,
                CourseCount = courseCount
            });
        }


        for (int i = 0; i < data.Count; i++)
        {

            data[i].Id = i + 1;
            data[i].Id = i + 1;
            data[i].RowNo = i + 1;
            data[i].DeptName = deptName;
            data[i].DeptFullName = deptName1;
            if (data[i].CourseCount > 0 && data[i].SubmitCount > 0)
                data[i].CompletionRate = data[i].SubmitCount / data[i].CourseCount;

            data[i].CompletionRate1 = $"{data[i].CompletionRate}%";
            //var examCount = await Db.Queryable<Ghre_ExamRecord>()
            //   .Where(x => x.StudyRecordId != null && studyRecordIds.Contains(x.StudyRecordId.Value))
            //   .CountAsync();
            //var passCount = await Db.Queryable<Ghre_ExamRecord>()
            //   .Where(x => x.StudyRecordId != null && studyRecordIds.Contains(x.StudyRecordId.Value) && x.IsPass == true)
            //   .CountAsync();
            //if (passCount > 0 && examCount > 0)
            //    data[i].PassPercent = passCount / examCount;
        }

        return new ServicePageResult<CompletionRateBLT>(filter.pageNum, totalCount, filter.pageSize, data);
    }
    #endregion
}