using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.ApiModel.SC.PR;
using APT.MS.Domain.Entities.SC.PR;
using APT.MS.Domain.Entities.SC.PT;
using APT.MS.Domain.Enums;
using APT.Utility;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace APT.SC.WebApi.Controllers.Api.PRController
{
    /// <summary>
    ///  药品搬运记录表
    /// </summary>
    [Route("api/PR/PRDrugCarryRecord")]
    public partial class DrugCarryRecordController : AuthorizeApiController<T_PR_DRUG_CARRY_RECORD>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 药品搬运记录表
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public DrugCarryRecordController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_PR_DRUG_CARRY_RECORD entity)
        {
            return SafeExecute(() =>
            {
                var carryUsers = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_USER>();
                var carryAccepts = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_ACCEPT>();
                var userIds = new List<Guid>();
                var userInfos = new List<T_FM_USER>();
                if (string.IsNullOrEmpty(entity.CODE))
                    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(9999).ToString().PadLeft(4, '0');
                entity.STATUS = PFStandardStatus.Draft;
                var confirms = entity.Nav_Confirms;
                entity.Nav_Confirms = null;
                if (confirms != null && confirms.Any())
                {
                    confirms.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.CARRY_RECORD_ID = entity.ID;
                        //if (t.IS_CONFIRM == false)
                        //    throw new Exception("搬运安全未全部确认");
                    });
                }
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        loginUserId = currTask.USER_ID;
                    }
                }
                var details = entity.Nav_Details;
                entity.Nav_Details = null;
                if (details != null && details.Any())
                {
                    details.ForEach(t => {
                        if (t.Nav_Users != null && t.Nav_Users.Any())
                        {
                            t.Nav_Users.ForEach(t1 => {
                                if (!t1.IS_DELETED && t1.USER_ID != null)
                                    userIds.Add(t1.USER_ID.Value);
                            });
                        }
                        //if (t.Nav_Accepts != null && t.Nav_Accepts.Any())
                        //{
                        //    t.Nav_Accepts.ForEach(t2 => {
                        //        if (!t2.IS_DELETED && t2.USER_ID != null)
                        //            userIds.Add(t2.USER_ID.Value);
                        //    });
                        //}
                    });
                    userInfos = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID), "Nav_Department").ToList();
                    details.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.CARRY_RECORD_ID = entity.ID; t.CARRY_TIME = DateTime.Now;
                        var departName = "";
                        if (t.Nav_Users != null && t.Nav_Users.Any())
                        {
                            t.Nav_Users.ForEach(t1 =>
                            {
                                carryUsers.Add(t1);
                                var departUser = userInfos.FirstOrDefault(m => m.ID == t1.USER_ID);
                                departName = departUser.Nav_Department?.NAME + " " + departName;
                            });
                        }
                        t.DEPARTMENT = departName;
                        t.Nav_Users = null;
                        if (t.Nav_Accepts != null && t.Nav_Accepts.Any())
                        {
                            t.Nav_Accepts.ForEach(t2 =>
                            {
                                carryAccepts.Add(t2);
                            });
                        }
                        t.Nav_Accepts = null;
                    });
                }
                T_FM_NOTIFICATION_TASK task = null;
                var notices = new List<T_FM_NOTIFICATION_TASK>();
                var drugUses = new List<T_PR_DRUG_USE_RECORD>();
                var drugUseDetails = new List<T_PR_DRUG_USE_RECORD_USER>();
                var drugUseConfirms = new List<T_PR_DRUG_USE_RECORD_CONFIRM>();
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = PFStandardStatus.Sign;
                    if (confirms != null && confirms.Any())
                    {
                        confirms.ForEach(t =>
                        {
                            t.ORG_ID = entity.ORG_ID; t.CARRY_RECORD_ID = entity.ID;
                            if (t.IS_CONFIRM == false)
                                throw new Exception("搬运安全未全部确认");
                        });
                    }
                    //判断是否已经有人确认过，没有的话为第一个人确认
                    bool isDeal = false;
                    if (carryUsers != null && carryUsers.Any())
                    {
                        carryUsers.ForEach(t =>
                        {
                            if (t.USER_ID == loginUserId)
                            {
                                t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                            }
                        });
                        var isExist = carryUsers.FirstOrDefault(t => t.DEAL_STATUS == FOUserShiftStatusEnum.已处理);
                        if (isExist != null)
                            isDeal = true;
                    }
                    //if (carryAccepts != null && carryAccepts.Any())
                    //{
                    //    carryAccepts.ForEach(t =>
                    //    {
                    //        if (t.USER_ID == loginUserId)
                    //        {
                    //            t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                    //        }
                    //    });
                    //}
                    if (!isDeal)
                    {
                        var userId = userIds.FirstOrDefault();
                        var userName = userInfos.FirstOrDefault(t => t.ID == userId)?.NAME;
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("药品（剂）搬运记录表-确认", entity.ID, entity.ORG_ID, userId, userName, DateTime.Now,
                                       DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR048"));
                    }
                    else
                    {
                        userIds = userIds.Where(t => t != loginUserId).Distinct().ToList();
                        if (userIds != null && userIds.Any())
                        {
                            var sendNames = new List<string>();
                            foreach (var user in userInfos)
                            {
                                sendNames.Add(user.NAME);
                            }
                            notices = NotificationTaskService.InsertUserNoticeTaskModels("药品（剂）搬运记录表-确认", entity.ID, entity.ORG_ID, userIds, sendNames, DateTime.Now,
                                        DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR048_SHOWPRINT");
                        }
                        else
                        {
                            var userUseIds = carryAccepts.Where(m => m.USER_ID != null).Select(t => t.USER_ID.Value).Distinct().ToList();
                            var userLinkDetails = new List<DrugCarryRecordModel>();
                            foreach (var item in details)
                            {
                                DrugCarryRecordModel model = new DrugCarryRecordModel();
                                model.SPECIFY_ID = item.SPECIFY_ID;
                                model.DRUG_SET_ID = item.DRUG_SET_ID;
                                model.UNIT = item.UNIT;
                                model.TYPE_ID = item.TYPE_ID;
                                model.QTY = item.QTY;
                                model.DEPARTMENT_NAME = item.DEPARTMENT;
                                userLinkDetails.Add(model);
                            }
                            entity.STATUS = PFStandardStatus.Archived;
                            userUseIds = userUseIds.Distinct().ToList();
                            var users = this.GetEntities<T_FM_USER>(t => userUseIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID));
                            var drugSets = new List<T_PR_DRUG_SET>();
                            if (userLinkDetails != null && userLinkDetails.Any())
                            {
                                var drugSetIds = userLinkDetails.Select(t => t.DRUG_SET_ID).Distinct().ToList();
                                drugSets = this.GetEntities<T_PR_DRUG_SET>(t => drugSetIds.Contains(t.ID), new BaseFilter(entity.ORG_ID), "Nav_Confirms").ToList();
                                foreach (var detail in userLinkDetails)
                                {
                                    T_PR_DRUG_USE_RECORD drugUse = new T_PR_DRUG_USE_RECORD();
                                    drugUse.ORG_ID = entity.ORG_ID;
                                    drugUse.USER_ID = users.FirstOrDefault().ID;
                                    drugUse.DEPARTMENT_ID = users.FirstOrDefault().DEPARTMENT_ID;
                                    drugUse.TIME = DateTime.Now;
                                    drugUse.CARRY_RECORD_ID = entity.ID;
                                    drugUse.DRUG_SET_ID = detail.DRUG_SET_ID;
                                    drugUse.SPECIFY_ID = detail.SPECIFY_ID;
                                    drugUse.TYPE_ID = detail.TYPE_ID;
                                    drugUse.QTY = detail.QTY;
                                    drugUse.UNIT = detail.UNIT;
                                    drugUse.STATUS = PFStandardStatus.Draft;
                                    drugUse.DEPARTMENT = detail.DEPARTMENT_NAME;
                                    drugUse.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();
                                    drugUses.Add(drugUse);
                                    var drugSetFirst = drugSets.FirstOrDefault(t => t.ID == detail.DRUG_SET_ID);
                                    if (drugSetFirst != null && drugSetFirst.Nav_Confirms != null && drugSetFirst.Nav_Confirms.Any())
                                    {
                                        foreach (var conf in drugSetFirst.Nav_Confirms)
                                        {
                                            T_PR_DRUG_USE_RECORD_CONFIRM confirm = new T_PR_DRUG_USE_RECORD_CONFIRM();
                                            confirm.ORG_ID = entity.ORG_ID;
                                            confirm.USE_RECORD_ID = drugUse.ID;
                                            confirm.NAME = conf.NAME;
                                            confirm.ROW_NO = conf.ROW_NO;
                                            confirm.IS_CONFIRM = false;
                                            drugUseConfirms.Add(confirm);
                                        }
                                    }
                                    if (userUseIds != null && userUseIds.Any())
                                    {
                                        foreach (var u in userUseIds)
                                        {
                                            T_PR_DRUG_USE_RECORD_USER recordUser = new T_PR_DRUG_USE_RECORD_USER();
                                            recordUser.ORG_ID = entity.ORG_ID;
                                            recordUser.USE_RECORD_ID = drugUse.ID;
                                            recordUser.USER_ID = u;
                                            drugUseDetails.Add(recordUser);
                                        };
                                    }
                                    var userID = userUseIds.FirstOrDefault();
                                    var userName = users.FirstOrDefault(t => t.ID == userID)?.NAME;
                                    notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("药品（剂）使用记录表", drugUse.ID, entity.ORG_ID, userID, userName, DateTime.Now,
                                               DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR050"));
                                }
                            }
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "PR048_SHOWPRINT";
                    }
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (confirms != null && confirms.Any())
                        this.BantchSaveEntityNoCommit(confirms);
                    //if (deleteUserIds != null && deleteUserIds.Any())
                    //    this.BantchDeleteEntityNoCommit<T_PR_DRUG_CARRY_RECORD_DETAIL_USER>(deleteUserIds);
                    //if (deleteAcceptIds != null && deleteAcceptIds.Any())
                    //    this.BantchDeleteEntityNoCommit<T_PR_DRUG_CARRY_RECORD_DETAIL_ACCEPT>(deleteAcceptIds);
                    if (carryUsers != null && carryUsers.Any())
                        this.BantchSaveEntityNoCommit(carryUsers);
                    if (carryAccepts != null && carryAccepts.Any())
                        this.BantchSaveEntityNoCommit(carryAccepts);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (drugUses != null && drugUses.Any())
                        this.BantchSaveEntityNoCommit(drugUses);
                    if (drugUseDetails != null && drugUseDetails.Any())
                        this.BantchSaveEntityNoCommit(drugUseDetails);
                    if (drugUseConfirms != null && drugUseConfirms.Any())
                        this.BantchSaveEntityNoCommit(drugUseConfirms);
                });
                return true;
            });
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateNew")]
        public JsonActionResult<bool> FullUpdateNew([FromBody] T_PR_DRUG_CARRY_RECORD entity)
        {
            return SafeExecute(() =>
            {
                var carryUsers = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_USER>();
                var acceptUsers = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_ACCEPT>();
                var userIds = new List<Guid>();
                var userInfos = new List<T_FM_USER>();
                if (string.IsNullOrEmpty(entity.CODE))
                    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(9999).ToString().PadLeft(4,'0');
                entity.STATUS = PFStandardStatus.Draft;
                var confirms = entity.Nav_Confirms;
                entity.Nav_Confirms = null;
                if (confirms != null && confirms.Any())
                {
                    confirms.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.CARRY_RECORD_ID = entity.ID;
                        //if (t.IS_CONFIRM == false)
                        //    throw new Exception("搬运安全未全部确认");
                    });
                }
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        loginUserId = currTask.USER_ID;
                    }
                }
                var details = entity.Nav_Details;
                entity.Nav_Details = null;
                if (details != null && details.Any())
                {
                    details.ForEach(t => {
                        if (t.Nav_Users != null && t.Nav_Users.Any())
                        {
                            t.Nav_Users.ForEach(t1 =>
                            {
                                if (!t1.IS_DELETED && t1.USER_ID != null)
                                    userIds.Add(t1.USER_ID.Value);
                                if (t1.USER_ID == loginUserId && entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                                    t1.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                carryUsers.Add(t1);
                            });
                        }
                        if (t.Nav_Accepts != null && t.Nav_Accepts.Any())
                        {
                            t.Nav_Accepts.ForEach(t2 =>
                            {
                                if (!t2.IS_DELETED && t2.USER_ID != null)
                                    userIds.Add(t2.USER_ID.Value);
                                if(t2.USER_ID == loginUserId && entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                                    t2.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                acceptUsers.Add(t2);
                            });
                        }
                    });
                    userInfos = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(entity.ORG_ID), "Nav_Department").ToList();
                }
                T_FM_NOTIFICATION_TASK task = null;
                var notices = new List<T_FM_NOTIFICATION_TASK>();
                var drugUses = new List<T_PR_DRUG_USE_RECORD>();
                var drugUseDetails = new List<T_PR_DRUG_USE_RECORD_USER>();
                var drugUseConfirms = new List<T_PR_DRUG_USE_RECORD_CONFIRM>();
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = PFStandardStatus.Sign;
                    if (confirms != null && confirms.Any())
                    {
                        confirms.ForEach(t =>
                        {
                            t.ORG_ID = entity.ORG_ID; t.CARRY_RECORD_ID = entity.ID;
                            if (t.IS_CONFIRM == false)
                                throw new Exception("搬运安全未全部确认");
                        });
                    }
                    //var userLinkDetails = new List<DrugCarryRecordModel>();
                    //foreach (var item in details)
                    //{
                    //    DrugCarryRecordModel model = new DrugCarryRecordModel();
                    //    model.SPECIFY_ID = item.SPECIFY_ID;
                    //    model.DRUG_SET_ID = item.DRUG_SET_ID;
                    //    model.UNIT = item.UNIT;
                    //    model.TYPE_ID = item.TYPE_ID;
                    //    model.QTY = item.QTY;
                    //    model.DEPARTMENT_NAME = item.DEPARTMENT;
                    //    userLinkDetails.Add(model);
                    //}
                    //var userUseIds = userIds.Where(m => m != null).Distinct().ToList();
                    var drugSets = new List<T_PR_DRUG_SET>();
                    var carryUserTemps = carryUsers.Where(t => t.USER_ID == loginUserId).Distinct().ToList();
                    if (carryUserTemps != null && carryUserTemps.Any())
                    {
                        var loginUserName = userInfos.FirstOrDefault(m => m.ID == loginUserId)?.NAME;
                        var notice = NotificationTaskService.InsertUserNoticeTaskModel("药品（剂）搬运记录表-确认", entity.ID, entity.ORG_ID, (Guid)loginUserId, loginUserName, DateTime.Now,
                          DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR048_ShowPrint");
                        notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                        notices.Add(notice);
                    }
                    var carryUserOthers = carryUsers.Where(t => t.USER_ID != loginUserId).Distinct().ToList();
                    if (carryUserOthers != null && carryUserOthers.Any())
                    {
                        var carryUserNames = new List<string>();
                        var carryUserIDs = carryUserOthers.Select(t => (Guid)t.USER_ID).Distinct().ToList();
                        if (carryUserIDs != null && carryUserIDs.Any())
                        {
                            foreach (var item in carryUserIDs)
                            {
                                var userName = userInfos.FirstOrDefault(t => t.ID == item)?.NAME;
                                carryUserNames.Add(userName);
                            }
                            notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("药品（剂）搬运记录表-确认", entity.ID, entity.ORG_ID, carryUserIDs, carryUserNames, DateTime.Now,
                                       DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR048_ShowPrint"));
                        }
                    }
                    else
                    {
                        var acceptUserInfos = acceptUsers.GroupBy(t => new { t.CARRY_RECORD_DETAIL_ID,t.USER_ID}).Distinct().ToList();
                        if (acceptUserInfos != null && acceptUserInfos.Any())
                        {
                            foreach (var u in acceptUserInfos)
                            {
                                var first = details.FirstOrDefault(t => t.ID == u.Key.CARRY_RECORD_DETAIL_ID);
                                T_PR_DRUG_USE_RECORD drugUse = new T_PR_DRUG_USE_RECORD();
                                drugUse.ORG_ID = entity.ORG_ID;
                                drugUse.USER_ID = u.Key.USER_ID;
                                drugUse.DEPARTMENT_ID = userInfos.FirstOrDefault(t => t.ID == u.Key.USER_ID).DEPARTMENT_ID;
                                drugUse.TIME = DateTime.Now;
                                drugUse.CARRY_RECORD_ID = entity.ID;
                                drugUse.DRUG_SET_ID = first.DRUG_SET_ID;
                                drugUse.SPECIFY_ID = first.SPECIFY_ID;
                                drugUse.TYPE_ID = first.TYPE_ID;
                                drugUse.QTY = first.QTY;
                                drugUse.UNIT = first.UNIT;
                                drugUse.STATUS = PFStandardStatus.Draft;
                                drugUse.DEPARTMENT = first.DEPARTMENT;
                                drugUse.CODE = entity.CODE;
                                drugUses.Add(drugUse);
                                var drugSetFirst = drugSets.FirstOrDefault(t => t.ID == first.DRUG_SET_ID);
                                if (drugSetFirst != null && drugSetFirst.Nav_Confirms != null && drugSetFirst.Nav_Confirms.Any())
                                {
                                    foreach (var conf in drugSetFirst.Nav_Confirms)
                                    {
                                        T_PR_DRUG_USE_RECORD_CONFIRM confirm = new T_PR_DRUG_USE_RECORD_CONFIRM();
                                        confirm.ORG_ID = entity.ORG_ID;
                                        confirm.USE_RECORD_ID = drugUse.ID;
                                        confirm.NAME = conf.NAME;
                                        confirm.ROW_NO = conf.ROW_NO;
                                        confirm.IS_CONFIRM = false;
                                        drugUseConfirms.Add(confirm);
                                    }
                                }
                                var userFirst= acceptUsers.Where(t =>t.ID == u.Key.USER_ID && t.CARRY_RECORD_DETAIL_ID == u.Key.CARRY_RECORD_DETAIL_ID).FirstOrDefault();
                                T_PR_DRUG_USE_RECORD_USER recordUser = new T_PR_DRUG_USE_RECORD_USER();
                                recordUser.ORG_ID = entity.ORG_ID;
                                recordUser.USE_RECORD_ID = drugUse.ID;
                                recordUser.USER_ID = u.Key.USER_ID;
                                recordUser.ROW_NO = userFirst?.ROW_NO;
                                drugUseDetails.Add(recordUser);
                                var userName = userInfos.FirstOrDefault(t => t.ID == u.Key.USER_ID)?.NAME;
                                notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("药品（剂）使用记录表", drugUse.ID, entity.ORG_ID, u.Key.USER_ID.Value, userName, DateTime.Now,
                                 DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR050"));
                            };
                        }
                        else
                            throw new Exception("使用人员不能为空");
                    }
                    //if (details != null && details.Any())
                    //{
                    //    var drugSetIds = details.Select(t => t.DRUG_SET_ID).Distinct().ToList();
                    //    drugSets = this.GetEntities<T_PR_DRUG_SET>(t => drugSetIds.Contains(t.ID), new BaseFilter(entity.ORG_ID), "Nav_Confirms").ToList();
                    //    foreach (var detail in details)
                    //    {
                    //        if (detail.Nav_Users != null && detail.Nav_Users.Any())
                    //        {
                    //            foreach (var u in detail.Nav_Users)
                    //            {
                    //                if (u.USER_ID == loginUserId)
                    //                {
                    //                    var loginUserName = userInfos.FirstOrDefault(m => m.ID == loginUserId)?.NAME;
                    //                    var notice = NotificationTaskService.InsertUserNoticeTaskModel("药品（剂）搬运记录表-确认", entity.ID, entity.ORG_ID, (Guid)loginUserId, loginUserName, DateTime.Now,
                    //                      DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR048_ShowPrint");
                    //                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                    //                    notices.Add(notice);
                    //                }
                    //            };
                    //        }
                    //        var carryUserNames = new List<string>();
                    //        var carryUserIDs = detail.Nav_Users.Where(t=>t.USER_ID!=loginUserId).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                    //        if (carryUserIDs != null && carryUserIDs.Any())
                    //        {
                    //            foreach (var item in carryUserIDs)
                    //            {
                    //                var userName = userInfos.FirstOrDefault(t => t.ID == item)?.NAME;
                    //                carryUserNames.Add(userName);
                    //            }
                    //            notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("药品（剂）搬运记录表-确认", entity.ID, entity.ORG_ID, carryUserIDs, carryUserNames, DateTime.Now,
                    //                       DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR048_ShowPrint"));
                    //        }
                    //        else
                    //        {
                    //            if (detail.Nav_Accepts != null && detail.Nav_Accepts.Any())
                    //            {
                    //                foreach (var u in detail.Nav_Accepts)
                    //                {
                    //                    T_PR_DRUG_USE_RECORD drugUse = new T_PR_DRUG_USE_RECORD();
                    //                    drugUse.ORG_ID = entity.ORG_ID;
                    //                    drugUse.USER_ID = userInfos.FirstOrDefault().ID;
                    //                    drugUse.DEPARTMENT_ID = userInfos.FirstOrDefault().DEPARTMENT_ID;
                    //                    drugUse.TIME = DateTime.Now;
                    //                    drugUse.CARRY_RECORD_ID = entity.ID;
                    //                    drugUse.DRUG_SET_ID = detail.DRUG_SET_ID;
                    //                    drugUse.SPECIFY_ID = detail.SPECIFY_ID;
                    //                    drugUse.TYPE_ID = detail.TYPE_ID;
                    //                    drugUse.QTY = detail.QTY;
                    //                    drugUse.UNIT = detail.UNIT;
                    //                    drugUse.STATUS = PFStandardStatus.Draft;
                    //                    drugUse.DEPARTMENT = detail.DEPARTMENT;
                    //                    drugUse.CODE = entity.CODE;
                    //                    drugUses.Add(drugUse);
                    //                    var drugSetFirst = drugSets.FirstOrDefault(t => t.ID == detail.DRUG_SET_ID);
                    //                    if (drugSetFirst != null && drugSetFirst.Nav_Confirms != null && drugSetFirst.Nav_Confirms.Any())
                    //                    {
                    //                        foreach (var conf in drugSetFirst.Nav_Confirms)
                    //                        {
                    //                            T_PR_DRUG_USE_RECORD_CONFIRM confirm = new T_PR_DRUG_USE_RECORD_CONFIRM();
                    //                            confirm.ORG_ID = entity.ORG_ID;
                    //                            confirm.USE_RECORD_ID = drugUse.ID;
                    //                            confirm.NAME = conf.NAME;
                    //                            confirm.ROW_NO = conf.ROW_NO;
                    //                            confirm.IS_CONFIRM = false;
                    //                            drugUseConfirms.Add(confirm);
                    //                        }
                    //                    }
                    //                    T_PR_DRUG_USE_RECORD_USER recordUser = new T_PR_DRUG_USE_RECORD_USER();
                    //                    recordUser.ORG_ID = entity.ORG_ID;
                    //                    recordUser.USE_RECORD_ID = drugUse.ID;
                    //                    recordUser.USER_ID = u.USER_ID;
                    //                    recordUser.ROW_NO = u.ROW_NO;
                    //                    drugUseDetails.Add(recordUser);
                    //                    var userName = userInfos.FirstOrDefault(t => t.ID == u.USER_ID)?.NAME;
                    //                    notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("药品（剂）使用记录表", drugUse.ID, entity.ORG_ID, u.USER_ID.Value, userName, DateTime.Now,
                    //                     DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR050"));
                    //                };
                    //            }
                    //            else
                    //                throw new Exception("使用人员不能为空");
                    //        }
                    //    }
                    //}
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "PR048_SHOWPRINT";
                    }
                    details.ForEach(t => { t.Nav_Users = null; t.Nav_Accepts = null; });
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (confirms != null && confirms.Any())
                        this.BantchSaveEntityNoCommit(confirms);
                    if (carryUsers != null && carryUsers.Any())
                        this.BantchSaveEntityNoCommit(carryUsers);
                    if (acceptUsers != null && acceptUsers.Any())
                        this.BantchSaveEntityNoCommit(acceptUsers);
                    //if (deleteUserIds != null && deleteUserIds.Any())
                    //    this.BantchDeleteEntityNoCommit<T_PR_DRUG_CARRY_RECORD_DETAIL_USER>(deleteUserIds);
                    //if (deleteAcceptIds != null && deleteAcceptIds.Any())
                    //    this.BantchDeleteEntityNoCommit<T_PR_DRUG_CARRY_RECORD_DETAIL_ACCEPT>(deleteAcceptIds);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (drugUses != null && drugUses.Any())
                        this.BantchSaveEntityNoCommit(drugUses);
                    if (drugUseDetails != null && drugUseDetails.Any())
                        this.BantchSaveEntityNoCommit(drugUseDetails);
                    if (drugUseConfirms != null && drugUseConfirms.Any())
                        this.BantchSaveEntityNoCommit(drugUseConfirms);
                });
                return true;
            });
        }
        /// <summary>
        /// 识别人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_PR_DRUG_CARRY_RECORD entity)
        {
            return SafeExecute(() =>
            {
                var carry = this.GetEntity<T_PR_DRUG_CARRY_RECORD>(entity.ID, "Nav_Details", "Nav_Details.Nav_Users", "Nav_Details.Nav_Accepts");
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userId = currTask.USER_ID;
                    }
                }
                var carryUsers = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_USER>();
                var acceptUsers = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_ACCEPT>();
                T_FM_NOTIFICATION_TASK task = null;
                var notices = new List<T_FM_NOTIFICATION_TASK>();
                var drugUses = new List<T_PR_DRUG_USE_RECORD>();
                var drugUseDetails = new List<T_PR_DRUG_USE_RECORD_USER>();
                var drugUseConfirms = new List<T_PR_DRUG_USE_RECORD_CONFIRM>();
                var isSend = true;
                var userIds = new List<Guid>();
                var userLinkDetails = new List<DrugCarryRecordModel>();
                if (carry != null && carry.Nav_Details != null && carry.Nav_Details.Any())
                {
                    foreach (var item in carry.Nav_Details)
                    {
                        if (item.Nav_Users != null && item.Nav_Users.Any())
                        {
                            item.Nav_Users.ForEach(t =>
                            {
                                if (t.USER_ID == userId)
                                {
                                    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                    carryUsers.Add(t);
                                }
                            });
                            var temp = item.Nav_Users.FirstOrDefault(t => t.USER_ID != userId && t.DEAL_STATUS == FOUserShiftStatusEnum.待处理);
                            if (temp != null)
                                isSend = false;
                        }

                        if (item.Nav_Accepts != null && item.Nav_Accepts.Any())
                        {
                            item.Nav_Accepts.ForEach(t =>
                            {
                                //if (t.USER_ID == userId)
                                //{
                                //    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                //    acceptUsers.Add(t);
                                //}
                                userIds.Add(t.USER_ID.Value);
                            });
                            //var temp = item.Nav_Accepts.FirstOrDefault(t => t.USER_ID != userId && t.DEAL_STATUS == FOUserShiftStatusEnum.待处理);
                            //if (temp != null)
                            //    isSend = false;
                        }
                        DrugCarryRecordModel model = new DrugCarryRecordModel();
                        model.SPECIFY_ID = item.SPECIFY_ID;
                        model.DRUG_SET_ID = item.DRUG_SET_ID;
                        model.UNIT = item.UNIT;
                        model.TYPE_ID = item.TYPE_ID;
                        model.QTY = item.QTY;
                        model.DEPARTMENT_NAME = item.DEPARTMENT;
                        userLinkDetails.Add(model);
                    }
                    if (isSend)
                    {
                        carry.STATUS = PFStandardStatus.Archived;
                        userIds = userIds.Distinct().ToList();
                        var users = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(carry.ORG_ID));
                        var drugSets = new List<T_PR_DRUG_SET>();
                        if (userLinkDetails != null && userLinkDetails.Any())
                        {
                            var drugSetIds = userLinkDetails.Select(t => t.DRUG_SET_ID).Distinct().ToList();
                            drugSets = this.GetEntities<T_PR_DRUG_SET>(t => drugSetIds.Contains(t.ID), new BaseFilter(carry.ORG_ID), "Nav_Confirms").ToList();
                            foreach (var detail in userLinkDetails)
                            {
                                T_PR_DRUG_USE_RECORD drugUse = new T_PR_DRUG_USE_RECORD();
                                drugUse.ORG_ID = carry.ORG_ID;
                                drugUse.USER_ID = users.FirstOrDefault().ID;
                                drugUse.DEPARTMENT_ID = users.FirstOrDefault().DEPARTMENT_ID;
                                drugUse.TIME = DateTime.Now;
                                drugUse.CARRY_RECORD_ID = carry.ID;
                                drugUse.DRUG_SET_ID = detail.DRUG_SET_ID;
                                drugUse.SPECIFY_ID = detail.SPECIFY_ID;
                                drugUse.TYPE_ID = detail.TYPE_ID;
                                drugUse.QTY = detail.QTY;
                                drugUse.UNIT = detail.UNIT;
                                drugUse.STATUS = PFStandardStatus.Sign;
                                drugUse.DEPARTMENT = detail.DEPARTMENT_NAME;
                                drugUse.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();
                                drugUses.Add(drugUse);
                                var drugSetFirst = drugSets.FirstOrDefault(t => t.ID == detail.DRUG_SET_ID);
                                if (drugSetFirst != null && drugSetFirst.Nav_Confirms != null && drugSetFirst.Nav_Confirms.Any())
                                {
                                    foreach (var conf in drugSetFirst.Nav_Confirms)
                                    {
                                        T_PR_DRUG_USE_RECORD_CONFIRM confirm = new T_PR_DRUG_USE_RECORD_CONFIRM();
                                        confirm.ORG_ID = carry.ORG_ID;
                                        confirm.USE_RECORD_ID = drugUse.ID;
                                        confirm.NAME = conf.NAME;
                                        confirm.IS_CONFIRM = false;
                                        drugUseConfirms.Add(confirm);
                                    }
                                }
                                if (userIds != null && userIds.Any())
                                {
                                    foreach (var u in userIds)
                                    {
                                        T_PR_DRUG_USE_RECORD_USER recordUser = new T_PR_DRUG_USE_RECORD_USER();
                                        recordUser.ORG_ID = carry.ORG_ID;
                                        recordUser.USE_RECORD_ID = drugUse.ID;
                                        recordUser.USER_ID = u;
                                        drugUseDetails.Add(recordUser);
                                    };
                                }
                                var userID = userIds.FirstOrDefault();
                                var userName = users.FirstOrDefault(t => t.ID == userID)?.NAME;
                                notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("药品（剂）使用记录表", drugUse.ID, carry.ORG_ID, userID, userName, DateTime.Now,
                                           DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR050"));
                            }
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "PR048_SHOWPRINT";
                    }

                }
                UnifiedCommit(() =>
                {
                    if (carry != null)
                        this.UpdateEntityNoCommit(carry);
                    if (carryUsers != null && carryUsers.Any())
                        this.BantchSaveEntityNoCommit(carryUsers);
                    if (acceptUsers != null && acceptUsers.Any())
                        this.BantchSaveEntityNoCommit(acceptUsers);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (drugUses != null && drugUses.Any())
                        this.BantchSaveEntityNoCommit(drugUses);
                    if (drugUseDetails != null && drugUseDetails.Any())
                        this.BantchSaveEntityNoCommit(drugUseDetails);
                    if (drugUseConfirms != null && drugUseConfirms.Any())
                        this.BantchSaveEntityNoCommit(drugUseConfirms);
                });
                return true;
            });
        }

        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdateNew")]
        public JsonActionResult<bool> IdentityUpdateNew([FromBody] T_PR_DRUG_CARRY_RECORD entity)
        {
            return SafeExecute(() => {
                var carryUsers = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_USER>();
                var carryUserTemps = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_USER>();
                var acceptUsers = new List<T_PR_DRUG_CARRY_RECORD_DETAIL_ACCEPT>();
                var notices = new List<T_FM_NOTIFICATION_TASK>();
                var drugUses = new List<T_PR_DRUG_USE_RECORD>();
                var drugUseDetails = new List<T_PR_DRUG_USE_RECORD_USER>();
                var drugUseConfirms = new List<T_PR_DRUG_USE_RECORD_CONFIRM>();
                var monitor = this.GetEntity<T_PR_DRUG_CARRY_RECORD>(entity.ID);
                var monitorDetail = this.GetEntities<T_PR_DRUG_CARRY_RECORD_DETAIL>(t=> t.CARRY_RECORD_ID == monitor.ID, new BaseFilter(monitor.ORG_ID),"Nav_Users", "Nav_Accepts").ToList();
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userId = currTask.USER_ID;
                    }
                }
                if (monitorDetail != null && monitorDetail.Any())
                {
                    var drugSetIds = monitorDetail.Select(t => t.DRUG_SET_ID).Distinct().ToList();
                    var drugSets = this.GetEntities<T_PR_DRUG_SET>(t => drugSetIds.Contains(t.ID), new BaseFilter(monitor.ORG_ID), "Nav_Confirms").ToList();
                    var userInfos = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0, new BaseFilter(monitor.ORG_ID), "Nav_Department").ToList();
                    foreach (var item in monitorDetail)
                    {
                        if (item.Nav_Users != null && item.Nav_Users.Any())
                        {
                            item.Nav_Users.ForEach(t =>
                            {
                                if (t.USER_ID == userId)
                                {
                                    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                    carryUsers.Add(t);
                                }
                                carryUserTemps.Add(t);
                            });
                        }
                        if (item.Nav_Accepts != null && item.Nav_Accepts.Any())
                        {
                            item.Nav_Accepts.ForEach(t =>
                            {
                                acceptUsers.Add(t);
                            });
                        }
                    }
                    //判断是否已经有人确认过，没有的话为第一个人确认
                    bool isDeal = false;
                    if (carryUserTemps != null && carryUserTemps.Any())
                    {
                        var isExist = carryUserTemps.FirstOrDefault(t => t.DEAL_STATUS == FOUserShiftStatusEnum.待处理);
                        if (isExist == null)
                        {
                            isDeal = true;
                            monitor.STATUS = PFStandardStatus.Archived;
                        }
                    }
                    if (isDeal)
                    {
                        var acceptUserInfos = acceptUsers.GroupBy(t => new { t.CARRY_RECORD_DETAIL_ID, t.USER_ID }).Distinct().ToList();
                        if (acceptUserInfos != null && acceptUserInfos.Any())
                        {
                            foreach (var u in acceptUserInfos)
                            {
                                var detail = monitorDetail.FirstOrDefault(t => t.ID == u.Key.CARRY_RECORD_DETAIL_ID);
                                T_PR_DRUG_USE_RECORD drugUse = new T_PR_DRUG_USE_RECORD();
                                drugUse.ORG_ID = monitor.ORG_ID;
                                drugUse.USER_ID = u.Key.USER_ID;
                                drugUse.DEPARTMENT_ID = userInfos.FirstOrDefault(t=>t.ID == u.Key.USER_ID)?.DEPARTMENT_ID;
                                drugUse.TIME = DateTime.Now;
                                drugUse.CARRY_RECORD_ID = entity.ID;
                                drugUse.DRUG_SET_ID = detail.DRUG_SET_ID;
                                drugUse.SPECIFY_ID = detail.SPECIFY_ID;
                                drugUse.TYPE_ID = detail.TYPE_ID;
                                drugUse.QTY = detail.QTY;
                                drugUse.UNIT = detail.UNIT;
                                drugUse.STATUS = PFStandardStatus.Draft;
                                drugUse.DEPARTMENT = detail.DEPARTMENT;
                                drugUse.CODE = monitor.CODE;
                                drugUses.Add(drugUse);
                                var drugSetFirst = drugSets.FirstOrDefault(t => t.ID == detail.DRUG_SET_ID);
                                if (drugSetFirst != null && drugSetFirst.Nav_Confirms != null && drugSetFirst.Nav_Confirms.Any())
                                {
                                    foreach (var conf in drugSetFirst.Nav_Confirms)
                                    {
                                        T_PR_DRUG_USE_RECORD_CONFIRM confirm = new T_PR_DRUG_USE_RECORD_CONFIRM();
                                        confirm.ORG_ID = monitor.ORG_ID;
                                        confirm.USE_RECORD_ID = drugUse.ID;
                                        confirm.NAME = conf.NAME;
                                        confirm.ROW_NO = conf.ROW_NO;
                                        confirm.IS_CONFIRM = false;
                                        drugUseConfirms.Add(confirm);
                                    }
                                }
                                var userFirst = acceptUsers.FirstOrDefault(t => t.ID == u.Key.USER_ID && t.CARRY_RECORD_DETAIL_ID == u.Key.CARRY_RECORD_DETAIL_ID);
                                T_PR_DRUG_USE_RECORD_USER recordUser = new T_PR_DRUG_USE_RECORD_USER();
                                recordUser.ORG_ID = monitor.ORG_ID;
                                recordUser.USE_RECORD_ID = drugUse.ID;
                                recordUser.USER_ID = u.Key.USER_ID;
                                recordUser.ROW_NO = userFirst?.ROW_NO;
                                drugUseDetails.Add(recordUser);
                                var userName = userInfos.FirstOrDefault(t => t.ID == u.Key.USER_ID)?.NAME;
                                notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("药品（剂）使用记录表", drugUse.ID, monitor.ORG_ID, u.Key.USER_ID.Value, userName, DateTime.Now,
                                 DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PR050"));
                            };
                        }
                        else
                            throw new Exception("使用人员不能为空");
                    }
                }
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "PR048_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (monitor != null)
                        UpdateEntityNoCommit(monitor, "STATUS");
                    if (carryUsers != null && carryUsers.Any())
                        this.BantchSaveEntityNoCommit(carryUsers);
                    //if (acceptUsers != null && acceptUsers.Any())
                    //    this.BantchSaveEntityNoCommit(acceptUsers);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (drugUses != null && drugUses.Any())
                        this.BantchSaveEntityNoCommit(drugUses);
                    if (drugUseDetails != null && drugUseDetails.Any())
                        this.BantchSaveEntityNoCommit(drugUseDetails);
                    if (drugUseConfirms != null && drugUseConfirms.Any())
                        this.BantchSaveEntityNoCommit(drugUseConfirms);
                });
                return true;
            });
        }
    }
}
