using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NPOI.SS.Formula;
using NPOI.Util;
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.Model.SearchModel.MTN;
using Ropin.Inspection.Service;
using Ropin.Inspection.Service.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;

namespace Ropin.Inspection.Api
{

    public class TmtnRepairOrderItemController : BaseController
    {
        public ILogger<TmtnRepairOrderItemController> _logger { get; }
        private readonly ITmtnRepairOrderItemService _TmtnRepairOrderItemService;
        private readonly ITmtnRepairOrderService _tmtnRepairOrderService;
        private readonly IPushMsgService _pushMsgService;
        private readonly ITsysUserService _tsysUserService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="TmtnRepairOrderItemService"></param>
        /// <param name="logger"></param>
        /// <param name="pushMsgService"></param>
        public TmtnRepairOrderItemController(ITmtnRepairOrderItemService TmtnRepairOrderItemService, ITsysUserService tsysUserService, ITmtnRepairOrderService tmtnRepairOrderService, IPushMsgService pushMsgService, ILogger<TmtnRepairOrderItemController> logger)
        {
            _TmtnRepairOrderItemService = TmtnRepairOrderItemService;
            _tmtnRepairOrderService = tmtnRepairOrderService;
            _logger = logger;
            _pushMsgService = pushMsgService;
            _tsysUserService = tsysUserService;
        }

