using Autofac.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using Ropin.Inspection.Api.Common;
using Ropin.Inspection.Model;
using Ropin.Inspection.Model.SearchModel;
using Ropin.Inspection.Model.ViewModel;
using Ropin.Inspection.Model.ViewModel.DEV;
using Ropin.Inspection.Service.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Ropin.Inspection.Api.Controllers
{
    public class ReportController : BaseController
    {
        public ILogger<ReportController> _logger { get; }
        private readonly IReportService _service;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="service"></param>
        /// <param name="logger"></param>
        public ReportController(IReportService service, ILogger<ReportController> logger)
        {
            _service = service;
            _logger = logger;
        }

        /// <summary>
        /// 通过ID获取报表信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetReportDataAsync/{id}")]
        public async Task<ApiResult> GetReportDataAsync(Guid id)
        {
            if (Guid.Empty == id)
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                object Report = await _service.GetReportDataByIdAsync(id);
                return new ApiResult<object>(Report);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }



        /// <summary>
        /// 条件获取报表记录,不包含报表数据,带分页
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetWithoutReportData")]
        public async Task<ApiResult> GetWithoutReportData(ReportSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var reportList = await _service.GetWithoutReportData(searchModel);
                return new ApiResult<PagesModel<ReportViewModel>>(new PagesModel<ReportViewModel>(reportList?.ToList(), searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 更新巡检记录
        /// </summary>
        /// <param name="id"></param>
        /// <param name="updateModel"></param>
        /// <returns></returns>
        [HttpPut("UpdateReportAsync/{id}")]
        public async Task<ApiResult> UpdateReportAsync(Guid id, ReportUpdateViewModel updateModel)
        {
            if (Guid.Empty == id|| updateModel == null)
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _service.UpdateAsync(id, updateModel);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteReportAsync/{id}")]
        public async Task<ApiResult> DeleteReportAsync(Guid id)
        {
            if (Guid.Empty == id)
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _service.DeleteAsync(id);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 导出报表-Excel
        /// </summary>
        /// <param name="id"></param>
        /// <param name="OrgName"></param>
        /// <param name="StoreName"></param>
        /// <returns></returns>
        [HttpPost("ReportExportExcel")]
        [AllowAnonymous]
        public async Task<IActionResult> ReportExportExcel(Guid id,string OrgName,string StoreName)
        {
            if (Guid.Empty == id)
            {
                throw new Exception("参数不能为空值");
            }
            try
            {
                ReportViewModel model = await _service.GetByIdAsync(id);
                if (model == null)
                {
                    throw new Exception("没有此报表");
                }
                object Report= await _service.GetReportDataByIdAsync(id);
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                #region 标题-第一行
                //标题加粗居中.
                IFont font = workbook.CreateFont();
                font.IsBold = true;
                font.FontHeightInPoints = 22;
                font.FontName = "宋体";
                ICellStyle titleCellStyle = workbook.CreateCellStyle();
                titleCellStyle.SetFont(font);
                titleCellStyle.Alignment = HorizontalAlignment.Center;  //字体居中
                titleCellStyle.VerticalAlignment = VerticalAlignment.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 font0 = workbook.CreateFont();
                font0.IsBold = false;
                font0.FontHeightInPoints = 14;
                font0.FontName = "宋体";
                ICellStyle headCellStyle1 = workbook.CreateCellStyle();
                headCellStyle1.SetFont(font0);
                headCellStyle1.Alignment = HorizontalAlignment.Left;  //字体左右居左
                headCellStyle1.VerticalAlignment = VerticalAlignment.Center;//字体上下居中
                //边框
                headCellStyle1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                headCellStyle1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                headCellStyle1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                headCellStyle1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                headCellStyle1.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.VerticalAlignment = VerticalAlignment.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.VerticalAlignment = VerticalAlignment.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
                string TitelName = model.C_DevName+"点检工单记录表"+(string.IsNullOrEmpty(model.C_DevNumber)?"":"(设备编号:"+model.C_DevNumber+" )");
                if (model.I_Type==5)
                {
                    IRow title = sheet.CreateRow(0);
                    title.Height = 30 * 25;
                    title.CreateCell(0).SetCellValue(TitelName);
                    foreach (var item in title.Cells)
                    {
                        item.CellStyle = titleCellStyle;
                    }
                    // 合并列示例,合并第 1 行的第 0 列到第 15 列
                    sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 4));

                    IRow row3 = sheet.CreateRow(3);
                    row3.CreateCell(0).SetCellValue("序号");
                    row3.CreateCell(1).SetCellValue("设备和设施");
                    row3.CreateCell(2).SetCellValue("巡视检查内容");
                    row3.CreateCell(3).SetCellValue("巡检状态");
                    row3.CreateCell(4).SetCellValue("维护维修记录");
                    foreach (var item in row3.Cells)
                    {
                        item.CellStyle = headCellStyle;
                    }
                    string UserName = "";
                    IEnumerable<InspectionWorkOrderModel> Report3 =(IEnumerable<InspectionWorkOrderModel>)Report;
                    if (Report3 == null || Report3.Count() == 0)
                    {
                        IRow row4 = sheet.CreateRow(4);
                        row4.CreateCell(0).SetCellValue("暂无数据");
                        row4.CreateCell(1).SetCellValue("");
                        row4.CreateCell(2).SetCellValue("");
                        row4.CreateCell(3).SetCellValue("");
                        row4.CreateCell(4).SetCellValue("");
                        foreach (var item in row4.Cells)
                        {
                            item.CellStyle = rowCellStyle;
                        }
                        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(4, 4, 0, 4));
                    }
                    else
                    {
                        int seriaNum = 1;int rowsNumber = 4;
                        List<string> nameList= new List<string>();
                        foreach (var item in Report3)
                        {
                            if (item.ContentRecordList != null&&item.ContentRecordList.Count()>0)
                            {
                                int mergeRowNum = 0;
                                foreach (var index in item.ContentRecordList)
                                {
                                    if (index != null)
                                    {
                                        nameList.AddRange(index.UserName);
                                        IRow rows = sheet.CreateRow(rowsNumber);
                                        if (mergeRowNum == 0)
                                        {
                                            rows.CreateCell(0).SetCellValue(seriaNum);
                                            rows.CreateCell(1).SetCellValue(item.PatrolItem);
                                            rows.CreateCell(4).SetCellValue(item.Remark);
                                        }
                                        else
                                        {
                                            rows.CreateCell(0).SetCellValue("");
                                            rows.CreateCell(1).SetCellValue("");
                                            rows.CreateCell(4).SetCellValue("");
                                        }
                                        rows.CreateCell(2).SetCellValue(index.Name);
                                        //string tick = "\u2713"; // 对勾的Unicode编码 "✓"; // 对勾
                                        //string cross = "\u2718"; // 叉号的Unicode编码  "✘"; // 叉号
                                        string FuHao = "\u25EF"; // 输出:◯
                                        switch (index.CheckStatus)
                                        {
                                            case "3": FuHao = "\u2717"; break;
                                            case "0":
                                            case "1":
                                            case "2":
                                            case "4": FuHao = "✓"; break;
                                            default: FuHao = "\u25EF"; break;
                                        }
                                        rows.CreateCell(3).SetCellValue(FuHao);

                                        foreach (var cel in rows.Cells)
                                        {
                                            cel.CellStyle = rowCellStyle;
                                        }
                                        rowsNumber++;
                                        mergeRowNum++;
                                    }                                   
                                }
                                if (mergeRowNum > 1)
                                {
                                    sheet.AddMergedRegion(new CellRangeAddress(rowsNumber - mergeRowNum, rowsNumber - 1, 0, 0));
                                    sheet.AddMergedRegion(new CellRangeAddress(rowsNumber - mergeRowNum, rowsNumber - 1, 1, 1));
                                    sheet.AddMergedRegion(new CellRangeAddress(rowsNumber - mergeRowNum, rowsNumber - 1, 4, 4));
                                }
                                seriaNum++;
                            }
                        }

                        UserName = string.Join(";", nameList.Distinct());

                        IRow rown = sheet.CreateRow(rowsNumber);
                        rown.Height = 30 * 20;
                        rown.CreateCell(0).SetCellValue("使用部门确认:");
                        rown.CreateCell(1).SetCellValue("");
                        rown.CreateCell(2).SetCellValue("");
                        rown.CreateCell(3).SetCellValue("日期:       年     月     日");
                        rown.CreateCell(4).SetCellValue("");
                        foreach (var item in rown.Cells)
                        {
                            item.CellStyle = headCellStyle1;
                        }
                        // 合并列示例,合并第 2 行的第 0 列到第 2 列
                        sheet.AddMergedRegion(new CellRangeAddress(rowsNumber, rowsNumber, 0, 2));
                        // 合并列示例,合并第 2 行的第 3 列到第 4 列
                        sheet.AddMergedRegion(new CellRangeAddress(rowsNumber, rowsNumber, 3, 4));

                        IRow rown1 = sheet.CreateRow(rowsNumber+1);
                        rown1.CreateCell(0).SetCellValue("巡检状态说明: ✓ = 已检查且正常; ✘ = 已检查且异常; ◯ = 未检查");
                        // 合并列示例,合并第 2 行的第 0 列到第 2 列
                        sheet.AddMergedRegion(new CellRangeAddress(rowsNumber+1, rowsNumber+1, 0, 4));
                    }

                    IRow row1 = sheet.CreateRow(1);
                    row1.Height = 30 * 15;
                    row1.CreateCell(0).SetCellValue("使用部门:" + StoreName);
                    row1.CreateCell(1).SetCellValue("");
                    row1.CreateCell(2).SetCellValue("");
                    row1.CreateCell(3).SetCellValue("维保时间:" + model.D_CreateTime.ToString("yyyy年MM月dd日"));
                    row1.CreateCell(4).SetCellValue("");
                    IRow row2 = sheet.CreateRow(2);
                    row2.Height = 30 * 15;
                    row2.CreateCell(0).SetCellValue("服务公司:" + OrgName);
                    row2.CreateCell(1).SetCellValue("");
                    row2.CreateCell(2).SetCellValue("");
                    row2.CreateCell(3).SetCellValue("维保人员:"+ UserName);
                    row2.CreateCell(4).SetCellValue("");
                    foreach (var item in row1.Cells)
                    {
                        item.CellStyle = headCellStyle1;
                    }
                    foreach (var item in row2.Cells)
                    {
                        item.CellStyle = headCellStyle1;
                    }
                    // 合并列示例,合并第 2 行的第 0 列到第 2 列
                    sheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, 2));
                    // 合并列示例,合并第 2 行的第 3 列到第 4 列
                    sheet.AddMergedRegion(new CellRangeAddress(1, 1, 3, 4));
                    // 合并列示例,合并第 3 行的第 0 列到第 2 列
                    sheet.AddMergedRegion(new CellRangeAddress(2, 2, 0, 2));
                    // 合并列示例,合并第 3 行的第 3 列到第 4 列
                    sheet.AddMergedRegion(new CellRangeAddress(2, 2, 3, 4));

                }
                // 自适应单元格
                //for (int i = 4; i < sheet.LastRowNum; i++)
                //{
                //    sheet.AutoSizeRow(i);
                //}
                for (int i = 0; i < 5; i++)
                {
                    if (i == 0)
                    {
                        sheet.SetColumnWidth(i, 256 * 10);
                    }
                    else if(i==2)
                    {
                        sheet.SetColumnWidth(i, 256 * 55);
                    }
                    else if (i == 4)
                    {
                        sheet.SetColumnWidth(i, 256 * 35);
                    }
                    else
                    {
                        sheet.SetColumnWidth(i, 256 * 22);
                    }
                }
                using (MemoryStream stream = new MemoryStream())
                {
                    workbook.Write(stream);
                    byte[] data = stream.ToArray();
                    return File(data, "application/vnd.ms-excel", $"{model.C_Name}.xlsx");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("导出Excel数据异常:"+ex.Message);
            }
        }
    }
}