
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Math;
using DocumentFormat.OpenXml.Office.CustomUI;
using Infrastructure;
using Infrastructure.Extensions;
using Infrastructure.Helpers;
using Microsoft.AspNetCore.Hosting;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Common;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.App.ServiceApp.MiManager.Request;
using OpenAuth.App.ServiceApp.MiManager.Response;
using OpenAuth.App.ServiceApp.MiManager.Resquest;
using OpenAuth.App.ServiceApp.Request;
using OpenAuth.App.ServiceApp.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using System.Globalization;
using static NPOI.HSSF.Util.HSSFColor;

namespace OpenAuth.App
{
    public class MiViolationReportApp : SqlSugarBaseApp<MiViolationReport, SugarDbContext>
    {
        private readonly IWebHostEnvironment _env;
        private MiWordHelper _helper;
        public MiViolationReportApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<MiViolationReport> repository,
            IAuth auth, IWebHostEnvironment env, MiWordHelper helper
            ) : base(unitWork, repository, auth)
        {
            _env = env;
            _helper = helper;
        }

        #region 查询
        /// <summary>
        /// 分页
        /// </summary>
        public async Task<Response<PageInfo<List<dynamic>>>> LoadAllPage(MiviolationReq req)
        {
            RefAsync<int> totalCount = 0;
            var user = _auth.GetCurrentUser();
            var users = user.User;
            var level = user.Orgs?.Min(x => x.Level);
            //如果不是超级管理员
            if (user != null && (users.Id == -1 || level == 0))
            {
                var list = await base.Repository.AsQueryable()
                    .Where(p => p.IsDelete == false)
                    .WhereIF(req.begindate != null && req.enddate != null, p => p.ReportTime >= req.begindate && p.ReportTime < req.enddate)
                    .WhereIF(req.status != null && req.status.Count > 0, p => req.status.Contains(p.Status))
                    .WhereIF(!string.IsNullOrEmpty(req.key), p => p.Title.Contains(req.key))
                    .WhereIF(req.viotype != null, p => p.ViolationType == req.viotype)
                    .LeftJoin<MiMinePoint>((p, m) => p.MinePointId == m.Id)
                    .LeftJoin<SysUser>((p, m, u) => p.Reporter == u.Id.ToString())
                    .LeftJoin<SysUser>((p, m, u, s) => p.Handler == s.Id.ToString())
                    .LeftJoin<SysOrg>((p, m, u, s, o) => p.ReportUnit == o.Id.ToString())
                    .LeftJoin<SysOrg>((p, m, u, s, o, d) => p.HandlingUnit == d.Id.ToString())
                    .WhereIF(!string.IsNullOrEmpty(req.pointname), (p, m, u, s, o, d) => m.Name.Contains(req.pointname))
                    .OrderBy((p, m, u, s, o, d) => p.Status)
                    .OrderByDescending((p, m, u, s, o, d) => p.ReportTime)
                    .Select<dynamic>((p, m, u, s, o, d) => new
                    {
                        Id = p.Id.SelectAll(),
                        ReportUserName = u.Name,
                        PointName = m.Name,
                        OrgName = o.Name,
                        HandelUserName = s.Name,
                        HandelUnit = d.Name
                    })
                    .ToPageListAsync(req.page, req.limit, totalCount);
                return new Response<PageInfo<List<dynamic>>>
                {
                    Result = new PageInfo<List<dynamic>>
                    {
                        Items = list,
                        Total = totalCount
                    }
                };
            }
            else
            {
                if (user.Orgs.Count == 0 || level == null)
                {
                    throw new Exception("无权限查看数据");
                }
                else
                {
                    //查询所有子部门
                    List<string> orgidlist = new List<string>();
                    var orgs = user.Orgs?.Select(r => r.Id).ToList();
                    using (var uow = base.UnitWork.CreateContext())
                    {
                        foreach (var item in orgs)
                        {
                            //orgidlist.Add(item.ToString());
                            var allchilds = uow.SysOrg.AsQueryable().ToChildList(r => r.ParentId, item);
                            if (allchilds.Count > 0)
                            {
                                orgidlist = orgidlist.Concat(allchilds.Select(r => r.Id.ToString())).ToList();
                            }
                        }

                        var list = await uow.MiViolationReport.AsQueryable()
                            .Where(p => p.IsDelete == false)
                            .WhereIF(req.begindate != null && req.enddate != null, p => p.ReportTime >= req.begindate && p.ReportTime < req.enddate)
                            .WhereIF(req.status != null, p => req.status.Contains(p.Status))
                            .WhereIF(!string.IsNullOrEmpty(req.key), p => p.Title.Contains(req.key))
                            .WhereIF(req.viotype != null, p => p.ViolationType == req.viotype)
                            .Where(p => orgidlist.Contains(p.ReportUnit) || orgidlist.Contains(p.HandlingUnit) || p.Reporter == user.User.Id.ToString() || p.Handler == user.User.Id.ToString())
                            .LeftJoin<MiMinePoint>((p, m) => p.MinePointId == m.Id)
                            .LeftJoin<SysUser>((p, m, u) => p.Reporter == u.Id.ToString())
                            .LeftJoin<SysUser>((p, m, u, s) => p.Handler == s.Id.ToString())
                            .LeftJoin<SysOrg>((p, m, u, s, o) => p.ReportUnit == o.Id.ToString())
                            .LeftJoin<SysOrg>((p, m, u, s, o, d) => p.HandlingUnit == d.Id.ToString())
                            .WhereIF(!string.IsNullOrEmpty(req.pointname), (p, m, u, s, o, d) => m.Name.Contains(req.pointname))
                            .OrderBy((p, m, u, s, o, d) => p.Status)
                            .OrderByDescending((p, m, u, s, o, d) => p.ReportTime)
                            .Select<dynamic>((p, m, u, s, o, d) => new
                            {
                                Id = p.Id.SelectAll(),
                                ReportUserName = u.Name,
                                PointName = m.Name,
                                OrgName = o.Name,
                                HandelUserName = s.Name,
                                HandelUnit = d.Name
                            })
                            .ToPageListAsync(req.page, req.limit, totalCount);

                        return new Response<PageInfo<List<dynamic>>>
                        {
                            Result = new PageInfo<List<dynamic>>
                            {
                                Items = list,
                                Total = totalCount
                            }
                        };
                    }
                }
            }
        }
        #endregion

        public async Task<dynamic> Get(string id)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                var result = await base.Repository.AsQueryable()
                  .Where(p => p.Id == id)
                  .LeftJoin<SysOrg>((p, r) => p.ReportUnit == r.Id.ToString())
                  .LeftJoin<MiMinePoint>((p, r, m) => p.MinePointId == m.Id)
                  .LeftJoin<MiParking>((p, r, m, pk) => p.ParkingId == pk.Id)
                  .LeftJoin<SysUser>((p, r, m, pk, u) => p.Reporter == u.Id.ToString())
                  .LeftJoin<SysUser>((p, r, m, pk, u, u2) => p.Handler == u2.Id.ToString())
                  .LeftJoin<SysOrg>((p, r, m, pk, u, u2, o) => p.HandlingUnit == o.Id.ToString())
                  .Select((p, r, m, pk, u, u2, o) => new
                  {
                      // 提车信息
                      ReporterName = u.Name,
                      HandlerName = u2.Name,
                      ReportUnitName = r.Name,
                      HandUnitName = o.Name,

                      // 违法上报信息
                      p.Id,
                      p.Title,
                      ReportStatus = p.Status,
                      p.PartyName,
                      p.PartyPhone,
                      p.ViolationType,
                      p.ProblemDescription,
                      p.HandlingOpinion,
                      p.HandlingUnit,
                      p.Handler,
                      p.HandlingTime,
                      p.ReportTime,
                      p.Reporter,
                      p.ReportUnit,
                      p.Lng,
                      p.Lat,
                      p.StatusName,
                      p.ViolationTypeName,
                      p.MineralTypes,
                      p.ReviewTime,
                      p.ReviewerName,
                      p.ReviewComments,
                      p.ReviewerSignature,
                      p.SeReviewTime,
                      p.SeReviewerName,
                      p.SeReviewComments,
                      p.SeReviewerSignature,
                      // 盗采点信息
                      MinePointId = m.Id,
                      MinePointName = m.Name,
                      m.CountyName,
                      MinePointLng = m.Lng,
                      MinePointLat = m.Lat,
                      // 停车场信息
                      ParkingId = pk.Id,
                      ParkingCode = pk.Num,
                      ParkingName = pk.Name,
                      pk.Phone,
                      pk.Address
                  })
                  .FirstAsync();

