using FrontendWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Repository.BackendRepository.Interface;
using System.Collections.Generic;
using System;
using System.IO;
using System.Data.SqlTypes;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace FrontendWebApi.ApiControllers
{
    //[Route("api/[controller]")]
    //[ApiController]
    public class AlertController : MyBaseApiController<AlertController>
    {
        private readonly IBackendRepository backendRepository;

        public AlertController(IBackendRepository backendRepository)
        {
            this.backendRepository = backendRepository;
        }

        [HttpPost]
        public FileResult OpeExportExcel([FromBody] List<Alert> alerts)
        {
            var workbook = new XSSFWorkbook();
            #region excel設定
            IFont font12 = workbook.CreateFont();
            font12.FontName = "新細明體";
            font12.FontHeightInPoints = 12;
            ICellStyle style12 = workbook.CreateCellStyle();
            style12.SetFont(font12);
            style12.Alignment = HorizontalAlignment.Center;
            style12.VerticalAlignment = VerticalAlignment.Center;
            IFont font12Times = workbook.CreateFont();
            font12Times.FontName = "Times New Roman";
            font12Times.FontHeightInPoints = 12;
            IFont font18 = workbook.CreateFont();
            font18.FontName = "新細明體";
            font18.FontHeightInPoints = 18;
            font18.IsBold = true;
            ICellStyle styleTitle18 = workbook.CreateCellStyle();
            styleTitle18.SetFont(font18);
            styleTitle18.Alignment = HorizontalAlignment.Center;
            styleTitle18.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLeft12 = workbook.CreateCellStyle();
            styleLeft12.SetFont(font12);
            styleLeft12.Alignment = HorizontalAlignment.Left;
            styleLeft12.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLine12 = workbook.CreateCellStyle();
            styleLine12.SetFont(font12);
            styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            styleLine12.VerticalAlignment = VerticalAlignment.Center;
            styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            ICellStyle stylein12 = workbook.CreateCellStyle();
            stylein12.SetFont(font12Times);
            stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            stylein12.VerticalAlignment = VerticalAlignment.Center;
            stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.WrapText = true;
            #endregion

            var sheet = workbook.CreateSheet("即時告警");
            int RowPosition = 0;
            #region set cell
            IRow row = sheet.CreateRow(RowPosition);
            sheet.SetColumnWidth(0, 4 * 160 * 12);
            sheet.SetColumnWidth(1, 4 * 160 * 12);
            sheet.SetColumnWidth(2, 4 * 160 * 12);
            sheet.SetColumnWidth(3, 4 * 160 * 12);
            sheet.SetColumnWidth(4, 4 * 160 * 12);
            sheet.SetColumnWidth(5, 4 * 160 * 12);
            sheet.SetColumnWidth(6, 4 * 160 * 12);
            sheet.SetColumnWidth(7, 4 * 160 * 12);
            ICell cell = row.CreateCell(0);
            cell.SetCellValue("東別-樓層");
            cell.CellStyle = styleLine12;
            cell = row.CreateCell(1);
            cell.SetCellValue("異常ID");
            cell.CellStyle = styleLine12;
            cell = row.CreateCell(2);
            cell.SetCellValue("發生時間");
            cell.CellStyle = styleLine12;
            cell = row.CreateCell(3);
            cell.SetCellValue("異常類別");
            cell.CellStyle = styleLine12;
            cell = row.CreateCell(4);
            cell.SetCellValue("設備編號");
            cell.CellStyle = styleLine12;
            cell = row.CreateCell(5);
            cell.SetCellValue("異常原因");
            cell.CellStyle = styleLine12;
            cell = row.CreateCell(6);
            cell.SetCellValue("Ack 確認");
            cell.CellStyle = styleLine12;
            cell = row.CreateCell(7);
            cell.SetCellValue("派工/維運單號");
            cell.CellStyle = styleLine12;
            #endregion

            if (alerts.Count > 0)
            {
                foreach (var a in alerts)
                {
                    var sqlString = $@"select formId from operation_record where error_code = @error_code";
                    var formId = backendRepository.GetOneAsync<string>(sqlString, new { @error_code = a.uuid });
                    RowPosition += 1;
                    row = sheet.CreateRow(RowPosition);
                    for (var i = 0; i < 8; i++)
                    {
                        cell = row.CreateCell(i);
                        if (i == 0)
                        {
                            cell.SetCellValue(a.buildingFloorName);
                        }
                        if (i == 1)
                        {
                            cell.SetCellValue(a.uuid);
                        }
                        if (i == 2)
                        {
                            //cell.SetCellValue(a.created_time);
                        }
                        if (i == 3)
                        {
                            cell.SetCellValue(a.alarmClass);
                        }
                        if (i == 4)
                        {
                            cell.SetCellValue(a.sourceName_zh);
                        }
                        if (i == 5)
                        {
                            cell.SetCellValue(a.msgText);
                        }
                        if (i == 6)
                        {
                            cell.SetCellValue(a.ackState_zh);
                        }
                        if (i == 7)
                        {
                            cell.SetCellValue(formId.Result);
                        }

                        cell.CellStyle = style12;
                    }
                }
            }

            var ms = new NpoiMemoryStream
            {
                AllowClose = false
            };
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            return File(ms, "application/vnd.ms-excel", "廠商資料.xlsx");
        }

        [HttpPost]
        public async Task<ApiResult<string>> AlertList([FromBody] FindFormId alerts)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try
            {
                var sqlString = $@"select formId from operation_record where error_code = @error_code and deleted = 0 limit 1";
                var formId = await backendRepository.GetOneAsync<string>(sqlString, new { @error_code = alerts.uuid });
                
                apiResult.Code = "0000";
                apiResult.Data = formId;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                string json = System.Text.Json.JsonSerializer.Serialize(alerts);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }
    }
}