
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.DM;
using APT.MS.Domain.Entities.SC.DM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Castle.Core;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.SC.WebApi.Controllers.Api.DM
{
    [Route("api/DM/DMDeviceOverhaul")]
    public class DeviceOverhaulController : AuthorizeApiController<T_DM_DEVICE_OVERHAUL>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public DeviceOverhaulController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("FullGet")]
        public JsonActionResult<T_DM_DEVICE_OVERHAUL> FullGet([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var entity = this.GetEntity<T_DM_DEVICE_OVERHAUL>(id,
                        "Nav_Device", "Nav_User", "Nav_Repair.Nav_Files", "Nav_Repair.Nav_User", "Nav_Repair.Nav_Files.Nav_ImgFile", "Nav_Files", "Nav_Files.Nav_ImgFile");
                if (entity != null)
                {
                    if (entity.Nav_Repair != null && entity.Nav_Repair.Nav_Files.Any())
                        entity.Nav_RepairFiles = entity.Nav_Repair.Nav_Files;
                   
                }

                return entity;
            });
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody]T_DM_DEVICE_OVERHAUL entity)
        {
            return SafeExecute<bool>(() =>
            {
                var files = entity.Nav_Files; 
                entity.Nav_Files = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK finishNotice = null;
                T_DM_DEVICE_BASE_OVERHAUL overhaul=null;
                List<T_DM_DEVICE_BASE_OVERHAUL_FILE> overhaulFiles = new List<T_DM_DEVICE_BASE_OVERHAUL_FILE>();

                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID,entity.ID, "DM021_SHOWPRINT");
                    if (entity.STATUS== PFStandardStatus.Draft)
                    {
                        entity.STATUS = PFStandardStatus.Sign;
                        var repair = GetEntity<T_DM_DEVICE_REPAIR>(entity.REPAIR_ID.Value);
                        if (repair != null)
                        {
                            var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("设备设施检修记录-"+entity.MACHINE_NAME+"-待验收", entity.ID, entity.ORG_ID, (Guid)repair.USER_ID, GetEntity<T_FM_USER>(repair.USER_ID.Value).NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "DM022");
                            sendNotices.Add(sendNotice);
                        }
                    }
                    else if (entity.STATUS == PFStandardStatus.Sign)
                    {
                        if (entity.CHECK_OPINION == MS.Domain.Enums.CheckOptionEnum.通过)
                        {
                            entity.STATUS = PFStandardStatus.Reading;
                            overhaul = new T_DM_DEVICE_BASE_OVERHAUL
                            {
                                ID = Guid.NewGuid(),
                                ORG_ID = entity.ORG_ID,
                                DEVICE_BASE_ID = (Guid)entity.DEVICE_BASE_ID,
                                OVERHAUL_TIME = entity.OVERHAUL_TIME,
                                MALFUCTION = entity.MALFUCTION,
                                DESCRIPTION = entity.DESCRIPTION,
                                USER_ID = entity.USER_ID,
                                EXTERNAL_SUPPORT = entity.EXTERNAL_SUPPORT,
                            };
                            foreach (var item in files)
                            {
                                var newFile = new T_DM_DEVICE_BASE_OVERHAUL_FILE
                                {
                                    FILE_PARENT_ID = overhaul.ID,
                                    IMG_FILE_ID = item.IMG_FILE_ID,
                                    ORG_ID = item.ORG_ID,
                                };
                                overhaulFiles.Add(newFile);
                            }
                            var repair = GetEntity<T_DM_DEVICE_REPAIR>(entity.REPAIR_ID.Value, "Nav_User");
                            if (repair != null)
                            {
                                if (repair.Nav_User!=null && repair.Nav_User.DEPARTMENT_ID!=null)
                                {
                                    var repairUser = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == repair.Nav_User.DEPARTMENT_ID && t.USER_ID != null);
                                    if (repairUser != null)
                                    {
                                        var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("设备设施检修记录审阅-" + entity.MACHINE_NAME, entity.ID, entity.ORG_ID, (Guid)repairUser.USER_ID, GetEntity<T_FM_USER>(repairUser.USER_ID.Value).NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "DM021_SHOWPRINT");
                                        sendNotices.Add(sendNotice);
                                    }
                                }
                            }
                            if (entity.USER_ID != null)
                            {
                                var entityUser = this.GetEntity<T_FM_USER>(t => t.ID == entity.USER_ID);
                                var overhUser = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entityUser.DEPARTMENT_ID && t.USER_ID != null);
                                if (overhUser != null)
                                {
                                    var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("设备设施检修记录审阅-" + entity.MACHINE_NAME, entity.ID, entity.ORG_ID, (Guid)overhUser.USER_ID, GetEntity<T_FM_USER>(overhUser.USER_ID.Value).NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "DM021_SHOWPRINT");
                                    sendNotices.Add(sendNotice);
                                }
                            }
                        }
                        else
                        {
                            entity.STATUS = PFStandardStatus.Draft;
                            entity.CHECK_OPINION = MS.Domain.Enums.CheckOptionEnum.通过;
                            if (entity.USER_ID != null)
                            {
                                var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("设备设施检修记录-" + entity.MACHINE_NAME, entity.ID, entity.ORG_ID, (Guid)entity.USER_ID, GetEntity<T_FM_USER>(entity.USER_ID.Value).NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "DM022");
                                sendNotices.Add(sendNotice);
                            }
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    UpdateEntity(entity);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (sendNotices != null && sendNotices.Any())
                        BantchSaveEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if(overhaul!=null)
                        AddEntityNoCommit(overhaul);
                    if(overhaulFiles!=null&&overhaulFiles.Any())
                        BantchAddEntityNoCommit(overhaulFiles);
                });
                return true;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_DM_DEVICE_OVERHAUL> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_DM_DEVICE_OVERHAUL> result)
            {
                var xxx = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "DEVICE_BASE_ID");
                if (xxx != null)
                {
                    var deviceInspection = this.GetEntity<T_DM_DEVICE_OVERHAUL>(xxx.Value.ToString());
                    pageFilter.FilterGroup = new FilterGroup();
                    PagedActionResult<T_DM_DEVICE_OVERHAUL> orderPageEntities = GetOrderPageEntities<T_DM_DEVICE_OVERHAUL>(t => t.DEVICE_BASE_ID == deviceInspection.DEVICE_BASE_ID && t.STATUS == PFStandardStatus.Archived, pageFilter, null);
                    result.Data = orderPageEntities.Data;
                    result.TotalCount = orderPageEntities.TotalCount;
                }
                else
                {
                    PagedActionResult<T_DM_DEVICE_OVERHAUL> orderPageEntities = GetOrderPageEntities<T_DM_DEVICE_OVERHAUL>(null, pageFilter, null);
                    result.Data = orderPageEntities.Data;
                    result.TotalCount = orderPageEntities.TotalCount;
                }

            });
        }

        /// <summary>
        /// 部门级负责人审阅
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_DM_DEVICE_OVERHAUL entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK finishNotice = null;
                var model = this.GetEntity<T_DM_DEVICE_OVERHAUL>(entity.ID);
                var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_DATA_ID == entity.ID && t.ID != entity.TaskID && t.NOTICE_STATUS == 0);
                if (task == null)
                {
                    entity.STATUS = PFStandardStatus.Archived;
                }
                if (entity.TaskID != Guid.Empty)
                {
                    finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "DM021_SHOWPRINT");
                }
                UnifiedCommit(() =>
                {
                    if (model != null)
                        this.UpdateEntityNoCommit(model);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
    }
}
