using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.PF;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Entities.SC.PT;
using APT.MS.Domain.Entities.SC.SC;
using APT.MS.Domain.Enums;
using APT.Utility;
using Castle.Core.Internal;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection.Metadata;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace APT.SC.WebApi.Controllers.Api.PTController
{
    /// <summary>
    ///  导航属性：考核方案审核表
    /// </summary>
    [Route("api/PT/PTAssessmentPlanAudit")]
    public partial class AssessmentPlanAuditController : AuthorizeApiController<T_PT_ASSESSMENT_PLAN_AUDIT>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        public class AssessmentData
        {
            public Guid? departId { get; set; }
            public string departType { get; set; }
            public int departType_Num { get; set; }
            public string departName { get; set; }
            public string postName { get; set; }
            public string userName { get; set; }
            public string chargeName { get; set; }
            public string target { get; set; }
            public string targetItem { get; set; }
            public string type { get; set; }
            public string score { get; set; }
            public string method { get; set; }
            public int? company_num { get; set; }
            public int? depart_num { get; set; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public AssessmentPlanAuditController(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_PT_ASSESSMENT_PLAN_AUDIT entity)
        {
            return SafeExecute(() =>
            {
                var details = entity.Nav_Details;
                if (details != null && details.Any())
                {
                    details= details.Where(t => !t.IS_DELETED).ToList();
                }
                entity.STATUS = PFStandardStatus.Draft;
                entity.YEAR = DateTime.Now.Year.ToString();
                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;
                    }
                }
                entity.USER_ID = loginUserId;
                //var department = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId.Value && t.ENABLE_STATUS == 0, "Nav_Department");
                entity.DEPARTMENT_ID = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.ID == (Guid)loginUserId)?.DEPARTMENT_ID;
                entity.SET_TIME = DateTime.Now;
                //entity.DEPARTMENT_TYPE = entity.DEPARTMENT_TYPE!=0? entity.DEPARTMENT_TYPE : FMDepartmentType.部门;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                List<T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL_CONTENT> contents = new List<T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL_CONTENT>();
                T_FM_NOTIFICATION_TASK task = null;
                List<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL> newDetailTemps = new List<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL>();
                List<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT> newContentTemps = new List<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT>();
                List<Guid> deleteIds = new List<Guid>();
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (details != null && details.Any())
                    {
                        //回写考核方案导入表
                        var departBack = details.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                        var userBack = details.Select(t => t.USER_ID).Distinct().ToList();
                        var tempDetails = this.GetEntities<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL>(t => (departBack.Contains(t.DEPARTMENT_ID.Value) || userBack.Contains(t.USER_ID.Value)) && t.YEAR == entity.YEAR, new BaseFilter(entity.ORG_ID), new string[] { "Nav_Contents" }).ToList();
                        details.ForEach(t =>
                        {
                            t.ORG_ID = entity.ORG_ID; t.ASSESSMENT_PLAN_ID = entity.ID;
                            if (t.ASSESSMENT_CYCLE == 0)
                                throw new Exception("考核周期必须填写");
                            var first = tempDetails.FirstOrDefault(f => f.DEPARTMENT_ID == t.DEPARTMENT_ID && f.USER_ID == t.USER_ID && f.YEAR == t.YEAR);
                            if (first == null)
                            {
                                T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL newDetailTemp = new T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL();
                                newDetailTemp.DEPARTMENT_ID = t.DEPARTMENT_ID;
                                newDetailTemp.USER_ID = t.USER_ID;
                                newDetailTemp.ASSESSMENT_CYCLE = t.ASSESSMENT_CYCLE;
                                newDetailTemp.CODE = t.CODE;
                                newDetailTemp.YEAR = t.YEAR;
                                newDetailTemp.ORG_ID = t.ORG_ID;
                                newDetailTemps.Add(newDetailTemp);
                                if (t.Nav_Contents != null && t.Nav_Contents.Any())
                                {
                                    var sum = t.Nav_Contents.Where(p => !p.IS_DELETED).Sum(x => x.SCORE);
                                    if (sum != 100)
                                        throw new Exception("目标与指标所有项目总分必须为100");
                                    t.Nav_Contents.ForEach(t1 =>
                                    {
                                        t1.ORG_ID = entity.ORG_ID;
                                        t1.PLAN_AUDIT_DETAIL_ID = t.ID;
                                        contents.Add(t1);
                                        T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT newContent = new T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT();
                                        newContent.ORG_ID = entity.ORG_ID;
                                        newContent.PLAN_AUDIT_DETAIL_ID = newDetailTemp.ID;
                                        newContent.SCORE = t1.SCORE;
                                        newContent.METHOD = t1.METHOD;
                                        newContent.NAME = t1.NAME;
                                        newContentTemps.Add(newContent);
                                    });
                                    t.Nav_Contents = null;
                                }
                                else
                                    throw new Exception("目标与指标未全部填写");
                            }
                            else
                            {
                                var ids = first.Nav_Contents.Select(p => p.ID).ToList();
                                deleteIds.AddRange(ids);
                                if (t.Nav_Contents != null && t.Nav_Contents.Any())
                                {
                                    var sum = t.Nav_Contents.Where(p => !p.IS_DELETED).Sum(x => x.SCORE);
                                    if (sum != 100)
                                        throw new Exception("目标与指标所有项目总分必须为100");
                                    t.Nav_Contents.ForEach(t1 =>
                                    {
                                        t1.ORG_ID = entity.ORG_ID;
                                        t1.PLAN_AUDIT_DETAIL_ID = t.ID;
                                        contents.Add(t1);
                                        T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT newContent = new T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT();
                                        newContent.ORG_ID = entity.ORG_ID;
                                        newContent.PLAN_AUDIT_DETAIL_ID = first.ID;
                                        newContent.SCORE = t1.SCORE;
                                        newContent.METHOD = t1.METHOD;
                                        newContent.NAME = t1.NAME;
                                        newContentTemps.Add(newContent);
                                    });
                                    t.Nav_Contents = null;
                                }
                                else
                                    throw new Exception("目标与指标未全部填写");
                            }
                        });
                    }
                    entity.STATUS = PFStandardStatus.Approving;
                    entity.Nav_Details = null;
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var serialCode = codes.Split(new char[] { ',' });
                    var param = Enum.GetName(typeof(FMDepartmentType), entity.DEPARTMENT_TYPE);
                    MFlowPermitService.InsertApprove(serialCode[0], "PT024", param, entity.ID, "PT024_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null)
                            this.UpdateEntityNoCommit(entity);
                        if (details != null && details.Any())
                            this.BantchSaveEntityNoCommit(details);
                        if (contents != null && contents.Any())
                            this.BantchSaveEntityNoCommit(contents);
                        if (newDetailTemps != null && newDetailTemps.Any())
                            this.BantchSaveEntityNoCommit(newDetailTemps);
                        if (deleteIds != null && deleteIds.Any())
                            this.BantchDeleteEntityNoCommit<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT>(deleteIds);
                        if (newContentTemps != null && newContentTemps.Any())
                            this.BantchSaveEntityNoCommit(newContentTemps);
                        if (task != null)
                            this.UpdateEntityNoCommit(task);
                        if (notices != null && notices.Any())
                            this.BantchSaveEntityNoCommit(notices);
                    }, null, null, null, null, null, "PT024_SHOWPRINT", null);
                    return true;
                    //if (entity.TaskID != Guid.Empty)
                    //{
                    //    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    //}
                }
                else
                {
                    details.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.ASSESSMENT_PLAN_ID = entity.ID;
                        if (t.Nav_Contents != null && t.Nav_Contents.Any())
                        {
                            t.Nav_Contents.ForEach(t1 =>
                            {
                                t1.ORG_ID = entity.ORG_ID;
                                t1.PLAN_AUDIT_DETAIL_ID = t.ID;
                                contents.Add(t1);
                            });
                            t.Nav_Contents = null;
                        }
                    });
                }
                entity.Nav_Details = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (contents != null && contents.Any())
                        this.BantchSaveEntityNoCommit(contents);
                    if (newDetailTemps != null && newDetailTemps.Any())
                        this.BantchSaveEntityNoCommit(newDetailTemps);
                    if (deleteIds != null && deleteIds.Any())
                        this.BantchDeleteEntityNoCommit<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT>(deleteIds);
                    if (newContentTemps != null && newContentTemps.Any())
                        this.BantchSaveEntityNoCommit(newContentTemps);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                });
                return true;
            });
        }

        /// <summary>
        /// 已阅
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_PT_ASSESSMENT_PLAN_AUDIT entity)
        {
            return SafeExecute(() => {
                //var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                //var audit = this.GetEntity<T_PT_ASSESSMENT_PLAN_AUDIT>(entity.ID);
                //当前表单安全员都签到完毕，才归档
                //var taskCount = this.GetCount<T_FM_NOTIFICATION_TASK>(t=>t.SOURCE_DATA_ID == audit.ID && t.USER_ID != loginUserId && t.SOURCE_FORMCODE == "PT024_SHOWPRINT" && t.NOTICE_STATUS == 0,new BaseFilter(audit.ORG_ID));
                //if (taskCount == 0)
                //{
                //    audit.STATUS = PFStandardStatus.Archived;
                //}
                //发起车间、班组、个人目标与指标
                //T_PT_ASSESSMENT_PLAN_AUDIT auditDepart = null;
                //var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                //var loginUser = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId.Value, "Nav_Department", "Nav_ApproveRole");
                //var name = ""; var type = 0; var departmentType = FMDepartmentType.公司;
                //switch (audit.DEPARTMENT_TYPE)
                //{
                //    case FMDepartmentType.公司:
                //        departmentType = FMDepartmentType.部门;
                //        name = "部门"; type = 1;
                //        break;
                //    case FMDepartmentType.部门:
                //        departmentType = FMDepartmentType.车间;
                //        name = "车间"; type = 2;
                //        break;
                //    case FMDepartmentType.车间:
                //        departmentType = FMDepartmentType.班组;
                //        name = "班组";
                //        break;
                //    case FMDepartmentType.班组:
                //        name = "";
                //        break;
                //    default:
                //        name = "";
                //        break;
                //}
                //List<T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL> auditDetails = new List<T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL>();
                //List<T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL_CONTENT> contents = new List<T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL_CONTENT>();
                //T_FM_NOTIFICATION_TASK notice = null;
                //if ((int)audit.DEPARTMENT_TYPE != loginUser.Nav_Department.DEPARTMENT_TYPE || ((int)audit.DEPARTMENT_TYPE == loginUser.Nav_Department.DEPARTMENT_TYPE && audit.DEPARTMENT_TYPE == FMDepartmentType.班组))
                //{
                //    if (name == "")
                //    {
                //        auditDepart = null;
                //        audit.STATUS = PFStandardStatus.Archived;
                //    }
                //    else
                //    {
                //        auditDepart = new T_PT_ASSESSMENT_PLAN_AUDIT();
                //        auditDepart.STATUS = PFStandardStatus.Draft;
                //        auditDepart.ORG_ID = audit.ORG_ID;
                //        auditDepart.YEAR = audit.YEAR;
                //        auditDepart.SET_TIME = DateTime.Now;
                //        auditDepart.USER_ID = loginUserId;
                //        auditDepart.DEPARTMENT_ID = loginUser?.DEPARTMENT_ID;
                //        auditDepart.DEPARTMENT_TYPE = departmentType;
                //        var departmentIds = this.GetEntities<T_FM_DEPARTMENT>(t => t.DEPARTMENT_TYPE == type && t.PARENT_ID == loginUser.DEPARTMENT_ID && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用, new BaseFilter(audit.ORG_ID)).Select(m => m.ID).ToList();
                //        if (departmentIds.Any())
                //        {
                //            foreach (var department in departmentIds)
                //            {
                //                //细表
                //                T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL auditDetail = new T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL();
                //                auditDetail.ORG_ID = audit.ORG_ID;
                //                auditDetail.DEPARTMENT_ID = department;
                //                auditDetail.ASSESSMENT_PLAN_ID = auditDepart.ID;
                //                auditDetail.YEAR = DateTime.Now.Year.ToString();
                //                auditDetails.Add(auditDetail);
                //            }
                //        }
                //        var userInfos = this.GetEntities<T_FM_USER>(t => t.DEPARTMENT_ID == loginUser.DEPARTMENT_ID && (t.Nav_ApproveRole==null ||(t.Nav_ApproveRole != null && !t.Nav_ApproveRole.NAME.Contains("副总"))) && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && !t.NAME.Contains("管理员"), new BaseFilter(entity.ORG_ID)).ToList();
                //        foreach (var info in userInfos)
                //        {
                //            //细表
                //            T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL auditDetail = new T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL();
                //            auditDetail.ORG_ID = audit.ORG_ID;
                //            auditDetail.DEPARTMENT_ID = info.DEPARTMENT_ID;
                //            auditDetail.USER_ID = info.ID;
                //            auditDetail.ASSESSMENT_PLAN_ID = auditDepart.ID;
                //            auditDetail.YEAR = DateTime.Now.Year.ToString();
                //            auditDetails.Add(auditDetail);
                //        }
                //        var userIds = userInfos.Select(t => t.ID).ToList();
                //        var tempDetails = this.GetEntities<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL>(t => departmentIds.Contains(t.DEPARTMENT_ID.Value) || userIds.Contains(t.USER_ID.Value), new BaseFilter(entity.ORG_ID), new string[] { "Nav_Contents" }).ToList();
                //        if (auditDetails != null && auditDetails.Any())
                //        {
                //            foreach (var auditDs in auditDetails)
                //            {
                //                var tempCurrent = tempDetails.FirstOrDefault(t => t.DEPARTMENT_ID == auditDs.DEPARTMENT_ID && t.USER_ID == auditDs.USER_ID && t.YEAR == auditDs.YEAR);
                //                if (tempCurrent != null)
                //                {
                //                    auditDs.ASSESSMENT_CYCLE = tempCurrent.ASSESSMENT_CYCLE;
                //                    if (tempCurrent.Nav_Contents != null && tempCurrent.Nav_Contents.Any())
                //                    {
                //                        tempCurrent.Nav_Contents.ForEach(t =>
                //                        {
                //                            T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL_CONTENT content = new T_PT_ASSESSMENT_PLAN_AUDIT_DETAIL_CONTENT();
                //                            content.ORG_ID = t.ORG_ID;
                //                            content.PLAN_AUDIT_DETAIL_ID = auditDs.ID;
                //                            content.NAME = t.NAME;
                //                            content.SCORE = t.SCORE;
                //                            content.METHOD = t.METHOD;
                //                            contents.Add(content);
                //                        });
                //                    }
                //                }
                //            }
                //        }
                //        //var name = Enum.GetName(typeof(FMDepartmentType), auditDepart.DEPARTMENT_TYPE);
                //        notice = NotificationTaskService.InsertUserNoticeTaskModel(name + "考核方案审核", auditDepart.ID, audit.ORG_ID, loginUser.ID, loginUser.NAME, DateTime.Now,
                //        DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PT024");//userIds, userNames,
                //    }
                //}
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "PT024_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    //if (audit != null)
                    //    this.UpdateEntityNoCommit(audit);
                    //if (auditDepart != null)
                    //    this.UpdateEntityNoCommit(auditDepart);
                    //if (auditDetails != null && auditDetails.Any())
                    //    this.BantchSaveEntityNoCommit(auditDetails);
                    //if (contents != null && contents.Any())
                    //    this.BantchSaveEntityNoCommit(contents);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    //if (notice != null)
                    //    this.UpdateEntityNoCommit(notice);
                });
                return true;
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_PT_ASSESSMENT_PLAN_AUDIT> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var result = this.GetEntity<T_PT_ASSESSMENT_PLAN_AUDIT>(id, new string[] { "Nav_User", "Nav_Department","Nav_Department.Nav_User",
            "Nav_Details","Nav_Indeicator","Nav_Details.Nav_Department","Nav_Details.Nav_Contents","Nav_Details.Nav_User"});
                if (result != null && result.Nav_Details != null && result.Nav_Details.Any())
                {
                    result.Nav_Details = result.Nav_Details.OrderByDescending(t => t.USER_ID).ThenBy(m => m.DEPARTMENT_ID).ToList();
                }
                return result;
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("PT/PTAssessmentPlanAudit/BackUpdate", id);
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdateYL")]
        public JsonActionResult<bool> BackUpdateYL(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("PT/PTAssessmentPlanAudit/BackUpdateYL", id);
            });
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAssessmentData")]
        public JsonActionResult<List<AssessmentData>> GetAssessmentData([FromBody] KeywordFilter filter)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value;
            var result = new JsonActionResult<List<AssessmentData>>();
            result.Data = new List<AssessmentData>();
            var newFilter = new BaseFilter(orgId);
            //所有部门
            newFilter.SelectField = new List<string> { "ID", "NAME", "DEPARTMENT_TYPE", "USER_ID","Nav_User.NAME","NUM", "Nav_Parent.NUM", "Nav_Parent.NAME", "Nav_Parent.Nav_User.NAME",  "Nav_Parent.Nav_Parent.NAME", "Nav_Parent.Nav_Parent.Nav_User.NAME" };
            Expression<Func<T_FM_DEPARTMENT, bool>> expressionDepart = e => !e.IS_DELETED;
            var departmentInfos = this.GetEntities<T_FM_DEPARTMENT>(expressionDepart, newFilter).ToList();
            //所有人员
            Expression<Func<T_FM_USER, bool>> expressionUser = t => !t.IS_DELETED && t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin");
            newFilter.SelectField = new List<string> { "ID", "NAME", "DEPARTMENT_ID", "Nav_Department", "Nav_Person.Nav_Post","Nav_ApproveRole.NAME" };
            var userInfos = this.GetOrderEntities<T_FM_USER>(expressionUser, newFilter);
            //取总经理
            var chargeInfo = userInfos.FirstOrDefault(t => t.Nav_Person != null && t.Nav_Person.Nav_Post != null && t.Nav_Person.Nav_Post.NAME == "总经理");
            var chargeName = chargeInfo?.NAME;
            //先取所有部门,配置为公司级
            var companyDeparts = departmentInfos.Where(t => t.DEPARTMENT_TYPE == 10 || t.DEPARTMENT_TYPE == 5).OrderBy(m => m.NUM).ToList();
            if (companyDeparts != null && companyDeparts.Any())
            {
                foreach (var company in companyDeparts)
                {
                    AssessmentData data = new AssessmentData();
                    data.departId = company.ID;
                    data.departType_Num = 0;
                    data.departType = "公司级";
                    data.departName = company.NAME;
                    data.postName = "";
                    data.userName = "";
                    data.chargeName = "安委会成员";
                    data.targetItem = "1、指标一。2、指标二。";
                    data.type = "(年度/季度/月度)";
                    data.score = "1、80。2、20。";
                    data.method = "1、方法一。2、方法二。";
                    if (company.DEPARTMENT_TYPE == 5)
                        data.company_num = 0;
                    else
                        data.company_num = 1;
                    //data.depart_num = 0;
                    result.Data.Add(data);
                }
            }
            //取公司级所有人
            var companyDepartId = departmentInfos.FirstOrDefault(t => t.DEPARTMENT_TYPE == 5 && !t.NAME.Contains("安全环保管理部"))?.ID;
            var companyUsers = userInfos.Where(t => t.DEPARTMENT_ID == companyDepartId || (t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("副总"))).Distinct().ToList();
            if (companyUsers != null && companyUsers.Any())
            {
                foreach (var company in companyUsers)
                {
                    AssessmentData data = new AssessmentData();
                    data.departId = company?.Nav_Department ?.ID;
                    data.departType_Num = 0;
                    data.company_num = 2;
                    //data.depart_num = company?.Nav_Department ?.NUM;
                    data.departType = "公司级";
                    data.departName = company?.Nav_Department?.NAME;
                    data.postName = company?.Nav_Person?.Nav_Post?.NAME;
                    data.userName = company?.NAME;
                    data.targetItem = "1、指标一。2、指标二。";
                    data.type = "(年度/季度/月度)";
                    data.score = "1、80。2、20。";
                    data.method = "1、方法一。2、方法二。";
                    if (company.ID == chargeInfo?.ID)
                    {
                        data.chargeName = "安委会成员";
                    }
                    else
                    {
                        data.chargeName = chargeName;
                    }
                    //data.depart_num = 0;
                    result.Data.Add(data);
                }
            }
            //取部门级
            var departInfos = departmentInfos.Where(t => t.DEPARTMENT_TYPE == 10 || t.NAME.Contains("安全环保管理部")).OrderBy(t=>t.NUM).ToList();
            if (departInfos != null && departInfos.Any())
            {
                foreach (var depart in departInfos)
                {
                    var departUsers = userInfos.Where(t => t.DEPARTMENT_ID == depart.ID).ToList();
                    //var departChargeInfo= departUsers.FirstOrDefault(t => t.Nav_ApproveRole !=null && (t.Nav_ApproveRole.NAME == "部门负责人" || t.Nav_ApproveRole.NAME == "安环部负责人"));
                    if (departUsers != null && departUsers.Any())
                    {
                        foreach (var user in departUsers)
                        {
                            if (user.Nav_ApproveRole != null && user.Nav_ApproveRole.NAME.Contains("副总"))
                            {

                            }
                            else
                            {
                                if (user.ID != depart?.USER_ID)
                                {
                                    AssessmentData data = new AssessmentData();
                                    data.departId = user?.Nav_Department?.ID;
                                    data.departType_Num = 1;
                                    data.company_num = 4;
                                    //data.depart_num = depart.NUM;
                                    data.departType = "部门级";
                                    data.departName = user?.Nav_Department?.NAME;
                                    data.postName = user?.Nav_Person?.Nav_Post?.NAME;
                                    data.userName = user?.NAME;
                                    data.chargeName = depart.Nav_User?.NAME;//departChargeInfo?.NAME;
                                    result.Data.Add(data);
                                }
                                else
                                {
                                    //var departRoleId = this.GetEntity<T_PF_APPROVE_ROLE_DEPARTMENT>(t => t.DEPARTMENT_ID == depart.ID)?.APPROVAL_ROLE_ID;
                                    //if (departRoleId != null)
                                    //    chargeName = userInfos.FirstOrDefault(t=>t.APPROVE_ROLE_ID == departRoleId)?.NAME;
                                    if (depart.CHARGEUSER_ID != null)
                                        chargeName = userInfos.FirstOrDefault(t => t.ID == depart.CHARGEUSER_ID)?.NAME;
                                    AssessmentData data = new AssessmentData();
                                    data.departId = user?.Nav_Department?.ID;
                                    data.departType_Num = 0;
                                    data.company_num = 3;
                                    //data.depart_num = depart.NUM;
                                    data.departType = "公司级";
                                    data.departName = user?.Nav_Department?.NAME;
                                    data.postName = user?.Nav_Person?.Nav_Post?.NAME;
                                    data.userName = user?.NAME;
                                    data.chargeName = chargeName;
                                    data.targetItem = "1、指标一。2、指标二。";
                                    data.type = "(年度/季度/月度)";
                                    data.score = "1、80。2、20。";
                                    data.method = "1、方法一。2、方法二。";
                                    result.Data.Add(data);
                                }
                            }
                        }
                    }
                }
            }
            //取车间级
            var shopInfos = new List<T_FM_DEPARTMENT>();
            var departIds = departInfos.OrderBy(m=>m.NUM).Select(t => t.ID).ToList();
            if (departIds != null && departIds.Any())
            {
                foreach (var item in departIds)
                {
                    var temp = departmentInfos.Where(t => t.DEPARTMENT_TYPE == 15 && t.PARENT_ID == item).OrderBy(m=>m.NUM).ToList();
                    shopInfos.AddRange(temp);
                }
            }
            if (shopInfos != null && shopInfos.Any())
            {
                foreach (var depart in shopInfos)
                {
                    var departUsers = userInfos.Where(t => t.DEPARTMENT_ID == depart.ID).ToList();
                    //var departChargeInfo = departUsers.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "车间负责人");
                    //if (departChargeInfo == null)
                    //{
                    //    var parentId = departmentInfos.FirstOrDefault(t => t.ID == depart)?.PARENT_ID;
                    //    departChargeInfo = userInfos.FirstOrDefault(t => t.DEPARTMENT_ID == parentId &&  t.Nav_ApproveRole != null && (t.Nav_ApproveRole.NAME == "部门负责人"||t.Nav_ApproveRole.NAME == "安环部负责人"));
                    //}
                    if (departUsers != null && departUsers.Any())
                    {
                        foreach (var user in departUsers)
                        {
                            if (user.ID != depart?.USER_ID)
                            {
                                AssessmentData data = new AssessmentData();
                                data.departId = user?.Nav_Department?.ID;
                                data.departType_Num = 2;
                                data.company_num = 5;
                                //data.depart_num = depart.Nav_Parent?.NUM;
                                data.departType = "车间级";
                                data.departName = user?.Nav_Department?.NAME;
                                data.postName = user?.Nav_Person?.Nav_Post?.NAME;
                                data.userName = user?.NAME;
                                data.chargeName = depart.Nav_User?.NAME!=null? depart.Nav_User?.NAME: depart.Nav_Parent?.Nav_User?.NAME; //departChargeInfo?.NAME;
                                result.Data.Add(data);
                            }
                            else
                            {
                                var shopChargeId = departmentInfos.FirstOrDefault(t => t.ID == user.Nav_Department.PARENT_ID)?.USER_ID;
                                var shopChargeName = userInfos.FirstOrDefault(t => t.ID == shopChargeId)?.NAME;
                                AssessmentData data = new AssessmentData();
                                data.departId = user?.Nav_Department?.ID;
                                data.departType_Num = 1;
                                data.company_num = 4;
                                //data.depart_num = depart.Nav_Parent?.NUM;
                                data.departType = "部门级";
                                data.departName = user?.Nav_Department?.NAME;
                                data.postName = user?.Nav_Person?.Nav_Post?.NAME;
                                data.userName = user?.NAME;
                                data.chargeName = shopChargeName;
                                result.Data.Add(data);
                            }
                        }
                    }
                }
            }
            //取班组级
            var classInfos = new List<T_FM_DEPARTMENT>();
            var shopIds = shopInfos.Select(t => t.ID).ToList();
            if (shopIds != null && shopIds.Any())
            {
                foreach (var item in shopIds)
                {
                    var temp = departmentInfos.Where(t => t.DEPARTMENT_TYPE == 20 && t.PARENT_ID == item).OrderBy(m=>m.NUM).ToList();
                    classInfos.AddRange(temp);
                }
            }
            if (classInfos != null && classInfos.Any())
            {
                foreach (var depart in classInfos)
                {
                    var departUsers = userInfos.Where(t => t.DEPARTMENT_ID == depart.ID).ToList();
                    //var departChargeInfo = departUsers.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "班组负责人");
                    //if (departChargeInfo == null)
                    //{
                    //    var parentId = departmentInfos.FirstOrDefault(t => t.ID == depart)?.PARENT_ID;
                    //    departChargeInfo = userInfos.FirstOrDefault(t => t.DEPARTMENT_ID == parentId && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "车间负责人");
                    //    if (departChargeInfo == null)
                    //    {
                    //        var parentPId = departmentInfos.FirstOrDefault(t => t.ID == parentId)?.PARENT_ID;
                    //        departChargeInfo = userInfos.FirstOrDefault(t => t.DEPARTMENT_ID == parentPId && t.Nav_ApproveRole != null && (t.Nav_ApproveRole.NAME == "部门负责人" || t.Nav_ApproveRole.NAME == "安环部负责人"));
                    //    }
                    //}
                    if (departUsers != null && departUsers.Any())
                    {
                        foreach (var user in departUsers)
                        {
                            if (user.ID != depart?.USER_ID)
                            {
                                AssessmentData data = new AssessmentData();
                                data.departId = user?.Nav_Department?.ID;
                                data.departType_Num = 3;
                                data.company_num = 6;
                                //data.depart_num = depart.Nav_Parent?.Nav_Parent?.NUM;
                                data.departType = "班组级";
                                data.departName = user?.Nav_Department?.NAME;
                                data.postName = user?.Nav_Person?.Nav_Post?.NAME;
                                data.userName = user?.NAME;
                                var charge= depart.Nav_User?.NAME != null ? depart.Nav_User?.NAME : depart.Nav_Parent?.Nav_User?.NAME;
                                data.chargeName = charge!=null? charge: depart.Nav_Parent?.Nav_Parent?.Nav_User?.NAME;
                                result.Data.Add(data);
                            }
                            else
                            {
                                var classChargeId = departmentInfos.FirstOrDefault(t => t.ID == user.Nav_Department.PARENT_ID)?.USER_ID;
                                var classChargeName = userInfos.FirstOrDefault(t => t.ID == classChargeId)?.NAME;
                                AssessmentData data = new AssessmentData();
                                data.departId = user?.Nav_Department?.ID;
                                data.departType_Num = 2;
                                data.company_num = 5;
                                //data.depart_num = depart.Nav_Parent?.Nav_Parent?.NUM;
                                data.departType = "车间级";
                                data.departName = user?.Nav_Department?.NAME;
                                data.postName = user?.Nav_Person?.Nav_Post?.NAME;
                                data.userName = user?.NAME;
                                data.chargeName = classChargeName;
                                result.Data.Add(data);
                            }
                        }
                    }
                }
            }
            result.Data = result.Data.OrderBy(t => t.departType_Num).ThenBy(m=>m.company_num).ToList();
            return result;
        }

        /// <summary>
        /// 获取导入数据  
        /// 参考         [Route("api/PF/Import")]
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportData()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
                ImportDataModel result = new ImportDataModel();
                var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                if (!Directory.Exists(dic))
                    Directory.CreateDirectory(dic);
                foreach (var key in httpRequest.Form.Files)  // 文件键
                {
                    var postedFile = key;    // 获取文件键对应的文件对象
                    string filePath = Path.Combine(dic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + postedFile.FileName);
                    Byte[] fileData = new Byte[postedFile.Length];
                    Stream sr = postedFile.OpenReadStream();//创建数据流对象 
                    sr.Read(fileData, 0, (int)postedFile.Length);
                    using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
                    {
                        fs.Write(fileData, 0, fileData.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    //获取数据
                    Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
                    startRowIndexs.Add(0, 1);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;

                    bool isOK = InsertModel(dataTables.Tables[0], orgId, ref Msg);

                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch { }

                    result.Data = Msg;
                    result.MessageList = new List<string> { Msg };
                }

                return result;
            });
        }

        /// <summary>
        /// 数据插入
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="OrgID"></param>
        /// <param name="Msg"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool InsertModel(DataTable dtSource, Guid? orgId, ref string Msg, int rowIndex = 1)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            var newFilter = new BaseFilter(orgId);
            newFilter.SelectField = new List<string> { "ID","DEPARTMENT_ID", "USER_ID", "YEAR", "ASSESSMENT_CYCLE" };
            var assessmentInfos = this.GetEntities<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL>(t => !t.IS_DELETED, newFilter);
            newFilter.SelectField = new List<string> { "ID", "PLAN_AUDIT_DETAIL_ID" };
            var assessmentContentInfos = this.GetEntities<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT>(t => !t.IS_DELETED, newFilter);
            List<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL> assessmentLists = new List<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL>();
            List<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT> contentLists = new List<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT>();
            List<Guid> deleteIds = new List<Guid>();
            List<Guid> contentDeleteIds = new List<Guid>();
            //var posts = GetEntities<T_SC_POST>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            var departments = GetEntities<T_FM_DEPARTMENT>(t => t.IS_DELETED == false && t.ENABLE_STATUS == 0, new BaseFilter(orgId));
            var users = GetEntities<T_FM_USER>(t => t.IS_DELETED == false && t.ENABLE_STATUS == 0, new BaseFilter(orgId));
            int j = 1;
            for (int i = 0; i < rowAll; i++)
            {
                T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL assess = new T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL();
                assess.ID = Guid.NewGuid();
                assess.YEAR = DateTime.Now.Year.ToString();
                assess.ORG_ID = orgId;
                if (dtSource.Rows[i][0].ToString().Trim() != "公司级" && dtSource.Rows[i][0].ToString().Trim() != "部门级" && dtSource.Rows[i][0].ToString().Trim() != "车间级" && dtSource.Rows[i][0].ToString().Trim() != "班组级")
                {
                    throw new Exception("公司层级未按规定填写(公司级，部门级，车间级，班组级)");
                }
                if (string.IsNullOrEmpty(dtSource.Rows[i][5].ToString().Trim()) || string.IsNullOrEmpty(dtSource.Rows[i][7].ToString().Trim()) || string.IsNullOrEmpty(dtSource.Rows[i][8].ToString().Trim()))
                {
                    throw new Exception("安全生产指标考核项目、分数、考核认定评分办法必须填写");
                }
                if (dtSource.Rows[i][6].ToString().Trim() != "年度" && dtSource.Rows[i][6].ToString().Trim() != "季度" && dtSource.Rows[i][6].ToString().Trim() != "月度")
                {

                    throw new Exception("考核周期未按规定填写(年度,季度,月度)");
                }
                else
                {
                    switch (dtSource.Rows[i][6].ToString().Trim())
                    {
                        case "年度":
                            assess.ASSESSMENT_CYCLE = PTAssessmentCycleEnums.Year;
                            break;
                        case "季度":
                            assess.ASSESSMENT_CYCLE = PTAssessmentCycleEnums.Quarter;
                            break;
                        case "月度":
                            assess.ASSESSMENT_CYCLE = PTAssessmentCycleEnums.Month;
                            break;
                        default:
                            assess.ASSESSMENT_CYCLE = PTAssessmentCycleEnums.Year;
                            break;
                    }
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][1].ToString().Trim()))
                {
                    var depart = departments.FirstOrDefault(t => t.NAME == dtSource.Rows[i][1].ToString().Trim());
                    if (depart != null)
                    {
                        if (!string.IsNullOrEmpty(dtSource.Rows[i][3].ToString().Trim()))
                        {
                            var user = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][3].ToString().Trim());
                            if (user != null)
                            {
                                var isExist = assessmentInfos.FirstOrDefault(t => t.DEPARTMENT_ID == depart.ID && t.USER_ID == user.ID && t.YEAR == DateTime.Now.Year.ToString() && t.ASSESSMENT_CYCLE == assess.ASSESSMENT_CYCLE);
                                if (isExist != null)
                                {
                                    deleteIds.Add(isExist.ID);
                                    var contentIds = assessmentContentInfos.Where(t => t.PLAN_AUDIT_DETAIL_ID == isExist.ID).Select(m => m.ID).ToList();
                                    contentDeleteIds.AddRange(contentIds);
                                    //throw new Exception("被考核部门" + dtSource.Rows[i][1].ToString().Trim() + "，被考核人员" + dtSource.Rows[i][3].ToString().Trim() + "已存在，不能重复导入");
                                }
                                assess.USER_ID = user.ID;
                            }
                            else
                                throw new Exception("被考核人员" + dtSource.Rows[i][3].ToString().Trim() + "不存在，请核对人员姓名");
                        }
                        else
                        {
                            var isExist = assessmentInfos.FirstOrDefault(t => t.DEPARTMENT_ID == depart.ID && t.USER_ID == null);
                            if (isExist != null)
                            {
                                deleteIds.Add(isExist.ID);
                                var contentIds = assessmentContentInfos.Where(t => t.PLAN_AUDIT_DETAIL_ID == isExist.ID).Select(m => m.ID).ToList();
                                contentDeleteIds.AddRange(contentIds);
                                //throw new Exception("被考核部门" + dtSource.Rows[i][1].ToString().Trim() + "已存在，不能重复导入");
                            }
                            assess.USER_ID = null;
                        }
                        assess.DEPARTMENT_ID = depart.ID;
                    }
                    else
                        throw new Exception("被考核部门" + dtSource.Rows[i][1].ToString().Trim() + "不存在，请核对部门名称");
                }
                else
                    throw new Exception("被考核部门必须填写");
                if (!string.IsNullOrEmpty(dtSource.Rows[i][4].ToString().Trim()))
                {
                    if (dtSource.Rows[i][4].ToString().Trim() != "安委会成员")
                    {
                        var user = users.FirstOrDefault(t => t.NAME == dtSource.Rows[i][4].ToString().Trim());
                        if (user == null)
                            throw new Exception("考核人员" + dtSource.Rows[i][4].ToString().Trim() + "不存在，请核对人员姓名");
                    }
                    assess.CHARGE_NAME = dtSource.Rows[i][4].ToString().Trim();
                }
                else
                    throw new Exception("考核人员必须填写");
                assessmentLists.Add(assess);
                var items = new List<string>();
                var scores = new List<string>();
                var methods = new List<string>();
                var itemLists = dtSource.Rows[i][5].ToString().Trim().Split("。").ToList();
                var scoreLists = dtSource.Rows[i][7].ToString().Trim().Split("。").ToList();
                var methodLists = dtSource.Rows[i][8].ToString().Trim().Split("。").ToList();
                foreach (var ite in itemLists)
                {
                    if (!string.IsNullOrEmpty(ite))
                        items.Add(ite);
                }
                foreach (var ite in scoreLists)
                {
                    if (!string.IsNullOrEmpty(ite))
                        scores.Add(ite);
                }
                foreach (var ite in methodLists)
                {
                    if (!string.IsNullOrEmpty(ite))
                        methods.Add(ite);
                }
                if (items.Count != scores.Count || items.Count != methods.Count)
                    throw new Exception("第" + (i + 2) + "行，安全生产指标考核项目与分数与评分办法不匹配");
                else
                {
                    if (items != null && items.Any())
                    {
                        var NO = 1;
                        foreach (var item in items)
                        {
                            T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT content = new T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT();
                            content.PLAN_AUDIT_DETAIL_ID = assess.ID;
                            content.ORG_ID = orgId;
                            var itemArr = item.Split("、");
                            if (itemArr.Length != 2)
                            {
                                content.ROW_NO = NO;
                                content.NAME = item.ToString();
                            }
                            else
                            {
                                content.ROW_NO = int.Parse(itemArr[0]);
                                content.NAME = itemArr[1].ToString();
                            }
                            contentLists.Add(content);
                            NO++;
                        }
                    }
                    if (scores != null && scores.Any())
                    {
                        var NO = 1;
                        foreach (var item in scores)
                        {
                            var itemArr = item.Split("、");
                            if (itemArr.Length != 2)
                            {
                                var content = contentLists.FirstOrDefault(t =>t.PLAN_AUDIT_DETAIL_ID == assess.ID && t.ROW_NO == NO);
                                if (content != null)
                                    content.SCORE = decimal.Parse(item);
                                else
                                    throw new Exception("考核项目对应序号的分数未填写");
                            }
                            else
                            {
                                var content = contentLists.FirstOrDefault(t => t.PLAN_AUDIT_DETAIL_ID == assess.ID && t.ROW_NO == int.Parse(itemArr[0]));
                                if (content != null)
                                    content.SCORE = decimal.Parse(itemArr[1]);
                                else
                                    throw new Exception("考核项目对应序号的分数未填写");
                            }
                            NO++;
                        }
                    }
                    if (methods != null && methods.Any())
                    {
                        var NO = 1;
                        foreach (var item in methods)
                        {
                            var itemArr = item.Split("、");
                            if (itemArr.Length != 2)
                            {
                                var content = contentLists.FirstOrDefault(t => t.PLAN_AUDIT_DETAIL_ID == assess.ID && t.ROW_NO == NO);
                                if (content != null)
                                    content.METHOD = item;
                                else
                                    throw new Exception("考核项目对应序号的评分办法未填写");
                            }
                            else
                            {
                                var content = contentLists.FirstOrDefault(t => t.PLAN_AUDIT_DETAIL_ID == assess.ID && t.ROW_NO == int.Parse(itemArr[0]));
                                if (content != null)
                                    content.METHOD = itemArr[1];
                                else
                                    throw new Exception("考核项目对应序号的评分办法未填写");
                            }
                            NO++;
                        }
                    }
                    var total = contentLists.Where(t => t.PLAN_AUDIT_DETAIL_ID == assess.ID).Sum(m => m.SCORE); ;
                    if (total != 100)
                    { 
                        if(string.IsNullOrEmpty(dtSource.Rows[i][3].ToString().Trim()))
                            throw new Exception("被考核部门" + dtSource.Rows[i][1].ToString().Trim() + "的考核项目总分必须为100");
                        else
                            throw new Exception("被考核部门" + dtSource.Rows[i][1].ToString().Trim() + "，被考核人员" + dtSource.Rows[i][3].ToString().Trim() + "的考核项目总分必须为100");
                    }
                        
                }
            }
            UnifiedCommit(() =>
            {
                if (assessmentLists != null && assessmentLists.Any())
                    BantchAddEntityNoCommit(assessmentLists);
                if (contentLists != null && contentLists.Any())
                    BantchAddEntityNoCommit(contentLists);
                if (deleteIds != null && deleteIds.Any())
                    BantchDeleteEntityNoCommit<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL>(deleteIds);
                if (contentDeleteIds != null && contentDeleteIds.Any())
                    BantchDeleteEntityNoCommit<T_PT_ASSESSMENT_PLAN_AUDIT_TEMP_DETAIL_CONTENT>(contentDeleteIds);
            });
            Msg = "导入成功！";
            return true;
        }

        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("RejectUpdate")]
        public JsonActionResult<bool> RejectUpdate(string id)
        {
            return SafeExecute(() =>
            {
                var entity = this.GetEntity<T_PT_ASSESSMENT_PLAN_AUDIT>(id);
                entity.STATUS = PFStandardStatus.Rejected;
                var param = entity.DEPARTMENT_TYPE.GetDescription();
                //发消息
                T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                var user = this.GetEntity<T_FM_USER>(t => t.ID == entity.USER_ID && t.ENABLE_STATUS == 0);
                if (user != null)
                {
                    notice = NotificationTaskService.InsertUserNoticeTaskModel(param + "考核方案审核已被驳回", entity.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now,
                    DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "PT024");
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notice != null)
                        this.UpdateEntityNoCommit(notice);
                });
                return true;
                //return ApproveCallBackService.CallReject("PT/PTIndicatorFormulation/RejectUpdate", id);
            });
        }
    }
}
