using FluentEmail.Core;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.Extensions.Logging;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula;
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.Service;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Ropin.Inspection.Api
{

    public class TmtnDevOpsRecordController : BaseController
    {
        public ILogger<TmtnDevOpsRecordController> _logger { get; }
        private readonly ITmtnDevOpsRecordService _TmtnDevOpsRecordService;
        private readonly ITpntStoreService _TpntStoreService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="TmtnDevOpsRecordService"></param>
        /// <param name="logger"></param>
        public TmtnDevOpsRecordController(ITmtnDevOpsRecordService TmtnDevOpsRecordService, ILogger<TmtnDevOpsRecordController> logger, ITpntStoreService TpntStoreService)
        {
            _TmtnDevOpsRecordService = TmtnDevOpsRecordService;
            _logger = logger;
            _TpntStoreService = TpntStoreService;
        }

        /// <summary>
        /// 通过id获取运维记录信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetDevOpsRecordAsync/{id}")]
        public async Task<ApiResult> GetDevOpsRecordAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _TmtnDevOpsRecordService.GetConditionAsync(new TmtnDevOpsRecordSearchModel { C_ID = id });
                return new ApiResult<TmtnDevOpsRecordViewModel>(content.FirstOrDefault());
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 获取所有运维记录
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetDevOpsRecordsAsync")]
        public async Task<ApiResult> GetDevOpsRecordsAsync()
        {
            try
            {
                var contentList = await _TmtnDevOpsRecordService.GetAllAsync();
                return new ApiResult<IEnumerable<TmtnDevOpsRecordViewModel>>(contentList);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 通过运维记录名称条件查询
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetDevOpsRecordsByAsync")]
        public async Task<ApiResult> GetDevOpsRecordsByAsync(TmtnDevOpsRecordSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnDevOpsRecordService.GetConditionAsync(searchModel);
                return new ApiResult<PagesModel<TmtnDevOpsRecordViewModel>>(new PagesModel<TmtnDevOpsRecordViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 创建运维记录
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateDevOpsRecordAsync")]
        public async Task<ApiResult> CreateDevOpsRecordAsync(TmtnDevOpsRecordViewModel content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _TmtnDevOpsRecordService.CreateOneAsync(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 创建运维记录,一起提交
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        [HttpPost("CreateDevOpsRecordListAsync")]
        public async Task<ApiResult> CreateDevOpsRecordListAsync(TmtnDevOpsRecordListCreateModel record)
        {
            if (record == null || record.TmtnRecordItemList == null || !record.TmtnRecordItemList.Any())
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _TmtnDevOpsRecordService.CreateDevOpsRecordListAsync(record);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 更新运维记录,一起提交
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        [HttpPost("UpdataDevOpsRecordListAsync")]
        public async Task<ApiResult> UpdataDevOpsRecordListAsync(TmtnDevOpsRecordListUpdataModel record)
        {
            if (record == null || record.TmtnRecordItemList == null || !record.TmtnRecordItemList.Any())
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _TmtnDevOpsRecordService.UpdataDevOpsRecordListAsync(record);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        

        /// <summary>
        /// 删除运维记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteDevOpsRecordAsync/{id}")]
        public async Task<ApiResult> DeleteDevOpsRecordAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnDevOpsRecordService.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("UpdateDevOpsRecordAsync/{id}")]
        public async Task<ApiResult> UpdateDevOpsRecordAsync(string id, TmtnDevOpsRecordUpdateModel updateModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnDevOpsRecordService.UpdateAsync(id, updateModel);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 条件获取运维记录
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetRecordsConditionAsync")]
        public async Task<ApiResult> GetRecordsConditionAsync(TmtnDevOpsRecordDetailSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var recordList = await _TmtnDevOpsRecordService.GetRecordsConditionAsync(searchModel);
                return new ApiResult<PagesModel<TmtnDevOpsRecordDetailViewModel>>(new PagesModel<TmtnDevOpsRecordDetailViewModel>(recordList?.ToList(), searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 条件获取运维工单记录
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetDevOpsAsync")]
        public async Task<ApiResult> GetDevOpsAsync(TmtnDevOpsDetailSearchModel searchModel)
        {
            if (searchModel == null || string.IsNullOrEmpty(searchModel.C_StoreCode))
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var recordList = await _TmtnDevOpsRecordService.GetDevOpsAsync(searchModel);
                
                    return new ApiResult<PagesModel<TmtnDevOpsDetailViewModel>>(new PagesModel<TmtnDevOpsDetailViewModel>(recordList?.ToList(), searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }


        /// <summary>
        ///  通过维保记录ID获取巡检详细信息,通过内容分组
        /// </summary>
        /// <param name="recordId"></param>
        /// <returns></returns>
        [HttpGet("GetRecordItemsGroupByRecordIdAsync/{recordId}")]
        [AllowAnonymous]
        public async Task<ApiResult> GetRecordItemsGroupByRecordIdAsync(string recordId)
        {
            if (string.IsNullOrEmpty(recordId))
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                List<List<TmtnDevOpsRecordDetailWithImageViewModel>> recordItems = await _TmtnDevOpsRecordService.GetRecordItemsGroupByRecordIdAsync(recordId);
                return new ApiResult<List<List<TmtnDevOpsRecordDetailWithImageViewModel>>>(recordItems);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        ///  通过维保记录ID获取巡检详细信息
        /// </summary>
        /// <param name="recordId"></param>
        /// <returns></returns>
        [HttpGet("GetRecordItemsByRecordIdAsync/{recordId}")]
        [AllowAnonymous]
        public async Task<ApiResult> GetRecordItemsByRecordIdAsync(string recordId)
        {
            if (string.IsNullOrEmpty(recordId))
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                IEnumerable<TmtnDevOpsRecordDetailWithImageViewModel> recordItems = await _TmtnDevOpsRecordService.GetRecordItemsByRecordIdAsync(recordId);
                return new ApiResult<List<TmtnDevOpsRecordDetailWithImageViewModel>>(recordItems.ToList());
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }


        /// <summary>
        /// 发送邮件(附件为维保记录)
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("SendDevOpsToEmail")]
        public async Task SendDevOpsToEmail(SendDevOpsToEmailModel searchModel)
        {
            if (searchModel == null || string.IsNullOrEmpty(searchModel.C_StoreCode))
            {
                return;
            }
            try
            {
                var recordList = await _TmtnDevOpsRecordService.GetDevOpsAsync(searchModel);

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

                #region Excel
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("sheet1");
                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 6));
                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(0).SetCellValue("设备名称");
                headRow.CreateCell(1).SetCellValue("维保位置");
                headRow.CreateCell(2).SetCellValue("维保人员 ");
                headRow.CreateCell(3).SetCellValue("维保时间");
                headRow.CreateCell(4).SetCellValue("维保状态");
                headRow.CreateCell(5).SetCellValue("备注");
                headRow.CreateCell(6).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;
                }
                #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
                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 recordList)
                {
                    if (item!=null)
                    {
                        var row = sheet.CreateRow(start);
                        row.CreateCell(0).SetCellValue(item.DevStoreName);
                        row.CreateCell(1).SetCellValue(item.C_Name);
                        row.CreateCell(2).SetCellValue(item.C_CreateByName);
                        row.CreateCell(3).SetCellValue(item.D_CreateOn.ToString("yyyy-MM-dd hh:mm:ss"));
                        switch (item.C_Status)
                        {
                            case "1":
                                row.CreateCell(4).SetCellValue("维保上报");
                                break;
                            case "2":
                                row.CreateCell(4).SetCellValue("维保确认");
                                break;
                            case "3":
                                row.CreateCell(4).SetCellValue("正在维保");
                                break;
                            case "4":
                                row.CreateCell(4).SetCellValue("维保完成");
                                break;
                            case "5":
                                row.CreateCell(4).SetCellValue("维保取消");
                                break;
                            case "6":
                                row.CreateCell(4).SetCellValue("维保返工");
                                break;
                            case "7":
                                row.CreateCell(4).SetCellValue("维保完成确认");
                                break;
                            default:
                                row.CreateCell(4).SetCellValue("未知状态");
                                break;
                        }
                        row.CreateCell(5).SetCellValue("");

                        //超链接
                        NPOI.SS.UserModel.ICell cellLink = row.CreateCell(6);
                        cellLink.SetCellValue("附件");
                        IHyperlink link = new XSSFHyperlink(HyperlinkType.Url);
                        link.Address = ("维保记录/" + item.C_DevOpsCode + ".docx");
                        cellLink.Hyperlink = link;
                        start++;
                        foreach (var cell in row.Cells)
                        {
                            cell.CellStyle = contentCellStyle;
                        }
                        cellLink.CellStyle = styleLInk;
                    }
                }
                // 自适应单元格
                for (int i = 0; i < sheet.LastRowNum; i++)
                {
                    sheet.AutoSizeRow(i);
                }
                for (int i = 0; i < 7; i++)
                {
                    sheet.AutoSizeColumn(i, true);
                }
                #endregion

                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)
                    {
                        List<List<TmtnDevOpsRecordDetailWithImageViewModel>> recordItems = await _TmtnDevOpsRecordService.GetRecordItemsGroupByRecordIdAsync(cell.C_DevOpsCode);
                        if (recordItems.Count > 0)
                        {
                            XWPFDocument doc = new XWPFDocument();
                            var paragraph = doc.CreateParagraph();
                            var run1 = paragraph.CreateRun();
                            run1.FontSize = 18;
                            run1.SetText("维保主题:" + cell.C_Name);
                            int serialNum = 1;
                            foreach (var recordItem in recordItems)
                            {
                                if (recordItem==null) { continue; }
                                var p0 = doc.CreateParagraph();
                                var run0 = p0.CreateRun();
                                run0.FontSize = 16;
                                run0.SetText(" " + serialNum.ToString() + "、" + recordItem.FirstOrDefault()?.C_Name);
                                int serialNum1 = 1;
                                foreach (var item in recordItem)
                                {
                                    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":
                                            item.C_Status = "维保上报";
                                            break;
                                        case "2":
                                            item.C_Status = "维保确认";
                                            break;
                                        case "3":
                                            item.C_Status = "正在维保";
                                            break;
                                        case "4":
                                            item.C_Status = "维保完成";
                                            break;
                                        case "5":
                                            item.C_Status = "维保取消";
                                            break;
                                        case "6":
                                            item.C_Status = "维保返工";
                                            break;
                                        case "7":
                                            item.C_Status = "维保完成确认";
                                            break;
                                    }
                                    run.SetText("   " + serialNum.ToString() + "." + serialNum1.ToString() + "、" + item.C_Status);
                                    run.AddCarriageReturn();
                                    run.AppendText("    操作时间:" + item.D_CreateOn);
                                    run.AddCarriageReturn();
                                    run.AppendText("    状态:" + item.C_Status);
                                    run.AddCarriageReturn();
                                    run.AppendText("    处理人员:" + item.ReportUserName);
                                    run.AddCarriageReturn();
                                    run.AppendText("    现场描述:" + item.C_Remark);
                                    run.AddCarriageReturn();
                                    run.AppendText("    现场记录:" + item.C_Record);
                                    if (item.RecordImageList != null && item.RecordImageList.Count() > 0)
                                    {
                                        run.AddCarriageReturn();
                                        run.AppendText("    现场拍照:");
                                        foreach (var path in item.RecordImageList)
                                        {
                                            string pathFile = path.C_ImageURL;
                                            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));
                                        }
                                    }
                                    serialNum1++;
                                }
                                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_DevOpsCode + ".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);

                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);
                //EmailHelper.SendEmail(searchModel.Mails, $"{searchModel.Start}-{searchModel.End}设备维保记录报表", "", "报表见附件", $"{searchModel.Start}-{searchModel.End}设备维保记录报表.xlsx", "application/vnd.ms-excel", stream);

                System.IO.File.Delete(zipPaht);

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 导出维保记录压缩包
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("ExportZip")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportZip(TmtnDevOpsDetailSearchModel searchModel)
        {
            var recordList = await _TmtnDevOpsRecordService.GetDevOpsAsync(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_DevOpsCode);
                    content.CreateCell(2).SetCellValue(x.C_Name);
                    content.CreateCell(3).SetCellValue(x.DevStoreName);
                    content.CreateCell(4).SetCellValue(x.C_CreateByName);
                    content.CreateCell(5).SetCellValue(x.D_CreateOn.ToString("yyyy-MM-dd HH:mm"));
                    content.CreateCell(6).SetCellValue(x.C_Number);
                    //超链接
                    NPOI.SS.UserModel.ICell cell = content.CreateCell(7);
                    cell.SetCellValue("附件");
                    IHyperlink link = new XSSFHyperlink(HyperlinkType.Url);
                    link.Address = ("维保记录/" + x.C_DevOpsCode + ".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)
                {
                    List<List<TmtnDevOpsRecordDetailWithImageViewModel>> recordItems = await _TmtnDevOpsRecordService.GetRecordItemsGroupByRecordIdAsync(cell.C_DevOpsCode);
                    if (recordItems.Count > 0)
                    {
                        XWPFDocument doc = new XWPFDocument();
                        var paragraph = doc.CreateParagraph();
                        var run1 = paragraph.CreateRun();
                        run1.FontSize = 18;
                        run1.SetText("维保主题:" + cell.C_Name);
                        int serialNum = 1;
                        foreach (var recordItem in recordItems)
                        {
                            if(recordItem==null) { continue; }
                            var p0 = doc.CreateParagraph();
                            var run0 = p0.CreateRun();
                            run0.FontSize = 16;
                            run0.SetText(" " + serialNum.ToString() + "、" + recordItem.FirstOrDefault()?.C_Name);
                            int serialNum1 = 1;
                            foreach (var item in recordItem)
                            {
                                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":
                                        item.C_Status = "维保上报";
                                        break;
                                    case "2":
                                        item.C_Status = "维保确认";
                                        break;
                                    case "3":
                                        item.C_Status = "正在维保";
                                        break;
                                    case "4":
                                        item.C_Status = "维保完成";
                                        break;
                                    case "5":
                                        item.C_Status = "维保取消";
                                        break;
                                    case "6":
                                        item.C_Status = "维保返工";
                                        break;
                                    case "7":
                                        item.C_Status = "维保完成确认";
                                        break;
                                }
                                run.SetText("   " + serialNum.ToString() + "." + serialNum1.ToString());
                                run.AddCarriageReturn();
                                run.AppendText("    操作时间:" + item.D_CreateOn);
                                run.AddCarriageReturn();
                                run.AppendText("    状态:" + item.C_Status);
                                run.AddCarriageReturn();
                                run.AppendText("    处理人员:" + item.ReportUserName);
                                run.AddCarriageReturn();
                                run.AppendText("    现场描述:" + item.C_Remark);
                                run.AddCarriageReturn();
                                run.AppendText("    现场记录:" + item.C_Record);
                                if (item.RecordImageList != null && item.RecordImageList.Count() > 0)
                                {
                                    run.AddCarriageReturn();
                                    run.AppendText("    现场拍照:");
                                    foreach (var path in item.RecordImageList)
                                    {
                                        string pathFile = path.C_ImageURL;
                                        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));
                                    }
                                }
                                serialNum1++;
                            }
                            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_DevOpsCode + ".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类型和文件扩展名。  
        }

        /// <summary>
        /// 发送邮件(附件为维保详情)
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("SendDevOpsItemToEmail")]
        public async Task<ApiResult> SendDevOpsItemToEmail(SendDevOpsToEmailModel searchModel)
        {
            if (searchModel == null && string.IsNullOrEmpty(searchModel.C_DevOpsCode))
            {
                return new ApiResult(ReturnCode.ArgsError, "请输入参数");
            }
            try
            {
                List<List<TmtnDevOpsRecordDetailWithImageViewModel>> recordItems = await _TmtnDevOpsRecordService.GetRecordItemsGroupByRecordIdAsync(searchModel.C_DevOpsCode);
                string zip = @"wwwroot\\ZipFile";
                if (!System.IO.Directory.Exists(zip))
                {
                    Directory.CreateDirectory(zip);
                }
                string zipPaht = zip + $"\\{searchModel.C_DevOpsCode}维保详情下载.zip";
                if (recordItems.Count > 0)
                {
                    XWPFDocument doc = new XWPFDocument();
                    var paragraph = doc.CreateParagraph();
                    var run1 = paragraph.CreateRun();
                    run1.FontSize = 18;
                    run1.SetText(searchModel.DevName);
                    int serialNum = 1;
                    foreach (var recordItem in recordItems)
                    {
                        if (recordItem==null)
                        {
                            continue;
                        }
                        var p0 = doc.CreateParagraph();
                        var run0 = p0.CreateRun();
                        run0.FontSize = 16;
                        run0.SetText(" " + serialNum.ToString() + "、" + recordItem.FirstOrDefault()?.C_Name);
                        int serialNum1 = 1;
                        foreach (var item in recordItem)
                        {
                            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":
                                    item.C_Status = "维保上报";
                                    break;
                                case "2":
                                    item.C_Status = "维保确认";
                                    break;
                                case "3":
                                    item.C_Status = "正在维保";
                                    break;
                                case "4":
                                    item.C_Status = "维保完成";
                                    break;
                                case "5":
                                    item.C_Status = "维保取消";
                                    break;
                                case "6":
                                    item.C_Status = "维保返工";
                                    break;
                                case "7":
                                    item.C_Status = "维保完成确认";
                                    break;
                            }
                            run.SetText("   " + serialNum.ToString() + "." + serialNum1.ToString() + "、" + item.C_Status);
                            run.AddCarriageReturn();
                            run.AppendText("    操作时间:" + item.D_CreateOn);
                            run.AddCarriageReturn();
                            run.AppendText("    状态:" + item.C_Status);
                            run.AddCarriageReturn();
                            run.AppendText("    处理人员:" + item.ReportUserName);
                            run.AddCarriageReturn();
                            run.AppendText("    现场描述:" + item.C_Remark);
                            run.AddCarriageReturn();
                            run.AppendText("    现场记录:" + item.C_Record);
                            if (item.RecordImageList != null && item.RecordImageList.Count() > 0)
                            {
                                run.AddCarriageReturn();
                                run.AppendText("    现场拍照:");
                                foreach (var path in item.RecordImageList)
                                {
                                    string pathFile = path.C_ImageURL;
                                    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));
                                }
                            }
                            serialNum1++;
                        }
                        serialNum++;
                    }
                    using (var zipFile = new FileStream(zipPaht, FileMode.Create))
                    {
                        using (var memoryStream = new NpoiMemoryStream())
                        {
                            doc.Write(memoryStream);
                            byte[] excelData = memoryStream.ToArray();

                            using (var archive = new ZipArchive(zipFile, ZipArchiveMode.Update))
                            {
                                archive.CreateEntry($"{searchModel.C_DevOpsCode}维保详情.docx").Open().Write(excelData, 0, excelData.Length);
                            }
                        }
                    }

                }

                string emailName = $"{searchModel.DevName}-维保详情";
                using (var zipFile1 = new FileStream(zipPaht, FileMode.Open))
                {
                    await Task.Run(() =>
                    {
                        EmailHelper.SendEmail(searchModel.Mails, emailName, "", "详情见附件", $"{emailName}.zip", "application/zip", zipFile1);
                    });
                }
                System.IO.File.Delete(zipPaht);
                return new ApiResult(ReturnCode.Success);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
    }
}