using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Ropin.Inspection.Api.Common;
using Ropin.Inspection.Model;
using Ropin.Inspection.Service.DEV.Interface;
using Ropin.Inspection.Service.MTN.Interface;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using Ropin.Inspection.Model.ViewModel.MTN;
using Ropin.Inspection.Model.SearchModel.MTN;
using Ropin.Inspection.Service;
using Microsoft.AspNetCore.Authorization;
using NPOI.SS.UserModel;
using NPOI.Util;
using NPOI.XSSF.UserModel;
using NPOI.XWPF.UserModel;
using Ropin.Inspection.Model.Common;
using System.IO.Compression;
using System.IO;
using System.Linq;
using log4net;
using NPOI.SS.Formula.Functions;
using Newtonsoft.Json;
using ICSharpCode.SharpZipLib.Zip;
using Ropin.Inspection.Common.Helper;
using NPOI.SS.Formula;
using Ropin.Inspection.Repository;
using Ropin.Inspection.Common;
using ICSharpCode.SharpZipLib.Core;
using Ropin.Inspection.Model.Entities;

namespace Ropin.Inspection.Api.Controllers.MTN
{
    public class TmtnAlarmOrderController : BaseController
    {
        public ILogger<TmtnAlarmOrderController> _logger { get; }
        private readonly ITmtnAlarmOrderService _repository;
        private readonly IPushMsgService _pushMsgService;
        private readonly ITmtnPushMsgResultService _tmtnPushMsgResultService;
        private readonly ITsysMessageService _tsysMessageService;

