using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
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.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.DM;
using APT.MS.Domain.Enums;
using APT.Utility;
using ICSharpCode.SharpZipLib.Core;
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/DMDeviceMaintenancePlan")]
    public class DMDeviceMaintenancePlanController : AuthorizeApiController<T_DM_DEVICE_MAINTENANCE_PLAN>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        public DMDeviceMaintenancePlanController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }

        /// <summary>
        /// 设备设施维保计划 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_DM_DEVICE_MAINTENANCE_PLAN entity)
        {
            return SafeExecute<bool>(() =>
            {
                var Files = entity.Nav_Files;
                entity.Nav_Files = null;
                var details = entity.Nav_PlanDetails;
                entity.Nav_PlanDetails = null;
                T_FM_NOTIFICATION_TASK listTask = null;
                var another = new List<T_FM_NOTIFICATION_TASK>();
                var loginUserId = 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)
                    {
                        loginUserId = currTask.USER_ID;
                    }
                }
                entity.USER_ID = loginUserId;
                entity.DEPARTMENT_ID = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.ID == (Guid)loginUserId)?.DEPARTMENT_ID;
                if (details != null && details.Any())
                {
                    var item = details.FirstOrDefault(t => t.RUNSETTIME == DateTime.Parse("0001-01-01 00:00:00"));
                    if (item != null)
                        throw new Exception("开始时间不能是0001-01-01 00:00:00，请重新选择时间！");
                    details.ForEach(t => { t.DEPARTMENT_ID = entity.DEPARTMENT_ID; });
                }
                if (entity.STATUS_APPROVE != PFStandardStatus.Draft)
                {
                    //List<Guid> UserId = new List<Guid>();
                    //List<string> userName = new List<string>();
                    //var listUserID = ListUser.Select(e => e.USER_ID);
                    //var listUser = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null);
                    //foreach (var item in ListUser)
                    //{
                    //    if (item.IS_DELETED)
                    //    {
                    //        continue;
                    //    }
                    //    UserId.Add(item.USER_ID);
                    //    userName.Add(item.Nav_User.NAME);
                    //}
                    entity.STATUS_APPROVE = PFStandardStatus.Archived;
                    //把其他人得待办置为已办
                    another = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => t.NOTICE_STATUS == 0 && t.SOURCE_DATA_ID == entity.ID && t.USER_ID != entity.USER_ID, new BaseFilter(entity.ORG_ID)).ToList();
                    if (another != null && another.Any())
                    {
                        another.ForEach(t => { t.NOTICE_STATUS = 1; t.SOURCE_FORMCODE = "DM008_SHOWPRINT"; });
                    }
                    //所有计划表都完成后汇总触发审批
                    var plans = this.GetEntities<T_DM_DEVICE_MAINTENANCE_PLAN>(t => t.SYNC_ID == entity.SYNC_ID,new BaseFilter(entity.ORG_ID));
                    var plan = plans.FirstOrDefault(t=>t.ID != entity.ID && t.STATUS_APPROVE == PFStandardStatus.Draft);
                    if (plan == null)
                    {
                        var userId = this.GetEntity<T_FM_PARAM_SET>(t => t.NAME == "设备设施管理员")?.USER_ID;
                        if (userId != null)
                        {
                            var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.ID == userId);
                            if (user != null)
                            {
                                entity.STATUS_APPROVE = PFStandardStatus.Approving;
                                //取审批流水码
                                var sysFilter = new SystemCodeFilter();
                                sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                                sysFilter.Count = 1;
                                sysFilter.OrgId = entity.ORG_ID;
                                var codes = CodeRuleService.NewGenSerial(sysFilter);
                                var serialCode = codes.Split(new char[] { ',' });
                                //if (entity.SYNC_ID == null || plans.Count() == 1)
                                //{
                                //    entity.SYNC_ID = entity.ID;
                                //}
                                MFlowPermitService.InsertApprove(serialCode[0], "DM008", "",entity.ID, "DM008_SHOWSUMMARY", entity.TaskID, true, () =>
                                {
                                    if (entity != null)
                                        UpdateEntityNoCommit(entity);
                                    if (Files != null && Files.Any())//维保工作方案
                                        BantchSaveEntityNoCommit(Files);
                                    if (details != null && details.Any())
                                        BantchSaveEntityNoCommit(details);
                                    if (another != null && another.Any())
                                        BantchSaveEntityNoCommit(another);
                                }, null, user.ID, null, null, null, "DM008_SHOWSUMMARY", null);
                                return true;
                            }
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        listTask = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        listTask.SOURCE_FORMCODE = "DM008_SHOWPRINT";
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (Files != null && Files.Any())//维保工作方案
                        BantchSaveEntityNoCommit(Files);
                    if (details != null && details.Any())
                        BantchSaveEntityNoCommit(details);
                    if (listTask != null)//维保工作方案
                        UpdateEntityNoCommit(listTask);
                    if (another != null && another.Any())
                        BantchSaveEntityNoCommit(another);
                });
                return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetAll")]
        public JsonActionResult<T_DM_DEVICE_MAINTENANCE_PLAN> GetAll([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_DM_DEVICE_MAINTENANCE_PLAN plan = new T_DM_DEVICE_MAINTENANCE_PLAN();
                List<T_DM_DEVICE_MAINTENANCE_PLAN_DETAIL> details = new List<T_DM_DEVICE_MAINTENANCE_PLAN_DETAIL>();
                List<T_DM_DEVICE_MAINTENANCE_PLAN_FILE> files = new List<T_DM_DEVICE_MAINTENANCE_PLAN_FILE>();
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    throw new Exception("ID未获取到，请联系管理员");
                var planTemp = GetEntity<T_DM_DEVICE_MAINTENANCE_PLAN>(id, "Nav_Department", "Nav_User");
                if (planTemp != null && planTemp.SYNC_ID != null)
                {
                    var baseFilter = new BaseFilter(filter.GetOrgId());
                    baseFilter.IgnoreDataRule = true;
                    baseFilter.SelectField = new string[] { "NAME", "MineType", "YEARPLAN", "DEPARTMENT_ID", "USER_ID", "SYNC_ID", "ID", "Nav_Department", "Nav_User", "Nav_PlanDetails", "Nav_PlanDetails.SPEC", "Nav_PlanDetails.POSITION", "Nav_PlanDetails.CONTENTS", "Nav_PlanDetails.RUNSETTIME", "Nav_PlanDetails.PLANCHECKFREQUENCY", "Nav_PlanDetails.Nav_DeviceBase", "Nav_PlanDetails.Nav_Department", "Nav_PlanDetails.Nav_User", "Nav_Files.Nav_ImgFile.FILE_NAME", "Nav_Files.Nav_ImgFile.FILE_ID", "Nav_Files.Nav_ImgFile.FILE_PATH", "Nav_Files.Nav_ImgFile.Nav_File" };
                    //baseFilter.Include = new string[] { "Nav_Department", "Nav_User", "Nav_PlanDetails", "Nav_PlanDetails.Nav_DeviceBase", "Nav_PlanDetails.Nav_Department", "Nav_PlanDetails.Nav_User", "Nav_Files.Nav_ImgFile.Nav_File" };
                    var plans = GetEntities<T_DM_DEVICE_MAINTENANCE_PLAN>(t => t.SYNC_ID == planTemp.SYNC_ID, baseFilter);
                    if (plans != null && plans.Any())
                    {
                        foreach (var item in plans)
                        {
                            if (item.Nav_PlanDetails != null)
                                details.AddRange(item.Nav_PlanDetails);
                            if (item.Nav_Files != null)
                                files.AddRange(item.Nav_Files);
                        }
                        plan = planTemp;
                        plan.Nav_PlanDetails = details;
                        plan.Nav_Files = files;
                    }
                }
                return plan;
            });
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("BackUpdateNew")]
        public JsonActionResult<bool> BackUpdateNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBackNew("DM/DMDeviceMaintenancePlan/BackUpdateNew", entity);
            });
        }
        /// <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;
        //        var Check = GetEntity<T_DM_DEVICE_MAINTENANCE_PLAN_USER>(e => e.USER_ID == loginID && e.PLAN_ID == guid);

        //        if (Check == null)
        //        {
        //            this.UnifiedCommit(() =>
        //            {
        //                if (task != null)
        //                    UpdateEntityNoCommit(task);
        //            });
        //        }
        //        else if (Check.ISCHECK)
        //        {
        //            this.UnifiedCommit(() =>
        //            {
        //                if (task != null)
        //                    UpdateEntityNoCommit(task);
        //            });
        //            throw new Exception("您已审阅,无需再次操作！");
        //        }
        //        else
        //        {
        //            Check.ISCHECK = true;
        //            var UnCheck = GetEntity<T_DM_DEVICE_MAINTENANCE_PLAN_USER>(e => e.USER_ID != loginID && e.PLAN_ID == guid && !e.ISCHECK);
        //            T_DM_DEVICE_MAINTENANCE_PLAN plan = null;
        //            if (UnCheck == null)
        //            {
        //                plan = GetEntity<T_DM_DEVICE_MAINTENANCE_PLAN>(e => e.ID == guid);
        //                plan.STATUS_APPROVE = PFStandardStatus.Archived;
        //            }

        //            //还有别人未 确认
        //            this.UnifiedCommit(() =>
        //            {
        //                if (task != null)
        //                    UpdateEntityNoCommit(task);
        //                if (Check != null)
        //                    UpdateEntityNoCommit(Check);
        //                if (plan != null)//状态修改
        //                    UpdateEntityNoCommit(plan);
        //            });
        //        }
        //        return true;
        //    });
        //}
    }
}