using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.AE;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.DM;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.SC.DM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using NPOI.POIFS.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.DM
{
    [Route("api/DM/DMDeviceBase")]
    public class DMDeviceBaseController : AuthorizeApiController<T_DM_DEVICE_BASE>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public DMDeviceBaseController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 设备设施维保计划 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_DM_DEVICE_BASE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var Files = entity.Nav_Files;
                entity.Nav_Files = null;
                var receiptFiles = entity.Nav_ReceiptFiles;
                entity.Nav_ReceiptFiles = null;
                entity.Nav_ListCheck = null;
                entity.Nav_ListCheckCircle = null;
                entity.Nav_Overhaul = null;
                entity.Nav_Inspection = null;
                var device = this.GetEntity<T_DM_DEVICE>(t=>t.NAME == entity.NAME);
                if (device != null)
                {
                    entity.DEVICE_ID = device.ID;
                }
                //List<T_DM_DEVICE_BASE_CHECK_USER> listCheckUser = new List<T_DM_DEVICE_BASE_CHECK_USER>();
                //int RowIndex = 1;
                //if (ListCheck != null && ListCheck.Any())
                //{
                //    foreach (var item in ListCheck)
                //    {
                //        item.CHECKTYPE = CheckType.Check;

                //        #region   周期判断
                //        if (item.DATA == 0)
                //        {
                //            item.DATA = null;
                //        }
                //        if (item.PLANCHECKFREQUENCY == null)
                //        {
                //            throw new Exception("点检周期行：【" + RowIndex + "】不能为空！");
                //        }
                //        else if (item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Week)
                //        {
                //            if (item.WEEKDATA == null)
                //            {
                //                throw new Exception("点检明细行：【" + RowIndex + "】【星期】不能为空！");
                //            }
                //            if (item.DATA != null)
                //            {
                //                throw new Exception("点检明细行：【" + RowIndex + "】【日】不能填写！");
                //            }
                //        }
                //        else if (item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Date)
                //        {
                //            if (item.WEEKDATA != null)
                //            {
                //                throw new Exception("点检明细行：【" + RowIndex + "】【星期】不能填写！");
                //            }
                //            if (item.DATA != null)
                //            {
                //                throw new Exception("点检明细行：【" + RowIndex + "】【日】不能填写！");
                //            }
                //        }
                //        else if (item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Quarter || item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Month || item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Year || item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.HalfYear)//OneTime
                //        {
                //            if (item.WEEKDATA != null)
                //            {
                //                throw new Exception("点检明细行：【" + RowIndex + "】【星期】不能填写！");
                //            }
                //            if (item.DATA == null)
                //            {
                //                throw new Exception("点检明细行：【" + RowIndex + "】【日】不能为空！");
                //            }
                //            if (item.DATA.Value < 1)
                //            {
                //                throw new Exception("点检明细行：【" + RowIndex + "】【日】必须大于零！");
                //            }
                //        }
                //        #endregion

                //        if (item.Nav_ListUser != null && item.Nav_ListUser.Any())
                //        {
                //            List<T_DM_DEVICE_BASE_CHECK_USER> listCheckUserTemp = item.Nav_ListUser.ToList();
                //            listCheckUserTemp[0].ISMAIN = true;
                //            listCheckUser.AddRange(listCheckUserTemp);
                //        }
                //        RowIndex++;
                //    }
                //}
                //if (ListCheckCircle != null && ListCheckCircle.Any())
                //{
                //    RowIndex = 1;
                //    foreach (var item in ListCheckCircle)
                //    {
                //        item.CHECKTYPE = CheckType.CheckCircuit;

                //        #region     周期判断
                //        if (item.DATA == 0)
                //        {
                //            item.DATA = null;
                //        }
                //        if (item.PLANCHECKFREQUENCY == null)
                //        {
                //            throw new Exception("巡检周期行：【" + RowIndex + "】不能为空！");
                //        }
                //        else if (item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Week)
                //        {
                //            if (item.WEEKDATA == null)
                //            {
                //                throw new Exception("巡检明细行：【" + RowIndex + "】【星期】不能为空！");
                //            }
                //            if (item.DATA != null)
                //            {
                //                throw new Exception("巡检明细行：【" + RowIndex + "】【日】不能填写！");
                //            }
                //        }
                //        else if (item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Date)
                //        {
                //            if (item.WEEKDATA != null)
                //            {
                //                throw new Exception("巡检明细行：【" + RowIndex + "】【星期】不能填写！");
                //            }
                //            if (item.DATA != null)
                //            {
                //                throw new Exception("巡检明细行：【" + RowIndex + "】【日】不能填写！");
                //            }
                //        }
                //        else if (item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Quarter || item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Month || item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.Year|| item.PLANCHECKFREQUENCY.Value == BSPLANCHECKFREQUENCYEnum.HalfYear)
                //        {
                //            if (item.WEEKDATA != null)
                //            {
                //                throw new Exception("巡检明细行：【" + RowIndex + "】【星期】不能填写！");
                //            }
                //            if (item.DATA == null)
                //            {
                //                throw new Exception("巡检明细行：【" + RowIndex + "】【日】不能为空！");
                //            }
                //        }

                //        #endregion

                //        if (item.Nav_ListUser != null && item.Nav_ListUser.Any())
                //        {
                //            List<T_DM_DEVICE_BASE_CHECK_USER> listCheckUserTemp = item.Nav_ListUser.ToList();
                //            listCheckUserTemp[0].ISMAIN = true;
                //            listCheckUser.AddRange(listCheckUserTemp);
                //        }
                //    }
                //}
                //发起设备申购记录表
                //T_FM_NOTIFICATION_TASK task = null;
                //T_DM_DEVICE_BASE_PURCHASE purchase = null;
                //List<T_DM_DEVICE_BASE_PURCHASE_DETAIL> purchaseDetails = new List<T_DM_DEVICE_BASE_PURCHASE_DETAIL>();
                //if (entity.USE_USER_POST_ID != null && entity.USE_DEPARTMENT_ID != null)
                //{
                //    var user = this.GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == entity.USE_DEPARTMENT_ID && t.Nav_Person != null && t.Nav_Person.POST_ID == entity.USE_USER_POST_ID && t.ENABLE_STATUS == 0);
                //    if (user != null)
                //    {
                //        purchase = new T_DM_DEVICE_BASE_PURCHASE();
                //        purchase.CODE = DateTime.Now.Year.ToString().PadLeft(4, '0') + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0') + new Random().Next().ToString();
                //        purchase.ORG_ID = user.ORG_ID;
                //        purchase.USER_ID = user.ID;
                //        purchase.DEPARTMENT_ID = user.DEPARTMENT_ID;
                //        purchase.MineType = int.Parse(user.MineType?.Split(",")[0]);
                //        T_DM_DEVICE_BASE_PURCHASE_DETAIL detail = new T_DM_DEVICE_BASE_PURCHASE_DETAIL();
                //        detail.ORG_ID = user.ORG_ID;
                //        detail.DEVICE_PURCHASE_ID = purchase.ID;
                //        detail.DEVICE_BASE_ID = entity.ID;
                //        detail.CATEGORY_ID = entity.CATEGORY_ID;
                //        detail.TYPE_ID = entity.TYPE_ID;
                //        detail.IS_EMERGENCY = entity.IS_EMERGENCY;
                //        detail.SPEC = entity.SPEC;
                //        detail.QTY = entity.QTY;
                //        detail.UNIT = entity.UNIT;
                //        purchaseDetails.Add(detail);
                //        task = NotificationTaskService.InsertUserNoticeTaskModel("设备设施申购表", purchase.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(30), (int)FMNoticeTypeEnum.消息, "DM034");
                //    }
                //}
                //if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                //{
                //    if (entity.TaskID != Guid.Empty)
                //    {
                //        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                //        task.SOURCE_FORMCODE = "DM002_SHOWPRINT";
                //    }
                //}
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (Files != null && Files.Any())//维保工作方案
                        BantchSaveEntityNoCommit(Files);
                    if (receiptFiles != null && receiptFiles.Any())//维保工作方案
                        BantchSaveEntityNoCommit(receiptFiles);
                    //if (ListCheck != null && ListCheck.Any())//维保工作方案
                    //    BantchSaveEntityNoCommit(ListCheck);
                    //if (ListCheckCircle != null && ListCheckCircle.Any())//维保工作方案
                    //    BantchSaveEntityNoCommit(ListCheckCircle);
                    //if (Purchases != null && Purchases.Any())//维保工作方案
                    //    BantchSaveEntityNoCommit(Purchases);
                    //if (listCheckUser != null && listCheckUser.Any())//检查人
                    //    BantchSaveEntityNoCommit(listCheckUser);
                    //if (sendNotice != null)
                    //    AddEntityNoCommit(sendNotice);
                    //if (task != null)
                    //    this.UpdateEntityNoCommit(task);
                    //if (purchase != null)
                    //    this.UpdateEntityNoCommit(purchase);
                    //if (purchaseDetails != null && purchaseDetails.Any())
                    //    BantchSaveEntityNoCommit(purchaseDetails);
                });

                return true;
            });
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetShow")]
        public JsonActionResult<T_DM_DEVICE_BASE> GetShow([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var result = this.GetEntity<T_DM_DEVICE_BASE>(id, new string[] { "Nav_Category", "Nav_User","Nav_Type",
            "Nav_Department","Nav_Files","Nav_Files.Nav_ImgFile","Nav_ReceiptFiles","Nav_ReceiptFiles.Nav_ImgFile","Nav_UseDepartment","Nav_UserPost","Nav_UseUserPost" });
                //var result = GetEntity<T_DM_DEVICE_BASE>(null, filter, null);
                if (result != null)
                {
                    //采购记录
                    var devicePurchase = this.GetEntity<T_DM_DEVICE_PURCHASE_DETAIL>(t => t.DEVICE_PURCHASE_ID == result.DEVICE_PURCHASE_ID);
                    if (devicePurchase != null)
                    {
                        result.Nav_PurchaseDetails = new List<T_DM_DEVICE_PURCHASE_DETAIL>();
                        result.Nav_PurchaseDetails.Add(devicePurchase);
                    }
                    //设备点检巡检
                    var deviceRuns = this.GetEntities<T_DM_TIME_RUN>(t => t.ENABLE_STATUS == 0 && t.DEVICE_BASE_ID == result.ID, new BaseFilter(result.ORG_ID), "Nav_Contents");
                    //点检
                    var deviceChek = deviceRuns.FirstOrDefault(t => t.SET_TYPE == DMSetTypeEnum.Check);
                    if (deviceChek != null)
                    {
                        if (deviceChek.Nav_Contents != null && deviceChek.Nav_Contents.Any())
                        {
                            var positions = deviceChek.Nav_Contents.Select(t => t.POSITION).ToList();
                            var standards = deviceChek.Nav_Contents.Select(t => t.STANDARD).ToList();
                            var contents = deviceChek.Nav_Contents.Select(t => t.CONTENT).ToList();
                            deviceChek.positons = String.Join(",", positions);
                            deviceChek.standards = String.Join(",", standards);
                            deviceChek.contents = String.Join(",", contents);
                            result.Nav_Check = deviceChek.Nav_Contents.ToList();
                        }
                    }
                    //巡检
                    var deviceCheckCircuit = deviceRuns.FirstOrDefault(t => t.SET_TYPE == DMSetTypeEnum.CheckCircuit);
                    if (deviceCheckCircuit != null)
                    {
                        if (deviceCheckCircuit.Nav_Contents != null && deviceCheckCircuit.Nav_Contents.Any())
                        {
                            var positions = deviceChek.Nav_Contents.Select(t => t.POSITION).ToList();
                            var standards = deviceChek.Nav_Contents.Select(t => t.STANDARD).ToList();
                            var contents = deviceChek.Nav_Contents.Select(t => t.CONTENT).ToList();
                            deviceCheckCircuit.positons = String.Join(",", positions);
                            deviceCheckCircuit.standards = String.Join(",", standards);
                            deviceCheckCircuit.contents = String.Join(",", contents);
                            result.Nav_CheckCircuit = deviceCheckCircuit.Nav_Contents.ToList();
                        }
                    }
                    var newFilter = new KeywordFilter();
                    newFilter.OrgId = filter.OrgId;
                    DataOrder order1 = new DataOrder();
                    order1.Field = "CREATE_TIME";
                    order1.Order = DbOrder.DESC;
                    newFilter.Orders.Add(order1);
                    //维保记录
                    var deviceMaintenances = this.GetEntities<T_DM_DEVICE_MAINTENANCE_PLAN_DETAIL>(t => t.DEVICEBASE_ID == result.ID, newFilter);
                    if (deviceMaintenances != null && deviceMaintenances.Any())
                    {
                        foreach (var item in deviceMaintenances)
                        {
                            switch (item.PLANCHECKFREQUENCY)
                            {
                                case BSPLANCHECKFREQUENCYEnum.Year:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddYears(1);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.HalfYear:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddMonths(6);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.Date:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddDays(1);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.Week:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddDays(7);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.Month:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddMonths(1);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.Quarter:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddMonths(3);
                                    break;
                                default:
                                    break;
                            }
                        }
                        result.Nav_Maintenance = deviceMaintenances.ToList();
                    }
                    //检修记录
                    var deviceOverhauls = this.GetEntities<T_DM_DEVICE_OVERHAUL>(t => t.DEVICE_BASE_ID == result.ID, newFilter);
                    if (deviceOverhauls != null && deviceOverhauls.Any())
                    {
                        result.Nav_OverhaulNew = deviceOverhauls.ToList();
                    }
                    //检测检验
                    var deviceInspections = this.GetEntities<T_DM_DETECTION_INSPECTION_RECORD>(t => t.DEVICE_BASE_ID == result.ID, newFilter);
                    if (deviceInspections != null && deviceInspections.Any())
                    {
                        foreach (var item in deviceInspections)
                        {
                            switch (item.PLANCHECKFREQUENCY)
                            {
                                case BSPLANCHECKFREQUENCYEnum.Year:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddYears(1);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.HalfYear:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddMonths(6);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.Date:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddDays(1);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.Week:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddDays(7);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.Month:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddMonths(1);
                                    break;
                                case BSPLANCHECKFREQUENCYEnum.Quarter:
                                    item.NEXT_DATE = item.CREATE_TIME.Value.AddMonths(3);
                                    break;
                                default:
                                    break;
                            }
                        }
                        result.Nav_InspectionNew = deviceInspections.ToList();
                    }
                    //报废记录
                    var deviceScrap = this.GetEntity<T_DM_DEVICE_SCRAP>(t => t.DEVICEBASE_ID == result.ID, newFilter);
                    if (deviceScrap != null)
                    {
                        result.Nav_Scrap = new List<T_DM_DEVICE_SCRAP>();
                        result.Nav_Scrap.Add(deviceScrap);
                    }
                    //foreach (var item in result.Nav_ListCheck)
                    //{
                    //    if (item.Nav_ListUser != null && item.Nav_ListUser.Any())
                    //    {
                    //        item.Nav_ListUser = item.Nav_ListUser.OrderByDescending(e => e.ISMAIN).ToList();
                    //    }
                    //}

                    //result.Nav_ListCheckCircle = result.Nav_ListCheck.Where(e => e.CHECKTYPE == CheckType.CheckCircuit).ToList();

                    //result.Nav_ListCheck = result.Nav_ListCheck.Where(e => e.CHECKTYPE == CheckType.Check).ToList();
                }
                return result;
            });
        }
    }
}