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.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.SC.DM;
using APT.Utility;
using log4net.Filter;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;

namespace APT.SC.WebApi.Controllers.Api.DMController
{
    /// <summary>
    ///  设备检测检验记录
    /// </summary>
    [Route("api/DM/DMDetectionInspectionRecord")]
    public partial class DetectionInspectionRecordController : AuthorizeApiController<T_DM_DETECTION_INSPECTION_RECORD>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 设备检测检验记录
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public DetectionInspectionRecordController(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_DETECTION_INSPECTION_RECORD entity)
        {
            return SafeExecute(() =>
            {
                entity.TIME = DateTime.Now;
                entity.STATUS = PFStandardStatus.Draft;
                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;
                var user = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId.Value && t.ENABLE_STATUS == 0);
                entity.DEPARTMENT_ID = user?.DEPARTMENT_ID;
                var files = entity.Nav_Files;
                entity.Nav_Files = null;
                if (files != null && files.Any())
                {
                    files.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.DEVICE_RECORD_ID = entity.ID;
                    });
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = 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[] { ',' });
                    MFlowPermitService.InsertApprove(serialCode[0], "DM012", "", entity.ID, "DM012_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null)
                            this.UpdateEntityNoCommit(entity);
                        if (files != null && files.Any())
                            this.BantchSaveEntityNoCommit(files);
                    }, null, null, null, null, null, "DM012_SHOWPRINT", null);
                    return true;
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                });
                return true;
            });
        }

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

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

            });
        }
    }
}
