using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Ropin.Inspection.Api.Common;
using Ropin.Inspection.Api.Controllers;
using Ropin.Inspection.Common;
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.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace Ropin.Inspection.Api
{

    public class TmtnPushMsgResultController : BaseController
    {
        public ILogger<TmtnPushMsgResultController> _logger { get; }
        private readonly ITmtnPushMsgResultService _TmtnPushMsgResultService;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IPushMsgService _pushMsgService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="TmtnPushMsgResultService"></param>
        /// <param name="logger"></param>
        public TmtnPushMsgResultController(ITmtnPushMsgResultService TmtnPushMsgResultService, IPushMsgService pushMsgService, IHttpClientFactory httpClientFactory, ILogger<TmtnPushMsgResultController> logger)
        {
            _TmtnPushMsgResultService = TmtnPushMsgResultService;
            _logger = logger;
            _httpClientFactory = httpClientFactory;
            _pushMsgService = pushMsgService;
        }

        /// <summary>
        /// 通过id获取推送消息结果信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetPushMsgResultAsync/{id}")]
        public async Task<ApiResult> GetPushMsgResultAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _TmtnPushMsgResultService.GetConditionAsync(new TmtnPushMsgResultSearchModel { C_ID = id });
                return new ApiResult<TmtnPushMsgResultViewModel>(content.FirstOrDefault());
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 获取所有推送消息结果
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetPushMsgResultsAsync")]
        public async Task<ApiResult> GetPushMsgResultsAsync()
        {
            try
            {
                var contentList = await _TmtnPushMsgResultService.GetAllAsync();
                return new ApiResult<IEnumerable<TmtnPushMsgResultViewModel>>(contentList);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 通过推送消息结果名称条件查询
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetPushMsgResultsByAsync")]
        public async Task<ApiResult> GetPushMsgResultsByAsync(TmtnPushMsgResultSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            //searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnPushMsgResultService.GetConditionAsync(searchModel);
                return new ApiResult<PagesModel<TmtnPushMsgResultViewModel>>(new PagesModel<TmtnPushMsgResultViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 通过设备ID取报警信息
        /// </summary>
        /// <param name="id"></param>
        /// <param type="type"></param>
        /// <returns></returns>
        [HttpGet("GetPushMsgResultByDevStoreIdAsync/{id}/{type}")]
        [AllowAnonymous]
        public async Task<IEnumerable<TpushMsgModel>> GetPushMsgResultByDevStoreIdAsync(string id,string type)
        {
            if (string.IsNullOrEmpty(id))
            {
                return await Task.FromResult<IEnumerable<TpushMsgModel>>(null);
            }
            try
            {
                IEnumerable<TmtnPushMsgResultViewModel> contentList = await _TmtnPushMsgResultService.GetConditionAsync(new TmtnPushMsgResultSearchModel { C_DevStoreCode = id });
                if (type == "0")
                    return contentList.Where(x => x.PushMsg.C_MsgTypeCode == "MSG_TYPE_012" || x.PushMsg.C_MsgTypeCode == "MSG_TYPE_013").Select(y=>y.PushMsg);
                else if (type == "1")
                    return contentList.Where(x => x.PushMsg.C_MsgTypeCode != "MSG_TYPE_012" && x.PushMsg.C_MsgTypeCode != "MSG_TYPE_013").Select(y => y.PushMsg);
                else
                    return await Task.FromResult<IEnumerable<TpushMsgModel>>(null);

            }
            catch (Exception ex)
            {
                return await Task.FromResult<IEnumerable<TpushMsgModel>>(null);
            }
        }

        /// <summary>
        /// 创建推送消息结果
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreatePushMsgResultAsync")]
        public async Task<ApiResult> CreatePushMsgResultAsync(TmtnPushMsgResultViewModel content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _TmtnPushMsgResultService.CreateOneAsync(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 删除推送消息结果
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeletePushMsgResultAsync/{id}")]
        public async Task<ApiResult> DeletePushMsgResultAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnPushMsgResultService.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("UpdatePushMsgResultAsync/{id}")]
        public async Task<ApiResult> UpdatePushMsgResultAsync(string id, TmtnPushMsgResultUpdateModel updateModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnPushMsgResultService.UpdateAsync(id, updateModel);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 测试推送消息
        /// </summary>
        /// <returns></returns>
        [HttpGet("PushMsgTestAsync")]
        [AllowAnonymous]
        public ApiResult PushMsgTestAsync()
        {
            try
            {
                //EmailHelper.SendEmail("154817501@qq.com", "环保数字","测试主题", "测试推送消息");
                _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel {
                    C_DevStoreCode = "f59ce998-6fd7-4f19-99eb-4fe567433d48",
                    C_MsgTypeCode = "MSG_TYPE_001",
                    Msg ="压力表要维修", 
                    Subject = "压力表维修通知",
                    DevNumber="20222214510",
                    DevName = "Dovc氨氮处理器",
                }, "压力表维修通知");
                return new ApiResult(ReturnCode.Success, "chenggong");
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 发送邮件(附件为报警记录)
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("SendPushMsgResultsToEmail")]
        public async Task SendPushMsgResultsToEmail(SendPushMsgResultsToEmailModel searchModel)
        {
            if (searchModel == null)
            {
                return;
            }
            //searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnPushMsgResultService.GetConditionAsync(searchModel);
                var pushMsg = contentList.Select(x => x.PushMsg).ToList();

                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;
                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("消息类型");
                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;
                }

                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 pushMsg)
                {
                    var row = sheet.CreateRow(start);
                    row.CreateCell(0).SetCellValue(item.DevName);
                    row.CreateCell(1).SetCellValue(item.DevNumber);
                    row.CreateCell(2).SetCellValue(item.CreateOn);
                    row.CreateCell(3).SetCellValue(item.Subject);
                    row.CreateCell(4).SetCellValue(item.Msg);
                    string msgVal = DataDictionaryHelper.GetValByCode(item.C_MsgTypeCode);
                    row.CreateCell(5).SetCellValue(msgVal);
                    row.CreateCell(6).SetCellValue(!string.IsNullOrEmpty(item.UserName) ? $"{item.UserName}({item.UserMobile})" : "");
                    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 stream = new NpoiMemoryStream())
                {

                    workbook.Write(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    string emailName = $"{searchModel.DevName} 设备报警记录报表 {searchModel.D_Start?.ToString("yyyy-MM-dd HH:mm:ss")}至{searchModel.D_End?.ToString("yyyy-MM-dd HH:mm:ss")}";
                    EmailHelper.SendEmail(searchModel.Mails, emailName, "", "报表见附件", $"{emailName}.xlsx", "application/vnd.ms-excel", stream);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        ///消息报警天数计量
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        //[HttpPost("GetPushMsgResultContentAsync")]
        //public async Task<ApiResult> GetPushMsgResultContentAsync(TmtnPushMsgResultSearchModel searchModel)
        //{
        //    if (searchModel == null)
        //    {
        //        return new ApiResult(ReturnCode.GeneralError);
        //    }
        //    try
        //    {
        //        DevAlarmCount data = await _TmtnPushMsgResultService.GetPushMsgResultContentAsync(searchModel);
        //        return new ApiResult<DevAlarmCount>(data);
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ApiResult(ReturnCode.GeneralError, ex.Message);
        //    }
        //}
    }
}