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.Infrastructure.Core;
using APT.MS.Domain.Entities.DM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.DM
{
    [Route("api/DM/DMDeviceMaintenanceCheck")]
    public class DMDeviceMaintenanceCheckController : AuthorizeApiController<T_DM_DEVICE_MAINTENANCE_CHECK>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        public DMDeviceMaintenanceCheckController(IFMNotificationTaskService notificationTaskService, IPFApproveCallBackService approveCallBackService, IFMFlowPermitService mflowPermitService)
        {
            NotificationTaskService = notificationTaskService;
            ApproveCallBackService = approveCallBackService;
            MFlowPermitService = mflowPermitService;
        }
        /// <summary>
        /// 设备设施维保计划 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_DM_DEVICE_MAINTENANCE_CHECK entity)
        {
            return SafeExecute<bool>(() =>
            {
                var ListUser = entity.Nav_ListUser;
                entity.Nav_ListUser = null;
                var ListDetail = entity.Nav_ListDetail;
                entity.Nav_ListDetail = null;
                T_FM_NOTIFICATION_TASK task = null;
                List<T_FM_NOTIFICATION_TASK> listTask = null;
                List<T_DM_DEVICE_MAINTENANCE_CHECK_DETAIL_FILE> files = new List<T_DM_DEVICE_MAINTENANCE_CHECK_DETAIL_FILE>();
                List<Guid> deleteIds = new List<Guid>();
                var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        loginID = currTask.USER_ID;
                    }
                }
                if (ListUser != null && ListUser.Any())
                {
                    ListUser.ForEach(t => { t.Nav_User = null;t.ORG_ID = entity.ORG_ID;t.CHECK_ID = entity.ID; });
                }
                if (ListDetail != null && ListDetail.Any())
                {
                    var detailIds = new List<Guid>();
                    foreach (var item in ListDetail)
                    {
                        detailIds.Add(item.ID);
                        if (item.Nav_Files!=null && item.Nav_Files.Any())
                        {
                            foreach (var itemFile in item.Nav_Files)
                            {
                                T_DM_DEVICE_MAINTENANCE_CHECK_DETAIL_FILE file = new T_DM_DEVICE_MAINTENANCE_CHECK_DETAIL_FILE();
                                file.ORG_ID = entity.ORG_ID;
                                file.IMG_FILE_ID = itemFile.IMG_FILE_ID;
                                file.DEVICE_MAINTENANCE_CHECK_DETAIL_ID = item.ID;
                                file.ID = Guid.NewGuid();
                                files.Add(file);
                            }
                        }
                    }
                    deleteIds = this.GetEntities<T_DM_DEVICE_MAINTENANCE_CHECK_DETAIL_FILE>(t => detailIds.Contains(t.DEVICE_MAINTENANCE_CHECK_DETAIL_ID), new BaseFilter(entity.ORG_ID)).Select(t => t.ID).ToList();
                }
                if (entity.STATUS_APPROVE != PFStandardStatus.Draft)
                {
                    int rowIndex = 1;
                    foreach (var item in ListDetail)
                    {
                        if (item.Result == null)
                        {
                            throw new Exception("请填写行：【" + rowIndex + "】的维保情况！");
                        }
                        rowIndex++;
                    }

                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetEntityTask(entity.TaskID, "DM030_SHOWPRINT");
                    }
                    //给其余人 确认
                    List<Guid> UserId = new List<Guid>();
                    foreach (var item in ListUser)
                    {
                        if (item.USER_ID != loginID)
                        {
                            UserId.Add(item.USER_ID);
                        }
                        else
                        {
                            item.ISCHECK = true;
                        }
                    }
                    var userName = this.GetEntities<T_FM_USER>(t => UserId.Contains(t.ID), new BaseFilter(entity.ORG_ID)).Select(m => m.NAME).ToList();
                    listTask = NotificationTaskService.InsertUserNoticeTaskModels("设备设施维保记录确认", entity.ID, entity.ORG_ID, UserId, userName, DateTime.Now, DateTime.Now.AddDays(1), 1, "DM030_SHOWPRINT");
                }

                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (ListDetail != null && ListDetail.Any())
                        BantchSaveEntityNoCommit(ListDetail);
                    if (deleteIds != null && deleteIds.Any())
                        BantchDeleteEntityNoCommit<T_DM_DEVICE_MAINTENANCE_CHECK_DETAIL_FILE>(deleteIds);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (ListUser != null && ListUser.Any())
                        BantchSaveEntityNoCommit(ListUser);
                    if (listTask != null && listTask.Any())//结束待办
                        BantchSaveEntityNoCommit(listTask);
                });
                return true;
            });
        }



        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetShow")]
        public JsonActionResult<T_DM_DEVICE_MAINTENANCE_CHECK> Get([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var check = GetEntity<T_DM_DEVICE_MAINTENANCE_CHECK>(null, filter, null);
                if (check != null && check.STATUS_APPROVE == PFStandardStatus.Draft)
                {
                    check.CHECKDATETIME = DateTime.Now;
                }
                if (check.Nav_ListUser != null && check.Nav_ListUser.Any())
                {
                    check.Nav_ListUser = check.Nav_ListUser.OrderByDescending(e => e.ISMAIN).ToList();
                }
                return check;
            });
        }

        /// <summary>
        /// 点检人 确认
        /// </summary>
        [HttpPost, Route("Check")]
        public JsonActionResult<bool> Check([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(filter.Keyword) || string.IsNullOrEmpty(filter.Parameter1))
                {
                    throw new Exception("传参有误！");
                }
                var guid = new Guid(filter.Keyword);
                var taskID = new Guid(filter.Parameter1);
                if (guid == Guid.Empty || taskID == Guid.Empty)
                {
                    throw new Exception("传参有误！");
                }
                var task = NotificationTaskService.GetEntityTask(taskID);

                var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                T_DM_DEVICE_MAINTENANCE_CHECK check = null;
                var CheckUser = GetEntity<T_DM_DEVICE_MAINTENANCE_CHECK_USER>(e => e.USER_ID == loginID && e.CHECK_ID == guid);

                if (CheckUser == null)
                {
                    //记录人 上级 确认
                    this.UnifiedCommit(() =>
                    {
                        if (task != null)
                            UpdateEntityNoCommit(task);
                    });

                    throw new Exception("未找到需要您确认的信息！");
                }
                else if (CheckUser.ISCHECK)
                {
                    this.UnifiedCommit(() =>
                    {
                        if (task != null)
                            UpdateEntityNoCommit(task);
                    });
                    throw new Exception("您已审阅,无需再次操作！");
                }
                else
                {
                    CheckUser.ISCHECK = true;
                    CheckUser.CHECKTIME = DateTime.Now;
                    var UnCheck = GetEntity<T_DM_DEVICE_MAINTENANCE_CHECK_USER>(e => e.USER_ID != loginID && e.CHECK_ID == guid && !e.ISCHECK);
                    List<T_FM_NOTIFICATION_TASK> ListTask = null;

                    if (UnCheck == null)
                    {
                        //check = GetEntity<T_DM_DEVICE_MAINTENANCE_CHECK>(guid, "Nav_ListDetail.Nav_DeviceBase.Nav_User");
                        check = GetEntity<T_DM_DEVICE_MAINTENANCE_CHECK>(guid, "Nav_User");
                        check.STATUS_APPROVE = PFStandardStatus.Approving;

                        //设备设施库 管理责任人员审阅 
                        //List<Guid> listUserId = new List<Guid>();
                        //List<string> listUserName = new List<string>();

                        //foreach (var item in check.Nav_ListDetail)
                        //{
                        //    if (item.Nav_DeviceBase.USER_ID.HasValue && !listUserId.Contains(item.Nav_DeviceBase.USER_ID.Value))
                        //    {
                        //        listUserId.Add(item.Nav_DeviceBase.USER_ID.Value);
                        //        listUserName.Add(item.Nav_DeviceBase.Nav_User.NAME);
                        //    }
                        //}

                        if (check.USER_ID.HasValue)
                        {
                            //listUserId.Add(check.USER_ID.Value);
                            //listUserName.Add(check.Nav_User.NAME);

                            //ListTask = NotificationTaskService.InsertUserNoticeTaskModels("设备设施维保确认", guid, CheckUser.ORG_ID, listUserId, listUserName, DateTime.Now, DateTime.Now.AddDays(1), 1, "DM030_SHOWPRINT");

                            //添加 审批流
                            check.APPROVE_ID = Guid.NewGuid();
                            //Dictionary<int, T_FM_USER> dicApproveUser = new Dictionary<int, T_FM_USER>();
                            //dicApproveUser.Add(1, check.Nav_User);

                            MFlowPermitService.InsertApprove("WB" + DateTime.Now.ToString("yyyyMMddHHmmss"), "DM030", null, check.ID, "DM030_SHOWPRINT", null, true, () =>
                               {
                                   if (task != null)
                                       UpdateEntityNoCommit(task);
                                   if (CheckUser != null)
                                       UpdateEntityNoCommit(CheckUser);
                                   if (ListTask != null && ListTask.Any())//给设备管理员 发送审阅
                                      BantchSaveEntityNoCommit(ListTask);
                                   if (check != null)//状态修改
                                      UpdateEntityNoCommit(check);

                               }, check.APPROVE_ID, check.USER_ID, null, null, null, "DM030_SHOWPRINT");//dicApproveUser

                        }
                        else
                        {
                            check.STATUS_APPROVE = PFStandardStatus.Archived;//如果没有找到负责人 
                            this.UnifiedCommit(() =>
                            {
                                if (task != null)
                                    UpdateEntityNoCommit(task);
                                if (CheckUser != null)
                                    UpdateEntityNoCommit(CheckUser);
                                if (ListTask != null && ListTask.Any())//给设备管理员 发送审阅
                                    BantchSaveEntityNoCommit(ListTask);
                                if (check != null)//状态修改
                                    UpdateEntityNoCommit(check);
                            });
                        }
                    }
                    else
                    {
                        //还有别人未 确认
                        this.UnifiedCommit(() =>
                        {
                            if (task != null)
                                UpdateEntityNoCommit(task);
                            if (CheckUser != null)
                                UpdateEntityNoCommit(CheckUser);
                            if (ListTask != null && ListTask.Any())//给设备管理员 发送审阅
                                BantchSaveEntityNoCommit(ListTask);
                            if (check != null)//状态修改
                                UpdateEntityNoCommit(check);
                        });
                    }
                }
                return true;
            });
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("Audit")]
        public JsonActionResult<bool> Audit(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("DM/DMDeviceMaintenanceCheck/Audit", id);
            });
        }

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

            });
        }
    }
}