                if (result == null)
                    return null;

                // 查询车辆信息
                var vehicles = await uow.MiVehicle.AsQueryable()
                    .Where(v => v.ViolationReportId == result.Id)
                    .ToListAsync();

                // 查询车辆图片
                List<MiVehicleImage> vehicleImages = new List<MiVehicleImage>();
                if (vehicles.Any())
                {
                    var vehicleIds = vehicles.Select(v => v.Id).ToList();
                    vehicleImages = await uow.MiVehicleImage.AsQueryable()
                        .Where(vi => vehicleIds.Contains(vi.VehicleId))
                        .ToListAsync();
                }

                // 查询现场照片
                var scenePhotos = await uow.MiScenePhoto.AsQueryable()
                    .Where(sp => sp.ViolationReportId == result.Id)
                    .ToListAsync();

                //查询其他人员
                var otherPersons = await uow.MiViolationUsers.AsQueryable()
                    .Where(r => r.ViolationReportId == result.Id)
                    .ToListAsync();

                // 查询其他人员图片
                List<MiOtherpersonImage> personImages = new List<MiOtherpersonImage>();
                if (otherPersons.Any())
                {
                    var personIds = otherPersons.Select(v => v.Id).ToList();
                    personImages = await uow.MiOtherpersonImage.AsQueryable()
                        .Where(vi => personIds.Contains(vi.PersonId))
                        .ToListAsync();
                }

