using Infrastructure; using Microsoft.Extensions.Configuration; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; using OpenAuth.App.BaseApp.Base; using OpenAuth.App.Interface; using OpenAuth.App.ServiceApp.Response; using OpenAuth.Repository; using OpenAuth.Repository.Domain; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenAuth.App.ServiceApp { /// /// 统计分析 /// public class DataAnalysisApp : SqlSugarBaseApp { private readonly IConfiguration _configuration; private readonly ISqlSugarClient client; private readonly IAuth _auth; public DataAnalysisApp(ISugarUnitOfWork unitWork, ISimpleClient repository, IAuth auth, ISqlSugarClient sqlSugarClient, IConfiguration configuration) : base(unitWork, repository, auth) { _configuration = configuration; this.client = sqlSugarClient; _auth = auth; } /// /// 时相统计 /// /// public async Task>>> GteTaskListForAdmin(int month, int week, DateTime beginTime, DateTime endTime, string taskName, int page, int limit) { using (var db = base.UnitWork.CreateContext()) { RefAsync totalCount = 0; var tsakList = await db.InsTask.AsQueryable() .WhereIF(string.IsNullOrEmpty(taskName), r => r.TaskName.Contains(taskName)) .ToPageListAsync(page, limit, totalCount); if (beginTime.Year == 0001) { beginTime = GetMonthStartAndEndDate(month).Start; endTime = GetMonthStartAndEndDate(month).End; } var tifList = await db.InsTif.AsQueryable() .WhereIF(beginTime.Year != 0001 || month != 0, r => r.CreateTime >= beginTime && r.CreateTime <= endTime) .ToListAsync(); //总面积 var totalTifArea = tifList.Sum(r => r.AreaNum); //个数 var totalTifCount = tifList.Count(); return new Response>> { Result = new PageInfo> { Items = tsakList, Total = totalCount } }; } } /// /// 每个县区的时相统计 /// /// public async Task>> GetShiXiangForArea(int month, int week, DateTime beginTime, DateTime endTime) { using (var db = base.UnitWork.CreateContext()) { if (beginTime.Year == 0001) { beginTime = GetMonthStartAndEndDate(month).Start; endTime = GetMonthStartAndEndDate(month).End; } var tifList = db.InsTif.AsQueryable() .WhereIF(beginTime.Year != 0001 || month != 0, r => r.CreateTime >= beginTime && r.CreateTime <= endTime); //总面积 var totalTifArea = tifList.Sum(r => r.AreaNum); //个数 var totalTifCount = tifList.Count(); var endData = await tifList.GroupBy(r => r.AreaNum).Select(r => new { r.AreaName, sumArea = SqlFunc.AggregateSum(r.AreaNum), }).ToListAsync(); return new Response> { Result = endData, }; } } /// /// 每天时相统计 /// /// public async Task>> GetShiXiangForTime(int month, int week, DateTime beginTime, DateTime endTime) { using (var db = base.UnitWork.CreateContext()) { if (beginTime.Year == 0001) { beginTime = GetMonthStartAndEndDate(month).Start; endTime = GetMonthStartAndEndDate(month).End; } var tifList = db.InsTif.AsQueryable() .WhereIF(beginTime.Year != 0001 || month != 0, r => r.CreateTime >= beginTime && r.CreateTime <= endTime); //总面积 var totalTifArea = tifList.Sum(r => r.AreaNum); //个数 var totalTifCount = tifList.Count(); var endData = await tifList.GroupBy(r => r.CreateTime).Select(r => new { r.CreateTime, sumArea = SqlFunc.AggregateSum(r.AreaNum), }).ToListAsync(); return new Response> { Result = endData, }; } } static (DateTime Start, DateTime End) GetMonthStartAndEndDate(int month) { int year = DateTime.Now.Year; // 获取当前年份 DateTime startDate = new DateTime(year, month, 1, 0, 0, 0); // 当月起始日期 DateTime endDate = startDate.AddMonths(1).AddSeconds(-1); // 当月结束日期 return (startDate, endDate); } // 获取本月的起始时间和结束时间 public static (DateTime startOfMonth, DateTime endOfMonth) GetStartEndOfMonth() { DateTime now = DateTime.Now; // 本月的第一天 DateTime startOfMonth = new DateTime(now.Year, now.Month, 1, 0, 0, 0); // 本月的最后一天 DateTime endOfMonth = startOfMonth.AddMonths(1).AddSeconds(-1); return (startOfMonth, endOfMonth); } public static (DateTime startOfWeek, DateTime endOfWeek) GetStartEndOfWeek() { DateTime now = DateTime.Now; // 计算本周的第一天(假设一周从周一开始) DateTime startOfWeek = now.AddDays(-((int)now.DayOfWeek - 1)); startOfWeek = startOfWeek.Date; // 计算本周的最后一天(假设一周从周一开始,周日为最后一天) DateTime endOfWeek = startOfWeek.AddDays(7).AddSeconds(-1); return (startOfWeek, endOfWeek); } #region 统计数据 /// /// 小组 人员 的任务数和图斑数 /// /// /// /// public async Task>> GetGroupOrUserTaskAndTuBan(int type, int dateType) { var user = _auth.GetCurrentUser().User; DateTime beginTime, endTime; if (dateType == 1) { beginTime = GetStartEndOfMonth().startOfMonth; endTime = GetStartEndOfMonth().endOfMonth; } else if (dateType == 2) { beginTime = GetStartEndOfWeek().startOfWeek; endTime = GetStartEndOfWeek().endOfWeek; } else { beginTime = DateTime.Today; endTime = DateTime.Now; } using (var db = base.UnitWork.CreateContext()) { // 获取当前用户相关的所有小组用户 var groupIds = await db.SysGroup.AsQueryable() .Where(r => r.GroupLeaderId == user.Id.ToString()) .Select(r => r.Id) .ToListAsync(); var groupUser = await db.SysGroupuser.AsQueryable() .Where(r => groupIds.Contains(r.GroupId) || r.UserId == user.Id.ToString()) .Select(r => r.UserId) .ToListAsync(); // 如果是小组统计 if (type == 1) { var result = await db.InsTaskgroup.AsQueryable() .LeftJoin((a, b) => a.ReciveUserId == b.Id.ToString()) .WhereIF(beginTime.Year != 0001, a => a.CreateTime >= beginTime && a.CreateTime <= endTime) .WhereIF(groupUser.Count > 0, a => groupUser.Contains(a.ReciveUserId)) .Where((a,b)=>!string.IsNullOrEmpty(a.ReciveUserId)) .GroupBy((a, b) => b.Name) .Select((a, b) => new UserOrGroupTaskResp { UserName = b.Name, TaskCount = SqlFunc.AggregateCount(a.Id), TuBanCount = SqlFunc.AggregateSum(a.EndNum - a.BeginNum), }).MergeTable().OrderByDescending((t)=>t.TuBanCount).ToListAsync(); return new Response> { Result = result, }; } // 如果是人员统计 else if (type == 2) { var result = await db.InsTaskgroup.AsQueryable() .LeftJoin((a, b) => a.ReciveUserId == b.UserId) .LeftJoin((a, b, c) => b.GroupId == c.Id) .WhereIF(beginTime.Year != 0001, a => a.CreateTime >= beginTime && a.CreateTime <= endTime) .WhereIF(groupUser.Count > 0, a => groupUser.Contains(a.ReciveUserId)) .Where((a, b) => !string.IsNullOrEmpty(a.ReciveUserId)) .GroupBy((a, b, c) => c.Name) .Select((a, b, c) => new UserOrGroupTaskResp { UserName = c.Name, TaskCount = SqlFunc.AggregateCount(a.Id), TuBanCount = SqlFunc.AggregateSum(a.EndNum - a.BeginNum), }).MergeTable().OrderByDescending((t) => t.TuBanCount).ToListAsync(); return new Response> { Result = result, }; } } return new Response>(); // 默认返回空列表 } //public async Task>> GetAiShpDataExpenseAccountingTableOld(DateTime beginTime, DateTime endTime) //{ // using (var db = base.UnitWork.CreateContext()) // { // var aiShpList = db.InsAishp.AsQueryable() // .WhereIF(beginTime.Year != 0001, r => r.CreateTime >= beginTime && r.CreateTime <= endTime); // //总面积 // var totalTifArea = aiShpList.Sum(r => r.AreaNum); // //个数 // var totalTifCount = aiShpList.Count(); // var endData = await aiShpList.GroupBy(r => r.ShpDate.Date).Select(r => new AiShpDataExpenseAccountingTableResp // { // ShapDate = r.ShpDate.Date.ToString("yyyyMMdd"), // AreaNum = SqlFunc.AggregateSum(r.AreaNum), // ShpCount = SqlFunc.AggregateSum(r.ShpCount), // }).ToListAsync(); // return new Response>() // { // Result = endData // }; // } //} public async Task> GetAiShpDataExpenseAccountingTable1(DateTime beginTime, DateTime endTime) { using (var db = base.UnitWork.CreateContext()) { List dateList = new List(); List dataList = new List(); if (beginTime > endTime) { throw new ArgumentException("开始时间需要小于结束时间"); } // 从开始日期遍历到结束日期 for (DateTime date = beginTime.Date; date <= endTime.Date; date = date.AddDays(1)) { dateList.Add(date); } var aiShpList = db.InsAishp.AsQueryable().WhereIF(beginTime.Year != 0001, r => r.CreateTime >= beginTime && r.CreateTime <= endTime); var taskList = db.InsTask.AsQueryable().WhereIF(beginTime.Year != 0001, t => t.CreateTime >= beginTime && t.CreateTime <= endTime); for (int i = 0; i < dateList.Count; i++) { AiShpDataExpenseAccountingResp aiShpDataExpenseAccountingResp = new AiShpDataExpenseAccountingResp(); var aiShpListDay = db.InsAishp.AsQueryable().Where(r => r.ShpDate >= dateList[i]); aiShpDataExpenseAccountingResp.Number = i + 1; aiShpDataExpenseAccountingResp.ShapDate = dateList[i].ToString("yyyyMMdd"); //提取个数 aiShpDataExpenseAccountingResp.AreaNum = await aiShpListDay.SumAsync(r => r.AreaNum); aiShpDataExpenseAccountingResp.ShpCount = await aiShpListDay.SumAsync(r => r.ShpCount); //下发数量 aiShpDataExpenseAccountingResp.IssuedCount = await taskList.Where(t => aiShpListDay.Select(r => r.Id).ToList().Contains(t.ShpId)).CountAsync(); } AiShpDataExpenseAccountingTableResp aiShpDataExpenseAccountingTableResp = new AiShpDataExpenseAccountingTableResp(); aiShpDataExpenseAccountingTableResp.RespData = dataList; //总面积 aiShpDataExpenseAccountingTableResp.TotalShpArea = aiShpList.Sum(r => r.AreaNum); //个数 aiShpDataExpenseAccountingTableResp.TotalShpCount = aiShpList.Count(); return new Response() { Result = aiShpDataExpenseAccountingTableResp }; } } public async Task> GetAiShpDataExpenseAccountingTable(DateTime beginTime, DateTime endTime) { using (var db = base.UnitWork.CreateContext()) { if (beginTime > endTime) { throw new ArgumentException("开始时间需要小于结束时间"); } var dateList = Enumerable.Range(0, (endTime.Date - beginTime.Date).Days + 1) .Select(offset => beginTime.Date.AddDays(offset)) .ToList(); var aiShpList = await db.InsAishp.AsQueryable() .Where(r => r.ShpDate >= beginTime && r.ShpDate <= endTime) .ToListAsync(); var taskList = await db.InsTask.AsQueryable() .Where(t => t.CreateTime >= beginTime && t.CreateTime <= endTime) .ToListAsync(); int TotalIssuedCount = 0; var dataList = dateList.Select(date => { var aiShpForDay = aiShpList.Where(r => r.ShpDate.Date == date).ToList(); var areaNum = aiShpForDay.Sum(r => r.AreaNum); var shpCount = aiShpForDay.Sum(r => r.ShpCount ?? 0); var issuedCount = taskList.Count(t => aiShpForDay.Any(r => r.Id == t.ShpId)); TotalIssuedCount += issuedCount; //文件夹 var folderPath = string.Join(",", aiShpForDay.Select(r => { var directory = Path.GetDirectoryName(r.ShpPath); // 获取目录部分 return directory != null ? Path.GetFileName(directory) : string.Empty; // 获取目录名 }).ToList()); return new AiShpDataExpenseAccountingResp { Number = dateList.IndexOf(date) + 1, ShapDate = date.ToString("yyyyMMdd"), AreaNum = areaNum, ShpCount = shpCount, IssuedCount = issuedCount, FolderPath = folderPath, }; }).ToList(); var totalShpArea = aiShpList.Sum(r => r.AreaNum); var totalShpCount = aiShpList.Count(); var aiShpDataExpenseAccountingTableResp = new AiShpDataExpenseAccountingTableResp { RespData = dataList, TotalShpArea = totalShpArea, TotalShpCount = totalShpCount, TotalShpProduction = 0, TotalShpInterpretation = 0, TotalJudgment = 0, TotalPush = 0, TotalCost = 0, TotalIssuedCount = TotalIssuedCount }; return new Response { Result = aiShpDataExpenseAccountingTableResp }; } } //导出 public Response CaseOfMineralsToExcelNew(DateTime startTime, DateTime endTime) { Response response = new Response(); try { var list = GetAiShpDataExpenseAccountingTable(startTime, endTime).Result; HSSFWorkbook workbook = new HSSFWorkbook(); #region 样式设置 ICellStyle CreateCellStyle(HSSFWorkbook wb, short fontHeight, string fontName, HorizontalAlignment hAlign, VerticalAlignment vAlign, bool bold = false) { IFont font = wb.CreateFont(); font.FontName = fontName; font.FontHeightInPoints = fontHeight; font.IsBold = bold; ICellStyle style = wb.CreateCellStyle(); style.BorderBottom = BorderStyle.Thin; style.BorderLeft = BorderStyle.Thin; style.BorderRight = BorderStyle.Thin; style.BorderTop = BorderStyle.Thin; style.Alignment = hAlign; style.VerticalAlignment = vAlign; style.SetFont(font); style.WrapText = true; return style; } ICellStyle CreateCellStyle2(HSSFWorkbook wb, short fontHeight, string fontName, HorizontalAlignment hAlign, VerticalAlignment vAlign, bool bold = false) { IFont font = wb.CreateFont(); font.FontName = fontName; font.FontHeightInPoints = fontHeight; font.IsBold = bold; ICellStyle style = wb.CreateCellStyle(); style.Alignment = hAlign; style.VerticalAlignment = vAlign; style.SetFont(font); style.WrapText = true; return style; } // 创建右对齐样式 ICellStyle rightAlignStyle = workbook.CreateCellStyle(); rightAlignStyle.Alignment = HorizontalAlignment.Right; // 设置右对齐 rightAlignStyle.VerticalAlignment = VerticalAlignment.Center; IFont font = workbook.CreateFont(); font.FontName = "宋体"; font.FontHeightInPoints = 12; rightAlignStyle.SetFont(font); rightAlignStyle.WrapText = true; //第二个sheet右对齐样式 ICellStyle rightAlignStyle2 = workbook.CreateCellStyle(); rightAlignStyle2.Alignment = HorizontalAlignment.Right; // 设置右对齐 rightAlignStyle2.VerticalAlignment = VerticalAlignment.Center; IFont font1 = workbook.CreateFont(); font1.FontName = "宋体"; font1.FontHeightInPoints = 9; rightAlignStyle2.SetFont(font1); rightAlignStyle2.WrapText = true; ICellStyle contentStyle = CreateCellStyle(workbook, 16, "宋体", HorizontalAlignment.Center, VerticalAlignment.Center); ICellStyle titleStyle = CreateCellStyle2(workbook, 10, "宋体", HorizontalAlignment.Left, VerticalAlignment.Center); ICellStyle headerStyle1 = CreateCellStyle2(workbook, 18, "方正小标宋简体", HorizontalAlignment.Center, VerticalAlignment.Center); ICellStyle headerStyle2 = CreateCellStyle(workbook, 16, "宋体", HorizontalAlignment.Right, VerticalAlignment.Center); ICellStyle headerStyle3 = CreateCellStyle(workbook, 16, "宋体", HorizontalAlignment.Center, VerticalAlignment.Center); //第二个sheet ICellStyle contentStyle22 = CreateCellStyle(workbook, 12, "宋体", HorizontalAlignment.Center, VerticalAlignment.Center); ICellStyle titleStyle2 = CreateCellStyle2(workbook, 9, "宋体", HorizontalAlignment.Left, VerticalAlignment.Center); ICellStyle headerStyle21 = CreateCellStyle2(workbook, 18, "方正小标宋简体", HorizontalAlignment.Center, VerticalAlignment.Center); ICellStyle headerStyle23 = CreateCellStyle(workbook, 12, "黑体", HorizontalAlignment.Center, VerticalAlignment.Center); ICellStyle beizhuStyle21 = CreateCellStyle2(workbook, 9, "宋体", HorizontalAlignment.Left, VerticalAlignment.Center); #endregion #region 第一个sheet #region 创建表头 IRow CreateRowWithHeight(ISheet sht, int rowIndex, float heightInPoints) { IRow row = sht.CreateRow(rowIndex); row.HeightInPoints = heightInPoints; return row; } void SetCellStyle(IRow row, ICellStyle style) { foreach (NPOI.SS.UserModel.ICell cell in row.Cells) { cell.CellStyle = style; } } #endregion #endregion #region 第二个sheet ISheet sheet2 = workbook.CreateSheet("Sheet2"); #region 创建表头 IRow row20 = CreateRowWithHeight(sheet2, 0, 42); row20.CreateCell(0).SetCellValue("汇总表"); IRow row22 = CreateRowWithHeight(sheet2, 1, 24); row22.CreateCell(0).SetCellValue("县区"); row22.CreateCell(1).SetCellValue("下发线索总数(个)"); row22.CreateCell(2).SetCellValue("总数"); row22.CreateCell(3); row22.CreateCell(4); row22.CreateCell(5).SetCellValue("定性"); row22.CreateCell(6); row22.CreateCell(7); row22.CreateCell(8); row22.CreateCell(9).SetCellValue("分类"); row22.CreateCell(10); row22.CreateCell(11).SetCellValue("超期未报(个)"); IRow row23 = CreateRowWithHeight(sheet2, 2, 69); row23.CreateCell(0); row23.CreateCell(1); row23.CreateCell(2).SetCellValue("已完成(个)"); row23.CreateCell(3).SetCellValue("未完成(个)"); row23.CreateCell(4).SetCellValue("完成率(%)"); row23.CreateCell(5).SetCellValue("合法(个)"); row23.CreateCell(6).SetCellValue("违法(个)"); row23.CreateCell(7).SetCellValue("其他(个)"); row23.CreateCell(8).SetCellValue("未定性(个)"); row23.CreateCell(9).SetCellValue("非法开采(个)"); row23.CreateCell(10).SetCellValue("非法加工(个)"); row23.CreateCell(11); // 设置样式 SetCellStyle(row20, headerStyle21); SetCellStyle(row22, headerStyle23); SetCellStyle(row23, headerStyle23); // 合并单元格 sheet2.AddMergedRegion(new CellRangeAddress(0, 0, 0, 11)); // 合并标题行 sheet2.AddMergedRegion(new CellRangeAddress(1, 2, 0, 0)); sheet2.AddMergedRegion(new CellRangeAddress(1, 2, 1, 1)); sheet2.AddMergedRegion(new CellRangeAddress(1, 1, 2, 4)); sheet2.AddMergedRegion(new CellRangeAddress(1, 1, 5, 8)); sheet2.AddMergedRegion(new CellRangeAddress(1, 1, 9, 10)); sheet2.AddMergedRegion(new CellRangeAddress(1, 2, 11, 11)); // 设置列宽 int[] normalColumns2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; foreach (var index in normalColumns2) sheet2.SetColumnWidth(index, 9 * 256); // 设置列宽 int[] normalColumns1 = { 9, 10, 11 }; foreach (var index in normalColumns1) sheet2.SetColumnWidth(index, 12 * 256); // 设置列宽 #endregion #region 填充数据 for (int i = 0; i < list.Result.RespData.Count - 1; i++) { var rowIndex = i + 3; // 数据从第5行开始 var row = CreateRowWithHeight(sheet2, rowIndex, 34); row.CreateCell(0).SetCellValue(list.Result.RespData[i].Number); row.CreateCell(1).SetCellValue(list.Result.RespData[i].ShpProduction); row.CreateCell(2).SetCellValue(list.Result.RespData[i].ShpInterpretation); row.CreateCell(3).SetCellValue(list.Result.RespData[i].Judgment); row.CreateCell(4).SetCellValue(list.Result.RespData[i].Push); row.CreateCell(5).SetCellValue(list.Result.RespData[i].Cost); row.CreateCell(6).SetCellValue(list.Result.RespData[i].ShpCount.ToString()); row.CreateCell(7).SetCellValue(list.Result.RespData[i].IssuedCount); row.CreateCell(8).SetCellValue(list.Result.RespData[i].FolderPath); row.CreateCell(9).SetCellValue(list.Result.RespData[i].Format); row.CreateCell(10).SetCellValue(list.Result.RespData[i].Remark); SetCellStyle(row, contentStyle22); } #endregion #endregion response.Result = new MemoryStream(); workbook.Write(response.Result); response.Result.Position = 0; workbook.Close(); response.Code = 200; response.Message = "获取成功"; } catch (Exception ex) { response.Code = 500; response.Message = ex.Message; } return response; } #endregion } }