using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Enums;
using APT.Utility;
using APT.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.BS.WebApi.Controllers.Api
{
    [Route("api/BS/BSRiskSubmitNoticePerson")]
    public partial class BSRiskSubmitNoticePersonController : AuthorizeApiController<T_BS_RISK_SUBMIT_NOTICE_PERSON>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        IBSOperateLogService OperateLogService { get; set; }
        public BSRiskSubmitNoticePersonController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFCodeRuleService codeRuleService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService, IBSOperateLogService operateLogService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            CodeRuleService = codeRuleService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
            OperateLogService = operateLogService;
        }


        /// <summary>
        /// 获取整改落实人验收
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetDetailCheck")]
        public JsonActionResult<T_BS_RISK_SUBMIT_NOTICE_PERSON> Get([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                Guid ID = Guid.Empty;
                int RiskContentState = 0;
                bool isLogin = false;
                if (filter.FilterGroup.Rules.Count > 0)
                {
                    List<FilterRule> listR = filter.FilterGroup.Rules.ToList();
                    foreach (FilterRule rule in listR)
                    {
                        if (rule.Field == "ID")
                        {
                            ID = new Guid(rule.Value.ToString());
                        }
                        else if (rule.Field == "ISLOGIN" && rule.Value.ToString() == "1")
                        {
                            isLogin = true;
                        }
                        else if (rule.Field == "RiskContentState")
                        {
                            RiskContentState = int.Parse(rule.Value.ToString());
                        }
                    }
                }

                Expression<Func<T_BS_RISK_SUBMIT_CONTENT, bool>> expression = e => e.RISK_SUBMIT_NOTICE_PERSON_ID == ID;

                if (RiskContentState == 32)
                {
                    //BS034Showprint 查看的时候 会报错
                    expression = expression.And(e => e.RiskContentState == RiskContentState && e.ACTUAL_DEAL_USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                }
                else if (isLogin)
                {
                    //责任人 或者整改落实人
                    expression = expression.And(e => e.DEAL_USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID || e.ACTUAL_DEAL_USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID || e.CHECK_USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                }
                var nitocePerson = GetEntity<T_BS_RISK_SUBMIT_NOTICE_PERSON>(e => e.ID == ID, new string[] { "Nav_Submit.Nav_Check", "Nav_User.Nav_Department" });
                var listRiskSubmitContentT = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(expression, null, new string[] { "Nav_Question", "Nav_ListRiskQuestionReason.Nav_RiskReason", "Nav_User", "Nav_Department", "Nav_DepartmentDeal", "Nav_UserDeal", "Nav_UserCheck", "Nav_UserActualDeal", "Nav_Files.Nav_ImgFile.Nav_File" });
                nitocePerson.Nav_ListRiskSubmitContent = listRiskSubmitContentT.ToList();
                if (nitocePerson.Nav_ListRiskSubmitContent != null && nitocePerson.Nav_ListRiskSubmitContent.Any() && DataHelper.GetRequestType(Request.Headers) == 2)
                {
                    foreach (var item in nitocePerson.Nav_ListRiskSubmitContent)
                    {
                        if (item.QUESTION_LEVEL > 0)
                        {
                            try
                            {
                                item.QUESTION_LEVEL_SHOW = ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription();
                            }
                            catch { }
                        }
                    }

                    try
                    {
                        nitocePerson.QUESTION_LEVEL_SHOW = ((BSQuestionLevelEnum)nitocePerson.QUESTION_LEVEL).GetDescription();
                    }
                    catch { }
                }
                if (nitocePerson.RISK_SUBMIT_ID.HasValue)
                {
                    var listFile = GetEntities<T_BS_RISK_SUBMIT_FILE>(e => e.RISK_SUBMIT_ID == nitocePerson.RISK_SUBMIT_ID, null, "Nav_ImgFile.Nav_File");
                    if (listFile != null && listFile.Any())
                        nitocePerson.Nav_Files = listFile;
                }
                return nitocePerson;
            });

        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_BS_RISK_SUBMIT_NOTICE_PERSON> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_BS_RISK_SUBMIT_NOTICE_PERSON> result)
            {
                bool isAll = true;
                List<Guid> departmentIds = new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value }, ref departmentIds, ref isAll);
                Expression<Func<T_BS_RISK_SUBMIT_NOTICE_PERSON, bool>> expression = e => !e.IS_DELETED;
                if (!isAll)
                {
                    pageFilter.Include.Add("Nav_Submit");
                    expression = expression.And(e => e.Nav_Submit.DEPARTMENT_ID.HasValue && departmentIds.Contains(e.Nav_Submit.DEPARTMENT_ID.Value));
                }

                PagedActionResult<T_BS_RISK_SUBMIT_NOTICE_PERSON> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
                if (result.TotalCount > 0 && DataHelper.GetRequestType(Request.Headers) == 2)
                {
                    result.Data.ForEach(e => { e.OPERATETYPE_SHOW = e.OPERATETYPE.GetDescription(); });
                }
            });
        }


        #region    需要额外同步


        /// <summary>
        /// 整改责任人指定 整改落实人 （BS074） 
        /// </summary>
        /// <param name="entity">对象实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_BS_RISK_SUBMIT_NOTICE_PERSON entity)
        {
            return SafeExecute<bool>(() =>
            {
                var listRiskSubminContentl = entity.Nav_ListRiskSubmitContent;
                if (listRiskSubminContentl == null || !listRiskSubminContentl.Any())
                {
                    throw new Exception("上报明细不能为空！");
                }
                //if (!APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue || !listContent[0].DEAL_USER_ID.HasValue || APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value != listContent[0].DEAL_USER_ID.Value)
                //{
                //    throw new Exception("您不是此单的整改责任人，不能处理此单据！");
                //}
                T_FM_NOTIFICATION_TASK task = null;
                DateTime? TASK_ENDDT = null;
                if (entity.OPERATETYPE == OperateType.Save)
                {
                    List<int> listIndex = new List<int>();
                    List<int> listIndexSame = new List<int>();
                    for (int i = 0; i < listRiskSubminContentl.Count; i++)
                    {
                        if (!listRiskSubminContentl[i].ACTUAL_DEAL_USER_ID.HasValue)
                        {
                            listIndex.Add(i + 1);
                        }
                        else if (listRiskSubminContentl[i].CHECK_USER_ID.HasValue && listRiskSubminContentl[i].ACTUAL_DEAL_USER_ID.Value == listRiskSubminContentl[i].CHECK_USER_ID.Value)
                        {
                            listIndexSame.Add(i + 1);
                        }
                    }
                    if (listIndex.Count > 0)
                    {
                        throw new Exception("请选择行【" + String.Join(",", listIndex) + "】的整改落实人！");
                    }
                    if (listIndexSame.Count > 0)
                    {
                        throw new Exception("行【" + String.Join(",", listIndex) + "】的整改落实人与验收人不能相同！");
                    }

                    task = NotificationTaskService.GetEntityTask(entity.TaskID, "BS074_SHOWPRINT");
                    if (task != null)
                        TASK_ENDDT = task.TASK_ENDDT;
                }

                //审核人 同意
                List<T_FM_NOTIFICATION_TASK> listNoticeDeal = new List<T_FM_NOTIFICATION_TASK>();

                //entity.Nav_ListRiskSubmitContent = null;//不能有 不然 对应外键 会被清空
                List<Guid> ListNoticeAll = new List<Guid>();
                List<string> ListNoticeAllNAME = new List<string>();
                List<T_BS_OPERATE_LOG> listOperateLog = new List<T_BS_OPERATE_LOG>();
                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_RiskUp_Deal, entity.ORG_ID.Value, DateTime.Now, null, null);

                listRiskSubminContentl.ForEach(item =>
                {
                    //item.ACTUAL_DEAL_USER_ID = item.DEAL_USER_ID;//整改落实人默认  整改责任人
                    item.RiskContentState = (int)RiskContentState.CheckerCheck;//CheckerCheck CheckerCheck

                    item.ISDEALUSERCHECK = true;

                    if (!ListNoticeAll.Contains(item.CHECK_USER_ID.Value))//DEAL_USER_ID
                    {
                        //整改责任人
                        ListNoticeAll.Add(item.CHECK_USER_ID.Value);//DEAL_USER_ID
                                                                    //数量少 每次获取 页面能选 这边就不会报错
                        ListNoticeAllNAME.Add(GetEntity<T_FM_USER>(item.CHECK_USER_ID.Value).NAME);//Nav_UserDeal

                        //给责任人 发送通知
                        listNoticeDeal.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("验收人确认：" + entity.NAME.Replace("隐患整改通知：", ""), entity.ID, entity.ORG_ID, ListNoticeAll, ListNoticeAllNAME, DateTime.Now, ((item.LastDateUser.HasValue && item.LastDateUser.Value < dtEnd) ? item.LastDateUser.Value : dtEnd), (int)FMNoticeTypeEnum.消息, "BS042_SHOWPRINT"));//HM001_SHOWPRINT  "整改责任人确认：" + entity.NAME.Replace("隐患整改通知：", "")

                        listOperateLog.AddRange(OperateLogService.GetListOperateLog(OPERATEPOINT_Enums.RiskAssignActure, entity.RISK_SUBMIT_ID.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, null, ListNoticeAll, ListNoticeAllNAME, entity.ORG_ID, item.ID, null, false, TASK_ENDDT));
                    }
                });

                this.UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);//保存状态
                    if (listRiskSubminContentl != null && listRiskSubminContentl.Any())//隐患上报明细表
                        BantchSaveEntity(listRiskSubminContentl);    //保存子表
                    if (listNoticeDeal != null && listNoticeDeal.Any())//整改责任人 按条数 收到整改单
                        BantchSaveEntity(listNoticeDeal);
                    if (listOperateLog != null && listOperateLog.Any())//日志
                        BantchSaveEntity(listOperateLog);
                    if (task != null)//代办消息 清除
                        UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                });

                return true;
            });
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetNoticePeson")]
        public JsonActionResult<T_BS_RISK_SUBMIT_NOTICE_PERSON> GetNoticePeson([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var result = GetEntity<T_BS_RISK_SUBMIT_NOTICE_PERSON>(null, filter, null);
                if (result != null && result.QUESTION_LEVEL > 0 && DataHelper.GetRequestType(HttpContext.Request.Headers) == 2)
                {
                    result.QUESTION_LEVEL_SHOW = ((BSQuestionLevelEnum)result.QUESTION_LEVEL).GetDescription();
                }
                return result;
            });
        }

        #endregion
    }
}