using FluentEmail.Core;
using ICSharpCode.SharpZipLib.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.Util;
using NPOI.XSSF.UserModel;
using NPOI.XWPF.UserModel;
using Ropin.Inspection.Api.Common;
using Ropin.Inspection.Api.Controllers;
using Ropin.Inspection.Common.Helper;
using Ropin.Inspection.Model;
using Ropin.Inspection.Model.Common;
using Ropin.Inspection.Model.Entities;
using Ropin.Inspection.Model.ViewModel;
using Ropin.Inspection.Service;
using Ropin.Inspection.Service.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using System.Security.Policy;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Ropin.Inspection.Api
{

    public class TmtnRepairOrderController : BaseController
    {
        public ILogger<TmtnRepairOrderController> _logger { get; }
        private readonly ITmtnRepairOrderService _TmtnRepairOrderService;
        private readonly ITmtnRepairOrderItemService _TmtnRepairOrderItemService;
        private readonly IPushMsgService _pushMsgService;
        private readonly ITsysUserService _tsysUserService;
        private readonly ITpntStoreService _TpntStoreService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="TmtnRepairOrderService"></param>
        /// <param name="logger"></param>
        /// <param name="pushMsgService"></param>
        public TmtnRepairOrderController(ITmtnRepairOrderService TmtnRepairOrderService, ITmtnRepairOrderItemService TmtnRepairOrderItemService, ITsysUserService tsysUserService, IPushMsgService pushMsgService, ILogger<TmtnRepairOrderController> logger, ITpntStoreService TpntStoreService)
        {
            _TmtnRepairOrderService = TmtnRepairOrderService;
            _TmtnRepairOrderItemService = TmtnRepairOrderItemService;
            _logger = logger;
            _pushMsgService = pushMsgService;
            _tsysUserService = tsysUserService;
            _TpntStoreService = TpntStoreService;
        }
        /// <summary>
        /// 获取30天维修完成统计
        /// </summary>
        /// <param name="storeCode"></param>
        /// <returns></returns>
        [HttpGet("Get30DaysRepairStatisticsAsync/{storeCode}")]
        public async Task<ApiResult> GetRecords30DaysStatisticsAsync(string storeCode)
        {
            if (string.IsNullOrEmpty(storeCode))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _TmtnRepairOrderService.GetRecords30DaysStatisticsAsync(storeCode);
                return new ApiResult<TispRecord30DaysStatisticsViewModel>(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 取维修工单统计
        /// </summary>
        /// <param name="storeCode"></param>
        /// <returns></returns>
        [HttpGet("GetRepairStatisticsAsync/{storeCode}")]
        public async Task<ApiResult> GetRepairStatisticsAsync(string storeCode)
        {
            if (string.IsNullOrEmpty(storeCode))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _TmtnRepairOrderService.GetRepairStatisticsAsync(storeCode);
                
                return new ApiResult<RepairStatistics>(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 维修次数统计,大屏
        /// </summary>
        /// <param name="storeCode"></param>
        /// <returns></returns>
        [HttpGet("GetRepairStatisticsFullScreenAsync/{storeCode}")]
        [AllowAnonymous]
        public async Task<IEnumerable<FullScreenRecordItem>> GetRepairStatisticsFullScreenAsync(string storeCode)
        {
            if (string.IsNullOrEmpty(storeCode))
            {
                return new FullScreenRecordItem[0];
            }
            try
            {
                var content = await _TmtnRepairOrderService.GetRepairStatisticsFullScreenAsync(storeCode);
                return content;
            }
            catch
            {
                return new FullScreenRecordItem[0];
            }
        }
        /// <summary>
        /// 通过id获取维修工单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetRepairOrderAsync/{id}")]
        public async Task<ApiResult> GetRepairOrderAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _TmtnRepairOrderService.GetConditionAsync(new TmtnRepairOrderSearchModel { C_ID = id,IsPagination = false });
                var repairOrder = content.FirstOrDefault();
                if (repairOrder != null)
                {
                    var user = await _tsysUserService.GetByIdAsync(repairOrder.C_CreateBy);
                    repairOrder.CreateByName = user.C_Name;
                }
                return new ApiResult<TmtnRepairOrderViewModel>(repairOrder);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 获取所有维修工单
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetRepairOrdersAsync")]
        public async Task<ApiResult> GetRepairOrdersAsync()
        {
            try
            {
                var contentList = await _TmtnRepairOrderService.GetAllAsync();
                return new ApiResult<IEnumerable<TmtnRepairOrderViewModel>>(contentList);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 通过维修工单名称条件查询
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetRepairOrdersByAsync")]
        public async Task<ApiResult> GetRepairOrdersByAsync(TmtnRepairOrderSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnRepairOrderService.GetConditionAsync(searchModel);
                return new ApiResult<PagesModel<TmtnRepairOrderViewModel>>(new PagesModel<TmtnRepairOrderViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }


        /// <summary>
        /// 条件查询维修工单列表包含图片
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetRepairOrderWithImageAsync")]
        public async Task<ApiResult> GetRepairOrderWithImageAsync(TmtnRepairOrderSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnRepairOrderService.GetRepairOrderWithImageAsync(searchModel);
                return new ApiResult<PagesModel<TmtnRepairOrderWithImageViewModel>>(new PagesModel<TmtnRepairOrderWithImageViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 条件查询维修工单列表包含模板图片
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetRepairOrderRecordDetailAsync/{name=}")]
        public async Task<ApiResult> GetRepairOrderRecordDetailAsync(TmtnRepairOrderRecordSearchModel searchModel, string name)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            //searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnRepairOrderService.GetRecordsConditionAsync(searchModel);
                if (contentList != null&& contentList.Count()>0)
                {                    
                    if (contentList.FirstOrDefault() != null&&!string.IsNullOrWhiteSpace(name))
                    {
                        contentList = contentList.Where(x => x.C_Name.Contains(name));
                    }
                }
                return new ApiResult<PagesModel<TmtnRepairOrderRecordDetailViewMode>>(new PagesModel<TmtnRepairOrderRecordDetailViewMode>(contentList, searchModel));

            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }


        /// <summary>
        /// 创建维修工单
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateRepairOrderAsync")]
        public async Task<ApiResult> CreateRepairOrderAsync(TmtnRepairOrderViewModel content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var results = await _TmtnRepairOrderService.CreateRepairOrderAsync(content);
                //await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel { 
                //    C_DevStoreCode = content.C_DevStoreCode, 
                //    C_MsgTypeCode = "MSG_TYPE_001",
                //    DevNumber = "未知",
                //    DevName = content.C_DevStoreCode,
                //    Msg = content.C_Name });
                await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
                {
                    C_DevStoreCode = content.C_DevStoreCode,
                    C_MsgTypeCode = "MSG_TYPE_001",
                    Msg = content.C_RepairContent,
                    Subject = "上报维修:" + content.C_Name,
                    DevNumber = "",
                    DevName = "",
                    GenerationType = 2,
                    msgStatus = 0,
                },"设备维修",null, results?.C_ID,"1");
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 删除维修工单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteRepairOrderAsync/{id}")]
        public async Task<ApiResult> DeleteRepairOrderAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnRepairOrderService.DeleteAsync(id);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 更新维修工单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="updateModel"></param>
        /// <returns></returns>
        [HttpPut("UpdateRepairOrderAsync/{id}")]
        public async Task<ApiResult> UpdateRepairOrderAsync(string id, TmtnRepairOrderUpdateModel updateModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnRepairOrderService.UpdateAsync(id, updateModel);
                await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
                {
                    C_DevStoreCode = updateModel.C_DevStoreCode,
                    C_MsgTypeCode = updateModel.C_Status switch
                    {
                        "5" => "MSG_TYPE_007",//维修取消消息
                        "2" => "MSG_TYPE_006",//维修确认消息
                        "3" => "MSG_TYPE_014",//正在维修消息
                        "4" => "MSG_TYPE_008",//维修完成消息
                        "6" => "MSG_TYPE_015",//维修返工消息
                        "7" => "MSG_TYPE_016",//维修完成确认
                        _ => throw new NotImplementedException()
                    }, 
                    Msg = updateModel.C_RepairContent,
                    Subject = updateModel.C_Status switch
                    {
                        "5" => "维修取消消息:",//维修取消消息
                        "2" => "维修确认消息:",//维修确认消息
                        "3" => "正在维修消息:",//正在维修消息
                        "4" => "维修完成消息:",//维修完成消息
                        "6" => "维修返工消息:",//维修返工消息
                        "7" => "维修完成确认:",//维修完成确认
                        _ => throw new NotImplementedException()
                    } + updateModel.C_Name,
                    DevNumber = "",
                    DevName = "",
                    GenerationType = 2,
                    msgStatus = 0,
                }, "设备维修",null, id,updateModel.C_Status);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 发送邮件(附件为维修记录)
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("SendRepairRecordToEmail")]
        public async Task SendRepairRecordToEmail(SendRepairRecordToEmailModel searchModel)
        {
            if (searchModel == null)
            {
                return;
            }
            //searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnRepairOrderService.GetRecordsConditionAsync(searchModel);

                string zip = @"wwwroot\\ZipFile";
                if (!System.IO.Directory.Exists(zip))
                {
                    Directory.CreateDirectory(zip);
                }
                string zipPaht = zip + "\\维修记录下载_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip";

                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("sheet1");
                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 5));
                var titleRow = sheet.CreateRow(0);
                titleRow.Height = 20 * 25;
                NPOI.SS.UserModel.ICell titleCell = titleRow.CreateCell(0);
                titleCell.SetCellValue("设备维修记录");
                //第一行字体样式
                IFont font = workbook.CreateFont();
                font.IsBold = true;
                font.FontHeightInPoints = 16;
                font.FontName = "宋体";
                ICellStyle titleCellStyle = workbook.CreateCellStyle();
                titleCellStyle.SetFont(font);
                titleCellStyle.Alignment = HorizontalAlignment.Center;  //字体居中
                                                                        //边框
                titleCellStyle.BorderBottom = BorderStyle.Thin;
                titleCellStyle.BorderLeft = BorderStyle.Thin;
                titleCellStyle.BorderRight = BorderStyle.Thin;
                titleCellStyle.BorderTop = BorderStyle.Thin;
                titleCell.CellStyle = titleCellStyle;

                var headRow = sheet.CreateRow(1);
                headRow.CreateCell(0).SetCellValue("维修名称");
                headRow.CreateCell(1).SetCellValue("设备名称");
                headRow.CreateCell(2).SetCellValue("维修时间");
                headRow.CreateCell(3).SetCellValue("维修状态");
                headRow.CreateCell(4).SetCellValue("维修人员");
                headRow.CreateCell(5).SetCellValue("备 注");
                //第二行,列名
                IFont font1 = workbook.CreateFont();
                font1.IsBold = true;
                font1.FontHeightInPoints = 12;
                font1.FontName = "宋体";
                ICellStyle headCellStyle = workbook.CreateCellStyle();
                headCellStyle.SetFont(font1);
                //边框
                headCellStyle.BorderBottom = BorderStyle.Thin;
                headCellStyle.BorderLeft = BorderStyle.Thin;
                headCellStyle.BorderRight = BorderStyle.Thin;
                headCellStyle.BorderTop = BorderStyle.Thin;
                foreach (var item in headRow.Cells)
                {
                    item.CellStyle = headCellStyle;
                }

                int start = 2;
                IFont font3 = workbook.CreateFont();
                font3.FontHeightInPoints = 9;
                font3.FontName = "宋体";
                ICellStyle contentCellStyle = workbook.CreateCellStyle();
                contentCellStyle.SetFont(font3);
                //边框
                contentCellStyle.BorderBottom = BorderStyle.Thin;
                contentCellStyle.BorderLeft = BorderStyle.Thin;
                contentCellStyle.BorderRight = BorderStyle.Thin;
                contentCellStyle.BorderTop = BorderStyle.Thin;
                foreach (var item in contentList)
                {
                    if (item!=null)
                    {
                        var row = sheet.CreateRow(start);
                        row.CreateCell(0).SetCellValue(item.C_Name);
                        row.CreateCell(1).SetCellValue(item.DevName);
                        row.CreateCell(2).SetCellValue(item.D_CreateOn.ToString("yyyy-MM-dd hh:mm:ss"));
                        switch (item.C_Status)
                        {
                            case "1":
                                row.CreateCell(3).SetCellValue("故障上报");
                                break;
                            case "2":
                                row.CreateCell(3).SetCellValue("维修确认");
                                break;
                            case "3":
                                row.CreateCell(3).SetCellValue("正在维修");
                                break;
                            case "4":
                                row.CreateCell(3).SetCellValue("维修完成");
                                break;
                            case "5":
                                row.CreateCell(3).SetCellValue("维修取消");
                                break;
                            case "6":
                                row.CreateCell(3).SetCellValue("维修返工");
                                break;
                            case "7":
                                row.CreateCell(3).SetCellValue("维修完成确认");
                                break;
                            default:
                                row.CreateCell(3).SetCellValue("未知状态");
                                break;
                        }
                        row.CreateCell(4).SetCellValue(item.CreateByName);
                        row.CreateCell(5).SetCellValue(item.C_Remark);
                        start++;
                        foreach (var cell in row.Cells)
                        {
                            cell.CellStyle = contentCellStyle;
                        }
                    }
                }
                // 自适应单元格
                for (int i = 0; i < sheet.LastRowNum; i++)
                {
                    sheet.AutoSizeRow(i);
                }
                for (int i = 0; i < 7; i++)
                {
                    sheet.AutoSizeColumn(i, true);
                }


                using (var zipFile = new FileStream(zipPaht, FileMode.Create))
                {
                    // 列表Excel  
                    using (var memoryStream = new NpoiMemoryStream())
                    {
                        workbook.Write(memoryStream);
                        byte[] excelData = memoryStream.ToArray();

                        using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Update))
                        {
                            archive.CreateEntry("维修记录报表.xlsx").Open().Write(excelData, 0, excelData.Length);
                        }
                    }
                }
                //内容word
                foreach (var cell in contentList.ToList())
                {
                    if (cell != null)
                    {
                        var repairOrders = await _TmtnRepairOrderItemService.GetConditionAsync(new TmtnRepairOrderItemSearchModel { C_RepairCode = cell.C_ID });
                        List<TmtnRepairOrderItemViewModel> recordItems = repairOrders.ToList();
                        if (recordItems.Count > 0)
                        {
                            XWPFDocument doc = new XWPFDocument();
                            var paragraph = doc.CreateParagraph();
                            var run1 = paragraph.CreateRun();
                            run1.FontSize = 18;
                            int serialNum = 1;
                            run1.SetText("维修主题:" + cell.C_Name);
                            foreach (var item in recordItems)
                            {
                                if (item==null)
                                {
                                    continue;
                                }
                                var p1 = doc.CreateParagraph();
                                var run = p1.CreateRun();
                                run.FontSize = 14;
                                string status = string.Empty;
                                switch (item.C_Status)
                                {
                                    case "1":
                                        status = "故障上报";
                                        break;
                                    case "2":
                                        status = "维修确认";
                                        break;
                                    case "3":
                                        status = "正在维修";
                                        break;
                                    case "4":
                                        status = "维修完成";
                                        break;
                                    case "5":
                                        status = "维修取消";
                                        break;
                                    case "6":
                                        status = "维修返工";
                                        break;
                                    case "7":
                                        status = "维修完成确认";
                                        break;
                                }
                                run.SetText(" " + serialNum.ToString());
                                run.AddCarriageReturn();
                                run.AppendText("    操作时间:" + item.D_CreateOn.ToString("yyyy-MM-dd HH:mm"));
                                run.AddCarriageReturn();
                                run.AppendText("    状态:" + status);
                                if (item.FilePaths != null && item.FilePaths.Count > 0)
                                {
                                    run.AddCarriageReturn();
                                    run.AppendText("    现场拍照:");
                                    foreach (var path in item.FilePaths)
                                    {
                                        string pathFile = path.ToString();
                                        if (pathFile[0].ToString() == @"/")
                                        {
                                            pathFile = pathFile.Substring(1);
                                        }
                                        if (!System.IO.File.Exists(pathFile))
                                        {
                                            pathFile = @"wwwroot/error.png";
                                        }
                                        FileStream fileStream = new FileStream(pathFile, FileMode.Open, FileAccess.Read);
                                        run.AddCarriageReturn();
                                        run.AddPicture(fileStream, 6, pathFile, Units.ToEMU(100), Units.ToEMU(100));
                                    }
                                }
                                run.AddCarriageReturn();
                                run.AppendText("    维修内容:" + item.C_RepairRecord);
                                run.AddCarriageReturn();
                                run.AppendText("    现场备注:" + item.C_Remark);
                                serialNum++;
                            }
                            using (var zipFile = new FileStream(zipPaht, FileMode.OpenOrCreate))
                            {
                                using (var memoryStream = new NpoiMemoryStream())
                                {
                                    doc.Write(memoryStream);
                                    byte[] excelData = memoryStream.ToArray();

                                    using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Update))
                                    {
                                        archive.CreateEntry("维修记录/" + cell.C_ID + ".docx").Open().Write(excelData, 0, excelData.Length);
                                    }
                                }
                            }
                        }
                    }
                }

                var zipFile1 = new FileStream(zipPaht, FileMode.Open);

                //using var stream = new NpoiMemoryStream();
                //workbook.Write(stream);
                //stream.Seek(0, SeekOrigin.Begin);
                //EmailHelper.SendEmail(searchModel.Mails, $"{searchModel.Start}-{searchModel.End}设备维修记录报表", "", "报表见附件", $"{searchModel.Start}-{searchModel.End}设备维修记录报表.xlsx", "application/vnd.ms-excel", stream);
                string emailName = $"{searchModel.DevName} 设备维修记录 {searchModel.Start.ToString("yyyy-MM-dd HH:mm:ss")}至{searchModel.End.ToString("yyyy-MM-dd HH:mm:ss")}";
                EmailHelper.SendEmail(searchModel.Mails, emailName, "", "报表见附件", $"{emailName}.zip", "application/zip", zipFile1);

                System.IO.File.Delete(zipPaht);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 导出维修记录-维修记录下载-压缩包
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("MaintenanceRecordsExportZip")]
        [AllowAnonymous]
        public async Task<IActionResult> MaintenanceRecordsExportZip(TmtnRepairOrderRecordSearchModel searchModel)
        {
            var recordList = await _TmtnRepairOrderService.GetRecordsConditionAsync(searchModel);
            string zip = @"wwwroot\\ZipFile";
            if (!System.IO.Directory.Exists(zip))
            {
                Directory.CreateDirectory(zip);
            }
            string zipPaht = zip + "\\维修记录下载.zip";
            System.IO.File.Delete(zipPaht);
            TpntStoreViewModel content = null;
            if (!string.IsNullOrEmpty(searchModel.C_StoreCode))
            {
                Guid guid = Guid.Parse(searchModel.C_StoreCode);
                content = await _TpntStoreService.GetByIdAsync(guid);
            }
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet();
            #region
            //标题加粗居中.
            IFont font = workbook.CreateFont();
            font.IsBold = true;
            font.FontHeightInPoints = 25;
            font.FontName = "宋体";
            ICellStyle titleCellStyle = workbook.CreateCellStyle();
            titleCellStyle.SetFont(font);
            titleCellStyle.Alignment = HorizontalAlignment.Center;  //字体居中
            //边框
            titleCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            titleCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            titleCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            titleCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            titleCellStyle.WrapText = true;
            #endregion
            #region
            //标题加粗居中.
            IFont font1 = workbook.CreateFont();
            font1.IsBold = true;
            font1.FontHeightInPoints = 14;
            font1.FontName = "宋体";
            ICellStyle headCellStyle = workbook.CreateCellStyle();
            headCellStyle.SetFont(font1);
            headCellStyle.Alignment = HorizontalAlignment.Center;  //字体居中
            //边框
            headCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            headCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            headCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            headCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            headCellStyle.WrapText = true;
            #endregion
            #region
            //标题加粗居中.
            IFont font2 = workbook.CreateFont();
            font2.IsBold = false;
            font2.FontHeightInPoints = 12;
            font2.FontName = "宋体";
            ICellStyle rowCellStyle = workbook.CreateCellStyle();
            rowCellStyle.SetFont(font2);
            rowCellStyle.Alignment = HorizontalAlignment.Center;  //字体居中
            //边框
            rowCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            rowCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            rowCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            rowCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            rowCellStyle.WrapText = true;
            #endregion
            #region 超链接
            // 创建样式
            ICellStyle styleLInk = workbook.CreateCellStyle();
            // 设置字体颜色为蓝色
            IFont fontLink = workbook.CreateFont();
            fontLink.IsBold = false;
            fontLink.FontHeightInPoints = 12;
            fontLink.FontName = "宋体";
            fontLink.Color = IndexedColors.Green.Index;
            styleLInk.SetFont(fontLink);
            // 设置下划线
            fontLink.Underline = FontUnderlineType.Single;
            styleLInk.SetFont(fontLink);
            styleLInk.Alignment = HorizontalAlignment.Center;  //字体居中
            //边框
            styleLInk.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLInk.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLInk.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLInk.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLInk.WrapText = true;
            #endregion
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 7));
            IRow title = sheet.CreateRow(0);
            title.Height = 30 * 25;
            title.CreateCell(0).SetCellValue("维修记录报表"+(content==null?"":"("+ content .C_Name+ ")"));
            foreach (var item in title.Cells)
            {
                item.CellStyle = titleCellStyle;
            }
            IRow head = sheet.CreateRow(1);
            head.CreateCell(0).SetCellValue("序号");
            head.CreateCell(1).SetCellValue("维修单编号");
            head.CreateCell(2).SetCellValue("维修名称");
            head.CreateCell(3).SetCellValue("设备名称");
            head.CreateCell(4).SetCellValue("申报人员");
            head.CreateCell(5).SetCellValue("维修时间");
            head.CreateCell(6).SetCellValue("备注");
            head.CreateCell(7).SetCellValue("记录查看");
            foreach (var item in head.Cells)
            {
                item.CellStyle = headCellStyle;
            }
            if (content != null)
            {
                byte[] imageBytes = null;
                string imagePath = content.C_Logo; // 指定图片的路径
                if (!System.IO.File.Exists(imagePath))
                {
                    imagePath = @"wwwroot/null.jpeg";
                }
                using (FileStream fs = new FileStream(imagePath, FileMode.Open))
                {
                    imageBytes = new byte[fs.Length];
                    fs.Read(imageBytes, 0, (int)fs.Length);
                }
                int pictureIdx = workbook.AddPicture(imageBytes, NPOI.SS.UserModel.PictureType.JPEG); // 将图像数据添加为图片资源
                IDrawing drawingPatriarch = sheet.CreateDrawingPatriarch(); // 创建绘制对象
                IClientAnchor anchor = workbook.GetCreationHelper().CreateClientAnchor();
                anchor.Row1 = 0;
                anchor.Col1 = 8;
                anchor.Row2 = 3;
                anchor.Col2 = 10;
                IPicture picture = drawingPatriarch.CreatePicture(anchor, pictureIdx); // 创建图片对象
            }
            int rowNumber = 2;int number = 1;
            if (recordList.Any()&&recordList.FirstOrDefault()!=null)
            {
                recordList.ForEach(x =>
                {
                    IRow content = sheet.CreateRow(rowNumber);
                    content.CreateCell(0).SetCellValue(number);
                    content.CreateCell(1).SetCellValue(x.C_ID);
                    content.CreateCell(2).SetCellValue(x.C_Name);
                    content.CreateCell(3).SetCellValue(x.DevName);
                    content.CreateCell(4).SetCellValue( x.CreateByName);
                    content.CreateCell(5).SetCellValue(x.D_CreateOn.ToString("yyyy-MM-dd HH:mm"));
                    content.CreateCell(6).SetCellValue(x.C_Remark);
                    //超链接
                    NPOI.SS.UserModel.ICell cell = content.CreateCell(7);
                    cell.SetCellValue("附件");
                    IHyperlink link = new XSSFHyperlink(HyperlinkType.Url);
                    link.Address = ("维修记录/" + x.C_ID + ".docx");
                    cell.Hyperlink = link;
                    foreach (var item in content.Cells)
                    {
                        item.CellStyle = rowCellStyle;
                    }
                    cell.CellStyle = styleLInk;
                    rowNumber++;
                    number++;
                });
            }
            else
            {
                IRow content1 = sheet.CreateRow(rowNumber);
                content1.CreateCell(0).SetCellValue("暂无数据");
                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 2, 0, 7));
            }
            for (int i = 0; i <= 7; i++)
            {
                if (i == 0)
                {
                    sheet.SetColumnWidth(i, 2000);
                }
                else if (i == 1)
                {
                    sheet.SetColumnWidth(i, 7000);
                }
                else
                {
                    sheet.SetColumnWidth(i, 4500);
                }
            }

            using (var zipFile = new FileStream(zipPaht, FileMode.Create))
            {
                // 列表Excel  
                using (var memoryStream = new NpoiMemoryStream())
                {
                    workbook.Write(memoryStream);
                    byte[] excelData = memoryStream.ToArray();

                    using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Update))
                    {
                        archive.CreateEntry("维修记录报表.xlsx").Open().Write(excelData, 0, excelData.Length);
                    }
                }
            }
            //内容word
            foreach (var cell in recordList.ToList())
            {
                if (cell!=null)
                {
                    var repairOrders = await _TmtnRepairOrderItemService.GetConditionAsync(new TmtnRepairOrderItemSearchModel { C_RepairCode = cell.C_ID });
                    List<TmtnRepairOrderItemViewModel> recordItems = repairOrders.ToList();
                    if (recordItems.Count > 0)
                    {
                        XWPFDocument doc = new XWPFDocument();
                        var paragraph = doc.CreateParagraph();
                        var run1 = paragraph.CreateRun();
                        run1.FontSize = 18;
                        int serialNum = 1;
                        run1.SetText("维修主题:" + cell.C_Name);
                        foreach (var item in recordItems)
                        {
                            if(item==null) continue;
                            var p1 = doc.CreateParagraph();
                            var run = p1.CreateRun();
                            run.FontSize = 14;
                            string status = string.Empty;
                            switch (item.C_Status)
                            {
                                case "1":
                                    status = "故障上报";
                                    break;
                                case "2":
                                    status = "维修确认";
                                    break;
                                case "3":
                                    status = "正在维修";
                                    break;
                                case "4":
                                    status = "维修完成";
                                    break;
                                case "5":
                                    status = "维修取消";
                                    break;
                                case "6":
                                    status = "维修返工";
                                    break;
                                case "7":
                                    status = "维修完成确认";
                                    break;
                            }
                            run.SetText(" " + serialNum.ToString());
                            run.AddCarriageReturn();
                            run.AppendText("    操作时间:" + item.D_CreateOn.ToString("yyyy-MM-dd HH:mm"));
                            run.AddCarriageReturn();
                            run.AppendText("    状态:" + status);
                            if (item.FilePaths != null && item.FilePaths.Count > 0)
                            {
                                run.AddCarriageReturn();
                                run.AppendText("    现场拍照:");
                                foreach (var path in item.FilePaths)
                                {
                                    string pathFile = path.ToString();
                                    if (pathFile[0].ToString() == @"/")
                                    {
                                        pathFile = pathFile.Substring(1);
                                    }
                                    if (!System.IO.File.Exists(pathFile))
                                    {
                                        pathFile = @"wwwroot/error.png";
                                    }
                                    FileStream fileStream = new FileStream(pathFile, FileMode.Open, FileAccess.Read);
                                    run.AddCarriageReturn();
                                    run.AddPicture(fileStream, 6, pathFile, Units.ToEMU(100), Units.ToEMU(100));
                                }
                            }
                            run.AddCarriageReturn();
                            run.AppendText("    维修内容:" + item.C_RepairRecord);
                            run.AddCarriageReturn();
                            run.AppendText("    现场备注:" + item.C_Remark);
                            serialNum++;
                        }
                        using (var zipFile = new FileStream(zipPaht, FileMode.OpenOrCreate))
                        {
                            using (var memoryStream = new NpoiMemoryStream())
                            {
                                doc.Write(memoryStream);
                                byte[] excelData = memoryStream.ToArray();

                                using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Update))
                                {
                                    archive.CreateEntry("维修记录/" + cell.C_ID + ".docx").Open().Write(excelData, 0, excelData.Length);
                                }
                            }
                        }
                    }
                }
            }

            var zipFile1 = new FileStream(zipPaht, FileMode.Open);
            // 将压缩后的数据作为响应返回给客户端(这里假设你使用的是HTTP GET请求)  
            return File(zipFile1, "application/zip", "维修记录报表.zip"); // 这里假设你的文件类型是.xlsx的GZip压缩文件。你可以根据需要调整MIME类型和文件扩展名。  
        }
    }
}