        private static readonly ILog log = LogManager.GetLogger(typeof(TmtnAlarmOrderController));
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="repository"></param>
        /// <param name="pushMsgService"></param>
        /// <param name="tmtnPushMsgResultService"></param>
        public TmtnAlarmOrderController(ILogger<TmtnAlarmOrderController> logger, ITmtnAlarmOrderService repository, IPushMsgService pushMsgService, ITmtnPushMsgResultService tmtnPushMsgResultService, ITsysMessageService tsysMessageService)
        {
            _logger = logger;
            _repository = repository;
            _pushMsgService = pushMsgService;
            _tmtnPushMsgResultService = tmtnPushMsgResultService;
            _tsysMessageService = tsysMessageService;
        }
        /// <summary>
        /// 创建报警工单
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateAsync")]
        public async Task<ApiResult> CreateAsync(AlarmOrderViewModel content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _repository.CreateOneAsync(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 创建报警工单+处理记录
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateAlarmOrderAsync")]
        public async Task<ApiResult> CreateAlarmOrderAsync(AddAlarmOrderViewModel content)
        {
            if (content == null|| content.C_MessageCode == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                TMTN_AlarmOrder alarmOrder = await _repository.CreateOrderAsync(content);
                log.Info($"创建报警工单+处理记录-保存数据成功【数据=[{JsonConvert.SerializeObject(content)}]】");
                if (alarmOrder!=null)
                {
                    //Guid guid = Guid.Parse(content.C_PushMsgResultCode);
                    var PushMsg = await _tsysMessageService.GetByIdAsync(content.C_MessageCode);
                    log.Info($"创建报警工单+处理记录-根据MessageCode获取 TSYS_Message 数据=[{JsonConvert.SerializeObject(PushMsg)}]");
                    if (PushMsg != null && !string.IsNullOrEmpty(PushMsg.C_DevStoreCode))
                    {
                        await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
                        {
                            C_DevStoreCode = PushMsg.C_DevStoreCode,
                            C_MsgTypeCode = "MSG_TYPE_019",
                            Msg = string.IsNullOrEmpty(content.C_Record)? "上报处理报警" : content.C_Record,//content.C_Name + "  " + content.C_Remark,
                            Subject = content.C_Name,//"上报报警," + content.C_Name,
                            DevNumber = PushMsg.C_DevStoreCode,
                            DevName = "",
                            GenerationType = 2,
                            msgStatus = 0,
                        }, "设备报警工单",null, alarmOrder.C_ID);
                    }
                }
                log.Info($"创建报警工单+处理记录-保存数据END");
            }
            catch (Exception ex)
            {
                log.Info($"创建报警工单+处理记录-保存数据成功异常【{ex.Message}】");
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 删除报警工单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteAsync/{id}")]
        public async Task<ApiResult> DeleteAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _repository.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("UpdateAsync/{id}")]
        public async Task<ApiResult> UpdateAsync(string id, AlarmOrderViewModel updateModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _repository.UpdateAsync(id, updateModel);
                log.Info($"更新报警工单-保存数据成功【id={id};数据=[{JsonConvert.SerializeObject(updateModel)}]】");
                var content = await _repository.GetByIdAsync(id);
                if (updateModel.C_Status=="5"&& content!=null&&!string.IsNullOrEmpty(content.C_DevStoreCode)) {
                    await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
                    {
                        C_DevStoreCode = content.C_DevStoreCode,
                        C_MsgTypeCode = "MSG_TYPE_020",
                        Msg = string.IsNullOrEmpty(updateModel.C_Remark)? "报警取消": updateModel.C_Remark,//content.C_Name + "  " + updateModel.C_Remark,
                        Subject = content.C_Name,//"报警取消," + content.C_Name,
                        DevNumber = content.C_DevStoreCode,
                        DevName = content.C_DevName,
                        GenerationType = 2,
                        msgStatus = 0,
                    },"设备报警工单",null, id,updateModel.C_Status);
                }
                log.Info($"更新报警工单-保存数据END");
            }
            catch (Exception ex)
            {
                log.Info($"更新报警工单-保存数据成功异常【{ex.Message}】");
                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("OrderFlowAsync/{id}")]
        public async Task<ApiResult> OrderFlowAsync(string id, UpdateAlarmOrderViewModel updateModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _repository.OrderFlowAsync(id, updateModel);
                log.Info($"报警工单-流程-保存数据成功【id={id};数据=[{JsonConvert.SerializeObject(updateModel)}]】");
                // 0 = 禁用(删除);1 = 上报报警(报警上报);5 = 报警取消;2 = 报警确认;
                // 3 = 正在处理报警;4 = 处理报警完成;6 = 报警处理维保返工; 7 = 报警处理完成确认
                if (updateModel.C_Status=="2"|| updateModel.C_Status=="4" || updateModel.C_Status == "5" || updateModel.C_Status == "6" || updateModel.C_Status == "7")
                {
                    var content = await _repository.GetByIdAsync(id);
                    if (content != null && !string.IsNullOrEmpty(content.C_DevStoreCode))
                    {
                        string title = ""; string code = "";
                        switch (updateModel.C_Status)
                        {
                            case "2": title = "报警确认,"; code = "MSG_TYPE_021"; break;
                            case "6": title = "报警返工处理,"; code = "MSG_TYPE_021"; break;
                            case "7": title = "报警完成确认,"; code = "MSG_TYPE_021"; break;
                            case "4": title = "报警完成,"; code = "MSG_TYPE_022"; break;
                            case "5": title = "报警取消,"; code = "MSG_TYPE_020"; break;
                        }
                        await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
                        {
                            C_DevStoreCode = content.C_DevStoreCode,
                            C_MsgTypeCode = code,
                            Msg = string.IsNullOrEmpty(updateModel.C_Record)?title: updateModel.C_Record,//content.C_Name + "  " + updateModel.C_Remark,
                            Subject = content.C_Name,// title + content.C_Name,
                            DevNumber = content.C_DevStoreCode,
                            DevName = content.C_DevName,
                            GenerationType = 2,
                            msgStatus = 0,
                        }, "设备报警工单",null, id, updateModel.C_Status);
                    }                    
                }
                log.Info($"报警工单-流程-保存数据END");
            }
            catch (Exception ex)
            {
                log.Info($"报警工单-流程-保存数据成功异常【{ex.Message}】");
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 通过id获取报警工单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetAlarmOrderAsync/{id}")]
        public async Task<ApiResult> GetAlarmOrderAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _repository.GetByIdAsync(id);
                return new ApiResult<AlarmOrderViewModel>(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 通过消息编号获取报警工单信息
        /// </summary>
        /// <param name="messageCode"></param>
        /// <returns></returns>
        [HttpGet("GetAlarmOrderByMessageCodeAsync/{messageCode}")]
        public async Task<ApiResult> GetAlarmOrderByMessageCodeAsync(string messageCode)
        {
            if (string.IsNullOrEmpty(messageCode))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _repository.GetByMessageCodeAsync(messageCode);
                return new ApiResult<AlarmOrderViewModel>(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 报警工单列表
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetAlarmOrderListAsync")]
        public async Task<ApiResult> GetAlarmOrderListAsync(AlarmOrderSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var contentList = await _repository.GetAlarmOrderList(searchModel);
                return new ApiResult<PagesModel<AlarmOrderViewModel>>(new PagesModel<AlarmOrderViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 报警工单处理记录列表
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetAlarmOrderRecordList")]
        public async Task<ApiResult> GetAlarmOrderRecordList(AlarmOrderSearchModel searchModel)
        {
            if (searchModel==null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                searchModel.IsPagination = false;
                var contentList = await _repository.GetAlarmOrderRecordList(searchModel);
                return new ApiResult<IEnumerable<AlarmOrderRecordViewModel>>(contentList);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 报警工单统计
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("AlarmOrderStatistics")]
        public async Task<ApiResult> AlarmOrderStatistics(AlarmOrderSearchModel searchModel)
        {
            if (searchModel == null&& searchModel.C_StoreCode!=null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                searchModel.IsPagination = false;
                var contentList = await _repository.AlarmOrderStatistics(searchModel);
                return new ApiResult<AlarmOrderStatistics>(contentList);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 工单表移动端统计(6个月)
        /// </summary>
        /// <param name="storeCode"></param>
        /// <returns></returns>
        [HttpGet("GetAlarmOrderStatisticsAsync/{storeCode}")]
        public async Task<ApiResult> GetAlarmOrderStatisticsAsync(string storeCode)
        {
            if (string.IsNullOrEmpty(storeCode))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _repository.GetAlarmOrderStatisticsAsync(storeCode);

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

        /// <summary>
        /// 导出报警记录压缩包
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("ExportZip")]
        [AllowAnonymous]
        public async Task<IActionResult> ExportZip(AlarmOrderSearchModel searchModel)
        {
            var recordList = await _repository.GetAlarmOrderList(searchModel);
            string zip = @"wwwroot\\ZipFile";
            if (!System.IO.Directory.Exists(zip))
            {
                Directory.CreateDirectory(zip);
            }
            string zipPaht = zip + "\\报警记录下载.zip";
            System.IO.File.Delete(zipPaht);
            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("报警记录报表" + (searchModel.C_StoreName == null ? "" : "(" + searchModel.C_StoreName + ")"));
            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;
            }
            int rowNumber = 2; int number = 1;
            if (recordList.Any() && recordList.FirstOrDefault() != null)
            {
                foreach (var x in recordList)
                {
                    if (x!=null)
                    {
                        string status = string.Empty;
                        switch (x.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;
                        }
                        IRow content = sheet.CreateRow(rowNumber);
                        content.CreateCell(0).SetCellValue(number);
                        content.CreateCell(1).SetCellValue(x.C_Name);
                        content.CreateCell(2).SetCellValue(status);
                        content.CreateCell(3).SetCellValue(x.C_ExamineName);
                        content.CreateCell(4).SetCellValue(x.D_ExamineOn?.ToString("yyyy-MM-dd"));
                        content.CreateCell(5).SetCellValue(x.C_CreateName);
                        content.CreateCell(6).SetCellValue(x.D_CreateOn.ToString("yyyy-MM-dd"));
                        //超链接
                        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)
                {
                    AlarmOrderSearchModel orderSearch = new AlarmOrderSearchModel();
                    orderSearch.IsPagination = false;
                    orderSearch.C_ID = cell.C_ID;
                    var recordItems = await _repository.GetAlarmOrderRecordList(orderSearch);
                    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());
                            var p1 = doc.CreateParagraph();
                            var run = p1.CreateRun();
                            run.FontSize = 14;
                            string status = string.Empty;
                            switch (recordItem.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.AppendText("    操作时间:" + recordItem.D_CreateOn.ToString("yyyy-MM-dd HH:mm:ss"));
                            run.AddCarriageReturn();
                            run.AppendText("    状态:" + status);
                            run.AddCarriageReturn();
                            run.AppendText("    处理人员:" + recordItem.C_CreateName);
                            run.AddCarriageReturn();
                            run.AppendText("    现场描述:" + recordItem.C_Remark);
                            run.AddCarriageReturn();
                            run.AppendText("    现场记录:" + recordItem.C_Record);
                            if (recordItem.fileList != null && recordItem.fileList.Count() > 0)
                            {
                                run.AddCarriageReturn();
                                run.AppendText("    现场拍照:");
                                foreach (var path in recordItem.fileList)
                                {
                                    string pathFile = path.C_Url;  
                                    if (!string.IsNullOrEmpty(pathFile))
                                    {
                                        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));
                                    }
                                }
                            }
                            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类型和文件扩展名。
        }

        /// <summary>
        /// 发送邮件-根据消息ID获取报警详情
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("SendEmilByPushMsgResultCode")]
        [AllowAnonymous]
        public async Task<ApiResult> SendEmilByPushMsgResultCode(SendAlarmOrderModel searchModel)
        {
            try
            {
                if (searchModel==null&&string.IsNullOrEmpty(searchModel.C_MessageCode))
                {
                    return new ApiResult(ReturnCode.ArgsError, "请输入参数");
                }
                AlarmOrderSearchModel orderSearchModel = new AlarmOrderSearchModel();
                orderSearchModel.IsPagination = false;
                orderSearchModel.C_MessageCode = searchModel.C_MessageCode;
                ////var recordItems = await _repository.GetAlarmOrderRecordList(orderSearchModel);
                var MsgData = await _repository.GetByMessageCodeAsync(searchModel.C_MessageCode);
                string zip = @"wwwroot\\ZipFile";
                if (!System.IO.Directory.Exists(zip))
                {
                    Directory.CreateDirectory(zip);
                }
                string zipPaht = zip + $"\\{searchModel.C_MessageCode}报警详情下载.zip";
                List<string> FileDel =new List<string>();
                if (MsgData!=null)
                {
                    var msgEntity = JsonConvert.DeserializeObject<TpushMsgModel>(MsgData.C_Content);
                    string msgTypeName= DataDictionaryHelper.GetValNameByCode(msgEntity.C_MsgTypeCode);
                    XWPFDocument doc = new XWPFDocument();
                    var paragraph = doc.CreateParagraph();
                    var run1 = paragraph.CreateRun();
                    run1.FontSize = 18;
                    run1.AppendText("报警主题:" + msgEntity.Subject);
                    run1.AddCarriageReturn();
                    run1.AppendText("报警设备:" + msgEntity.DevName);
                    run1.AddCarriageReturn();
                    run1.AppendText("报警来源:" + msgEntity.UserName);
                    run1.AddCarriageReturn();
                    run1.AppendText("报警时间:" + msgEntity.CreateOn);
                    run1.AddCarriageReturn();
                    run1.AppendText("报警内容:" + msgEntity.Msg);
                    run1.AddCarriageReturn();
                    run1.AppendText("报警类型:" + msgTypeName);
                    #region 消息图片信息
                    if (MsgData.messageFile != null&& MsgData.messageFile.Count>0)
                    {
                        foreach (var files in MsgData.messageFile)
                        {
                            if (files != null)
                            {
                                if (files.C_Type== "FILE_TYP_006")
                                {
                                    try
                                    {
                                        var fileText = JsonConvert.DeserializeObject<AlmImage>(files.C_Text);
                                        string images = AIConst.AIImageUrl+fileText.PanoramaUrl;
                                        var imgArray= fileText.PanoramaUrl.Split('/');
                                        string AiAlmFile = @"wwwroot\\AiAlm";// + fileText.PanoramaUrl;
                                        string imgName = "";int fI = 0;
                                        foreach (var img in imgArray)
                                        {
                                            if (fI>0)
                                            {
                                                if (!img.Contains("."))
                                                {
                                                    AiAlmFile = AiAlmFile + "/" + img;
                                                }
                                                else
                                                {
                                                    imgName = img;
                                                }
                                            }
                                            fI++;
                                        }
                                        if (!System.IO.Directory.Exists(AiAlmFile))
                                        {
                                            Directory.CreateDirectory(AiAlmFile);
                                        }
                                        string pathFile = AiAlmFile + "/" + imgName;
                                        bool IsDown = true;
                                        if (!System.IO.File.Exists(pathFile))
                                        {
                                            IsDown = FileHelp.FilesDown(images, pathFile);
                                        }
                                        if (IsDown)
                                        {
                                            if (!string.IsNullOrEmpty(pathFile))
                                            {
                                                if (pathFile[0].ToString() == @"/")
                                                {
                                                    pathFile = pathFile.Substring(1);
                                                }
                                                if (System.IO.File.Exists(pathFile))
                                                {
                                                    FileStream fileStream = new FileStream(pathFile, FileMode.Open, FileAccess.Read);
                                                    run1.AddCarriageReturn();
                                                    run1.AddPicture(fileStream, 6, pathFile, Units.ToEMU(400), Units.ToEMU(300));
                                                    FileDel.Add(pathFile);
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                                else if (files.C_Type == "FILE_TYP_003")
                                {
                                    string pathFile = files.C_Url;
                                    if (!string.IsNullOrEmpty(pathFile))
                                    {
                                        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);
                                        run1.AddCarriageReturn();
                                        run1.AddPicture(fileStream, 6, pathFile, Units.ToEMU(100), Units.ToEMU(100));
                                    }
                                }
                                else
                                {

                                }
                            }
                        }
                    }
                    #endregion
                    int serialNum = 1;
                    foreach (var recordItem in MsgData.historyRecord)
                    {
                        if (recordItem == null) { continue; }
                        var p0 = doc.CreateParagraph();
                        var run0 = p0.CreateRun();
                        run0.FontSize = 16;
                        run0.SetText(" " + serialNum.ToString());
                        var p1 = doc.CreateParagraph();
                        var run = p1.CreateRun();
                        run.FontSize = 14;
                        string status = string.Empty;
                        switch (recordItem.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.AppendText("    操作时间:" + recordItem.D_CreateOn.ToString("yyyy-MM-dd HH:mm:ss"));
                        run.AddCarriageReturn();
                        run.AppendText("    状态:" + status);
                        run.AddCarriageReturn();
                        run.AppendText("    处理人员:" + recordItem.C_CreateName);
                        run.AddCarriageReturn();
                        run.AppendText("    现场描述:" + recordItem.C_Remark);
                        run.AddCarriageReturn();
                        run.AppendText("    现场记录:" + recordItem.C_Record);
                        if (recordItem.fileList != null && recordItem.fileList.Count() > 0)
                        {
                            run.AddCarriageReturn();
                            run.AppendText("    现场拍照:");
                            foreach (var path in recordItem.fileList)
                            {
                                string pathFile = path.C_Url;
                                if (!string.IsNullOrEmpty(pathFile))
                                {
                                    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));
                                }
                            }
                        }
                        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_MessageCode}报警详情.docx").Open().Write(excelData, 0, excelData.Length);
                            }
                        }
                    }
                }
                string emailName = $"{searchModel.AlarmContent}-报警详情";
                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);
                //foreach (var item in FileDel)
                //{
                //    if (System.IO.File.Exists(item))
                //    {
                //        System.IO.File.Delete(item);
                //    };
                //}
                return new ApiResult(ReturnCode.Success);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
    }
}