using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
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.HM;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Entities.SC.SC;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace APT.SC.WebApi.Controllers.Api.SC
{
    [Route("api/SC/Post")]
    public class SCPostController : AuthorizeApiController<T_SC_POST>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        public SCPostController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody]T_SC_POST entity)
        {
            return SafeExecute(() =>
            {
                //if (entity.CODE == null)
                //{
                //    SystemCodeFilter questionFilter = new SystemCodeFilter
                //    {
                //        CodeType = (int)PFCodeRuleType.责任制岗位,
                //        Count = 1,
                //        OrgId = entity.ORG_ID,
                //    };
                //    entity.CODE = CodeRuleService.NewGenSerial(questionFilter);
                //}
                List<T_SC_DEPARTMENT_POST> postList = new List<T_SC_DEPARTMENT_POST>();
                var deposts = entity.Nav_Depts;
                entity.Nav_Depts = null;
                entity.CODE = DateTime.Now.Year.ToString().PadLeft(4, '0') + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0') + new Random().Next().ToString();
                var deleteIds =this.GetEntities<T_SC_DEPARTMENT_POST>(t=>t.DEPOST_ID == entity.ID,new BaseFilter(entity.ORG_ID)).Select(t=>t.ID).ToList();
                if (deposts != null && deposts.Any())
                {
                    deposts.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID;
                        t.POST_ID = entity.ID;
                        t.Nav_Department = null;
                        t.Nav_Post = null;
                        if (t.Nav_Posts != null && t.Nav_Posts.Any())
                        {
                            var posts = t.Nav_Posts.ToList();
                            posts.ForEach(x =>
                            {
                                x.DEPT_ID = t.ID;
                                x.ORG_ID = t.ORG_ID;
                                x.Nav_Dept = null;
                                x.Nav_Depost = null;
                                postList.Add(x);
                            });
                        }
                        t.Nav_Posts = null;
                    });
                }
                //var template_files = entity.Nav_Files;
                //if (template_files != null) {
                //    template_files.ForEach(file =>
                //    {
                //        file.POST_ID = entity.ID;
                //        file.ORG_ID = entity.ORG_ID;
                //    });
                //}

                UnifiedCommit(() =>
                {
                    UpdateEntity(entity);
                    if (deleteIds != null && deleteIds.Any())
                        BantchDeleteEntity<T_SC_DEPARTMENT_POST>(deleteIds);
                    if (deposts != null && deposts.Any())
                        BantchSaveEntity(deposts);
                    if (postList != null && postList.Any())
                        BantchSaveEntity(postList);
                    //if (template_files != null)
                    //{
                    //    BantchSaveEntity(template_files);
                    //}
                });
                //UpdateBySCPostID(entity.ID);
                return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("UpdateAll")]
        public JsonActionResult<bool> UpdateAll([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(()=> {
                var entities = GetEntities<T_SC_POST>(null, new BaseFilter(filter.GetOrgId())).ToList();
                if (entities != null)
                {
                    entities.ForEach(it =>
                    {
                        //UpdateBySCPostID(it.ID);
                    });
                }
                return true;
            });
        }
        /// <summary>
        /// 人员岗位取值
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetPersonPost")]
        public PagedActionResult<T_FM_USER_POST> GetPersonPost([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FM_USER_POST>();// this.GetOrderPageEntities<T_FM_USER>(null, pageFilter);
            var filter = pageFilter.FilterGroup.Groups.Select(t=>t.Rules.FirstOrDefault(m=>m.Field == "DEPARTMENT_ID")).FirstOrDefault();
            if (filter == null)
            {
                filter = pageFilter.FilterGroup.Rules.FirstOrDefault(m => m.Field == "DEPARTMENT_ID");
            }
            if (filter != null)
            {
                //部门下的人员岗位
                var ogRelated = this.GetEntities<T_FM_USER>(t => t.DEPARTMENT_ID == Guid.Parse(filter.Value.ToString()) && t.ENABLE_STATUS==0, new BaseFilter(pageFilter.OrgId),new string[] { "Nav_Person.Nav_Post" });
                if (ogRelated != null && ogRelated.Any())
                {
                    var postList = ogRelated.Where(t => t.Nav_Person != null && t.Nav_Person.POST_ID!=null).Select(m => m.Nav_Person.Nav_Post).Distinct().ToList();
                    var userList = new List<T_FM_USER_POST>();
                    if (postList != null && postList.Any())
                    {
                        var postIds = postList.Select(t => t.ID).Distinct().ToList();
                        foreach (var postId in postIds)
                        {
                            var t = postList.FirstOrDefault(t => t.ID == postId);
                            T_FM_USER_POST user = new T_FM_USER_POST();
                            user.ID = t.ID;
                            user.CODE = t.CODE;
                            user.NAME = t.NAME;
                            userList.Add(user);
                        }
                         result.Data = userList;
                    }
                    else
                    {
                        result.Data = this.GetOrderPageEntities<T_FM_USER_POST>(null, new BasePageFilter(pageFilter.PageIndex, 10)).Data;
                    }
                }
                else
                {
                    result.Data = this.GetOrderPageEntities<T_FM_USER_POST>(null, new BasePageFilter(pageFilter.PageIndex, 10)).Data;
                }
            }
            else
            {
                result = this.GetOrderPageEntities<T_FM_USER_POST>(null, new BasePageFilter(pageFilter.PageIndex, 10));
            }
            return result;
        }
        ///// <summary>
        ///// 按责任制岗位ID更新用户责任制岗位
        ///// </summary>
        //public void UpdateBySCPostID(Guid SCPostId)
        //{
        //    var entity = GetEntity<T_SC_POST>(t => t.ID == SCPostId, new BaseFilter(null, FilterOrgTypeEnum.忽略组织));
        //    if (entity == null)
        //    {
        //        return;
        //    }
        //    var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;

        //    //查询当前责任制岗位所有的部门岗位
        //    var deposts = GetEntities<T_SC_POST_DEPOST>(
        //    t => t.POST_ID == SCPostId,
        //        new BaseFilter(orgId),
        //        new string[] { "Nav_Depost" }
        //    ).ToList();
        //    //生成查出来的所有部门岗位的所有人员
        //    var depostids = deposts.Select(t => t.DEPOST_ID).Distinct().ToList();
        //    var allUids = GetEntities<T_FM_USER>(t => t.POSITION_ID != null && depostids.Contains(t.POSITION_ID.Value), new BaseFilter(null, Core.Data.FilterOrgTypeEnum.忽略组织)).Select(t => t.ID).ToList();
        //    //兼职安全员
        //    if (entity.AS_SAFE_USER)
        //    {
        //        //获取当前责任制关联部门中职务为安全员的人
        //        var departIds = deposts.Select(t => t.Nav_Depost.DEPARTMENT_ID).Distinct().ToList();
        //        var safeUids = GetEntities<T_FM_DEPARTMENT_POST_USER>(
        //            t => t.Nav_DepartmentPost.Nav_Workduty.NAME == "安全员" &&
        //            departIds.Contains(t.Nav_DepartmentPost.DEPARTMENT_ID),
        //            new BaseFilter(null, Core.Data.FilterOrgTypeEnum.忽略组织),
        //            new string[] { "Nav_DepartmentPost", "Nav_DepartmentPost.Nav_Workduty" }
        //        ).ToList().Select(u => u.USER_ID).ToList();
        //        //关联的所有人员与关联的所有部门所有安全员的交集
        //        allUids = allUids.Intersect(safeUids).Distinct().ToList();
        //    }
        //    var datas = GetEntities<T_FM_USER_RESPON_POST>(
        //    t => t.RESPON_POST_ID == SCPostId,
        //        new BaseFilter(orgId)).ToList();
        //    datas.ForEach(t =>
        //    {
        //        if (!allUids.Contains(t.USER_ID))
        //        {
        //            t.IS_DELETED = true;
        //        }
        //    });
        //    var existIds = datas.Select(t => t.USER_ID).Distinct().ToList();
        //    var newIds = allUids.Except(existIds).ToList();
        //    newIds.ForEach(uid =>
        //    {
        //        datas.Add(new T_FM_USER_RESPON_POST
        //        {
        //            ID = Guid.NewGuid(),
        //            ENTITY_ORG_TPYE = 2,
        //            ORG_ID = entity.ORG_ID,
        //            USER_ID = uid,
        //            RESPON_POST_ID = SCPostId,
        //        });
        //    });
        //    BantchSaveEntity(datas);
        //}
        ///// <summary>
        ///// 按用户ID更新用户责任制岗位
        ///// </summary>
        //public void UpdateByUserId(Guid UserId)
        //{
        //    var user = GetEntity<T_FM_USER>(t => t.ID == UserId, new BaseFilter(null, FilterOrgTypeEnum.忽略组织));
        //    if (user == null)
        //        return;
        //    var currentUserSCPosts = GetEntities<T_FM_USER_RESPON_POST>(
        //        t => t.USER_ID == UserId,
        //        new BaseFilter(null, Core.Data.FilterOrgTypeEnum.忽略组织)).ToList();
        //    var SCPOSTIDS = new List<Guid>();
        //    if (currentUserSCPosts != null)
        //    {
        //        SCPOSTIDS = currentUserSCPosts.
        //            Where(it => it.RESPON_POST_ID != null).
        //            Distinct(it => it.RESPON_POST_ID).
        //            Select(it => it.RESPON_POST_ID.Value).ToList();
        //    }
        //    if (user.POSITION_ID != null)
        //    {
        //        var currentPostDeposts = GetEntities<T_SC_POST_DEPOST>(it =>
        //            it.DEPOST_ID == user.POSITION_ID.Value,
        //            new BaseFilter(null, FilterOrgTypeEnum.忽略组织)
        //        ).ToList();
        //        if (currentPostDeposts != null)
        //        {
        //            currentPostDeposts.ForEach(it =>
        //            {
        //                if (!SCPOSTIDS.Contains(it.POST_ID))
        //                {
        //                    SCPOSTIDS.Add(it.POST_ID);
        //                }
        //            });
        //        }
        //    }
        //    if (SCPOSTIDS.Count == 0)
        //        return;
        //    SCPOSTIDS.ForEach(id =>
        //    {
        //        try
        //        {
        //            UpdateBySCPostID(id);
        //        }
        //        catch { }
        //    });

        //}
    }
}