                return new
                {
                    ViolationReport = new
                    {
                        result.Id,
                        result.Title,
                        Status = result.ReportStatus,
                        result.PartyName,
                        result.PartyPhone,
                        result.ViolationType,
                        result.ProblemDescription,
                        result.HandlingOpinion,
                        result.HandlingUnit,
                        result.Handler,
                        result.HandlingTime,
                        result.ReportTime,
                        result.Reporter,
                        result.ReporterName,
                        result.HandlerName,
                        result.ReportUnit,
                        result.ReportUnitName,
                        result.Lng,
                        result.Lat,
                        result.StatusName,
                        result.ViolationTypeName,
                        result.HandUnitName,
                        result.MineralTypes,
                        result.ReviewTime,
                        result.ReviewerName,
                        result.ReviewComments,
                        result.ReviewerSignature,
                        result.SeReviewTime,
                        result.SeReviewerName,
                        result.SeReviewComments,
                        result.SeReviewerSignature,
                    },

                    MinePoint = string.IsNullOrEmpty(result.MinePointId) ? null : new
                    {
                        result.MinePointId,
                        result.MinePointName,
                        result.CountyName,
                        result.MinePointLng,
                        result.MinePointLat
                    },
                    Parking = string.IsNullOrEmpty(result.ParkingId) ? null : new
                    {
                        result.ParkingId,
                        result.ParkingCode,
                        result.ParkingName,
                        result.Phone,
                        result.Address
                    },
                    Vehicles = vehicles.Select(v => new
                    {
                        v.Id,
                        v.LicensePlate,
                        v.Type,
                        v.Name,
                        v.IdCard,
                        v.Phone,
                        v.TypeName,
                        v.Remark,
                        v.State,
                        VehicleImages = vehicleImages
                            .Where(img => img.VehicleId == v.Id)
                            .Select(img => new
                            {
                                img.Id,
                                img.Image,
                                img.Lng,
                                img.Lat,
                                img.Angle,
                                img.CreateTime
                            })
                            .ToList()
                    }).ToList(),

                    ScenePhotos = scenePhotos.Select(sp => new
                    {
                        sp.Id,
                        sp.Image,
                        sp.Lng,
                        sp.Lat,
                        sp.Angle,
                        sp.CreateTime
                    }).ToList(),
                    OtherPersons = otherPersons.Select(v => new
                    {
                        v.Id,
                        v.Name,
                        v.Phone,
                        v.RelationShip,
                        Images = personImages
                        .Where(img => img.PersonId == v.Id)
                        .Select(img => new
                        {
                            img.Id,
                            img.Image,
                            img.Lng,
                            img.Lat,
                            img.Angle,
                            img.CreateTime
                        })
                        .ToList()
                    }).ToList()
                };
            }
        }


        /// <summary>
        /// 添加
        /// </summary>
        public async Task<Response<bool>> Add(MiViolationReport model)
        {
            var flag = await Repository.InsertAsync(model);

            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }



        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        public async Task<Response<bool>> Delete(List<string> ids)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                await uow.MiViolationReport.UpdateSetColumnsTrueAsync(a => new MiViolationReport
                {
                    IsDelete = true
                }, a => ids.Contains(a.Id));

                var flag = uow.Commit();

                return new Response<bool>
                {
                    Result = flag,
                    Message = flag ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="obj"></param>
        public async Task<Response<bool>> Update(MiViolationReportRequest request)
        {
            using (var uwo = UnitWork.CreateContext())
            {
                var user = _auth.GetCurrentUser();
                var org = user.Orgs.FirstOrDefault();
                if (org == null)
                {
                    throw new Exception("请先分配部门");
                }

                if (string.IsNullOrEmpty(request.Id))
                {
                    throw new Exception("数据id错误，请重新数据");
                }

                await uwo.MiScenePhoto.DeleteAsync(r => r.ViolationReportId == request.Id);  //删除现场照片
                await uwo.MiViolationUsers.DeleteAsync(r => r.ViolationReportId == request.Id);  //删除其他人员
                await uwo.MiOtherpersonImage.DeleteAsync(r => r.ViolationReportId == request.Id);  //删除其他人员
                await uwo.MiSeizureDocument.DeleteAsync(r => r.ViolationReportId == request.Id);  //删除扣押财务信息
                await uwo.MiVehicleImage.DeleteAsync(r => r.ViolationReportId == request.Id);  //删除车辆图片
                await uwo.MiVehicle.DeleteAsync(r => r.ViolationReportId == request.Id);  //删除车辆信息

                //上报信息
                var model = request.MapTo<MiViolationReport>();
                //现场照片
                var photos = request.SencePhotos.MapToList<MiScenePhoto>();
                photos.ForEach(a =>
                {
                    a.Id = Guid.NewGuid().ToString();
                    a.ViolationReportId = model.Id;
                    a.CreateTime = DateTime.Now;
                });

                //其他人员
                var personList = new List<MiViolationUsers>();
                var personImageList = new List<MiOtherpersonImage>();
                foreach (var item in request.OtherPersons)
                {
                    var person = item.MapTo<MiViolationUsers>();
                    person.Id = Guid.NewGuid().ToString();
                    person.ViolationReportId = model.Id;

                    //人员图片
                    var images = item.Images.MapToList<MiOtherpersonImage>();
                    images.ForEach(a =>
                    {
                        a.Id = Guid.NewGuid().ToString();
                        a.ViolationReportId = model.Id;
                        a.PersonId = person.Id;
                        a.CreateTime = DateTime.Now;
                        personImageList.Add(a);

                    });

                    personList.Add(person);
                }
                //var others = request.OtherPersons.MapToList<MiViolationUsers>();
                //others.ForEach(a =>
                //{
                //    a.Id = Guid.NewGuid().ToString();
                //    a.ViolationReportId = model.Id;
                //});

                //车辆信息
                var vehicleList = new List<MiVehicle>();
                var vehicleImageList = new List<MiVehicleImage>();
                foreach (var item in request.Vehicles)
                {
                    var vehicle = item.MapTo<MiVehicle>();
                    vehicle.Id = Guid.NewGuid().ToString();
                    vehicle.ViolationReportId = model.Id;
                    vehicle.CreateTime = DateTime.Now;
                    vehicle.State = 0;    //初始默认未提车

                    //车辆图片
                    var images = item.VehicleImages.MapToList<MiVehicleImage>();
                    images.ForEach(a =>
                    {
                        a.Id = Guid.NewGuid().ToString();
                        a.ViolationReportId = model.Id;
                        a.ParkingId = model.ParkingId;
                        a.VehicleId = vehicle.Id;
                        a.CreateTime = DateTime.Now;
                        vehicleImageList.Add(a);

                    });

                    vehicleList.Add(vehicle);
                }

                //扣押财务单信息
                MiSeizureDocument mr = new MiSeizureDocument();
                mr.Id = Guid.NewGuid().ToString();
                mr.CreatedAt = DateTime.Now;
                mr.CreatedBy = user.User.Id.ToString();
                mr.Year = DateTime.Now.Year.ToString();
                mr.SeizureDate = DateTime.Now;
                var mrinfo = base.Repository.ChangeRepository<SugarRepositiry<MiSeizureDocument>>().AsQueryable().ToList();
                if (mrinfo.Count == 0)
                {
                    mr.SerialNumber = 1;
                }
                else
                {
                    mr.SerialNumber = (int)mrinfo.Max(r => r.SerialNumber) + 1;
                }
                mr.ViolationReportId = model.Id;
                mr.ViolationType = model.ViolationTypeName;
                mr.Party = model.PartyName;
                //查询巡查点信息
                var point = await uwo.MiMinePoint.AsQueryable().Where(r => r.Id == model.MinePointId).FirstAsync();
                if (point != null)
                {
                    mr.ClueLocation = point.CountyName + point.StreetName + point.CommunityName + point.Name;
                }

                var type = vehicleList
                    .GroupBy(r => r.TypeName)
                    .Select(g => new
                    {
                        name = g.Key,
                        count = g.Count()
                    }).ToList();
                string items = "";
                foreach (var item in type)
                {
                    items += item.name + "*" + item.count + ";";
                }
                mr.Items = items;

                //此处创建word并上传，调用新方法
                string wordPath = _helper.GenerateSeizureDocumentWord(mr, _env);
                mr.FilePath = wordPath;  // 设置文件路径

                await uwo.MiViolationReport.UpdateAsync(r => new MiViolationReport
                {
                    PartyName = model.PartyName,
                    ParkingId = model.ParkingId,
                    PartyPhone = model.PartyPhone,
                    Title = model.Title,
                    ProblemDescription = model.ProblemDescription,
                    ViolationType = model.ViolationType,
                    ViolationTypeName = model.ViolationTypeName,
                    MinePointId = model.MinePointId,
                    MineralTypes = model.MineralTypes,
                    Status = 0,
                    StatusName = "待处理"
                }, r => r.Id == model.Id);
                await uwo.MiScenePhoto.InsertRangeAsync(photos);
                await uwo.MiViolationUsers.InsertRangeAsync(personList);   //其他人员
                await uwo.MiOtherpersonImage.InsertRangeAsync(personImageList);   //其他人员图片
                await uwo.MiVehicle.InsertRangeAsync(vehicleList);
                await uwo.MiVehicleImage.InsertRangeAsync(vehicleImageList);
                await uwo.MiSeizureDocument.InsertAsync(mr);

                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 事务示例
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AssignModule()
        {
            using (var uwo = UnitWork.CreateContext())
            {
                //await uwo.SysRoleElement.InsertRangeAsync(model.ElementIds.Select(a => new SysRoleElement { RoleId = model.RoleId, ElementId = a }).ToList());

                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 上报违法
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Response<bool>> Report(MiViolationReportRequest request)
        {
            using (var uwo = UnitWork.CreateContext())
            {
                var user = _auth.GetCurrentUser();
                var org = user.Orgs.FirstOrDefault();
                if (org == null)
                {
                    throw new Exception("请先分配部门");
                }
                //上报信息
                var model = request.MapTo<MiViolationReport>();
                model.Id = Guid.NewGuid().ToString();
                model.Status = 0;
                model.StatusName = "待处理";
                model.ReportTime = DateTime.Now;
                model.Reporter = user.User.Id.ToString();
                model.IsDelete = false;
                model.ReportUnit = org.Id.ToString();

                //现场照片
                var photos = request.SencePhotos.MapToList<MiScenePhoto>();
                photos.ForEach(a =>
                {
                    a.Id = Guid.NewGuid().ToString();
                    a.ViolationReportId = model.Id;
                    a.CreateTime = DateTime.Now;
                });
                //其他人员
                var personList = new List<MiViolationUsers>();
                var personImageList = new List<MiOtherpersonImage>();
                foreach (var item in request.OtherPersons)
                {
                    var person = item.MapTo<MiViolationUsers>();
                    person.Id = Guid.NewGuid().ToString();
                    person.ViolationReportId = model.Id;

                    //人员图片
                    var images = item.Images.MapToList<MiOtherpersonImage>();
                    images.ForEach(a =>
                    {
                        a.Id = Guid.NewGuid().ToString();
                        a.ViolationReportId = model.Id;
                        a.PersonId = person.Id;
                        a.CreateTime = DateTime.Now;
                        personImageList.Add(a);

                    });

                    personList.Add(person);
                }
                //其他人员
                //var others = request.OtherPersons.MapToList<MiViolationUsers>();
                //others.ForEach(a =>
                //{
                //    a.Id = Guid.NewGuid().ToString();
                //    a.ViolationReportId = model.Id;
                //});

                //车辆信息
                var vehicleList = new List<MiVehicle>();
                var vehicleImageList = new List<MiVehicleImage>();
                foreach (var item in request.Vehicles)
                {
                    var vehicle = item.MapTo<MiVehicle>();
                    vehicle.Id = Guid.NewGuid().ToString();
                    vehicle.ViolationReportId = model.Id;
                    vehicle.CreateTime = DateTime.Now;
                    vehicle.State = 0;    //初始默认未提车

                    //车辆图片
                    var images = item.VehicleImages.MapToList<MiVehicleImage>();
                    images.ForEach(a =>
                    {
                        a.Id = Guid.NewGuid().ToString();
                        a.ViolationReportId = model.Id;
                        a.ParkingId = model.ParkingId;
                        a.VehicleId = vehicle.Id;
                        a.CreateTime = DateTime.Now;
                        vehicleImageList.Add(a);

                    });

                    vehicleList.Add(vehicle);
                }

                //扣押财务单信息
                MiSeizureDocument mr = new MiSeizureDocument();
                mr.Id = Guid.NewGuid().ToString();
                mr.CreatedAt = DateTime.Now;
                mr.CreatedBy = user.User.Id.ToString();
                mr.Year = DateTime.Now.Year.ToString();
                mr.SeizureDate = DateTime.Now;
                var mrinfo = base.Repository.ChangeRepository<SugarRepositiry<MiSeizureDocument>>().AsQueryable().ToList();
                if (mrinfo.Count == 0)
                {
                    mr.SerialNumber = 1;
                }
                else
                {
                    mr.SerialNumber = (int)mrinfo.Max(r => r.SerialNumber) + 1;
                }
                mr.ViolationReportId = model.Id;
                mr.ViolationType = model.ViolationTypeName;
                mr.Party = model.PartyName;
                //查询巡查点信息
                var point = await uwo.MiMinePoint.AsQueryable().Where(r => r.Id == model.MinePointId).FirstAsync();
                if (point != null)
                {
                    mr.ClueLocation = point.CountyName + point.StreetName + point.CommunityName + point.Name;
                }

                var type = vehicleList
                    .GroupBy(r => r.TypeName)
                    .Select(g => new
                    {
                        name = g.Key,
                        count = g.Count()
                    }).ToList();
                string items = "";
                foreach (var item in type)
                {
                    items += item.name + "*" + item.count + ";";
                }
                mr.Items = items;

                //此处创建word并上传，调用新方法
                string wordPath = _helper.GenerateSeizureDocumentWord(mr, _env);
                mr.FilePath = wordPath;  // 设置文件路径


                await uwo.MiViolationReport.InsertAsync(model);
                await uwo.MiScenePhoto.InsertRangeAsync(photos);
                await uwo.MiViolationUsers.InsertRangeAsync(personList);   //其他人员
                await uwo.MiOtherpersonImage.InsertRangeAsync(personImageList);   //其他人员图片
                await uwo.MiVehicle.InsertRangeAsync(vehicleList);
                await uwo.MiVehicleImage.InsertRangeAsync(vehicleImageList);
                await uwo.MiSeizureDocument.InsertAsync(mr);


                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        public async Task<Response<bool>> ReportHandle(HandleInfo info)
        {
            var user = _auth.GetCurrentUser().User;

            var level = _auth.GetCurrentUser().Orgs.Min(a => a.Level);
            //路径
            var org = _auth.GetCurrentUser().Orgs.FirstOrDefault();
            if (org == null)
            {
                throw new Exception("请先分配部门");
            }
            int count = await base.Repository.AsUpdateable().SetColumns(
                a => new MiViolationReport
                {
                    HandlingOpinion = info.HandlingOpinion,
                    HandlingTime = DateTime.Now,
                    HandlingUnit = org.Id.ToString(),
                    Handler = user.Id.ToString(),
                    Status = 5,
                    StatusName = "已处理"
                }).Where(a => a.Id == info.Id).ExecuteCommandAsync();

            return new Response<bool>
            {
                Result = count > 0,
                Message = count > 0 ? "success" : "error"
            };
        }

        #region  扣押单信息
        /// <summary>
        /// 扣押设备审核 （已根据权限修改）
        /// </summary>
        /// <param name="obj"></param>
        public async Task<Response<bool>> ReportAudit(ReportAuditReq model)
        {
            var user = _auth.GetCurrentUser();
            var level = user.Orgs.ToList();
            if (level.Count == 0)
            {
                throw new Exception("暂无权限");
            }
            else
            {
                //查询违法上报信息
                var info = await base.Repository.AsQueryable().Where(R => R.Id == model.Id).FirstAsync();
                if (info != null)
                {
                    using (var uow = base.UnitWork.CreateContext())
                    {
                        var userlevel = level.Min(x => x.Level);
                        if (userlevel == 1)    //初审
                        {
                            if (info.Status != 0)
                            {
                                throw new Exception("不符合初审条件");
                            }
                            if (model.Isagree)
                            {
                                info.Status = 1;
                                info.StatusName = "初审审核通过";
                            }
                            else
                            {
                                info.Status = 2;
                                info.StatusName = "初审审核拒绝";
                            }
                            info.ReviewComments = model.ReviewComments;
                            info.Reviewer = user.User.Id.ToString();
                            info.ReviewTime = DateTime.Now;
                            info.ReviewerSignature = user.User.Signature;
                            info.ReviewerName = user.User.Name;
                            await uow.MiViolationReport.UpdateAsync(info);
                        }
                        else
                        {
                            if (userlevel == 0)
                            {
                                if (info.Status != 1)
                                {
                                    throw new Exception("不符合复审条件");
                                }
                                if (model.Isagree)
                                {
                                    info.Status = 3;
                                    info.StatusName = "复审审核通过";
                                }
                                else
                                {
                                    info.Status = 4;
                                    info.StatusName = "复审审核拒绝";
                                }
                                info.SeReviewComments = model.ReviewComments;
                                info.SeReviewer = user.User.Id.ToString();
                                info.SeReviewTime = DateTime.Now;
                                info.SeReviewerSignature = user.User.Signature;
                                info.SeReviewerName = user.User.Name;
                                await uow.MiViolationReport.UpdateAsync(info);
                            }
                            else
                            {
                                throw new Exception("暂无权限");
                            }
                        }

                        var flag = uow.Commit();
                        return new Response<bool>
                        {
                            Result = flag,
                            Message = flag == true ? "success" : "error"
                        };
                    }
                }
                else
                {
                    throw new Exception("数据丢失");
                }
            }

        }
        /// <summary>
        /// 根据id查询解除扣押单信息
        /// </summary>
        /// <param name="reportid">违法上报id</param>
        /// <returns></returns>
        public async Task<dynamic> GetSeizureDocument(string reportid)
        {
            using (var uow = UnitWork.CreateContext())
            {
                var item = await uow.MiSeizureDocument.AsQueryable()
                        .Where(p => p.ViolationReportId == reportid)
                        .OrderByDescending(p => p.CreatedAt)
                        .Select<dynamic>((p) => new
                        {
                            Id = p.Id.SelectAll()
                        }).FirstAsync();
                var result = new
                {
                    item.Id,
                    item.Year,
                    Number = item.SerialNumber.ToString("D3"),  // 格式化为 "002"
                    item.Party,
                    item.ClueLocation,
                    item.ViolationType,
                    item.SeizureDate,
                    item.Items,
                    item.CreatedAt,
                    item.CreatedBy,
                    item.ViolationReportId,
                    item.FilePath
                };
                return result;
            }
        }
        #endregion

        #region  报表导出
        public async Task<List<PunchStatistics>> GetPunchStatistics(DateTime? begindate, DateTime? enddate)
        {
            using (var uow = UnitWork.CreateContext())
            {
                //查询巡查角色的id
                var role = await uow.Role.AsQueryable().Where(r => r.Name.Contains("巡查人员")).FirstAsync();
                if (role != null)
                {
                    //查询用户
                    var users = await uow.User.AsQueryable()
                        .LeftJoin<SysUserRole>((u, r) => u.Id == r.UserId)
                    .Where((u, r) => r.RoleId == role.Id)
                    .LeftJoin<SysUserOrg>((u, r, o) => u.Id == o.UserId)
                    .LeftJoin<SysOrg>((u, r, o, g) => o.OrgId == g.Id)
                    .Select((u, r, o, g) => new UserInfo
                    {
                        Id = u.Id,
                        Name = u.Name,
                        OrgName = g.Name,
                    }).Distinct().ToListAsync();
                    List<PunchStatistics> plist = new List<PunchStatistics>();
                    foreach (var item in users)
                    {
                        PunchStatistics ps = new PunchStatistics();
                        ps.OrgName = item.OrgName;
                        ps.UserName = item.Name;
                        ps.UserId = item.Id;
                        //巡查信息
                        var punchdata = uow.MiPunchRecord.AsQueryable()
                            .Where(r => r.UserId == item.Id)
                             .WhereIF(begindate != null && enddate != null, r => r.PunchTime >= begindate && r.PunchTime <= enddate); 
                        if (punchdata.Any())
                        {
                            // 假设 PunchTime 是 DateTime 类型
                            DateTime minPunch = Convert.ToDateTime(punchdata.Min(r => r.PunchTime));
                            DateTime maxPunch = Convert.ToDateTime(punchdata.Max(r => r.PunchTime));

                            string mintime = minPunch.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                            string maxtime = maxPunch.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);

                            ps.PunchScope = $"{mintime}-{maxtime}";
                            var punchcount = punchdata.Count();
                            ps.PunchCount = punchcount;
                            ps.ReportCount = punchdata.Where(r => r.PunchStatus == 1).Count();
                        }
                        else
                        {
                            ps.PunchScope = "";
                            ps.PunchCount = 0;
                            ps.ReportCount = 0;
                        }
                        //违法信息
                        var violatedata = uow.MiViolationReport.AsQueryable().
                            Where(r => r.Reporter == item.Id.ToString())
                            .WhereIF(begindate != null && enddate != null, r => r.ReportTime >= begindate && r.ReportTime <= enddate);
                        if (violatedata.Any())
                        {
                            var violatecount = violatedata.Count();
                            ps.DealCount = violatecount;
                            //var dealCount = violatedata.Where(r => r.Status == 3 || r.Status > 4).Count();
                            //ps.DealCount = dealCount;
                        }
                        else
                        {
                            //ps.ReportCount = 0; 
                            ps.DealCount = 0;
                        }
                        plist.Add(ps);
                    }
                    return plist;
                }
                else
                {
                    throw new Exception("暂无巡查人员");
                }
            }
        }


        /// <summary>
        /// 巡查台账--点位
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<PunchPointStatistics>> GetPointPunchStatistics(DateTime? begindate,DateTime? enddate)
        {
            using (var uow = UnitWork.CreateContext())
            {
                //查询巡查点
                var points = await uow.MiMinePoint.AsQueryable()
                .OrderBy(r => r.Name)
                .Select(r => new Point
                {
                    Id = r.Id,
                    Name = r.Name,
                    StreetName = r.StreetName,
                    CommunityName = r.CommunityName,
                    CountyName = r.CountyName
                }).ToListAsync();
                List<PunchPointStatistics> plist = new List<PunchPointStatistics>();
                foreach (var item in points)
                {
                    PunchPointStatistics ps = new PunchPointStatistics();
                    ps.Name = item.Name;
                    ps.StreetName = item.StreetName;
                    ps.CommunityName = item.CommunityName;
                    ps.CountyName = item.CountyName;
                    ps.PointId = item.Id;
                    //巡查信息
                    var punchdata = uow.MiPunchRecord.AsQueryable()
                        .Where(r => r.MinePointId == item.Id)
                        .WhereIF(begindate != null && enddate != null, r => r.PunchTime >= begindate && r.PunchTime <= enddate);
                    if (punchdata.Any())
                    {
                        // 假设 PunchTime 是 DateTime 类型
                        DateTime minPunch = Convert.ToDateTime(punchdata.Min(r => r.PunchTime));
                        DateTime maxPunch = Convert.ToDateTime(punchdata.Max(r => r.PunchTime));

                        string mintime = minPunch.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                        string maxtime = maxPunch.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);

                        ps.PunchScope = $"{mintime}-{maxtime}";
                        var punchcount = punchdata.Count();
                        ps.PunchCount = punchcount;
                        ps.ReportCount = punchdata.Where(r=>r.PunchStatus==1).Count();
                    }
                    else
                    {
                        ps.PunchScope = "";
                        ps.PunchCount = 0;
                        ps.ReportCount = 0;
                    }
                    //违法信息
                    var violatedata = uow.MiViolationReport.AsQueryable()
                        .Where(r => r.MinePointId == item.Id)
                        .WhereIF(begindate != null && enddate != null, r => r.ReportTime >= begindate && r.ReportTime <= enddate);
                    
                    if (violatedata.Any())
                    {
                        var violatecount = violatedata.Count();
                        ps.DealCount = violatecount;
                        //var dealCount = violatedata.Where(r => r.Status == 3||r.Status>4).Count();
                        //ps.DealCount = dealCount;
                    }
                    else
                    {
                        //ps.ReportCount = 0; 
                        ps.DealCount = 0;
                    }
                    plist.Add(ps);
                }
                return plist;
            }
        }


        /// <summary>
        /// 违法处理台账
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<PageInfo<List<ViolateReportStatistics>>> GetReportStatistics(int page,int limit)
        {
            using (var uow = UnitWork.CreateContext())
            {
                RefAsync<int> totalCount = 0;
                var data = await base.Repository.AsQueryable()
                    .Where(p => p.IsDelete == false)
                    .LeftJoin<MiMinePoint>((p, m) => p.MinePointId == m.Id)
                    .LeftJoin<SysUser>((p, m, u) => p.Reporter == u.Id.ToString())
                    .Select((p, m, u) => new ViolateReportStatistics
                    {
                        Id = p.Id,
                        PointName = m.Name,
                        StreetName = m.StreetName,
                        CountyName = m.CountyName,
                        CommunityName = m.CommunityName,
                        ReportTime = p.ReportTime,
                        ReporterName = u.Name,
                        ViolationTypeName = p.ViolationTypeName,
                        MineralTypes = p.MineralTypes,
                        PartyName = p.PartyName,
                        Status=p.Status,
                        VechileCount = SqlFunc.Subqueryable<MiVehicle>().Where(r => r.ViolationReportId == p.Id).Count(),
                        ImageCount = SqlFunc.Subqueryable<MiScenePhoto>().Where(r => r.ViolationReportId == p.Id).Count(),
                        OtherPersonCount = SqlFunc.Subqueryable<MiViolationUsers>().Where(r => r.ViolationReportId == p.Id).Count(),
                    }).ToPageListAsync(page, limit, totalCount); 
                foreach (var item in data)
                {
                    var vechile = uow.MiVehicle.AsQueryable().Where(r => r.ViolationReportId == item.Id).ToList();
                    if (vechile.Where(r => r.State == 2 || r.State == 3).Count()==0)
                    {
                        item.CurrentStatusName = "扣押中";
                    }
                    else
                    {
                        if (vechile.Where(r => r.State == 0 || r.State == 1).Count()==0)
                        {
                            item.CurrentStatusName = "全部放还";
                        }
                        else
                        {
                            item.CurrentStatusName = "部分放还";
                        }
                    }
                }

                return new PageInfo<List<ViolateReportStatistics>>
                {
                    Items = data,
                    Total = totalCount
                }; 
            }
        }


        /// <summary>
        /// 巡查台账清单
        /// </summary>
        public async Task<Response<PageInfo<List<dynamic>>>> LoadPunchRecordPage(int page,int limit)
        {
            using (var uow = UnitWork.CreateContext())
            {
                RefAsync<int> totalCount = 0;
                var list = await uow.MiPunchRecord.AsQueryable()
                    .LeftJoin<SysUser>((r, u) => r.UserId == u.Id)
                    .LeftJoin<MiMinePoint>((r, u, p) => r.MinePointId == p.Id)
                    .OrderByDescending((r, u, p) => r.PunchTime)
                    .Select<dynamic>((r, u, p) => new
                    {
                        Id = r.Id.SelectAll(),
                        UserName = u.Name,
                        PointName = p.Name,
                        StreetName = p.StreetName,
                        p.CountyName,
                        p.CommunityName,
                        StatusName = SqlFunc.Subqueryable<SysDataItemDetail>().Where(a => a.ItemCode == "JGMinePointStatus" && a.ItemValue == r.PunchStatus.ToString()).Select(a => a.ItemName)
                    })
                    .ToPageListAsync(page, limit, totalCount);

                return new Response<PageInfo<List<dynamic>>>
                {
                    Result = new PageInfo<List<dynamic>>
                    {
                        Items = list,
                        Total = totalCount
                    }
                };
            }
        }

        /// <summary>
        /// 巡查台账-人员-巡查次数数据获取
        /// </summary>
        /// <param name="reportid"></param>
        /// <returns></returns>
        public async Task<dynamic> GetPunchDetailData(long userid, DateTime? begindate, DateTime? enddate)
        {
            using (var uow = UnitWork.CreateContext())
            {
                var result = await uow.MiPunchRecord.AsQueryable()
                        .Where(p => p.UserId == userid)
                        .WhereIF(begindate != null && enddate != null, p => p.PunchTime >= begindate && p.PunchTime <= enddate)
                        .OrderByDescending(p => p.PunchTime)
                        .Select<dynamic>((p) => new
                        {
                            Id = p.Id.SelectAll()
                        }).ToListAsync();
                return result;
            }
        }

        /// <summary>
        /// 巡查台账-人员-违法上报次数
        /// </summary>
        /// <param name="reportid"></param>
        /// <returns></returns>
        public async Task<dynamic> GetReportDetailData(long userid, DateTime? begindate, DateTime? enddate)
        {
            using (var uow = UnitWork.CreateContext())
            {
                var result = await uow.MiPunchRecord.AsQueryable()
                        .Where(p => p.UserId == userid&&p.PunchStatus==1)
                        .WhereIF(begindate != null && enddate != null, p => p.PunchTime >= begindate && p.PunchTime <= enddate)
                        .OrderByDescending(p => p.PunchTime)
                        .Select<dynamic>((p) => new
                        {
                            Id = p.Id.SelectAll()
                        }).ToListAsync();
                return result;
            }
        }

        /// <summary>
        /// 巡查台账-人员-违法处理次数
        /// </summary>
        /// <param name="reportid"></param>
        /// <returns></returns>
        public async Task<dynamic> GetDealDetailData(long userid, DateTime? begindate, DateTime? enddate)
        {
            using (var uow = UnitWork.CreateContext())
            {
                var result = await uow.MiViolationReport.AsQueryable()
                        .Where(p => p.Reporter == userid.ToString())
                         .WhereIF(begindate != null && enddate != null, p => p.ReportTime >= begindate && p.ReportTime <= enddate)
                        .OrderByDescending(p => p.ReportTime)
                        .Select<dynamic>((p) => new
                        {
                            Id = p.Id.SelectAll()
                        }).ToListAsync();
                return result;
            }
        }


        /// <summary>
        /// 巡查台账-点位-巡查次数数据获取
        /// </summary>
        /// <param name="pointid">点位id</param>
        /// <returns></returns>
        public async Task<dynamic> GetPointPunchDetailData(string pointid, DateTime? begindate, DateTime? enddate)
        {
            using (var uow = UnitWork.CreateContext())
            {
                var result = await uow.MiPunchRecord.AsQueryable()
                    .Where(r=>r.MinePointId==pointid)
                    .WhereIF(begindate != null && enddate != null, r => r.PunchTime >= begindate && r.PunchTime <= enddate)
                    .LeftJoin<SysUser>((r, u) => r.UserId == u.Id)
                    .LeftJoin<MiMinePoint>((r, u, p) => r.MinePointId == p.Id)
                    .OrderByDescending((r, u, p) => r.PunchTime)
                    .Select<dynamic>((r, u, p) => new
                    {
                        Id = r.Id.SelectAll(),
                        UserName = u.Name,
                        PointName = p.Name,
                        StreetName = p.StreetName,
                        p.CountyName,
                        p.CommunityName,
                        StatusName = SqlFunc.Subqueryable<SysDataItemDetail>().Where(a => a.ItemCode == "JGMinePointStatus" && a.ItemValue == r.PunchStatus.ToString()).Select(a => a.ItemName)
                    })
                    .ToListAsync();
                return result;
            }
        }

        /// <summary>
        /// 巡查台账-点位-违法上报次数
        /// </summary>
        /// <param name="reportid"></param>
        /// <returns></returns>
        public async Task<dynamic> GetPointReportDetailData(string pointid, DateTime? begindate, DateTime? enddate)
        {
            using (var uow = UnitWork.CreateContext())
            {
                var result = await uow.MiPunchRecord.AsQueryable()
                    .Where(r => r.MinePointId == pointid&&r.PunchStatus==1)
                    .WhereIF(begindate != null && enddate != null, r => r.PunchTime >= begindate && r.PunchTime <= enddate)
                    .LeftJoin<SysUser>((r, u) => r.UserId == u.Id)
                    .LeftJoin<MiMinePoint>((r, u, p) => r.MinePointId == p.Id)
                    .OrderByDescending((r, u, p) => r.PunchTime)
                    .Select<dynamic>((r, u, p) => new
                    {
                        Id = r.Id.SelectAll(),
                        UserName = u.Name,
                        PointName = p.Name,
                        StreetName = p.StreetName,
                        p.CountyName,
                        p.CommunityName,
                        StatusName = SqlFunc.Subqueryable<SysDataItemDetail>().Where(a => a.ItemCode == "JGMinePointStatus" && a.ItemValue == r.PunchStatus.ToString()).Select(a => a.ItemName)
                    })
                    .ToListAsync();
                return result;
            }
        }

        /// <summary>
        /// 巡查台账-点位-违法处理次数
        /// </summary>
        /// <param name="reportid"></param>
        /// <returns></returns>
        public async Task<dynamic> GetPointDealDetailData(string pointid, DateTime? begindate, DateTime? enddate)
        {
            using (var uow = UnitWork.CreateContext())
            {
                var result = await uow.MiViolationReport.AsQueryable()
                        .Where(p => p.MinePointId == pointid)
                        .WhereIF(begindate != null && enddate != null, p => p.ReportTime >= begindate && p.ReportTime <= enddate)
                        .OrderByDescending(p => p.ReportTime)
                        .Select<dynamic>((p) => new
                        {
                            Id = p.Id.SelectAll()
                        }).ToListAsync();
                return result;
            }
        }
        #endregion

        #region
        //导出 巡查台账--人员
        public async Task<Response<MemoryStream>> ExportPunchStatistics(DateTime? begindate, DateTime? enddate)
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();

                #region 内容样式
                IFont font1 = workbook.CreateFont();
                font1.FontName = "Microsoft YaHei";
                font1.FontHeightInPoints = 12;
                ICellStyle style = workbook.CreateCellStyle();
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.SetFont(font1);
                style.WrapText = true;
                #endregion

                #region 标题样式
                IFont font = workbook.CreateFont();
                font.FontName = "Microsoft YaHei";
                font.Boldweight = (short)FontBoldWeight.Bold;
                font.FontHeightInPoints = 12;
                ICellStyle style1 = workbook.CreateCellStyle();
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.SetFont(font);
                #endregion

                // 获取统计数据
                var list = await GetPunchStatistics(begindate,enddate);
                int totalCount = list.Count;
                int pageSize = 60000; // 每个Sheet最大行数
                int sheetCount = (totalCount / pageSize) + (totalCount % pageSize > 0 ? 1 : 0);

                for (int s = 0; s < sheetCount; s++)
                {
                    ISheet sheet = workbook.CreateSheet($"Sheet{s + 1}");

                    #region 创建表头
                    IRow headerRow = sheet.CreateRow(0);
                    headerRow.Height = 20 * 30;
                    string[] headers = { "单位", "人员", "巡查日期（范围）", "巡查次数", "上报异常次数", "违法处理次数" };
                    for (int i = 0; i < headers.Length; i++)
                    {
                        ICell cell = headerRow.CreateCell(i);
                        cell.SetCellValue(headers[i]);
                        cell.CellStyle = style1;
                        sheet.SetColumnWidth(i, 20 * 350); // 适当调整列宽
                    }
                    #endregion

                    #region 填充数据
                    int startIndex = s * pageSize;
                    int endIndex = Math.Min(startIndex + pageSize, totalCount);
                    for (int i = startIndex, row = 1; i < endIndex; i++, row++)
                    {
                        var item = list[i];
                        IRow dataRow = sheet.CreateRow(row);

                        // 单位
                        ICell cell0 = dataRow.CreateCell(0);
                        cell0.SetCellValue(item.OrgName ?? "");
                        cell0.CellStyle = style;

                        // 人员
                        ICell cell1 = dataRow.CreateCell(1);
                        cell1.SetCellValue(item.UserName ?? "");
                        cell1.CellStyle = style;

                        // 巡查日期范围
                        ICell cell2 = dataRow.CreateCell(2);
                        cell2.SetCellValue(item.PunchScope ?? "");
                        cell2.CellStyle = style;

                        // 巡查次数
                        ICell cell3 = dataRow.CreateCell(3);
                        cell3.SetCellValue(item.PunchCount);
                        cell3.CellStyle = style;

                        // 上报异常次数
                        ICell cell4 = dataRow.CreateCell(4);
                        cell4.SetCellValue(item.ReportCount);
                        cell4.CellStyle = style;

                        // 违法处理次数
                        ICell cell5 = dataRow.CreateCell(5);
                        cell5.SetCellValue(item.DealCount);
                        cell5.CellStyle = style;
                    }
                    #endregion
                }

                response.Result = new MemoryStream();
                workbook.Write(response.Result);
                workbook = null;
                response.Result.Position = 0; // 重置流位置，便于后续读取
                response.Code = 200;
                response.Message = "导出成功";
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }
            return response;
        }


        public async Task<Response<MemoryStream>> ExportPointPunchStatistics(DateTime? begindate, DateTime? enddate)
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();

                #region 内容样式
                IFont font1 = workbook.CreateFont();
                font1.FontName = "Microsoft YaHei";
                font1.FontHeightInPoints = 12;
                ICellStyle style = workbook.CreateCellStyle();
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.SetFont(font1);
                style.WrapText = true;
                #endregion

                #region 标题样式
                IFont font = workbook.CreateFont();
                font.FontName = "Microsoft YaHei";
                font.Boldweight = (short)FontBoldWeight.Bold;
                font.FontHeightInPoints = 12;
                ICellStyle style1 = workbook.CreateCellStyle();
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.SetFont(font);
                #endregion

                // 获取统计数据
                var list = await GetPointPunchStatistics(begindate,enddate);
                int totalCount = list.Count;
                int pageSize = 60000; // 每个Sheet最大行数
                int sheetCount = (totalCount / pageSize) + (totalCount % pageSize > 0 ? 1 : 0);

                for (int s = 0; s < sheetCount; s++)
                {
                    ISheet sheet = workbook.CreateSheet($"Sheet{s + 1}");

                    #region 创建表头
                    IRow headerRow = sheet.CreateRow(0);
                    headerRow.Height = 20 * 30;
                    string[] headers = { "片区", "乡镇", "村居", "点位名称", "巡查日期（范围）", "巡查次数", "上报异常次数", "违法处理次数" };
                    for (int i = 0; i < headers.Length; i++)
                    {
                        ICell cell = headerRow.CreateCell(i);
                        cell.SetCellValue(headers[i]);
                        cell.CellStyle = style1;
                        sheet.SetColumnWidth(i, 20 * 350); // 可根据实际内容调整列宽
                    }
                    #endregion

                    #region 填充数据
                    int startIndex = s * pageSize;
                    int endIndex = Math.Min(startIndex + pageSize, totalCount);
                    for (int i = startIndex, row = 1; i < endIndex; i++, row++)
                    {
                        var item = list[i];
                        IRow dataRow = sheet.CreateRow(row);

                        // 片区
                        ICell cell0 = dataRow.CreateCell(0);
                        cell0.SetCellValue(item.CountyName ?? "");
                        cell0.CellStyle = style;

                        // 乡镇
                        ICell cell1 = dataRow.CreateCell(1);
                        cell1.SetCellValue(item.StreetName ?? "");
                        cell1.CellStyle = style;

                        // 村居
                        ICell cell2 = dataRow.CreateCell(2);
                        cell2.SetCellValue(item.CommunityName ?? "");
                        cell2.CellStyle = style;

                        // 点位名称
                        ICell cell3 = dataRow.CreateCell(3);
                        cell3.SetCellValue(item.Name ?? "");
                        cell3.CellStyle = style;

                        // 巡查日期范围
                        ICell cell4 = dataRow.CreateCell(4);
                        cell4.SetCellValue(item.PunchScope ?? "");
                        cell4.CellStyle = style;

                        // 巡查次数
                        ICell cell5 = dataRow.CreateCell(5);
                        cell5.SetCellValue(item.PunchCount);
                        cell5.CellStyle = style;

                        // 上报异常次数
                        ICell cell6 = dataRow.CreateCell(6);
                        cell6.SetCellValue(item.ReportCount);
                        cell6.CellStyle = style;

                        // 违法处理次数
                        ICell cell7 = dataRow.CreateCell(7);
                        cell7.SetCellValue(item.DealCount);
                        cell7.CellStyle = style;
                    }
                    #endregion
                }

                response.Result = new MemoryStream();
                workbook.Write(response.Result);
                workbook = null;
                response.Result.Position = 0; // 重置流位置，便于后续读取
                response.Code = 200;
                response.Message = "导出成功";
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }
            return response;
        }

        public async Task<Response<MemoryStream>> ExportPunchRecordDetails()
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();

                #region 内容样式
                IFont font1 = workbook.CreateFont();
                font1.FontName = "Microsoft YaHei";
                font1.FontHeightInPoints = 12;
                ICellStyle style = workbook.CreateCellStyle();
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.SetFont(font1);
                style.WrapText = true;
                #endregion

                #region 标题样式
                IFont font = workbook.CreateFont();
                font.FontName = "Microsoft YaHei";
                font.Boldweight = (short)FontBoldWeight.Bold;
                font.FontHeightInPoints = 12;
                ICellStyle style1 = workbook.CreateCellStyle();
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.SetFont(font);
                #endregion

                // 获取数据（使用 dynamic 接收匿名类型列表）
                using (var uow = UnitWork.CreateContext())
                {
                    var list = await uow.MiPunchRecord.AsQueryable()
                        .LeftJoin<SysUser>((r, u) => r.UserId == u.Id)
                        .LeftJoin<MiMinePoint>((r, u, p) => r.MinePointId == p.Id)
                        .OrderByDescending((r, u, p) => r.PunchTime)
                        .Select((r, u, p) => new
                        {
                            PunchTime = r.PunchTime,
                            UserName = u.Name,
                            PointName = p.Name,
                            StreetName = p.StreetName,
                            CountyName = p.CountyName,
                            CommunityName = p.CommunityName,
                            StatusName = SqlFunc.Subqueryable<SysDataItemDetail>()
                                .Where(a => a.ItemCode == "JGMinePointStatus" && a.ItemValue == r.PunchStatus.ToString())
                                .Select(a => a.ItemName)
                        })
                        .ToListAsync();

                    int totalCount = list.Count;
                    int pageSize = 60000;
                    int sheetCount = (totalCount / pageSize) + (totalCount % pageSize > 0 ? 1 : 0);

                    // 即使无数据，也创建一个带表头的空 Sheet
                    if (sheetCount == 0) sheetCount = 1;

                    for (int s = 0; s < sheetCount; s++)
                    {
                        ISheet sheet = workbook.CreateSheet($"Sheet{s + 1}");

                        #region 创建表头
                        IRow headerRow = sheet.CreateRow(0);
                        headerRow.Height = 20 * 30;
                        string[] headers = { "片区", "乡镇", "村居", "点位名称", "巡查时间", "人员", "巡查结果" };
                        for (int i = 0; i < headers.Length; i++)
                        {
                            ICell cell = headerRow.CreateCell(i);
                            cell.SetCellValue(headers[i]);
                            cell.CellStyle = style1;
                            sheet.SetColumnWidth(i, 20 * 350);
                        }
                        #endregion

                        #region 填充数据
                        int startIndex = s * pageSize;
                        int endIndex = Math.Min(startIndex + pageSize, totalCount);
                        for (int i = startIndex, row = 1; i < endIndex; i++, row++)
                        {
                            var item = list[i];
                            IRow dataRow = sheet.CreateRow(row);

                            // 片区
                            ICell cell0 = dataRow.CreateCell(0);
                            cell0.SetCellValue(item.CountyName ?? "");
                            cell0.CellStyle = style;

                            // 乡镇
                            ICell cell1 = dataRow.CreateCell(1);
                            cell1.SetCellValue(item.StreetName ?? "");
                            cell1.CellStyle = style;

                            // 村居
                            ICell cell2 = dataRow.CreateCell(2);
                            cell2.SetCellValue(item.CommunityName ?? "");
                            cell2.CellStyle = style;

                            // 点位名称
                            ICell cell3 = dataRow.CreateCell(3);
                            cell3.SetCellValue(item.PointName ?? "");
                            cell3.CellStyle = style;

                            // 巡查时间（格式化为 yyyy-MM-dd HH:mm:ss，若为空则显示空字符串）
                            ICell cell4 = dataRow.CreateCell(4);
                            cell4.SetCellValue(item.PunchTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "");
                            cell4.CellStyle = style;

                            // 人员
                            ICell cell5 = dataRow.CreateCell(5);
                            cell5.SetCellValue(item.UserName ?? "");
                            cell5.CellStyle = style;

                            // 巡查结果
                            ICell cell6 = dataRow.CreateCell(6);
                            cell6.SetCellValue(item.StatusName ?? "");
                            cell6.CellStyle = style;
                        }
                        #endregion
                    }
                }

                response.Result = new MemoryStream();
                workbook.Write(response.Result);
                workbook = null;
                response.Result.Position = 0;
                response.Code = 200;
                response.Message = "导出成功";
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }
            return response;
        }


        public async Task<Response<MemoryStream>> ExportViolationReportDetails()
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();

                #region 内容样式
                IFont font1 = workbook.CreateFont();
                font1.FontName = "Microsoft YaHei";
                font1.FontHeightInPoints = 12;
                ICellStyle style = workbook.CreateCellStyle();
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.SetFont(font1);
                style.WrapText = true;
                #endregion

                #region 标题样式
                IFont font = workbook.CreateFont();
                font.FontName = "Microsoft YaHei";
                font.Boldweight = (short)FontBoldWeight.Bold;
                font.FontHeightInPoints = 12;
                ICellStyle style1 = workbook.CreateCellStyle();
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.SetFont(font);
                #endregion

                // 获取数据
                List<ViolateReportStatistics> list = new List<ViolateReportStatistics>();
                using (var uow = UnitWork.CreateContext())
                {
                    var data = await uow.MiViolationReport.AsQueryable()
                        .Where(p => p.IsDelete == false)
                        .LeftJoin<MiMinePoint>((p, m) => p.MinePointId == m.Id)
                        .LeftJoin<SysUser>((p, m, u) => p.Reporter == u.Id.ToString())
                        .Select((p, m, u) => new ViolateReportStatistics
                        {
                            Id = p.Id,
                            PointName = m.Name,
                            StreetName = m.StreetName,
                            CountyName = m.CountyName,
                            CommunityName = m.CommunityName,
                            ReportTime = p.ReportTime,
                            ReporterName = u.Name,
                            ViolationTypeName = p.ViolationTypeName,
                            MineralTypes = p.MineralTypes,
                            PartyName = p.PartyName,
                            Status = p.Status,
                            VechileCount = SqlFunc.Subqueryable<MiVehicle>().Where(r => r.ViolationReportId == p.Id).Count(),
                            ImageCount = SqlFunc.Subqueryable<MiScenePhoto>().Where(r => r.ViolationReportId == p.Id).Count(), // 注意：原查询条件是 !=，保留原样
                            OtherPersonCount = SqlFunc.Subqueryable<MiViolationUsers>().Where(r => r.ViolationReportId == p.Id).Count(),
                        })
                        .ToListAsync();

                    // 计算当前状态
                    foreach (var item in data)
                    {
                        var vechile = uow.MiVehicle.AsQueryable().Where(r => r.ViolationReportId == item.Id).ToList();
                        if (vechile.Where(r => r.State == 2 || r.State == 3).Count() == 0)
                        {
                            item.CurrentStatusName = "扣押中";
                        }
                        else
                        {
                            if (vechile.Where(r => r.State == 0 || r.State == 1).Count() == 0)
                            {
                                item.CurrentStatusName = "全部放还";
                            }
                            else
                            {
                                item.CurrentStatusName = "部分放还";
                            }
                        }
                    }
                    list = data;
                }

                int totalCount = list.Count;
                int pageSize = 60000;
                int sheetCount = (totalCount / pageSize) + (totalCount % pageSize > 0 ? 1 : 0);
                if (sheetCount == 0) sheetCount = 1;

                for (int s = 0; s < sheetCount; s++)
                {
                    ISheet sheet = workbook.CreateSheet($"Sheet{s + 1}");

                    #region 创建表头
                    IRow headerRow = sheet.CreateRow(0);
                    headerRow.Height = 20 * 30;
                    string[] headers = {
                "片区", "乡镇", "村居", "点位名称", "处置时间", "人员",
                "违法类型", "矿产品种", "当事人", "车辆及设备数量",
                "现场照片数量", "其他涉案人员数量", "当前状态"
            };
                    for (int i = 0; i < headers.Length; i++)
                    {
                        ICell cell = headerRow.CreateCell(i);
                        cell.SetCellValue(headers[i]);
                        cell.CellStyle = style1;
                        sheet.SetColumnWidth(i, 20 * 350);
                    }
                    #endregion

                    #region 填充数据
                    int startIndex = s * pageSize;
                    int endIndex = Math.Min(startIndex + pageSize, totalCount);
                    for (int i = startIndex, row = 1; i < endIndex; i++, row++)
                    {
                        var item = list[i];
                        IRow dataRow = sheet.CreateRow(row);

                        // 片区
                        dataRow.CreateCell(0).SetCellValue(item.CountyName ?? "");
                        dataRow.Cells[0].CellStyle = style;

                        // 乡镇
                        dataRow.CreateCell(1).SetCellValue(item.StreetName ?? "");
                        dataRow.Cells[1].CellStyle = style;

                        // 村居
                        dataRow.CreateCell(2).SetCellValue(item.CommunityName ?? "");
                        dataRow.Cells[2].CellStyle = style;

                        // 点位名称
                        dataRow.CreateCell(3).SetCellValue(item.PointName ?? "");
                        dataRow.Cells[3].CellStyle = style;

                        // 处置时间
                        dataRow.CreateCell(4).SetCellValue(item.ReportTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "");
                        dataRow.Cells[4].CellStyle = style;

                        // 人员
                        dataRow.CreateCell(5).SetCellValue(item.ReporterName ?? "");
                        dataRow.Cells[5].CellStyle = style;

                        // 违法类型
                        dataRow.CreateCell(6).SetCellValue(item.ViolationTypeName ?? "");
                        dataRow.Cells[6].CellStyle = style;

                        // 矿产品种
                        dataRow.CreateCell(7).SetCellValue(item.MineralTypes ?? "");
                        dataRow.Cells[7].CellStyle = style;

                        // 当事人
                        dataRow.CreateCell(8).SetCellValue(item.PartyName ?? "");
                        dataRow.Cells[8].CellStyle = style;

                        // 车辆及设备数量
                        dataRow.CreateCell(9).SetCellValue(item.VechileCount);
                        dataRow.Cells[9].CellStyle = style;

                        // 现场照片数量
                        dataRow.CreateCell(10).SetCellValue(item.ImageCount);
                        dataRow.Cells[10].CellStyle = style;

                        // 其他涉案人员数量
                        dataRow.CreateCell(11).SetCellValue(item.OtherPersonCount);
                        dataRow.Cells[11].CellStyle = style;

                        // 当前状态
                        dataRow.CreateCell(12).SetCellValue(item.CurrentStatusName ?? "");
                        dataRow.Cells[12].CellStyle = style;
                    }
                    #endregion
                }

                response.Result = new MemoryStream();
                workbook.Write(response.Result);
                workbook = null;
                response.Result.Position = 0;
                response.Code = 200;
                response.Message = "导出成功";
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }
            return response;
        }
        #endregion
    }
}