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

namespace APT.LR.WebApi.Controllers.Api
{
    [Route("api/LR/LRLawIntegrate")]
    public class LawIntegrateController : AuthorizeApiController<T_LR_LAW_INTEGRATE>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public LawIntegrateController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_LR_LAW_INTEGRATE entity)
        {
            return SafeExecute<bool>(() =>
            {
                List<T_LR_LAW_SC_SYSTEM> lawSystems = new List<T_LR_LAW_SC_SYSTEM>();
                T_FM_NOTIFICATION_TASK finishNotice = null;
                var integrateDetails = entity.Nav_IntegrateDetail;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = PFStandardStatus.Archived;
                    if (!entity.RATE.StartsWith("100"))
                    {
                        throw new Exception("融入比例不为100%");
                    }
                    var lawsystemsAll = GetEntities<T_LR_LAW_SC_SYSTEM>(t => t.IS_DELETED == false, new BaseFilter(entity.ORG_ID));
                    foreach (var item in integrateDetails)
                    {
                        var isSystem = lawsystemsAll.Where(t => t.LAW_ID == item.LAW_ID);
                        if (!isSystem.Any())
                        {
                            T_LR_LAW_SC_SYSTEM lawsystem = new T_LR_LAW_SC_SYSTEM
                            {
                                ID = Guid.NewGuid(),
                                LAW_ID = item.LAW_ID,
                                ORG_ID = item.ORG_ID,
                                SC_SYSTEM_ID = (Guid)item.SYSTEM_ID
                            };
                            lawSystems.Add(lawsystem);
                        }
                    }
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                }
                entity.Nav_IntegrateDetail = null;
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (integrateDetails != null && integrateDetails.Any())
                        BantchSaveEntityNoCommit(integrateDetails);
                    if (lawSystems != null && lawSystems.Any())
                        BantchSaveEntityNoCommit(lawSystems);
                });

                return true;
            });
        }

        /// <summary>
		/// 获得单条实体数据
		/// </summary>
		/// <param name="filter"></param>
		/// <returns></returns>
		[HttpPost, Route("Get")]
        public JsonActionResult<T_LR_LAW_INTEGRATE> Get([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_LR_LAW_INTEGRATE>(() =>
            {
                var entity = GetEntity<T_LR_LAW_INTEGRATE>(null, filter);
                if (entity == null)
                {
                    entity = new T_LR_LAW_INTEGRATE();
                    entity.YEAR = DateTime.Now.Year;
                }
                double lawCount = 0;
                double institutionsCount = 0;
                BaseFilter baseFilter = new BaseFilter();
                baseFilter.OrgType = FilterOrgTypeEnum.忽略组织;
                var laws = GetEntities<T_LR_LAW>(t => t.LAW_STATUS == BSLawStatusEnum.现行, baseFilter, new string[] { "Nav_LawVersion", "Nav_LawSCSystem.Nav_SCSystem" }).ToList();
                if (laws != null && laws.Count() > 0)
                {
                    List<T_LR_LAW_INTEGRATE_DETAIL> LawInstitutions = new List<T_LR_LAW_INTEGRATE_DETAIL>();
                    laws.ForEach(t =>
                    {
                        lawCount++;
                        T_LR_LAW_INTEGRATE_DETAIL lawInstitution = new T_LR_LAW_INTEGRATE_DETAIL();
                        lawInstitution.LAW_ID = t.ID;
                        lawInstitution.LAW_INTEGRATE_ID = entity.ID;
                        if (t.Nav_LawSCSystem != null && t.Nav_LawSCSystem.Count() > 0)
                        {
                            var lawSCSystem = t.Nav_LawSCSystem.Where(li => li.Nav_SCSystem.FILE_STATUS == SCSystemFileStatus.有效).FirstOrDefault();
                            if (lawSCSystem != null)
                            {
                                lawInstitution.SYSTEM_ID = lawSCSystem.SC_SYSTEM_ID;
                                lawInstitution.Nav_Law = lawSCSystem.Nav_Law;
                                lawInstitution.Nav_SCSystem = lawSCSystem.Nav_SCSystem;
                                institutionsCount++;
                            }
                        }
                        else
                        {
                            lawInstitution.Nav_Law = t;
                        }
                        LawInstitutions.Add(lawInstitution);
                    });
                    entity.Nav_IntegrateDetail = LawInstitutions;
                }
                if (lawCount == 0)
                {
                    entity.RATE = "0";
                }
                else
                {
                    entity.RATE = ((institutionsCount / lawCount) * 100).ToString("#0.00");
                }

                return entity;
            });
        }
    }
}