        /// <summary>
        /// 通过id获取维修详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetRepairOrderItemAsync/{id}")]
        [AllowAnonymous]
        public async Task<ApiResult> GetRepairOrderItemAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _TmtnRepairOrderItemService.GetConditionAsync(new TmtnRepairOrderItemSearchModel { C_RepairCode = id });
                var repairOrder = content.FirstOrDefault();
                if (repairOrder != null)
                {
                    var user = await _tsysUserService.GetByIdAsync(repairOrder.C_CreateBy);
                    repairOrder.CreateByName = user.C_Name;
                }
                return new ApiResult<TmtnRepairOrderItemViewModel>(repairOrder);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 通过维修id获取维修详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetRepairOrderItemListAsync/{id}")]
        [AllowAnonymous]
        public async Task<ApiResult> GetRepairOrderItemListAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var repairOrders = await _TmtnRepairOrderItemService.GetConditionAsync(new TmtnRepairOrderItemSearchModel { C_RepairCode = id });
                var users = await _tsysUserService.GetAllAsync();
                if (repairOrders.Any())
                {
                    var q = from m in repairOrders
                            join n in users on m.C_CreateBy equals n.C_UserID
                            select new TmtnRepairOrderItemViewModel
                            {
                                C_ID  = m.C_ID,
                                C_RepairCode = m.C_RepairCode,
                                C_RepairRecord = m.C_RepairRecord,
                                C_Remark = m.C_Remark,
                                C_CreateBy = m.C_CreateBy,
                                D_CreateOn = m.D_CreateOn,
                                C_LastUpdatedBy = m.C_LastUpdatedBy,
                                D_LastUpdatedOn = m.D_LastUpdatedOn,
                                C_Status = m.C_Status,
                                FilePaths = m.FilePaths,
                                CreateByName = n.C_Name,
                            };
                    return new ApiResult<IEnumerable<TmtnRepairOrderItemViewModel>>(q);
                }
                return new ApiResult<IEnumerable<TmtnRepairOrderItemViewModel>>(repairOrders);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 通过维修id获取维修列表
        /// </summary>
        /// <param name="devId"></param>
        /// <param name="repairId"></param>
        /// <returns></returns>
        [HttpGet("GetRepairOrderItemViewAsync/{devId}/{repairId}")]
        public async Task<ApiResult> GetRepairOrderItemViewAsync(string devId, string repairId)
        {
            if (string.IsNullOrEmpty(devId))
                return new ApiResult(ReturnCode.GeneralError);
            if (string.IsNullOrEmpty(repairId))
                return new ApiResult(ReturnCode.GeneralError);
            try
            {
                var content = await _TmtnRepairOrderItemService.GetRepairOrderItemAsync(devId,repairId);
                return new ApiResult<TmtnRepairOrderItemDetailViewMode>(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }

        }

        /// <summary>
        /// 获取所有维修详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetRepairOrderItemsAsync")]
        public async Task<ApiResult> GetRepairOrderItemsAsync()
        {
            try
            {
                var contentList = await _TmtnRepairOrderItemService.GetAllAsync();
                return new ApiResult<IEnumerable<TmtnRepairOrderItemViewModel>>(contentList);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 通过维修详情名称条件查询
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetRepairOrderItemsByAsync")]
        public async Task<ApiResult> GetRepairOrderItemsByAsync(TmtnRepairOrderItemSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnRepairOrderItemService.GetConditionAsync(searchModel);
                return new ApiResult<PagesModel<TmtnRepairOrderItemViewModel>>(new PagesModel<TmtnRepairOrderItemViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }


        ///// <summary>
        ///// 条件查询维修详情列表包含图片
        ///// </summary>
        ///// <param name="searchModel"></param>
        ///// <returns></returns>
        //[HttpPost("GetRepairOrderItemWithImageAsync")]
        //public async Task<ApiResult> GetRepairOrderItemWithImageAsync(TmtnRepairOrderItemSearchModel searchModel)
        //{
        //    if (searchModel == null)
        //    {
        //        return new ApiResult(ReturnCode.ArgsError);
        //    }
        //    searchModel.IsPagination = false;
        //    try
        //    {
        //        var contentList = await _TmtnRepairOrderItemService.GetRepairOrderItemWithImageAsync(searchModel);
        //        return new ApiResult<PagesModel<TmtnRepairOrderItemWithImageViewModel>>(new PagesModel<TmtnRepairOrderItemWithImageViewModel>(contentList, searchModel));
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ApiResult(ReturnCode.GeneralError, ex.Message);
        //    }
        //}

        ///// <summary>
        ///// 条件查询维修详情列表包含模板图片
        ///// </summary>
        ///// <param name="searchModel"></param>
        ///// <returns></returns>
        //[HttpPost("GetRepairOrderItemRecordDetailAsync")]
        //public async Task<ApiResult> GetRepairOrderItemRecordDetailAsync(TmtnRepairOrderItemRecordSearchModel searchModel)
        //{
        //    if (searchModel == null)
        //    {
        //        return new ApiResult(ReturnCode.ArgsError);
        //    }
        //    searchModel.IsPagination = false;
        //    try
        //    {
        //        var contentList = await _TmtnRepairOrderItemService.GetRecordsConditionAsync(searchModel);
        //        return new ApiResult<PagesModel<TmtnRepairOrderItemRecordDetailViewMode>>(new PagesModel<TmtnRepairOrderItemRecordDetailViewMode>(contentList, searchModel));
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ApiResult(ReturnCode.GeneralError, ex.Message);
        //    }
        //}


        /// <summary>
        /// 创建维修详情
        /// </summary>
        /// <param name="devStoreCode"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateRepairOrderItemAsync/{devStoreCode}")]
        public async Task<ApiResult> CreateRepairOrderItemAsync(string devStoreCode, TmtnRepairOrderItemViewModel content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                //await _tmtnRepairOrderService.UpdateAsync(content.C_RepairRecord, TmtnRepairOrderItemUpdateModel updateModel);
                await _TmtnRepairOrderItemService.CreateRepairOrderItemAsync(content);
                //await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel { C_DevStoreCode = devStoreCode, C_MsgTypeCode = "MSG_TYPE_008", Msg = content.C_RepairRecord });
                await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
                {
                    C_DevStoreCode = devStoreCode,
                    C_MsgTypeCode = content.C_Status switch
                    {
                        "5" => "MSG_TYPE_007",//维修取消消息
                        "2" => "MSG_TYPE_006",//维修确认消息
                        "3" => "MSG_TYPE_014",//正在维修消息
                        "4" => "MSG_TYPE_008",//维修完成消息
                        "6" => "MSG_TYPE_015",//维修返工消息
                        "7" => "MSG_TYPE_016",//维修完成确认
                        _ => throw new NotImplementedException()
                    },
                    Subject = content.C_Status switch
                    {
                        "5" => "维修取消消息:",//维修取消消息
                        "2" => "维修确认消息:",//维修确认消息
                        "3" => "正在维修消息:",//正在维修消息
                        "4" => "维修完成消息:",//维修完成消息
                        "6" => "维修返工消息:",//维修返工消息
                        "7" => "维修完成确认:",//维修完成确认
                        _ => throw new NotImplementedException()
                    },
                    Msg = content.C_RepairRecord,
                    DevNumber = "",
                    DevName = "",
                    GenerationType = 2,
                    msgStatus = 0,
                },"设备维修");
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 删除维修详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteRepairOrderItemAsync/{id}")]
        public async Task<ApiResult> DeleteRepairOrderItemAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnRepairOrderItemService.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("UpdateRepairOrderItemAsync/{id}")]
        public async Task<ApiResult> UpdateRepairOrderItemAsync(string id, TmtnRepairOrderItemUpdateModel updateModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnRepairOrderItemService.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("SendEmilOrderItem")]
        [AllowAnonymous]
        public async Task<ApiResult> SendEmilOrderItem(SendRepairRecordToEmailModel searchModel)
        {
            try
            {
                if (searchModel == null && string.IsNullOrEmpty(searchModel.C_ID))
                {
                    return new ApiResult(ReturnCode.ArgsError, "请输入参数");
                }
                var repairOrders = await _TmtnRepairOrderItemService.GetConditionAsync(new TmtnRepairOrderItemSearchModel { C_RepairCode = searchModel.C_ID });
                var users = await _tsysUserService.GetAllAsync();
                List< TmtnRepairOrderItemViewModel > dataList=new List< TmtnRepairOrderItemViewModel >();
                if (repairOrders.Any())
                {
                    var q = from m in repairOrders
                            join n in users on m.C_CreateBy equals n.C_UserID
                            select new TmtnRepairOrderItemViewModel
                            {
                                C_ID = m.C_ID,
                                C_RepairCode = m.C_RepairCode,
                                C_RepairRecord = m.C_RepairRecord,
                                C_Remark = m.C_Remark,
                                C_CreateBy = m.C_CreateBy,
                                D_CreateOn = m.D_CreateOn,
                                C_LastUpdatedBy = m.C_LastUpdatedBy,
                                D_LastUpdatedOn = m.D_LastUpdatedOn,
                                C_Status = m.C_Status,
                                FilePaths = m.FilePaths,
                                CreateByName = n.C_Name,
                            };
                    dataList=q.ToList();
                }

                string zip = @"wwwroot\\ZipFile";
                if (!System.IO.Directory.Exists(zip))
                {
                    Directory.CreateDirectory(zip);
                }
                string zipPaht = zip + $"\\{searchModel.C_ID}维修详情下载.zip";
                if (dataList.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 dataList)
                    {
                        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;
                        //0=禁用(删除) 1 = 报修(故障上报) 5 = 维修取消 2 = 维修确认 3 = 正在维修 4 = 维修完成 6 = 故障修复(维修返工) 7 = 维修完成确认
                        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("    维修人员:" + recordItem.CreateByName);
                        run.AddCarriageReturn();
                        run.AppendText("    现场描述:" + recordItem.C_Remark);
                        run.AddCarriageReturn();
                        run.AppendText("    现场记录:" + recordItem.C_RepairRecord);
                        if (recordItem.FilePaths != null && recordItem.FilePaths.Count() > 0)
                        {
                            run.AddCarriageReturn();
                            run.AppendText("    现场拍照:");
                            foreach (var path in recordItem.FilePaths)
                            {
                                string pathFile = path;
                                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_ID}维修详情.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);
            }
        }
    }
}