using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.SC.PE;
using APT.MS.Domain.Entities.SC.PM;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.SC.WebApi.Controllers.Api.PEController
{
    /// <summary>
    ///  标准化评分导入
    /// </summary>
    [Route("api/PE/PEStandardizedScoreImport")]
    public partial class StandardizedScoreImportController : AuthorizeTreeApiController<T_PE_STANDARDIZED_SCORE_IMPORT>
    {
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="ids">id字符串（id用逗号分隔）</param>
        /// <returns></returns>
        [HttpGet, Route("FullBatchDelete")]
        public JsonActionResult<bool> FullBatchDelete(string ids)
        {
            return SafeExecute<bool>(() =>
            {
                var id = ids.Split(',')[0];
                if (string.IsNullOrEmpty(id))
                    throw new Exception("id不能为空");
                //判断没有子集才能删
                var parentEntity = GetEntity<T_PE_STANDARDIZED_SCORE_IMPORT>(t => t.PARENT_ID == Guid.Parse(id), false);
                if(parentEntity!=null)
                    throw new Exception("请先删除子级数据");
                var entity = GetEntity<T_PE_STANDARDIZED_SCORE_IMPORT>(t => t.ID == Guid.Parse(id));
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.DeleteEntityNoCommit(entity);
                });
                return true;
            });
        }

        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_PE_STANDARDIZED_SCORE_IMPORT entity)
        {
            return SafeExecute(() =>
            {
                //同步更新T_PE_STANDARDIZED_SCORE_IMPORT_DETAIL表
                var deleteIds = new List<Guid>();
                var detailList = new List<T_PE_STANDARDIZED_SCORE_IMPORT_DETAIL>();
                var details = entity.Nav_Details;
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.STANDARDIZED_SCORE_IMPORT_ID = entity.ID;
                        T_PE_STANDARDIZED_SCORE_IMPORT_DETAIL item = new T_PE_STANDARDIZED_SCORE_IMPORT_DETAIL();
                        item.ORG_ID = entity.ORG_ID;
                        item.PRIMARY_ELEMENTS_ID = null;
                        item.SECOND_ELEMENTS_ID = null;
                        item.THREE_ELEMENTS_ID = null;
                        item.PRODUCTION_UNIT_ID = null;
                        item.EVALUATION_ITEM = t.EVALUATION_ITEM;
                        item.NUM = t.NUM;
                        item.CONTENTS = t.CONTENTS;
                        item.STANDARDIZED_SCORE = t.STANDARDIZED_SCORE;
                        item.NON_STANDARDIZED_SCORE = t.NON_STANDARDIZED_SCORE;
                        detailList.Add(item);
                    });
                    var items = this.GetEntities<T_PE_STANDARDIZED_SCORE_IMPORT_DETAIL>(t => t.THREE_ELEMENTS_ID == entity.ID || t.SECOND_ELEMENTS_ID == entity.ID || t.PRIMARY_ELEMENTS_ID == entity.ID || t.PRODUCTION_UNIT_ID == entity.ID, new BaseFilter(entity.ORG_ID)).ToList();
                    if (items != null && items.Any())
                    {
                        var ids = items.Select(t => t.ID).ToList();
                        deleteIds.AddRange(ids);
                        var thirds = items.Where(t => t.THREE_ELEMENTS_ID == entity.ID).ToList();
                        if (thirds != null && thirds.Any())
                        {
                            var main = this.GetEntity<T_PE_STANDARDIZED_SCORE_IMPORT>(t => t.ID == entity.PARENT_ID, "Nav_Parent");
                            detailList.ForEach(t =>
                            {
                                t.THREE_ELEMENTS_ID = entity.ID;
                                t.SECOND_ELEMENTS_ID = entity.PARENT_ID;
                                t.PRIMARY_ELEMENTS_ID = main?.PARENT_ID;
                                t.PRODUCTION_UNIT_ID = main?.Nav_Parent?.PARENT_ID;
                            });
                        }
                        var seconds = items.Where(t => t.SECOND_ELEMENTS_ID == entity.ID).ToList();
                        if (seconds != null && seconds.Any())
                        {
                            var main = this.GetEntity<T_PE_STANDARDIZED_SCORE_IMPORT>(t => t.ID == entity.PARENT_ID);
                            detailList.ForEach(t =>
                            {
                                t.SECOND_ELEMENTS_ID = entity.ID;
                                t.PRIMARY_ELEMENTS_ID = entity.PARENT_ID;
                                t.PRODUCTION_UNIT_ID = main?.PARENT_ID;
                            });
                        }
                        var primarys = items.Where(t => t.PRIMARY_ELEMENTS_ID == entity.ID).ToList();
                        if (primarys != null && primarys.Any())
                        {
                            detailList.ForEach(t =>
                            {
                                t.PRIMARY_ELEMENTS_ID = entity.ID;
                                t.PRODUCTION_UNIT_ID = entity.PARENT_ID;
                            });
                        }
                        var products = items.Where(t => t.PRODUCTION_UNIT_ID == entity.ID).ToList();
                        if (products != null && products.Any())
                        {
                            detailList.ForEach(t =>
                            {
                                t.PRODUCTION_UNIT_ID = entity.ID;
                            });
                        }
                    }
                }
                entity.Nav_Details = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (deleteIds != null && deleteIds.Any())
                        this.BantchDeleteEntityNoCommit<T_PE_STANDARDIZED_SCORE_IMPORT_DETAIL>(deleteIds);
                    if (detailList != null && detailList.Any())
                        this.BantchSaveEntityNoCommit(detailList);
                });
                return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据(新增部门人员子表)
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAll")]
        public JsonActionResult<T_PE_STANDARDIZED_SCORE_IMPORT> GetAll([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    throw new Exception("数据错误，请联系管理员");
                var entity = this.GetEntity<T_PE_STANDARDIZED_SCORE_IMPORT>(id, false, "Nav_Details", "Nav_Parent");
                if (entity != null && entity.Nav_Details.Any())
                {
                    entity.Nav_Details = entity.Nav_Details.OrderBy(t => t.NUM).ToList();
                }
                return entity;
            });
        }
    }
}
