using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
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;

namespace APT.LR.WebApi.Controllers.Api
{
    [Route("api/LR/LRDemandDistinguish")]
    public class DemandDistinguishController : AuthorizeApiController<T_LR_DEMAND_DISTINGUISH>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public DemandDistinguishController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_LR_DEMAND_DISTINGUISH entity)
        {
            return SafeExecute<bool>(() =>
            {
                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (DateTime.Now > entity.END_TIME)
                {
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "LR001_SHOWPRINT");
                    UpdateEntity(finishNotice);
                    throw new Exception("已过截止时间!");
                }
                if (entity.Nav_DemandLaw.Count() == 0)
                {
                    throw new Exception("请对法律法规识别再进行提交!");
                }
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.USER_ID.Equals(Guid.Empty))
                {
                    entity.USER_ID = (Guid)userID;
                }
                if (entity.YEARS == 0)
                {
                    entity.YEARS = DateTime.Now.Year;
                }
                if (entity.DISTINGUISH_TIME==null)
                {
                    entity.DISTINGUISH_TIME = DateTime.Now;
                }
                BaseFilter basefilter = new BaseFilter(entity.ORG_ID);
                List<T_LR_OTHER_DISTINGUISH> otherDistinguishList = new List<T_LR_OTHER_DISTINGUISH>();
                List<T_LR_DEMAND_USER> DemandUserList = new List<T_LR_DEMAND_USER>();
                var demandLaw = entity.Nav_DemandLaw;
                var demandOther = entity.Nav_DemandOther;
                var demandType = entity.Nav_DemandTypes;
                basefilter.SelectField = new string[] { "ID", "NAME" };
                var demandIds = demandType.Where(x => x.IS_DELETED == false).Select(x => x.DEMANDTYPE_ID);
                var alldemands = GetEntities<T_LR_LAW_TYPE>(t => demandIds.Contains(t.ID), basefilter);
                foreach (var item in demandType)
                {
                    item.Nav_DemandType = null;
                }
                foreach (var demand in alldemands)
                {
                    entity.demandTypeStr += demand.NAME+",";
                }
                entity.Nav_DemandLaw = null;
                entity.Nav_DemandOther = null;
                entity.Nav_DemandTypes = null;
                if (demandOther != null && demandOther.Count() > 0)
                {
                    var otherDistinguishs = GetEntities<T_LR_OTHER_DISTINGUISH>(t => t.IS_DELETED == false, new BaseFilter(entity.ORG_ID)).ToList();
                    demandOther.ForEach(t =>
                    {
                        t.Nav_DemandDistinguish = null;
                        if (t.NAME != null)
                        {
                            var otherDistinguish = otherDistinguishs.Where(o => o.NAME == t.NAME).FirstOrDefault();
                            if (otherDistinguish == null)//不存在则需要新增
                            {
                                T_LR_OTHER_DISTINGUISH newOtherDistinguish = new T_LR_OTHER_DISTINGUISH();
                                newOtherDistinguish.ID = Guid.NewGuid();
                                newOtherDistinguish.NAME = t.NAME;
                                newOtherDistinguish.ORG_ID = entity.ORG_ID;
                                otherDistinguishList.Add(newOtherDistinguish);
                                t.OTHER_ID = newOtherDistinguish.ID;
                                T_LR_DEMAND_USER user = new T_LR_DEMAND_USER();
                                user.ID = Guid.NewGuid();
                                user.OTHER_ID = t.OTHER_ID;
                                user.USER_ID = userID.Value;
                                user.ORG_ID = entity.ORG_ID;
                                DemandUserList.Add(user);
                            }
                            else//存在则需要判断是否新增当前用户到其他识别表中
                            {
                                t.OTHER_ID = otherDistinguish.ID;
                                var demand = GetEntity<T_LR_DEMAND_USER>(d => d.USER_ID == userID && d.OTHER_ID == t.OTHER_ID, new BaseFilter());
                                if (demand == null) //没有该用户则需要新增
                                {
                                    T_LR_DEMAND_USER user = new T_LR_DEMAND_USER();
                                    user.ID = Guid.NewGuid();
                                    user.OTHER_ID = t.OTHER_ID;
                                    user.USER_ID = userID.Value;
                                    user.ORG_ID = entity.ORG_ID;
                                    DemandUserList.Add(user);
                                }
                            }
                        }
                    });
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.DISTINGUISH_TYPE = LRDistinguishEnum.已识别;
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "LR001_SHOWPRINT");
                    }
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (demandLaw != null && demandLaw.Any())
                        BantchSaveEntityNoCommit(demandLaw);
                    if (demandOther != null && demandOther.Any())
                        BantchSaveEntityNoCommit(demandOther);
                    if (demandType != null && demandType.Any())
                        BantchSaveEntityNoCommit(demandType);
                    //插入其他识别用户
                    if (otherDistinguishList.Any())
                        BantchSaveEntityNoCommit(otherDistinguishList);
                    if (DemandUserList.Any())
                        BantchSaveEntityNoCommit(DemandUserList);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
    }
}