using System;
using System.Collections.Generic;
using System.Linq;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.OP;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.MS.Domain.Entities.OG;
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;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SENewUsers")]
    public class SENewUsersController : AuthorizeApiController<T_SE_NEW_USERS>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        ISENewUserService NewUserService { get; set; }
        public SENewUsersController(IFMNotificationTaskService notificationTaskService, IFMUserService userService, ISENewUserService newUserService)
        {
            NotificationTaskService = notificationTaskService;
            UserService = userService;
            NewUserService = newUserService;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_NEW_USERS entity)
        {
            return SafeExecute<bool>(() =>
            {
                List<T_FM_NOTIFICATION_TASK> sendNoticeList = new List<T_FM_NOTIFICATION_TASK>();
                List<T_SE_NEW_USER_DETAIL_FILE> detailFiles = new List<T_SE_NEW_USER_DETAIL_FILE>();
                T_FM_NOTIFICATION_TASK finishNotice = null;
                var Nav_NewUserDetail = entity.Nav_NewUserDetail;
                entity.Nav_NewUserDetail = null;
                var Nav_Files = entity.Nav_Files;
                entity.Nav_Files = null;
                var Nav_Teachers = entity.Nav_Teachers;
                entity.Nav_Teachers = null;
                if (Nav_Files != null && Nav_Files.Count() > 0)
                {
                    foreach (var item in Nav_Files)
                        item.Nav_NewUser = null;
                }
                if (Nav_Teachers != null && Nav_Teachers.Count() > 0)
                {
                    foreach (var item in Nav_Teachers)
                        item.Nav_User = null;
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var listCodeCheck = Nav_NewUserDetail.Where(e => !e.IS_DELETED && e.CODE != null && e.CODE.Length > 0).Select(e => e.CODE);
                    if (listCodeCheck != null && listCodeCheck.Count() > 0)
                    {
                        var listUserID = Nav_NewUserDetail.Where(e => !e.IS_DELETED && e.USER_ID.HasValue && e.CODE != null && e.CODE.Length > 0).Select(e => e.USER_ID.Value);
                        var listUCodeCheck = GetEntities<T_FM_USER>(e => !e.IS_DELETED && listCodeCheck.Contains(e.CODE) && !listUserID.Contains(e.ID), null, null).Select(e => e.CODE);
                        if (listUCodeCheck != null && listUCodeCheck.Count() > 0)
                        {
                            throw new Exception("工号不能重复【" + String.Join("，", listUCodeCheck) + "】");
                        }
                    }

                    var endTime = DateTime.Now.AddDays(10);
                    var newEndTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59);
                    if (entity.TRAINNING_TIME == "0" || string.IsNullOrEmpty(entity.TRAINNING_TIME))
                    {
                        throw new Exception("学时不能为0!");
                    }

                    if (entity.TaskID == Guid.Empty)
                    {
                        throw new Exception("获取待办信息失败，请到主页处理待办！");
                    }
                    else
                    {
                        finishNotice = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.ID == entity.TaskID);
                        if (finishNotice.SOURCE_FORMCODE == "SE061_SHOWPRINT")
                        {
                            throw new Exception("请勿重复提交！");
                        }
                    }

                    BaseFilter bf = new BaseFilter(entity.ORG_ID);
                    bf.Include = new string[] { "Nav_Parent.Nav_Parent" };
                    var alldeps = GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, bf);
                    var currUserDepId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                    var auditDep = GetEntity<T_FM_DEPARTMENT>(currUserDepId.ToString());

                    //var listCode = Nav_NewUserDetail.Where(e => e.CODE.Length > 0).Select(e => e.CODE);
                    //var listUserCheck = GetEntities<T_FM_USER>(e => listCode.Contains(e.CODE), null, null);

                    //var listCode = Nav_NewUserDetail.Where(e => e.CODE != null).Where(e => e.CODE.Length > 0).Select(e => e.CODE);
                    //IEnumerable<T_FM_USER> listUserCheck = null;
                    //if (listCode != null && listCode.Count() > 0)
                    //{
                    //    listUserCheck = GetEntities<T_FM_USER>(e => listCode.Contains(e.CODE), null, null);
                    //}

                    #region NEXT_DEPARTMENT_ID  系统按规律给下级组织  自己可修改下级组织

                    int index = 0;
                    foreach (var item in Nav_NewUserDetail)
                    {
                        if (item.IS_DELETED)
                        {
                            continue;
                        }
                        index++;
                        if (!item.NEXT_DEPARTMENT_ID.HasValue || entity.TRAIN_STATUS == SEThreeLevelSafeTrainType.班组级)
                        {
                            // 下个部门没填 就是最后一级了  或者  班组级培训 
                            if (string.IsNullOrEmpty(item.CODE))
                            {
                                throw new Exception("请填写行：" + index + "的工号!");
                            }
                            if (!item.USER_DEPARTMENT_ID.HasValue)
                            {
                                throw new Exception("请填写行：" + index + "的组织!");
                            }
                            if (item.USER_POST_ID == Guid.Empty || item.USER_POST_ID == null)
                            {
                                throw new Exception("请填写行：" + index + "的岗位!");
                            }
                        }
                        item.Nav_DepartmentNext = null;
                    }

                    #endregion
                    var allDepartment = Nav_NewUserDetail.Where(t => t.IS_DELETED == false).Select(t => t.USER_DEPARTMENT_ID);
                    if (allDepartment == null || allDepartment.Count() < 1)
                    {
                        //全部都删除了
                        entity.IS_DELETED = true;
                        foreach (var item in Nav_NewUserDetail)
                        {
                            item.IS_DELETED = true;
                        }
                        foreach (var item in Nav_Teachers)
                        {
                            item.IS_DELETED = true;
                        }
                        foreach (var item in Nav_Files)
                        {
                            item.IS_DELETED = true;
                        }
                        foreach (var item in detailFiles)
                        {
                            item.IS_DELETED = true;
                        }
                    }
                    else
                    {
                        var allUser = GetEntities<T_FM_USER>(t => allDepartment.Contains(t.DEPARTMENT_ID) && t.Nav_ApproveRole != null, new BaseFilter(entity.ORG_ID));
                        index = 1;
                        if (entity.IS_CREATETEST == SETrainNeedSuvey.否)
                        {
                            foreach (var item in Nav_NewUserDetail)
                            {
                                if (item.IS_DELETED)
                                    continue;
                                if (string.IsNullOrEmpty(item.SCORE))
                                {
                                    throw new Exception("线下考试请填写分数，行【" + index + "】!");
                                }
                                if (!item.EXAMINATION_RESULTS.HasValue)
                                {
                                    throw new Exception("线下考试请完善考核结果，行【" + index + "】!");
                                }
                                if (item.Nav_Files == null)
                                {
                                    throw new Exception("线下考试请上传附件，行【" + index + "】!");
                                }
                                if (item.Nav_Files != null && item.Nav_Files.Count() > 0)
                                {
                                    item.Nav_Files.ForEach(nf =>
                                    {
                                        nf.USER_DETAIL_ID = item.ID;
                                    });
                                    detailFiles.AddRange(item.Nav_Files);
                                    item.Nav_Files = null;
                                }
                                index++;
                            }
                        }
                        var listUserID = Nav_NewUserDetail.Where(e => e.USER_ID.HasValue).Select(e => e.USER_ID.Value);
                        var listUser = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null);

                        foreach (var item in Nav_NewUserDetail)
                        {
                            if (!item.USER_ID.HasValue || item.IS_DELETED)
                                continue;
                            sendNoticeList.Add(NotificationTaskService.InsertUserNoticeTaskModel("三级安全培训记录-" + entity.TRAIN_STATUS.GetDescription() + "-签到", item.ID, entity.ORG_ID, (Guid)item.USER_ID, listUser.FirstOrDefault(e => e.ID == item.USER_ID.Value)?.NAME, DateTime.Now, DateTime.Now.AddDays(1), 1, "SE062_SHOWPRINT"));
                        }
                    }
                    finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE061_SHOWPRINT");
                }

                var deleteD = Nav_NewUserDetail.Where(e => e.IS_DELETED && e.USER_ID.HasValue);
                List<T_FM_USER> listUserDel = null;
                List<T_FM_PERSON> listPersonDel = null;
                List<T_FM_USER_BELONG_ROLE> listRoleDel = null;
                IEnumerable<T_SE_USER_TEMP> listUT = null;

                if (deleteD != null && deleteD.Count() > 0)
                {
                    var listUserIDDel = deleteD.Select(e => e.USER_ID.Value);
                    var listUsers = GetEntities<T_FM_USER>(e => listUserIDDel.Contains(e.ID), null, "Nav_Person", "Nav_BelongRoles");
                    listUT = GetEntities<T_SE_USER_TEMP>(e => e.USER_ID.HasValue && listUserIDDel.Contains(e.USER_ID.Value), null, null);
                    listUserDel = new List<T_FM_USER>();
                    listPersonDel = new List<T_FM_PERSON>();
                    listRoleDel = new List<T_FM_USER_BELONG_ROLE>();

                    foreach (var item in listUsers)
                    {
                        item.Nav_Person.IS_DELETED = true;
                        item.Nav_Person.MODIFY_TIME = DateTime.Now;
                        listPersonDel.Add(item.Nav_Person);
                        if (item.Nav_BelongRoles != null && item.Nav_BelongRoles.Any())
                        {
                            foreach (var itemr in item.Nav_BelongRoles)
                            {
                                itemr.IS_DELETED = true;
                                itemr.MODIFY_TIME = DateTime.Now;
                            }
                            listRoleDel.AddRange(item.Nav_BelongRoles);
                        }
                        item.Nav_BelongRoles = null;
                        item.Nav_Person = null;
                        item.IS_DELETED = true;
                        item.MODIFY_TIME = DateTime.Now;
                        listUserDel.Add(item);
                    }
                }

                var DetailDel = Nav_NewUserDetail.Where(e => e.IS_DELETED);
                if (DetailDel != null && DetailDel.Count() > 0)
                    Nav_NewUserDetail = Nav_NewUserDetail.Where(e => !e.IS_DELETED).ToList();
                var FilesDel = Nav_Files.Where(e => e.IS_DELETED);
                if (FilesDel != null && FilesDel.Count() > 0)
                    Nav_Files = Nav_Files.Where(e => !e.IS_DELETED).ToList();
                var detailFilesDel = detailFiles.Where(e => e.IS_DELETED);
                if (detailFilesDel != null && detailFilesDel.Count() > 0)
                    detailFiles = detailFiles.Where(e => !e.IS_DELETED).ToList();
                var TeachersDel = Nav_Teachers.Where(e => e.IS_DELETED);
                if (TeachersDel != null && TeachersDel.Count() > 0)
                    Nav_Teachers = Nav_Teachers.Where(e => !e.IS_DELETED).ToList();

                //老师 附件 明细附件 都是页面传值 BantchUpdateEntity_noneBase处理需要判断是否确实有值 没有就去除
                IEnumerable<Guid> IlistID = null;
                if (FilesDel != null && FilesDel.Count() > 0)
                {
                    IlistID = FilesDel.Select(e => e.ID);
                    FilesDel = GetEntities<T_SE_NEW_USERS_FILE>(e => IlistID.Contains(e.ID), null, null);
                    if (FilesDel != null && FilesDel.Count() > 0)
                    {
                        FilesDel.ForEach(e => e.IS_DELETED = true);
                    }
                }

                if (detailFilesDel != null && detailFilesDel.Count() > 0)
                {
                    IlistID = detailFilesDel.Select(e => e.ID);
                    detailFilesDel = GetEntities<T_SE_NEW_USER_DETAIL_FILE>(e => IlistID.Contains(e.ID), null, null);
                    if (detailFilesDel != null && detailFilesDel.Count() > 0)
                    {
                        detailFilesDel.ForEach(e => e.IS_DELETED = true);
                    }
                }

                if (TeachersDel != null && TeachersDel.Count() > 0)
                {
                    IlistID = TeachersDel.Select(e => e.ID);
                    TeachersDel = GetEntities<T_SE_NEW_USERS_TEACHER>(e => IlistID.Contains(e.ID), null, null);
                    if (TeachersDel != null && TeachersDel.Count() > 0)
                    {
                        TeachersDel.ForEach(e => e.IS_DELETED = true);
                    }
                }

                UnifiedCommit(() =>
                {
                    if (sendNoticeList != null && sendNoticeList.Any())
                        BantchAddEntityNoCommit(sendNoticeList);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (Nav_NewUserDetail != null && Nav_NewUserDetail.Any())
                        BantchSaveEntityNoCommit(Nav_NewUserDetail);//BantchSaveEntityNoCommit(Nav_NewUserDetail); BantchUpdateEntity_noneBase
                    if (DetailDel != null && DetailDel.Any())
                        BantchUpdateEntity_noneBase(DetailDel);
                    if (Nav_Files != null && Nav_Files.Any())
                        BantchSaveEntityNoCommit(Nav_Files);//BantchSaveEntityNoCommit  BantchUpdateEntity_noneBase
                    if (FilesDel != null && FilesDel.Any())
                        BantchUpdateEntity_noneBase(FilesDel);
                    if (detailFiles.Any())
                        BantchSaveEntityNoCommit(detailFiles);//BantchSaveEntityNoCommit  BantchUpdateEntity_noneBase
                    if (detailFilesDel != null && detailFilesDel.Any())
                        BantchUpdateEntity_noneBase(detailFilesDel);
                    if (Nav_Teachers.Any())
                        BantchSaveEntityNoCommit(Nav_Teachers);//BantchSaveEntityNoCommit  BantchUpdateEntity_noneBase
                    if (TeachersDel != null && TeachersDel.Count() > 0)
                        BantchUpdateEntity_noneBase(TeachersDel);
                    if (listUserDel != null && listUserDel.Any())
                        BantchUpdateEntity_noneBase(listUserDel);
                    if (listPersonDel != null && listPersonDel.Any())
                        BantchUpdateEntity_noneBase(listPersonDel);
                    if (listRoleDel != null && listRoleDel.Any())
                        BantchUpdateEntity_noneBase(listRoleDel);
                    if (listUT != null && listUT.Any())
                        BantchUpdateEntity_noneBase(listUT);
                    //if (entity.IS_DELETED)
                    //{
                    BantchUpdateEntity_noneBase(new List<T_SE_NEW_USERS>() { entity });
                    //}
                    //else
                    //{
                    //    UpdateEntityNoCommit(entity);
                    //}
                });

                if (listUserDel != null && listUserDel.Count() > 0)
                {
                    var listCode = listUserDel.Select(e => e.CODE);
                    using (var context = new MigrationContext())
                    {
                        var listDel = context.GetEntities<T_OP_ALLUSER>(e => listCode.Contains(e.CODE) && e.ORG_ID == entity.ORG_ID, null, null);
                        foreach (var item in listDel)
                        {
                            item.IS_DELETED = true;
                        }
                        context.DeleteEntities(listDel);
                        context.SaveChanges();
                    }
                }

                return true;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = filter.GetOrgId();
                var currID = Guid.Parse(filter.Parameter1);
                var taskID = Guid.Parse(filter.Parameter2);
                var eduCardID = Guid.Parse(filter.Parameter3);
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (taskID != null && taskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == taskID);
                    if (currTask != null)
                    {
                        userID = currTask.USER_ID;
                    }
                }
                T_FM_NOTIFICATION_TASK finishNotice = null;
                T_FM_NOTIFICATION_TASK sendNotice = null;
                finishNotice = NotificationTaskService.GetTaskFinishModel(taskID);
                List<T_SE_NEW_USER_DETAIL_PAPER> Nav_Papers = null;
                #region
                var eduCard = GetEntity<T_SE_NEW_USERS>(eduCardID);
                List<T_FM_USER_PRODUCTION_UNIT> units = new List<T_FM_USER_PRODUCTION_UNIT>();
                var currUser = GetEntity<T_FM_USER>(t => t.ID == userID);
                var currUserDeail = GetEntity<T_SE_NEW_USER_DETAIL>(t => t.ID == currID);
                var currPerson = GetEntity<T_FM_PERSON>(t => t.ID == currUser.PERSON_ID);
                T_FM_DEPARTMENT departInfo = null;
                if (!string.IsNullOrEmpty(currUserDeail.CODE))//不一样才进行 修改 比如一开始 是手机号码 配置的是工号
                {
                    departInfo = this.GetEntity<T_FM_DEPARTMENT>(currUserDeail.USER_DEPARTMENT_ID.ToString());
                    if (departInfo != null && departInfo.MineType != null)
                    {
                        var enumList = this.GetEntity<T_FM_ENUMS>(t => t.CODE == "BSMineTypeEnum" && t.VALUE == departInfo.MineType);
                        currUser.MineType = departInfo.MineType.ToString();
                        T_FM_USER_PRODUCTION_UNIT unit = new T_FM_USER_PRODUCTION_UNIT();
                        unit.ORG_ID = orgId;
                        unit.USER_ID = (Guid)userID;
                        unit.ENUMS_ID = enumList?.ID;
                        unit.Nav_Enums = null;
                        units.Add(unit);
                    }
                    if (!string.IsNullOrEmpty(currUserDeail.CODE) && currUserDeail.CODE != currUser.CODE)
                    {
                        var userCodeCheck = GetEntity<T_FM_USER>(e => e.CODE == currUserDeail.CODE && e.ID != currUser.ID);
                        if (userCodeCheck != null)
                        {
                            throw new Exception("工号不能重复，请核对工号并联系管理员处理！");
                        }

                        using (var context = new MigrationContext(ConfigurationManager.ConnectionStrings["default"]))
                        {
                            var opuser = context.GetEntity<T_OP_ALLUSER>(t => t.CODE == currUser.CODE, null);
                            opuser.CODE = currUserDeail.CODE;
                            context.UpdateEntity(opuser);
                            context.SaveChanges();
                        }
                    }
                    currUser.CODE = currUserDeail.CODE;
                    currUser.DEPARTMENT_ID = currUserDeail.USER_DEPARTMENT_ID;
                    currPerson.CODE = currUserDeail.CODE;
                    currPerson.DEPARTMENT_ID = currUserDeail.USER_DEPARTMENT_ID;
                    currPerson.POST_ID = currUserDeail.USER_POST_ID;
                    UpdateEntity(currUser);
                    UpdateEntity(currPerson);
                }
                T_SE_NEW_USERS eduCardRef = null;
                T_SE_NEW_USERS newEduCard = null;
                List<T_SE_NEW_USER_DETAIL> userDetailList = null;
                T_SE_NEW_USER_DETAIL currDetail = null;
                T_FM_NOTIFICATION_TASK sendNoticeRef = null;
                T_FM_NOTIFICATION_TASK sendNoticeRefZRZ = null;//安全生产责任制签订

                T_OG_SAFE_PDT_SIGNED signRecord = null;
                T_OG_SAFE_PDT_SIGNED_POST signPost = null;
                T_SE_NEW_USER_DETAIL_TEXT UserText = null;

                if (eduCard.IS_CREATETEST == SETrainNeedSuvey.是)
                {
                    //生成考题 
                    string Msg = string.Empty;
                    bool isOK = NewUserService.GetText(eduCard.ORG_ID.Value, currID, userID.Value, eduCard, null, ref UserText, ref Nav_Papers, ref sendNotice, ref Msg, 1);

                    if (!isOK)
                    {
                        throw new Exception(Msg);
                    }

                    //List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                    //var config = GetEntity<T_SE_SECONFIG>(t => true);
                    //var SCount = 1;
                    //var MCount = 1;
                    //var CCount = 1;
                    //if (config != null)
                    //{
                    //    if (config.M_TEST_COUNT > 0 || config.S_TEST_COUNT > 0 || config.C_TEST_COUNT > 0)
                    //    {
                    //        //王永文 只要有配置 就获取
                    //        MCount = config.M_TEST_COUNT;
                    //        SCount = config.S_TEST_COUNT;
                    //        CCount = config.C_TEST_COUNT;
                    //    }
                    //    else
                    //    {
                    //        //保持原来的版本  
                    //        if (config.M_TEST_COUNT > 0)
                    //        {
                    //            MCount = config.M_TEST_COUNT;
                    //        }
                    //        if (config.S_TEST_COUNT > 0)
                    //        {
                    //            SCount = config.S_TEST_COUNT;
                    //        }
                    //        if (config.C_TEST_COUNT > 0)
                    //        {
                    //            CCount = config.C_TEST_COUNT;
                    //        }
                    //    }
                    //}
                    //var testidlist = new List<Guid>();
                    //var testFilter = new BaseFilter(filter.GetOrgId());
                    //testFilter.Include = new string[] { "Nav_Points" };
                    //var currStatus = eduCard.TRAIN_STATUS;
                    //IEnumerable<T_SE_TEST_ENUM_POINT> pointS = new List<T_SE_TEST_ENUM_POINT>();
                    //string PointName = "";
                    //if (eduCard.TRAIN_STATUS == SEThreeLevelSafeTrainType.公司级)
                    //{
                    //    PointName = "三级安全教育-公司级";
                    //}
                    //else if (eduCard.TRAIN_STATUS == SEThreeLevelSafeTrainType.部门级)
                    //{
                    //    PointName = "三级安全教育-部门级";
                    //}
                    //else if (eduCard.TRAIN_STATUS == SEThreeLevelSafeTrainType.班组级)
                    //{
                    //    PointName = "三级安全教育-班组级";
                    //}
                    //pointS = GetEntities<T_SE_TEST_ENUM_POINT>(t => t.NAME == PointName, new BaseFilter(orgId));
                    //if (pointS == null || pointS.Count() < 1)
                    //{
                    //    throw new Exception("未找到试题知识点【" + PointName + "】的配置信息，配置路径：系统管理 > 安全教育培训配置 > 知识点类型。");
                    //}
                    //var pointIDS = pointS.Select(t => t.ID).ToList();
                    //var allTests = GetEntities<T_SE_TEST>(st => st.Nav_Points.Any(pt => pointIDS.Contains((Guid)pt.POINT_ID)), testFilter).ToList();
                    ////var errorMsg = "";
                    ////if (errorMsg != "")
                    ////{
                    ////    throw new Exception("知识点 " + errorMsg + " 没有题目!");
                    ////}
                    //var errorMsg = "";
                    //foreach (var testPoint in pointIDS)
                    //{
                    //    var havepoint = allTests.Where(st => st.Nav_Points.Any(pt => pt.POINT_ID == testPoint));
                    //    if (havepoint.Count() < 1)
                    //    {
                    //        var noPoint = GetEntity<T_SE_TEST_ENUM_POINT>(testPoint);
                    //        errorMsg += noPoint.NAME + ",";
                    //    }
                    //}
                    //if (errorMsg != "")
                    //{
                    //    throw new Exception("知识点 " + errorMsg + " 没有题目!");
                    //}
                    //var SCurrentCount = allTests.Count(t => t.TYPE == SETestTypeEnum.单选题);
                    //var MCurrentCount = allTests.Count(t => t.TYPE == SETestTypeEnum.多选题);
                    //var CCurrentCount = allTests.Count(t => t.TYPE == SETestTypeEnum.是非题);
                    //errorMsg = "";
                    //if (SCurrentCount < SCount)
                    //{
                    //    errorMsg += "题库中题目数量不足!";
                    //    errorMsg += "单选题还需" + (SCount - SCurrentCount) + "题\n";
                    //}
                    //if (MCurrentCount < MCount)
                    //{
                    //    errorMsg += "题库中题目数量不足!";
                    //    errorMsg += "多选题还需" + (MCount - MCurrentCount) + "题\n";
                    //}
                    //if (CCurrentCount < CCount)
                    //{
                    //    errorMsg += "题库中题目数量不足!";
                    //    errorMsg += "是非题还需" + (CCount - CCurrentCount) + "题\n";
                    //}
                    //if (errorMsg != "")
                    //{
                    //    throw new Exception(errorMsg);
                    //}
                    //CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.是非题, CCount);
                    //CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.单选题, SCount);
                    //CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.多选题, MCount);

                    //if (testidlist.Count == 0 || testidlist.Count < (SCount + MCount + CCount))
                    //{
                    //    throw new Exception("当前题库数据不足，未能正常生成试卷! 知识点：" + PointName + "是非题：" + CCount + "题，单选题：" + SCount + "题，多选题：" + MCount + "题！");
                    //}
                    //Nav_Papers = new List<T_SE_NEW_USER_DETAIL_PAPER>();

                    //UserText = new T_SE_NEW_USER_DETAIL_TEXT();
                    //UserText.RECORD_ID = currID;
                    //UserText.ID = Guid.NewGuid();
                    //UserText.ORG_ID = filter.GetOrgId();
                    //UserText.USER_ID = userID;
                    //UserText.TEXT_TIMES = 1;

                    //testidlist.ForEach(testid =>
                    //{
                    //    var p = new T_SE_NEW_USER_DETAIL_PAPER
                    //    {
                    //        RECORD_ID = currID,
                    //        ID = Guid.NewGuid(),
                    //        ORG_ID = filter.GetOrgId(),
                    //        TEXT_ID = UserText.ID,
                    //        USER_ID = userID,
                    //        TEST_ID = testid,
                    //        ANSWER = 0,
                    //    };
                    //    Nav_Papers.Add(p);
                    //});
                    //sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("三级安全教育在线答题-" + eduCard.TRAIN_STATUS.GetDescription(), UserText.ID, UserText.ORG_ID, (Guid)userID, GetEntity<T_FM_USER>((Guid)userID).NAME, DateTime.Now, DateTime.Now.AddHours(12), 1, "SE061_PAPERPAGE");
                }
                else
                {
                    CreateNextLevel(orgId, currID, taskID, eduCardID, null, ref eduCardRef, ref newEduCard, ref userDetailList, ref currDetail, ref sendNoticeRef);


                    #region  wyw  如果没有继续触发下一级  直接触发    安全生产责任制签订 OG001_SHOWPRINT  如果找不到对应的责任制 就给对应组织安全员（或班长） 触发今日提醒

                    GetOG001(taskID, currUser, currPerson, departInfo, ref signRecord, ref signPost, ref sendNoticeRefZRZ);


                    //if (sendNoticeRef == null)
                    //{
                    //    var post = GetEntity<T_SC_DEPARTMENT_POST>(t => t.Nav_Dept.DEPARTMENT_ID == currUser.DEPARTMENT_ID && t.DEPOST_ID == currPerson.POST_ID, new string[] { "Nav_Dept.Nav_Post" });
                    //    if (post != null)
                    //    {
                    //        var standardCreate = GetEntity<T_SC_STANDARD_CREATE>(t => t.POST_ID == post.Nav_Dept.POST_ID && t.STATUS == SCSystemEditStatus.已归档 && t.FILE_STATUS == SCSystemFileStatus.有效);
                    //        if (standardCreate != null)
                    //        {
                    //            var chargeUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == post.Nav_Dept.Nav_Post.DEPARTMENT_ID && t.Nav_Person.POST_ID == post.Nav_Dept.Nav_Post.DEPOST_ID && t.ENABLE_STATUS == 0);
                    //            if (chargeUser != null)
                    //            {
                    //                signRecord = new T_OG_SAFE_PDT_SIGNED
                    //                {
                    //                    ID = Guid.NewGuid(),
                    //                    ORG_ID = currUser.ORG_ID,
                    //                    STATUS = (int)PFStandardStatus.Draft,
                    //                    TRIGGER_TYPE = OGPersonalSignedTriggerType.新员工触发,
                    //                    //TRIGGER_TYPE = OGPersonalSignedTriggerType.手动新增,
                    //                    STANDARD_ID = standardCreate.ID,
                    //                    FILE_CONTENT = standardCreate.FILE_CONTENT,
                    //                    DEPARTMENT_ID = currUser.DEPARTMENT_ID,
                    //                    ANNUAL = DateTime.Now.Year
                    //                };
                    //                if (chargeUser != null)
                    //                {
                    //                    signRecord.CHARGE_USER_ID = chargeUser.ID;
                    //                }
                    //                signPost = new T_OG_SAFE_PDT_SIGNED_POST
                    //                {
                    //                    SAFE_PDT_SIGNED_ID = signRecord.ID,
                    //                    ID = Guid.NewGuid(),
                    //                    ORG_ID = currUser.ORG_ID,
                    //                    USER_ID = currUser.ID,
                    //                    POST_ID = currPerson.POST_ID,
                    //                    CHARGE_USER_ID = signRecord.CHARGE_USER_ID
                    //                };
                    //                sendNoticeRef = NotificationTaskService.InsertUserNoticeTaskModel(DateTime.Now.ToShortDateString() + "安全生产责任制个人签订表", signRecord.ID, currUser.ORG_ID, currUser.ID, currUser.NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "OG001_SHOWPRINT");
                    //            }
                    //        }
                    //    }
                    //    else
                    //    {
                    //        //找不到 责任制
                    //        T_FM_USER sendUser = null;
                    //        var userApprol = GetEntities<T_FM_USER>(e => e.ENABLE_STATUS == 0 && e.DEPARTMENT_ID.HasValue && e.APPROVE_ROLE_ID.HasValue && e.DEPARTMENT_ID.Value == currUser.DEPARTMENT_ID.Value, null, "Nav_ApproveRole");
                    //        if (userApprol != null && userApprol.Count() > 0 && currPerson.POST_ID.HasValue)
                    //        {
                    //            switch (departInfo.DEPARTMENT_TYPE)//FMDepartmentType 部门=0,  车间=1,   班组=2,  公司=3
                    //            {
                    //                case 2:
                    //                    sendUser = userApprol.FirstOrDefault(e => e.Nav_ApproveRole.NAME.Contains("负责人"));
                    //                    break;
                    //                default:
                    //                    sendUser = userApprol.FirstOrDefault(e => e.Nav_ApproveRole.NAME.Contains("安全"));
                    //                    break;
                    //            }
                    //        }
                    //        if (sendUser == null)
                    //        {
                    //            //找不到人只能给她自己做联系人员处理
                    //            sendNoticeRef = NotificationTaskService.InsertUserNoticeTaskModel("请联系你所在组织安全员绑定责任制岗位并上传责任状", currID, currUser.ORG_ID, currUser.ID, currUser.NAME, DateTime.Now, DateTime.Now.AddDays(7), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                    //        }
                    //        else
                    //        {
                    //            var UserPost = GetEntity<T_FM_USER_POST>(currPerson.POST_ID.Value);
                    //            sendNoticeRef = NotificationTaskService.InsertUserNoticeTaskModel("请为《" + currUser.NAME + "：" + UserPost.NAME + "》绑定责任制岗位并上传责任状", currID, currUser.ORG_ID, sendUser.ID, sendUser.NAME, DateTime.Now, DateTime.Now.AddDays(7), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                    //        }
                    //    }
                    //}
                    #endregion
                }
                #endregion

                if (currDetail == null && userDetailList != null)
                    currDetail = userDetailList.FirstOrDefault(e => e.USER_ID == userID);
                if (currDetail == null && currUserDeail != null)
                    currDetail = currUserDeail;
                if (currDetail != null)
                    currDetail.ISSIGN = true;

                UnifiedCommit(() =>
                {
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (Nav_Papers != null && Nav_Papers.Any())
                        BantchAddEntityNoCommit(Nav_Papers);
                    if (UserText != null)//考试记录
                        UpdateEntityNoCommit(UserText);
                    if (units.Any())
                        BantchSaveEntityNoCommit(units);
                    //CreateNextLevel  wyw 从 方法体抽出来的
                    if (eduCardRef != null)
                        UpdateEntityNoCommit(eduCardRef);
                    if (newEduCard != null)
                        AddEntityNoCommit(newEduCard);
                    if (userDetailList != null)
                        BantchAddEntityNoCommit(userDetailList);
                    if (currDetail != null)
                        UpdateEntityNoCommit(currDetail);
                    if (sendNoticeRef != null)
                        AddEntityNoCommit(sendNoticeRef);

                    //责任制签订
                    if (signRecord != null)
                        UpdateEntityNoCommit(signRecord);
                    if (signPost != null)
                        UpdateEntityNoCommit(signPost);
                    if (sendNoticeRefZRZ != null)
                        UpdateEntityNoCommit(sendNoticeRefZRZ);
                });
                return true;
            });
        }
        public class TrainUserPaperModel
        {
            public List<T_SE_NEW_USER_DETAIL_PAPER> Nav_Papers { get; set; }
            public T_SE_SECONFIG Nav_Config { get; set; }
            public Guid TaskID { get; set; }
            public Guid ORG_ID { get; set; }
            public Guid TEXT_ID { get; set; }

        }

        [HttpPost, Route("GetUserPapers")]
        public JsonActionResult<TrainUserPaperModel> GetUserPapers([FromBody] KeywordFilter filter)
        {
            var papers = GetEntities<T_SE_NEW_USER_DETAIL_PAPER>(null, filter).OrderByDescending(e => e.Nav_Text.TEXT_TIMES).ToList();
            var config = GetEntity<T_SE_SECONFIG>(t => true);
            var ret = new JsonActionResult<TrainUserPaperModel>();
            ret.Data = new TrainUserPaperModel
            {
                Nav_Papers = papers,
                Nav_Config = config
            };
            ret.IsSuccessful = true;
            ret.TotalCount = 1;
            ret.ErrorMessage = "";
            return ret;
        }
        [HttpPost, Route("SavePapers")]
        public JsonActionResult<bool> SavePapers([FromBody] TrainUserPaperModel entity)
        {
            return SafeExecute(() =>
            {
                if (entity.Nav_Papers == null || entity.Nav_Papers.Count == 0)
                {
                    throw new Exception("试卷不能为空");
                }
                Guid TEXT_ID = entity.TEXT_ID;
                if (TEXT_ID == Guid.Empty)
                {
                    string Msg = "传参有误";
                    if (DataHelper.GetRequestType(Request.Headers) == 2)
                    {
                        Msg += ",请升级APP或者清理缓存后再试";
                    }
                    Msg += "！";
                    throw new Exception(Msg);
                }
                var score = 0;
                var sscore = entity.Nav_Config.S_TEST_SCORE;
                var mscore = entity.Nav_Config.M_TEST_SCORE;
                var cscore = entity.Nav_Config.C_TEST_SCORE;
                foreach (var item in entity.Nav_Papers)
                {
                    if (item.ANSWER != 0 && item.ANSWER == item.Nav_Test.ANSWER)
                    {
                        if (item.Nav_Test.TYPE == SETestTypeEnum.是非题)
                        {
                            score += cscore;
                        }
                        else if (item.Nav_Test.TYPE == SETestTypeEnum.单选题)
                        {
                            score += sscore;
                        }
                        else if (item.Nav_Test.TYPE == SETestTypeEnum.多选题)
                        {
                            score += mscore;
                        }
                    }
                }
                T_SE_NEW_USERS eduCard = null;
                T_SE_NEW_USER_DETAIL_TEXT modelTextNew = null;
                var finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                //var passMark = GetEntity<T_SE_SECONFIG>(t => t.IS_DELETED == false);

                T_SE_NEW_USER_DETAIL_TEXT modelText = GetEntity<T_SE_NEW_USER_DETAIL_TEXT>(TEXT_ID);
                modelText.SCORE = score;
                if (modelText.SCORE >= entity.Nav_Config.PASS_MARK)
                {
                    modelText.ISPASS = true;
                }
                else
                {
                    modelText.ISPASS = false;
                }

                if (entity.Nav_Config != null) // 原本有这个判断  现改为没这个 就不判断了 好像也合理 
                {
                    //if (entity.Nav_Config.PASS_MARK != 0)
                    //{
                    //    if (score < entity.Nav_Config.PASS_MARK)
                    //    {
                    if (!modelText.ISPASS)
                    {
                        try
                        {
                            eduCard = GetEntity<T_SE_NEW_USERS>(entity.Nav_Papers[0].Nav_Record.EDU_CARD_ID);
                            List<T_SE_NEW_USER_DETAIL_PAPER> listPaper = null;
                            T_FM_NOTIFICATION_TASK taskReSend = null;
                            //重新生成考题 
                            string Msg = string.Empty;
                            bool isOK = NewUserService.GetText(modelText.ORG_ID.Value, modelText.RECORD_ID, modelText.USER_ID.Value, eduCard, null, ref modelTextNew, ref listPaper, ref taskReSend, ref Msg, modelText.TEXT_TIMES + 1);
                            UnifiedCommit(() =>
                            {
                                if (finishNotice != null)
                                    UpdateEntityNoCommit(finishNotice);
                                BantchSaveEntityNoCommit(entity.Nav_Papers);//更新试题明细
                                                                            //试题更新
                                if (modelText != null)//旧试题
                                    UpdateEntityNoCommit(modelText);
                                if (modelTextNew != null)//新试题
                                    UpdateEntityNoCommit(modelTextNew);
                                if (listPaper != null)//新试题
                                    BantchSaveEntityNoCommit(listPaper);
                                if (taskReSend != null)//新待办
                                    UpdateEntityNoCommit(taskReSend);
                            });
                            if (!isOK)
                            {
                                throw new Exception("考试成绩：" + score + "分小于标准线" + entity.Nav_Config.PASS_MARK + "，请重新考试！" + Msg);
                            }
                        }
                        catch
                        {
                            //新加表单 T_SE_NEW_USER_DETAIL_TEXT 以支持多次考试 手动添加数据 
                            throw new Exception("获取试卷信息失败，请联系系统运维人员！");
                        }
                        throw new Exception("考试成绩：" + score + "分小于标准线" + entity.Nav_Config.PASS_MARK + "，请重新考试！");
                    }
                    //    }
                    //}
                }
                foreach (var item in entity.Nav_Papers)
                {
                    item.SCORE = score;
                }

                T_SE_NEW_USERS newEduCard = null;
                List<T_SE_NEW_USER_DETAIL> userDetailList = null;
                T_SE_NEW_USER_DETAIL currDetail = null;
                T_FM_NOTIFICATION_TASK sendNotice = null;

                T_OG_SAFE_PDT_SIGNED signRecord = null;
                T_OG_SAFE_PDT_SIGNED_POST signPost = null;

                //考试通过 继续往下的流程
                CreateNextLevel(entity.ORG_ID, entity.Nav_Papers[0].RECORD_ID, entity.TaskID, entity.Nav_Papers[0].Nav_Record.EDU_CARD_ID, score.ToString(), ref eduCard, ref newEduCard, ref userDetailList, ref currDetail, ref sendNotice);

                var currUser = GetEntity<T_FM_USER>(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value);
                if (currUser.DEPARTMENT_ID.HasValue)
                {
                    var currPerson = GetEntity<T_FM_PERSON>(currUser.PERSON_ID.Value);
                    var departInfo = GetEntity<T_FM_DEPARTMENT>(currUser.DEPARTMENT_ID.Value);
                    GetOG001(entity.TaskID, currUser, currPerson, departInfo, ref signRecord, ref signPost, ref sendNotice);
                }


                UnifiedCommit(() =>
                {
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    BantchSaveEntityNoCommit(entity.Nav_Papers);

                    //CreateNextLevel  wyw 从 方法体抽出来的
                    if (eduCard != null)
                        UpdateEntityNoCommit(eduCard);
                    if (newEduCard != null)
                        AddEntityNoCommit(newEduCard);
                    if (userDetailList != null)
                        BantchAddEntityNoCommit(userDetailList);
                    if (currDetail != null)
                        UpdateEntityNoCommit(currDetail);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);

                    //责任制签订
                    if (signRecord != null)
                        UpdateEntityNoCommit(signRecord);
                    if (signPost != null)
                        UpdateEntityNoCommit(signPost);

                    //试题更新
                    if (modelText != null)//新试题
                        UpdateEntityNoCommit(modelText);
                });
                return true;
            });

        }
        private void CreateTestList(List<T_SE_TEST> allTests, List<Guid> ret, List<Guid> contentFilter, int type, int count)
        {
            var tests = allTests.Where(st =>
               st.Nav_Points.Any(pt => contentFilter.Contains(pt.POINT_ID.Value)) &&
               st.TYPE == (SETestTypeEnum)type).OrderBy(t => Guid.NewGuid()).Take(count); ;
            if (tests != null)
            {
                ret.AddRange(tests.Select(it => it.ID));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ORG_ID"></param>
        /// <param name="RECORD_ID"></param>
        /// <param name="TaskID"></param>
        /// <param name="EDU_CARD_ID"></param>
        /// <param name="score"></param>
        /// <param name="eduCard"></param>
        /// <param name="newEduCard"></param>
        /// <param name="userDetailList"></param>
        /// <param name="currDetail"></param>
        /// <param name="sendNotice"></param>
        private void CreateNextLevel(Guid ORG_ID, Guid RECORD_ID, Guid TaskID, Guid EDU_CARD_ID, string score, ref T_SE_NEW_USERS eduCard, ref T_SE_NEW_USERS newEduCard, ref List<T_SE_NEW_USER_DETAIL> userDetailList, ref T_SE_NEW_USER_DETAIL currDetail, ref T_FM_NOTIFICATION_TASK sendNotice)
        {
            #region
            var orgId = ORG_ID;
            var currID = RECORD_ID;
            var taskID = TaskID;
            var eduCardID = EDU_CARD_ID;
            //T_FM_NOTIFICATION_TASK sendNotice = null; 
            userDetailList = new List<T_SE_NEW_USER_DETAIL>();
            T_SE_THREE_LEVEL_SAFE_CONTENT train_contents = null;
            var basefilter = new BaseFilter(orgId);
            var userDetails = GetEntities<T_SE_NEW_USER_DETAIL>(t => t.EDU_CARD_ID == eduCardID, basefilter);
            var currDetailT = userDetails.FirstOrDefault(t => t.ID == currID);//不能直接用 故定义中间参数
            if (currDetailT != null)
            {
                if (score != null)
                {
                    currDetailT.SCORE = score;
                    currDetailT.EXAMINATION_RESULTS = SEExaminationResultsEnum.合格;
                }
                currDetailT.STATUS = SEThreeLevelSafeTrainStatus.公司培训;
            }
            var isFinish = userDetails.Count(t => t.NEXT_DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID && t.ID != currID && t.STATUS == 0);
            eduCard = GetEntity<T_SE_NEW_USERS>(eduCardID);
            var currSattus = SEThreeLevelSafeTrainType.公司级;
            if (isFinish == 0 && eduCard.TRAIN_STATUS != SEThreeLevelSafeTrainType.班组级)
            {
                T_FM_USER sendUser = null;

                if (eduCard.TRAIN_STATUS == SEThreeLevelSafeTrainType.公司级)
                {
                    sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "部门安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                    if (sendUser == null)
                    {
                        sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "安环部安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                        if (sendUser == null)
                        {
                            sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "部门负责人" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                            if (sendUser == null)
                            {
                                sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "车间安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                                if (sendUser == null)
                                {
                                    sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "车间负责人" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                                }
                            }
                        }
                        //currSattus = SEThreeLevelSafeTrainType.部门级;
                        //train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == SEThreeLevelSafeTrainType.部门级);
                    }
                    //wyw  T_SE_NEW_USERS  train_contents 找不到会报错
                    currSattus = SEThreeLevelSafeTrainType.部门级;
                    train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == SEThreeLevelSafeTrainType.部门级);
                }
                else if (eduCard.TRAIN_STATUS == SEThreeLevelSafeTrainType.部门级)
                {
                    //找班组级培训 的

                    //找对应班组
                    sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "班组负责人" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                    if (sendUser == null)
                    {
                        //班组级培训 可能也是部门或者车间
                        sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME.Contains("安全员") && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                    }
                    if (sendUser == null)
                    {
                        //找不到人 找安环人 省得单据没了
                        sendUser = UserService.GetSafeApproveUser(eduCard.ORG_ID.Value);
                    }
                    if (sendUser != null)
                    {
                        currSattus = SEThreeLevelSafeTrainType.班组级;
                        train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == SEThreeLevelSafeTrainType.班组级);
                    }
                }
                if (sendUser != null)
                {
                    newEduCard = GetEntity<T_SE_NEW_USERS>(e => e.PARENT_ID.HasValue && e.PARENT_ID.Value == EDU_CARD_ID);
                    if (newEduCard == null || newEduCard.ID == Guid.Empty)
                    {
                        newEduCard = new T_SE_NEW_USERS();
                        newEduCard.ID = Guid.NewGuid();
                        newEduCard.ORG_ID = orgId;
                        newEduCard.USER_ID = sendUser.ID;
                        newEduCard.DEPARTMENT_ID = sendUser.DEPARTMENT_ID;
                        newEduCard.CONTENT_ID = train_contents.ID;
                        newEduCard.TRAIN_STATUS = currSattus;
                        newEduCard.TRAINTYPE = TrainType.InOffLine;
                        var commonDeptartmentUsers = userDetails.Where(t => t.NEXT_DEPARTMENT_ID == currDetailT.NEXT_DEPARTMENT_ID);
                        var commonUserIds = commonDeptartmentUsers.Select(t => t.USER_ID);
                        var userFilter = new BaseFilter(orgId);
                        userFilter.Include = new string[] { "Nav_Person" };

                        var listDeps = GetEntities<T_FM_DEPARTMENT>(e => e.ENABLE_STATUS == 0 && !e.IS_DELETED, null);
                        T_FM_DEPARTMENT modelDep = null;
                        foreach (var user in commonDeptartmentUsers)
                        {
                            T_SE_NEW_USER_DETAIL userDetail = new T_SE_NEW_USER_DETAIL();
                            userDetail.ID = Guid.NewGuid();
                            userDetail.CODE = user.CODE;
                            userDetail.EDU_CARD_ID = newEduCard.ID;
                            userDetail.USER_ID = user.USER_ID;
                            userDetail.ID_CARD_NUMBER = user.ID_CARD_NUMBER;
                            userDetail.ORG_ID = newEduCard.ORG_ID;
                            userDetail.IN_TIME = user.CREATE_TIME;
                            userDetail.USER_POST_ID = user.USER_POST_ID;
                            userDetail.USER_DEPARTMENT_ID = user.USER_DEPARTMENT_ID;
                            //userDetail.EXAMINATION_RESULTS = SEExaminationResultsEnum.合格;//260228 不能直接上来就合格

                            #region     NEXT_DEPARTMENT_ID 

                            if (user.USER_DEPARTMENT_ID.HasValue && currSattus != SEThreeLevelSafeTrainType.班组级)
                            {
                                //userDetail.NEXT_DEPARTMENT_ID=
                                modelDep = listDeps.FirstOrDefault(e => e.ID == user.USER_DEPARTMENT_ID.Value);
                                if (modelDep.DEPARTMENT_TYPE == 5)
                                {
                                    //公司领导
                                }
                                else if (modelDep.DEPARTMENT_TYPE == 10)
                                {
                                    //部门人员
                                    if (modelDep.DEPARTMENT_STATUS == 1)//FMDepartmentStatus  职能部门 = 0,  生产部门 = 1,  安全部门 = 2, 
                                    {
                                        userDetail.NEXT_DEPARTMENT_ID = modelDep.ID;
                                    }
                                    else
                                    {
                                        modelDep = listDeps.FirstOrDefault(e => e.DEPARTMENT_STATUS == 2);
                                        if (modelDep != null)
                                        {
                                            userDetail.NEXT_DEPARTMENT_ID = modelDep.ID;
                                        }
                                    }
                                }
                                else if (modelDep.DEPARTMENT_TYPE == 15)
                                {
                                    userDetail.NEXT_DEPARTMENT_ID = modelDep.PARENT_ID;//给组织对应上级组织
                                }
                                else if (modelDep.DEPARTMENT_TYPE == 20)
                                {
                                    //班主 对应组织 的父级的父级
                                    if (modelDep.PARENT_ID.HasValue)
                                    {
                                        modelDep = listDeps.FirstOrDefault(e => e.ID == modelDep.PARENT_ID.Value);
                                    }
                                    if (modelDep != null)
                                    {
                                        userDetail.NEXT_DEPARTMENT_ID = modelDep.PARENT_ID;
                                    }
                                }
                            }

                            #endregion

                            userDetailList.Add(userDetail);
                        }
                        var endTime = DateTime.Now.AddDays(10);
                        var newEndTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59);
                        sendNotice = NotificationTaskService.InsertUserNoticeTaskModel(DateTime.Now.ToShortDateString() + "-三级安全培训-" + newEduCard.TRAIN_STATUS.GetDescription(), newEduCard.ID, orgId, sendUser.ID, sendUser.NAME, DateTime.Now, newEndTime, 1, "SE062");
                    }
                }
                var isAllDone = userDetails.Count(t => t.STATUS == 0);
                if (isAllDone == 0)
                {
                    eduCard.STATUS = SENewUserStatus.归档;
                }

                currDetail = currDetailT;

                if (sendNotice == null)
                {
                    //wyw 当三级安全教育结束时 为了三级安全卡 签名正常 SE063ShowPrint
                    currDetail.STATUS = SEThreeLevelSafeTrainStatus.公司培训;
                }


                #endregion
                //UnifiedCommit(() =>
                //{
                //    if (eduCard != null)
                //        UpdateEntityNoCommit(eduCard);
                //    if (newEduCard != null)
                //        AddEntityNoCommit(newEduCard);
                //    if (userDetailList != null)
                //        BantchAddEntityNoCommit(userDetailList);
                //    if (currDetail != null)
                //        UpdateEntityNoCommit(currDetail);
                //    if (sendNotice != null)
                //        AddEntityNoCommit(sendNotice);
                //});
            }
            else
            {
                //不考试 还有人
                currDetail = currDetailT;
                switch (eduCard.TRAIN_STATUS)
                {
                    case SEThreeLevelSafeTrainType.公司级:
                        currDetail.STATUS = SEThreeLevelSafeTrainStatus.公司培训;
                        break;
                    case SEThreeLevelSafeTrainType.部门级:
                        currDetail.STATUS = SEThreeLevelSafeTrainStatus.部门培训;
                        break;
                    case SEThreeLevelSafeTrainType.车间级:
                        currDetail.STATUS = SEThreeLevelSafeTrainStatus.部门培训;
                        break;
                    case SEThreeLevelSafeTrainType.班组级:
                        currDetail.STATUS = SEThreeLevelSafeTrainStatus.班组培训;
                        break;
                    default:
                        break;
                }

                //public enum SEThreeLevelSafeTrainStatus
                //{
                //    草稿 = 0,
                //    公司培训 = 1,
                //    部门培训 = 2,
                //    班组培训 = 3,
                //    员工签到 = 4,
                //    审阅中 = 5,
                //    归档 = 6,
                //} 

                // <summary>培训组织部门类型</summary>
                //public enum SEThreeLevelSafeTrainType
                //{
                //    公司级 = 0,
                //    部门级 = 1,
                //    车间级 = 2,
                //    班组级 = 3,
                //} 
            }
        }
        //private void CreateNextLevel(Guid ORG_ID, Guid RECORD_ID, Guid TaskID, Guid EDU_CARD_ID, string score)
        //{
        //    #region
        //    var orgId = ORG_ID;
        //    var currID = RECORD_ID;
        //    var taskID = TaskID;
        //    var eduCardID = EDU_CARD_ID;
        //    T_FM_NOTIFICATION_TASK sendNotice = null;
        //    T_SE_NEW_USERS newEduCard = null;
        //    List<T_SE_NEW_USER_DETAIL> userDetailList = new List<T_SE_NEW_USER_DETAIL>();
        //    T_SE_THREE_LEVEL_SAFE_CONTENT train_contents = null;
        //    var basefilter = new BaseFilter(orgId);
        //    var userDetails = GetEntities<T_SE_NEW_USER_DETAIL>(t => t.EDU_CARD_ID == eduCardID, basefilter);
        //    var currDetail = userDetails.FirstOrDefault(t => t.ID == currID);
        //    if (currDetail != null)
        //    {
        //        if (score != null)
        //        {
        //            currDetail.SCORE = score;
        //            currDetail.EXAMINATION_RESULTS = SEExaminationResultsEnum.合格;
        //        }
        //        currDetail.STATUS = SEThreeLevelSafeTrainStatus.公司培训;
        //    }
        //    var isFinish = userDetails.Count(t => t.NEXT_DEPARTMENT_ID == currDetail.NEXT_DEPARTMENT_ID && t.STATUS == 0);
        //    var eduCard = GetEntity<T_SE_NEW_USERS>(eduCardID);
        //    var currSattus = SEThreeLevelSafeTrainType.公司级;
        //    if (isFinish == 0 && eduCard.TRAIN_STATUS != SEThreeLevelSafeTrainType.班组级)
        //    {
        //        T_FM_USER sendUser = null;

        //        if (eduCard.TRAIN_STATUS == SEThreeLevelSafeTrainType.公司级)
        //        {
        //            sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetail.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "部门安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
        //            if (sendUser == null)
        //            {
        //                sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetail.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "安环部安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
        //                if (sendUser == null)
        //                {
        //                    sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetail.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "部门负责人" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
        //                    if (sendUser == null)
        //                    {
        //                        sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetail.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "车间安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
        //                        if (sendUser == null)
        //                        {
        //                            sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetail.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "车间负责人" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
        //                        }
        //                    }
        //                }
        //                currSattus = SEThreeLevelSafeTrainType.部门级;
        //                train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == SEThreeLevelSafeTrainType.部门级);
        //            }
        //        }
        //        else if (eduCard.TRAIN_STATUS == SEThreeLevelSafeTrainType.部门级)
        //        {
        //            sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == currDetail.NEXT_DEPARTMENT_ID && t.Nav_ApproveRole.NAME == "班组负责人" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
        //            if (sendUser != null)
        //            {
        //                currSattus = SEThreeLevelSafeTrainType.班组级;
        //                train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == SEThreeLevelSafeTrainType.班组级);
        //            }
        //        }
        //        if (sendUser != null)
        //        {
        //            newEduCard = new T_SE_NEW_USERS();
        //            newEduCard.ID = Guid.NewGuid();
        //            newEduCard.ORG_ID = orgId;
        //            newEduCard.USER_ID = sendUser.ID;
        //            newEduCard.DEPARTMENT_ID = sendUser.DEPARTMENT_ID;
        //            newEduCard.CONTENT_ID = train_contents.ID;
        //            newEduCard.TRAIN_STATUS = currSattus;
        //            var commonDeptartmentUsers = userDetails.Where(t => t.NEXT_DEPARTMENT_ID == currDetail.NEXT_DEPARTMENT_ID);
        //            var commonUserIds = commonDeptartmentUsers.Select(t => t.USER_ID);
        //            var userFilter = new BaseFilter(orgId);
        //            userFilter.Include = new string[] { "Nav_Person" };

        //            foreach (var user in commonDeptartmentUsers)
        //            {
        //                T_SE_NEW_USER_DETAIL userDetail = new T_SE_NEW_USER_DETAIL();
        //                userDetail.ID = Guid.NewGuid();
        //                userDetail.CODE = user.CODE;
        //                userDetail.EDU_CARD_ID = newEduCard.ID;
        //                userDetail.USER_ID = user.USER_ID;
        //                userDetail.ID_CARD_NUMBER = user.ID_CARD_NUMBER;
        //                userDetail.ORG_ID = newEduCard.ORG_ID;
        //                userDetail.IN_TIME = user.CREATE_TIME;
        //                userDetail.USER_POST_ID = user.USER_POST_ID;
        //                userDetail.USER_DEPARTMENT_ID = user.USER_DEPARTMENT_ID;
        //                userDetail.EXAMINATION_RESULTS = SEExaminationResultsEnum.合格;
        //                userDetailList.Add(userDetail);
        //            }
        //            var endTime = DateTime.Now.AddDays(10);
        //            var newEndTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59);
        //            sendNotice = NotificationTaskService.InsertUserNoticeTaskModel(DateTime.Now.ToShortDateString() + "-三级安全培训-" + newEduCard.TRAIN_STATUS.GetDescription(), newEduCard.ID, orgId, sendUser.ID, sendUser.NAME, DateTime.Now, newEndTime, 1, "SE062");
        //        }
        //        var isAllDone = userDetails.Count(t => t.STATUS == 0);
        //        if (isAllDone == 0)
        //        {
        //            eduCard.STATUS = SENewUserStatus.归档;
        //        }
        //        #endregion
        //        UnifiedCommit(() =>
        //        {
        //            if (eduCard != null)
        //                UpdateEntityNoCommit(eduCard);
        //            if (newEduCard != null)
        //                AddEntityNoCommit(newEduCard);
        //            if (userDetailList != null)
        //                BantchAddEntityNoCommit(userDetailList);
        //            if (currDetail != null)
        //                UpdateEntityNoCommit(currDetail);
        //            if (sendNotice != null)
        //                AddEntityNoCommit(sendNotice);

        //        });
        //    }
        //}

        /// <summary>
        /// 责任状签订信息获取
        /// </summary>
        /// <param name="TaskID"></param>
        /// <param name="currUser"></param>
        /// <param name="currPerson"></param>
        /// <param name="departInfo"></param>
        /// <param name="signRecord"></param>
        /// <param name="signPost"></param>
        /// <param name="sendNoticeRef"></param>
        public void GetOG001(Guid TaskID, T_FM_USER currUser, T_FM_PERSON currPerson, T_FM_DEPARTMENT departInfo, ref T_OG_SAFE_PDT_SIGNED signRecord, ref T_OG_SAFE_PDT_SIGNED_POST signPost, ref T_FM_NOTIFICATION_TASK sendNoticeRef)
        {
            //  如果没有继续触发下一级  直接触发    安全生产责任制签订 OG001_SHOWPRINT  如果找不到对应的责任制 就给对应组织安全员（或班长） 触发今日提醒
            //如果对应的人员有 责任状了 就不再次触发
            if (sendNoticeRef == null && currPerson.POST_ID.HasValue)//&& currPerson.POST_ID.HasValue 三级安全教育的没填 岗位
            {
                var post = GetEntity<T_SC_DEPARTMENT_POST>(t => t.Nav_Dept.DEPARTMENT_ID == currUser.DEPARTMENT_ID && t.DEPOST_ID == currPerson.POST_ID, new string[] { "Nav_Dept.Nav_Post" });
                if (post != null)
                {
                    var standardCreate = GetEntity<T_SC_STANDARD_CREATE>(t => t.POST_ID == post.Nav_Dept.POST_ID && t.STATUS == SCSystemEditStatus.已归档 && t.FILE_STATUS == SCSystemFileStatus.有效);
                    if (standardCreate != null)
                    {
                        var chargeUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == post.Nav_Dept.Nav_Post.DEPARTMENT_ID && t.Nav_Person.POST_ID == post.Nav_Dept.Nav_Post.DEPOST_ID && t.ENABLE_STATUS == 0);
                        //没有签订 才进行签订
                        T_OG_SAFE_PDT_SIGNED_POST check = GetEntity<T_OG_SAFE_PDT_SIGNED_POST>(e => e.USER_ID.HasValue && e.USER_ID.Value == currUser.ID && e.POST_ID.HasValue && e.POST_ID.Value == currPerson.POST_ID.Value && e.CHARGE_USER_ID.HasValue && e.CHARGE_USER_ID.Value == chargeUser.ID);
                        if (check == null)
                        {
                            if (chargeUser != null)
                            {
                                signRecord = new T_OG_SAFE_PDT_SIGNED
                                {
                                    ID = Guid.NewGuid(),
                                    ORG_ID = currUser.ORG_ID,
                                    STATUS = (int)PFStandardStatus.Draft,
                                    TRIGGER_TYPE = OGPersonalSignedTriggerType.新员工触发,
                                    //TRIGGER_TYPE = OGPersonalSignedTriggerType.手动新增,
                                    STANDARD_ID = standardCreate.ID,
                                    FILE_CONTENT = standardCreate.FILE_CONTENT,
                                    DEPARTMENT_ID = currUser.DEPARTMENT_ID,
                                    ANNUAL = DateTime.Now.Year
                                };
                                if (chargeUser != null)
                                {
                                    signRecord.CHARGE_USER_ID = chargeUser.ID;
                                }
                                signPost = new T_OG_SAFE_PDT_SIGNED_POST
                                {
                                    SAFE_PDT_SIGNED_ID = signRecord.ID,
                                    ID = Guid.NewGuid(),
                                    ORG_ID = currUser.ORG_ID,
                                    USER_ID = currUser.ID,
                                    POST_ID = currPerson.POST_ID,
                                    CHARGE_USER_ID = signRecord.CHARGE_USER_ID
                                };
                                sendNoticeRef = NotificationTaskService.InsertUserNoticeTaskModel(DateTime.Now.ToShortDateString() + "安全生产责任制个人签订表", signRecord.ID, currUser.ORG_ID, currUser.ID, currUser.NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "OG001_SHOWPRINT");
                            }
                        }
                    }
                }
                else
                {
                    //找不到 责任制
                    T_FM_USER sendUser = null;
                    var userApprol = GetEntities<T_FM_USER>(e => e.ENABLE_STATUS == 0 && e.DEPARTMENT_ID.HasValue && e.APPROVE_ROLE_ID.HasValue && e.DEPARTMENT_ID.Value == currUser.DEPARTMENT_ID.Value, null, "Nav_ApproveRole");
                    if (departInfo == null && currUser.DEPARTMENT_ID.HasValue)
                    {
                        departInfo = GetEntity<T_FM_DEPARTMENT>(currUser.DEPARTMENT_ID.Value);
                    }
                    if (userApprol != null && userApprol.Count() > 0 && currPerson.POST_ID.HasValue)
                    {
                        switch (departInfo.DEPARTMENT_TYPE)//FMDepartmentType 部门=0,  车间=1,   班组=2,  公司=3
                        {
                            case 20:
                                sendUser = userApprol.FirstOrDefault(e => e.Nav_ApproveRole.NAME.Contains("负责人"));
                                break;
                            default:
                                sendUser = userApprol.FirstOrDefault(e => e.Nav_ApproveRole.NAME.Contains("安全"));
                                break;
                        }
                    }
                    if (sendUser == null)
                    {
                        //找不到人只能给她自己做联系人员处理
                        sendNoticeRef = NotificationTaskService.InsertUserNoticeTaskModel("请联系你所在组织安全员绑定责任制岗位并上传责任状让你签订", TaskID, currUser.ORG_ID, currUser.ID, currUser.NAME, DateTime.Now, DateTime.Now.AddDays(7), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                    }
                    else
                    {
                        var UserPost = GetEntity<T_FM_USER_POST>(currPerson.POST_ID.Value);
                        string Title = "请为《" + currUser.NAME + "：" + UserPost.NAME + "》绑定责任制岗位并上传责任状，并让其签订";
                        var chaen = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.USER_ID == sendUser.ID && e.SOURCE_FORMCODE == "PF135" && e.NOTICE_TITLE == Title);
                        if (chaen == null)
                        {
                            sendNoticeRef = NotificationTaskService.InsertUserNoticeTaskModel(Title, TaskID, currUser.ORG_ID, sendUser.ID, sendUser.NAME, DateTime.Now, DateTime.Now.AddDays(7), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUsers")]
        public JsonActionResult<IEnumerable<T_FM_USER>> GetUsers([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_FM_USER>>(() =>
            {
                return GetEntities<T_SE_NEW_USER_DETAIL_PAPER>(null, filter).Select(it => it.Nav_User).Distinct(it => it.ID).ToList();
            });
        }

        #region      新增人员

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="model">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("RegisterUser")]
        public JsonActionResult<T_SE_NEW_USER_DETAIL> RegisterUser([FromBody] RegisterUserModel model)
        {
            return SafeExecute(() =>
            {
                if (model.EDU_CARD_ID == Guid.Empty)
                {
                    throw new Exception("传参有误，获取三级安全教育表单ID失败，请刷新后再试！");
                }
                T_FM_PERSON newPerson = null;
                T_FM_USER newUser = null;
                List<T_FM_USER_BELONG_ROLE> listRole = null;
                T_OP_ALLUSER alluser = null;
                string Msg = String.Empty;
                int code = UserService.RegisterUser(model.Name, model.Phone, model.Code, model.Sex, model.ID_CARD, model.InTime, model.WORKINGYEAR, model.ORG_ID, model.DEPARTMENT_ID, model.POST_ID, this.Request.Headers["Tenant"], ref alluser, ref newPerson, ref newUser, ref listRole, ref Msg);
                if (code != 200)
                {
                    throw new Exception(Msg);
                }

                T_SE_USER_TEMP newTemp = new T_SE_USER_TEMP();
                newTemp.ID = Guid.NewGuid();
                newTemp.USER_ID = newUser.ID;
                newTemp.ORG_ID = model.ORG_ID;

                T_SE_NEW_USER_DETAIL userDetail = new T_SE_NEW_USER_DETAIL();
                userDetail.ID = Guid.NewGuid();
                userDetail.EDU_CARD_ID = model.EDU_CARD_ID;
                userDetail.USER_ID = newUser.ID;
                userDetail.ID_CARD_NUMBER = newUser.ID_CARD;
                userDetail.STATUS = 0;
                userDetail.ORG_ID = newUser.ORG_ID;
                userDetail.IN_TIME = newUser.ENTRYTIME;
                userDetail.USER_DEPARTMENT_ID = newUser.DEPARTMENT_ID;
                userDetail.USER_POST_ID = model.POST_ID;

                #region     NEXT_DEPARTMENT_ID //默认到对应部门  给矿山 选矿  否则给 安环

                if (newUser.DEPARTMENT_ID.HasValue)
                {
                    var listDeps = GetEntities<T_FM_DEPARTMENT>(e => e.ENABLE_STATUS == 0 && !e.IS_DELETED, null);
                    var modelDep = listDeps.FirstOrDefault(e => e.ID == newUser.DEPARTMENT_ID.Value);
                    if (modelDep.DEPARTMENT_TYPE == 5)
                    {
                        //公司领导
                    }
                    else if (modelDep.DEPARTMENT_TYPE == 10)
                    {
                        //部门人员
                        if (modelDep.DEPARTMENT_STATUS == 1)//FMDepartmentStatus  职能部门 = 0,  生产部门 = 1,  安全部门 = 2, 
                        {
                            userDetail.NEXT_DEPARTMENT_ID = modelDep.ID;
                        }
                        else
                        {
                            modelDep = listDeps.FirstOrDefault(e => e.DEPARTMENT_STATUS == 2);
                            if (modelDep != null)
                            {
                                userDetail.NEXT_DEPARTMENT_ID = modelDep.ID;
                            }
                        }
                    }
                    else if (modelDep.DEPARTMENT_TYPE == 15)
                    {
                        userDetail.NEXT_DEPARTMENT_ID = modelDep.PARENT_ID;//给组织对应上级组织
                    }
                    else if (modelDep.DEPARTMENT_TYPE == 20)
                    {
                        //班主 对应组织 的父级的父级
                        if (modelDep.PARENT_ID.HasValue)
                        {
                            modelDep = listDeps.FirstOrDefault(e => e.ID == modelDep.PARENT_ID.Value);
                        }
                        if (modelDep != null)
                        {
                            userDetail.NEXT_DEPARTMENT_ID = modelDep.PARENT_ID;
                        }
                    }
                }

                #endregion

                using (var context = new MigrationContext())
                {
                    context.AddEntity(alluser);
                    context.SaveChanges();
                }

                UnifiedCommit(() =>
                {
                    if (newUser != null)
                        AddEntityNoCommit(newUser);
                    if (newPerson != null)
                        AddEntityNoCommit(newPerson);
                    if (userDetail != null)
                        AddEntityNoCommit(userDetail);
                    if (listRole != null && listRole.Count() > 0)
                        BantchSaveEntityNoCommit(listRole);
                    if (newTemp != null)
                        AddEntityNoCommit(newTemp);
                });

                return GetEntity<T_SE_NEW_USER_DETAIL>(e => e.ID == userDetail.ID, "Nav_Department", "Nav_Post", "Nav_User", "Nav_DepartmentNext");
            });
        }

        #endregion

    }

    public class RegisterUserModel
    {
        public string Name { get; set; }
        public int Sex { get; set; }
        public string Phone { get; set; }
        /// <summary>
        /// 没值取 Phone
        /// </summary>
        public string Code { get; set; }
        public string ID_CARD { get; set; }
        public DateTime InTime { get; set; }
        public int WORKINGYEAR { get; set; }
        public Guid ORG_ID { get; set; }
        public Guid? DEPARTMENT_ID { get; set; }
        public Guid? POST_ID { get; set; }
        public Guid EDU_CARD_ID { get; set; }
    }
}
