using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Office2021.DocumentTasks;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Infrastructure;
using Infrastructure.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Common;
using OpenAuth.App.FormModule;
using OpenAuth.App.Interface;
using OpenAuth.App.Response;
using OpenAuth.App.ServiceApp.FireManagement.Response;
using OpenAuth.App.ServiceApp.FmFireSiteManage.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Domain.FireManagement;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace OpenAuth.App.ServiceApp.FmFireSiteManage
{
    public class FmFireSiteApp : SqlSugarBaseApp<FmSiteInfo, SugarDbContext>
    {

        public FmFireSiteApp( ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<FmSiteInfo> repository, IAuth auth) : base(unitWork, repository, auth)
        {
            _auth = auth;
        }

        #region 站点管理
        /// <summary>
        /// 查询所有站点
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<FmSiteInfo>>>> LoadAllSite(string siteName, int pageIndex, int pageSize, int? state)
        {
            var currentUser = _auth.GetCurrentUser();
            using (var db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var list = await db.FmSiteInfo.AsQueryable()
                 .WhereIF(state != null, (a) => a.State == state)
                 .WhereIF(!string.IsNullOrEmpty(siteName), (a) => a.SiteName.Contains(siteName))
                 .Select((a) => new FmSiteInfo
                 {
                     Id = a.Id.SelectAll(),
                 })
                 .OrderByDescending(a => a.CreateTime)
                 .ToPageListAsync(pageIndex, pageSize, totalNumber);
                return new Response<PageInfo<List<FmSiteInfo>>>
                {
                    Result = new PageInfo<List<FmSiteInfo>> { Items = list, Total = totalNumber }
                };
            }
        }
        /// <summary>
        /// 导出所有站点
        /// </summary>
        /// <returns></returns>
        public Response<MemoryStream> ExportSite(int? state)
        {
            var currentUser = _auth.GetCurrentUser();
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                #region 内容样式

                IFont font1 = workbook.CreateFont(); //创建一个字体样式对象
                font1.FontName = "Microsoft YaHei"; //和excel里面的字体对应
                //font1.Boldweight = short.MaxValue;//字体加粗
                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"; //和excel里面的字体对应
                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


                using (var db = base.UnitWork.CreateContext())
                {
                    List<FmSiteInfo> list = new List<FmSiteInfo>();
                    list = db.FmSiteInfo.AsQueryable()
                     .WhereIF(state != null, (a) => a.State == state)
                     .Select((a) => new FmSiteInfo
                     {
                         Id = a.Id.SelectAll(),
                     })
                     .OrderByDescending(a => a.CreateTime)
                     .ToList();

                    #region 创建表头
                    int m = list.Count / 60000 + 1;
                    for (int k = 0; k < m; k++)
                    {
                        ISheet sheet = workbook.CreateSheet("Sheet" + k.ToString());
                        IRow rowHeader = sheet.CreateRow(0);
                        rowHeader.Height = 20 * 30;
                        for (int i = 0; i < 5; i++)
                        {
                            //ModuleColumn header = headers[i];
                            rowHeader.CreateCell(i);
                            rowHeader.Cells[i].CellStyle = style1;
                            sheet.SetColumnWidth(i, 20 * 350);
                        }
                        rowHeader.Cells[0].SetCellValue("站点名称");
                        rowHeader.Cells[1].SetCellValue("站点地址");
                        rowHeader.Cells[2].SetCellValue("审核状态");
                        rowHeader.Cells[3].SetCellValue("负责人");
                        rowHeader.Cells[4].SetCellValue("负责人电话");
                        #endregion

                    #region 填充数据
                        var val = (k + 1) * 60000;
                        var num = 60000;
                        if (val > list.Count)
                        {
                            num = list.Count - k * 60000;
                        }
                        for (int i = 0; i < num; i++) //循环数据
                        {
                            var item = list[k * 60000 + i];     //获取数据
                            IRow dataRow = sheet.CreateRow(i + 1);  //创建行
                            for (int j = 0; j < 5; j++) //循环表头
                            {
                                //创建单元格
                                dataRow.CreateCell(j);
                                dataRow.Cells[j].CellStyle = style;  //添加单元格样式
                            }
                            dataRow.Cells[0].SetCellValue(list[i].SiteName == null ? "" : list[i].SiteName);
                            dataRow.Cells[1].SetCellValue(list[i].SiteAddress == null ? "" : list[i].SiteAddress);
                            dataRow.Cells[2].SetCellValue(list[i].State == 0 ? "未审核" : (list[i].State == 1 ? "审核通过" : "审核未通过"));
                            dataRow.Cells[3].SetCellValue(list[i].Director == null ? "" : list[i].Director);
                            dataRow.Cells[4].SetCellValue(list[i].Phone == null ? "" : list[i].Phone);
                        }
                    }

                    #endregion
                    #endregion
                    response.Result = new MemoryStream();
                    workbook.Write(response.Result);
                    workbook = null;
                    response.Result.Close();
                    response.Result.Dispose();
                    response.Code = 200;
                    response.Message = "获取成功";
                }
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }
            return response;
        }
        /// <summary>
        /// 站点审核
        /// </summary>
        /// <param name="siteId">站点id</param>
        /// <param name="state"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AuditSite(long siteId, int state, string content)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var model = db.FmSiteInfo.AsQueryable().First(r => r.Id == siteId);
                if (model == null)
                {
                    throw new Exception("未查询到站点");
                }
                else
                {
                    model.AuditTime = DateTime.Now;
                    model.State = state;
                    model.StateContent = content;
                    var flag = await db.FmSiteInfo.UpdateAsync(model);
                    if (db.Commit() && flag)
                    {
                        return new Response<bool> { Result = true, Message = "审核成功" };
                    }
                    else
                    {
                        return new Response<bool> { Result = false, Message = "审核失败" };
                    }
                }
            }
        }

        #region 站点管理 
        /// <summary>
        /// 获取站点管理人员及消息接收人员
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<SiteUserRes>>>> LoadSiteUser(long siteId, long? roleid, int pageIndex, int pageSize)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var list = await db.FmSiteUser.AsQueryable()
                 .LeftJoin<SysUser>((a, b) => a.SiteUserId == b.Id.ToString())
                 .LeftJoin<SysUserRole>((a, b, c) => a.SiteUserId == c.UserId.ToString())
                 .Where((a, b, c) => a.SiteId == siteId)
                 .WhereIF(roleid != null, (a, b, c) => c.RoleId == roleid)
                 .Select((a, b) => new SiteUserRes()
                 {
                     Id = a.Id,
                     Name = b.Name,
                     SiteId = a.SiteId,
                     SiteUserId = a.SiteUserId,
                     UserRole = a.UserRole,
                     Account = b.Account
                 }).ToPageListAsync(pageIndex, pageSize, totalNumber);

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

        /// <summary>
        /// 获取林场所有管理员
        /// </summary>
        /// <param name="roleid">角色id（传林场管理员角色id）</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<dynamic>>>> LoadSiteAllUser(long roleid, int pageIndex, int pageSize)
        {
            TableData data = new TableData();
            using (var db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var list = await db.User.AsQueryable()
                    .LeftJoin<SysUserRole>((a, r) => a.Id == r.UserId)
                 .Where((a, r) => r.RoleId == roleid)
                 .Select((a, r) => (dynamic)new
                 {
                     a.Id,
                     a.Name,
                     a.Account
                 })
                 .ToPageListAsync(pageIndex, pageSize, totalNumber);
                return new Response<PageInfo<List<dynamic>>>
                {
                    Result = new PageInfo<List<dynamic>> { Items = list, Total = totalNumber }
                };
            }
        }
        /// <summary>
        /// 获取站点列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns> 
        public async Task<Response<PageInfo<List<dynamic>>>> LoadSiteByUserId(string userId, int pageIndex, int pageSize)
        {
            TableData data = new TableData();
            using (var db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                //查询user的所有场地
                var siteids = db.FmSiteUser.AsQueryable().Where(a => a.SiteUserId == userId).Select(a => a.SiteId).ToList();
                var startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                var endTime = DateTime.Now;

                var list = await db.FmSiteInfo.AsQueryable()
                 .Where((a) => siteids.Contains(a.Id))
                 .Select((a) => (dynamic)new
                 {
                     Id = a.Id.SelectAll(),
                     incount = SqlFunc.Subqueryable<FmEnteringInfo>().Where(r => r.SiteId == a.Id && r.InTime >= startTime && r.InTime <= endTime).Count(),
                 }).ToPageListAsync(pageIndex, pageSize, totalNumber);
                return new Response<PageInfo<List<dynamic>>>
                {
                    Result = new PageInfo<List<dynamic>> { Items = list, Total = totalNumber }
                };
            }
        }

        /// <summary>
        /// 站点注册
        /// </summary>
        /// <param name="FmSiteInfo">站点信息</param>
        /// <returns></returns>
        public async Task<Response<bool>> AddSite(FmSiteInfo fmSite)
        {
            if (fmSite != null)
            {
                fmSite.CreateTime = DateTime.Now;
                fmSite.State = 0;
                using (var db = base.UnitWork.CreateContext())
                {
                    if (db.FmSiteInfo.AsQueryable().Any(a => a.SiteName == fmSite.SiteName))
                    {
                        throw new Exception("该站点名称已被注册");
                    }
                    else
                    {
                        fmSite.Id = YitIdHelper.NextId();
                        fmSite.AuditTime = fmSite.CreateTime;
                        if (fmSite.State != 1)
                        {
                            fmSite.State = 0;
                        }

                        fmSite.SiteUser.ForEach(a =>
                        {
                            a.Id = YitIdHelper.NextId();
                            a.SiteId = fmSite.Id;
                        });
                        FmSiteUser sugar_SiteUser = new FmSiteUser();
                        sugar_SiteUser.Id = YitIdHelper.NextId();
                        sugar_SiteUser.SiteId = fmSite.Id;
                        sugar_SiteUser.SiteUserId = fmSite.CreateUserId;
                        sugar_SiteUser.UserRole = 1;
                        fmSite.SiteUser.Add(sugar_SiteUser);
                        await db.FmSiteInfo.InsertAsync(fmSite);
                        await db.FmSiteUser.InsertRangeAsync(fmSite.SiteUser);
                        if (db.Commit())
                        {
                            return new Response<bool> { Result = true, Message = "操作成功" };
                        }
                        else
                        {
                            return new Response<bool> { Result = false, Message = "操作失败" };
                        }
                    }
                }
            }
            else
            {
                throw new Exception("提交数据为空");
            }
        }
        /// <summary>
        /// 站点编辑
        /// </summary>
        /// <param name="fmSite">站点编辑</param>
        /// <returns></returns>
        public async Task<Response<bool>> EditSite(FmSiteInfo fmSite)
        {
            if (fmSite != null)
            {
                using (var db = base.UnitWork.CreateContext())
                {
                    if (fmSite.SiteUser != null)
                    {
                        fmSite.SiteUser.ForEach(a =>
                        {
                            a.Id = YitIdHelper.NextId();
                            a.SiteId = fmSite.Id;
                        });
                        await db.FmSiteUser.DeleteAsync(r => r.SiteId == fmSite.Id);
                        await db.FmSiteUser.InsertRangeAsync(fmSite.SiteUser);
                    }
                    // Update the fmSite object
                    await db.FmSiteInfo.UpdateAsync(fmSite);

                    if (db.Commit())
                    {
                        return new Response<bool> { Result = true, Message = "操作成功" };
                    }
                    else
                    {
                        return new Response<bool> { Result = false, Message = "操作失败" };
                    }
                }
            }
            else
            {
                throw new Exception("提交数据为空");
            }
        }

        /// <summary>
        /// 获取站点详情
        /// </summary>
        /// <param name="siteId"></param>
        /// <returns></returns>
        public async Task<Response<FmSiteRes>> GetSiteInfo(long siteId)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var info = await db.FmSiteInfo.AsQueryable()
                  .Where((a) => a.Id == siteId)
                  .Select((a) => new FmSiteRes
                  {
                      Id = a.Id.SelectAll(),
                      Accumulate = SqlFunc.Subqueryable<FmEnteringInfo>().Where(r => r.SiteId == a.Id).Count(),
                  }).FirstAsync();
                var inf = await db.FmSiteUser.AsQueryable()
                    .LeftJoin<SysUser>((a, b) => a.SiteUserId == b.Id.ToString())
                    .Where(a => a.SiteId == siteId)
                    .Select((a, b) => new FmSiteUser()
                    {
                        Id = a.Id,
                        SiteUserId = a.SiteUserId,
                        SiteId = a.SiteId,
                        UserRole = a.UserRole,
                        Name = b.Name,
                        Phone = b.Account
                    }).ToListAsync();
                info.SiteUser = inf;
                return new Response<FmSiteRes> { Result = info };
            }
        }
        #endregion
        #region 进山人员管理
        /// <summary>
        /// 进出山类型
        /// </summary>
        /// <returns></returns>
        public Response<List<EnumItem>> InTypes()
        {
            List<EnumItem> list = new List<EnumItem>();

            foreach (var e in Enum.GetValues(typeof(InType)))
            {
                list.Add(new EnumItem
                {
                    Value = Convert.ToInt32(e),
                    Descprtion = ((InType)e).GetDescription()
                });
            }

            return new Response<List<EnumItem>> { Result = list };
        }
        /// <summary>
        /// 获取进出山人员信息
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="cardNo"></param>
        /// <param name="siteId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<EnteringInfoResp>>>> LoadInUser(string userName, string cardNo, long? siteId, int pageIndex, int pageSize, DateTime startTime, DateTime endTime)
        {
            if (startTime.Year == 0001)
            {
                startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                endTime = DateTime.Now;
            }
            using (var db = base.UnitWork.CreateContext())
            {
                RefAsync<int> totalNumber = 0;
                var list = await db.FmEnteringInfo.AsQueryable()
                     .LeftJoin<SysUser>((a, b) => a.CreateUserId == b.Id.ToString())
                     .LeftJoin<FmSiteInfo>((a, b, c) => a.SiteId == c.Id)
                     .WhereIF(siteId != null, (a, b, c) => a.SiteId == siteId)
                     .WhereIF(!string.IsNullOrEmpty(userName), (a, b, c) => a.UserName.Contains(userName))
                     .WhereIF(!string.IsNullOrEmpty(cardNo), (a, b, c) => a.CardNo == cardNo)
                     .Where((a, b, c) => a.InTime >= startTime && a.InTime <= endTime)
                     .Select((a, b, c) => new EnteringInfoResp()
                     {
                         Id = a.Id,
                         UserName = a.UserName,
                         InType = a.InType,
                         Phone = a.Phone,
                         InTime = a.InTime,
                         SiteName = c.SiteName,
                         CardNo = a.CardNo,
                         UserAddress = a.UserAddress,
                         Name = b.Name,
                         OutTime = a.OutTime,
                         Reason = a.Reason,
                         RegistrationType = a.RegistrationType,
                         ProjectName = a.ProjectName
                     })
                     .OrderBy((a) => a.InTime, OrderByType.Desc)//倒序 
                     .Mapper(it => it.InTypeName = ((InType)it.InType).GetDescription())
                     .Mapper(it => it.RegistrationTypeName = ((RegistrationType)it.RegistrationType).GetDescription())
                     .ToPageListAsync(pageIndex, pageSize, totalNumber);
                return new Response<PageInfo<List<EnteringInfoResp>>>
                {
                    Result = new PageInfo<List<EnteringInfoResp>> { Items = list, Total = totalNumber }
                };
            }
        }
        /// <summary>
        /// 导出进出山人员信息
        /// </summary>
        /// <returns></returns>
        public Response<MemoryStream> ExportInUser(long? siteId, DateTime startTime, DateTime endTime)
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            if (startTime.Year == 0001)
            {
                startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                endTime = DateTime.Now;
            }
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                #region 内容样式

                IFont font1 = workbook.CreateFont(); //创建一个字体样式对象
                font1.FontName = "Microsoft YaHei"; //和excel里面的字体对应
                //font1.Boldweight = short.MaxValue;//字体加粗
                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"; //和excel里面的字体对应
                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
                using (var db = base.UnitWork.CreateContext())
                {
                    List<EnteringInfoResp> list = new List<EnteringInfoResp>();
                    //获取当前用户的乡镇信息
                    list = db.FmEnteringInfo.AsQueryable()
                     .LeftJoin<SysUser>((a, b) => a.CreateUserId == b.Id.ToString())
                     .LeftJoin<FmSiteInfo>((a, b, c) => a.SiteId == c.Id)
                    .WhereIF(siteId != null, (a, b, c) => a.SiteId == siteId)
                     .Where((a, b, c) => a.InTime >= startTime && a.InTime <= endTime)
                     .Select((a, b, c) => new EnteringInfoResp()
                     {
                         Id = a.Id,
                         UserName = a.UserName,
                         InType = a.InType,
                         Phone = a.Phone,
                         InTime = a.InTime,
                         SiteName = c.SiteName,
                         CardNo = a.CardNo,
                         UserAddress = a.UserAddress,
                         Name = b.Name,
                         OutTime = a.OutTime,
                         Reason = a.Reason,
                         RegistrationType = a.RegistrationType,
                         ProjectName = a.ProjectName
                     })
                     .OrderBy((a) => a.InTime, OrderByType.Desc)//倒序 
                     .Mapper(it => it.InTypeName = ((InType)it.InType).GetDescription())
                     .Mapper(it => it.RegistrationTypeName = ((RegistrationType)it.RegistrationType).GetDescription())
                     .ToList();

                    #region 创建表头
                    int m = list.Count / 60000 + 1;
                    for (int k = 0; k < m; k++)
                    {
                        ISheet sheet = workbook.CreateSheet("Sheet" + k.ToString());
                        IRow rowHeader = sheet.CreateRow(0);
                        rowHeader.Height = 20 * 30;
                        for (int i = 0; i < 9; i++)
                        {
                            //ModuleColumn header = headers[i];
                            rowHeader.CreateCell(i);
                            rowHeader.Cells[i].CellStyle = style1;
                            sheet.SetColumnWidth(i, 20 * 350);
                        }
                        rowHeader.Cells[0].SetCellValue("人员姓名");
                        rowHeader.Cells[1].SetCellValue("身份证号");
                        rowHeader.Cells[2].SetCellValue("电话");
                        rowHeader.Cells[3].SetCellValue("登记类型");
                        rowHeader.Cells[4].SetCellValue("进山时间");
                        rowHeader.Cells[5].SetCellValue("出山时间");
                        rowHeader.Cells[6].SetCellValue("防火站点");
                        rowHeader.Cells[7].SetCellValue("登记方式");
                        rowHeader.Cells[8].SetCellValue("进山原因");

                        #endregion

                    #region 填充数据   
                        var val = (k + 1) * 60000;
                        var num = 60000;
                        if (val > list.Count)
                        {
                            num = list.Count - k * 60000;
                        }
                        for (int i = 0; i < num; i++) //循环数据
                        {
                            var item = list[k * 60000 + i];     //获取数据
                            IRow dataRow = sheet.CreateRow(i + 1);  //创建行
                            for (int j = 0; j < 9; j++) //循环表头
                            {
                                //创建单元格
                                dataRow.CreateCell(j);
                                dataRow.Cells[j].CellStyle = style;  //添加单元格样式
                            }
                            dataRow.Cells[0].SetCellValue(list[i].UserName == null ? "" : list[i].UserName);
                            dataRow.Cells[1].SetCellValue(list[i].CardNo == null ? "" : list[i].CardNo);
                            dataRow.Cells[2].SetCellValue(list[i].Phone == null ? "" : list[i].Phone);
                            dataRow.Cells[3].SetCellValue(list[i].RegistrationTypeName == null ? "" : list[i].RegistrationTypeName);
                            dataRow.Cells[4].SetCellValue(list[i].InTime == null ? "" : list[i].InTime.ToString());
                            dataRow.Cells[5].SetCellValue(list[i].OutTime == null ? "" : list[i].OutTime.ToString());
                            dataRow.Cells[6].SetCellValue(list[i].SiteName == null ? "" : list[i].SiteName);
                            dataRow.Cells[7].SetCellValue(list[i].InTypeName == null ? "" : list[i].InTypeName);
                            dataRow.Cells[8].SetCellValue(list[i].Reason == null ? "" : list[i].Reason);
                        }
                    }

                    #endregion
                    response.Result = new MemoryStream();
                    workbook.Write(response.Result);
                    workbook = null;
                    response.Result.Close();
                    response.Result.Dispose();
                    response.Code = 200;
                    response.Message = "获取成功";     
                }
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }
            return response;
        }
        #endregion
    }
}
