using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.SC.PE;
using APT.MS.Domain.Entities.SC.SC;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Entities.SC.PT;
using System;
using APT.MS.Domain.Entities.HM;
using APT.BaseData.Services.Services.FM;
using System.Numerics;
using AutoMapper;
using Google.Protobuf.WellKnownTypes;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Threading;
using Enum = System.Enum;
using APT.BaseData.Domain.ApiModel;
using System.IO;
using System.Data;
using APT.MS.Domain.Entities.LR;
using APT.MS.Domain.Entities.SC;
using APT.BaseData.Domain.ApiModel.FM;
using System.Linq.Expressions;
using APT.MS.Domain.Entities.FO;

namespace APT.SC.WebApi.Controllers.Api.SCController
{
    /// <summary>
    ///  标准化创建
    /// </summary>
    [Route("api/SC/SCStandardCreate")]
    public partial class StandardCreateController : AuthorizeApiController<T_SC_STANDARD_CREATE>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="notificationTaskService"></param>
        public StandardCreateController(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("FullImport")]
        public JsonActionResult<bool> FullImport([FromBody] T_SC_STANDARD_CREATE entity)
        {
            return SafeExecute(() =>
            {
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var departmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                List<T_SC_STANDARD_CREATE> stas = new List<T_SC_STANDARD_CREATE>();
                List<T_SC_STANDARD_CREATE_FILE> files = new List<T_SC_STANDARD_CREATE_FILE>();
                //List<T_SC_STANDARD_CREATE_POST> posts = new List<T_SC_STANDARD_CREATE_POST>();
                var detail = entity.Nav_Details;
                if (detail != null && detail.Any())
                {
                    KeywordFilter filter = new KeywordFilter();
                    filter.OrgId = orgId;
                    filter.Keyword = detail.FirstOrDefault()?.TYPE.GetInt().ToString();
                    var code = GetFileCode(filter).Data;
                    int i = 1;
                    foreach (var item in detail)
                    {
                        // 取最后五位序列号
                        var serial = code.Substring(code.Length - 5);
                        //序列号+1，不足五位补0
                        var num = (int.Parse(serial) + i).ToString().PadLeft(5, '0');
                        var temp = code.Substring(0, code.Length - 5);
                        var entityCode = temp + num;
                        T_SC_STANDARD_CREATE sta = new T_SC_STANDARD_CREATE();
                        sta.STATUS = SCSystemEditStatus.已归档;
                        sta.USER_ID = loginUserId;
                        sta.DEPARTMENT_ID = item.DEPARTMENT_ID;
                        sta.VERSION = 1;
                        sta.FILE_STATUS = SCSystemFileStatus.有效;
                        sta.ORG_ID = orgId;
                        sta.CODE = entityCode;
                        sta.NAME = item.NAME;
                        sta.UNIT = item.UNIT;
                        sta.COMPILE_TIME = item.COMPILE_TIME;
                        sta.PUBLISH_TIME = item.PUBLISH_TIME;
                        sta.NOTE = item.NOTE;
                        sta.TYPE = item.TYPE;
                        sta.IMPORT_TYPE = DisableStatusEnum.是;
                        sta.POST_ID = item.POST_ID;
                        sta.DEPARTMENT_TYPE = item.DEPARTMENT_TYPE;
                        sta.MineType = item.MineType;
                        if (!string.IsNullOrEmpty(item.FILE_CONTENT))
                        {
                            sta.FILE_CONTENT = item.FILE_CONTENT.Replace("\x20", "&nbsp;").Replace("\x0A", "<br />&nbsp;&nbsp;&nbsp;&nbsp;");
                        }
                        if (item.Nav_Files != null && item.Nav_Files.Any())
                        {
                            item.Nav_Files.ForEach(t =>
                            {
                                T_SC_STANDARD_CREATE_FILE file = new T_SC_STANDARD_CREATE_FILE();
                                file.ORG_ID = orgId; file.STANDARD_CREATE_ID = sta.ID;
                                file.IMG_FILE_ID = t.IMG_FILE_ID;
                                files.Add(file);
                            });
                        }
                        i++;
                        //if (item.Nav_Posts != null && item.Nav_Posts.Any())
                        //{
                        //    item.Nav_Posts.ForEach(t =>
                        //    {
                        //        T_SC_STANDARD_CREATE_POST post = new T_SC_STANDARD_CREATE_POST();
                        //        post.ORG_ID = orgId; post.STANDARD_CREATE_ID = sta.ID;
                        //        post.POST_ID = t.POST_ID;
                        //        posts.Add(post);
                        //    });
                        //}
                        stas.Add(sta);
                    }
                }
                entity = null;
                UnifiedCommit(() =>
                {
                    if (stas != null && stas.Any())
                        this.BantchSaveEntityNoCommit(stas);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                    //if (posts != null && posts.Any())
                    //    this.BantchSaveEntityNoCommit(posts);
                });
                return true;
            });
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SC_STANDARD_CREATE entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK task = null;
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                KeywordFilter filter = new KeywordFilter();
                filter.OrgId = orgId;
                filter.Keyword = entity.TYPE.GetInt().ToString();
                var files = entity.Nav_Files;
                entity.STATUS = SCSystemEditStatus.草稿;
                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;
                entity.DEPARTMENT_ID = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.ID == (Guid)loginUserId)?.DEPARTMENT_ID;
                entity.VERSION = entity.VERSION == null ? 1 : entity.VERSION;
                entity.FILE_STATUS = SCSystemFileStatus.失效;
                //entity.IMPORT_TYPE = DisableStatusEnum.否;
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    var code = GetFileCode(filter).Data;
                    if (string.IsNullOrEmpty(code))
                        throw new Exception("制度编号不能为空，请关闭当前页面重新新增");
                    else
                    {
                        if (code.Length <= 5)
                            throw new Exception("制度编号错误，请关闭当前页面重新新增");
                        else
                            entity.CODE = code;
                    }
                }
                if (files != null && files.Any())
                {
                    files.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.STANDARD_CREATE_ID = entity.ID;
                    });
                }
                if (!string.IsNullOrEmpty(entity.FILE_CONTENT))
                {
                    entity.FILE_CONTENT = entity.FILE_CONTENT.Replace("\x20", "&nbsp;").Replace("\x0A", "<br />&nbsp;&nbsp;&nbsp;&nbsp;");
                }
                var userInfo = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == loginUserId, "Nav_Department");
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (userInfo != null && userInfo.Nav_Department != null)
                    {
                        //if (userInfo.Nav_Department.DEPARTMENT_TYPE != (int)entity.DEPARTMENT_TYPE)
                        //{
                        //    throw new Exception("选择的部门类型与发起人部门层级不一致,请修改");
                        //}
                        if (userInfo.Nav_Department.NAME == "安全环保管理部" || userInfo.Nav_Department.NAME == "安全环保部" || userInfo.Nav_Department.NAME == "安全环保科" || userInfo.Nav_Department.NAME == "安环部")
                        {
                            entity.DEPARTMENT_TYPE = SCDepartmentType.公司;
                        }
                        else
                        {
                            var type = userInfo.Nav_Department.DEPARTMENT_TYPE;
                            switch (type)
                            {
                                case 10:
                                    entity.DEPARTMENT_TYPE = SCDepartmentType.公司;
                                    break;
                                case 15:
                                    entity.DEPARTMENT_TYPE = SCDepartmentType.部门;
                                    break;
                                case 20:
                                    entity.DEPARTMENT_TYPE = SCDepartmentType.车间;
                                    break;
                                case 5:
                                    entity.DEPARTMENT_TYPE = SCDepartmentType.公司;
                                    break;
                                default:
                                    entity.DEPARTMENT_TYPE = SCDepartmentType.部门;
                                    break;
                            }

                        }
                        if (entity.IMPORT_TYPE == DisableStatusEnum.否)
                        {
                            entity.STATUS = SCSystemEditStatus.审核中;
                            entity.Nav_Files = 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(SCDepartmentType), entity.DEPARTMENT_TYPE);
                            if (entity.TaskID != Guid.Empty)
                            {
                                //task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                                //task.SOURCE_FORMCODE = "SC046_SHOWPRINT";
                                task = NotificationTaskService.GetEntityTask(entity.TaskID, "SC046_SHOWPRINT");
                                if (!task.SOURCE_DATA_ID.HasValue)
                                    task.SOURCE_DATA_ID = entity.ID;
                            }

                            MFlowPermitService.InsertApprove(serialCode[0], "SC046", param, entity.ID, "SC046_SHOWPRINT", null, true, () =>
                            {
                                if (entity != null)
                                    this.UpdateEntityNoCommit(entity);
                                if (files != null && files.Any())
                                    this.BantchSaveEntityNoCommit(files);
                                if (task != null)
                                    this.UpdateEntityNoCommit(task);
                            }, null, null, null, null, null, "SC046_SHOWPRINT", null, entity.NAME + "创建");
                            return true;
                        }
                        else
                        {
                            entity.STATUS = SCSystemEditStatus.已归档;
                            entity.FILE_STATUS = SCSystemFileStatus.有效;
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetEntityTask(entity.TaskID, "SC046_SHOWPRINT");
                        if (!task.SOURCE_DATA_ID.HasValue)
                            task.SOURCE_DATA_ID = entity.ID;
                    }
                }
                entity.Nav_Files = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_SC_STANDARD_CREATE> 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_SC_STANDARD_CREATE>(id, new string[] { "Nav_User", "Nav_User.Nav_Department",
                    "Nav_Files","Nav_Files.Nav_ImgFile","Nav_Files.Nav_ImgFile","Nav_Post"
                });
                if (result != null && !string.IsNullOrEmpty(result.FILE_CONTENT))
                {
                    result.FILE_CONTENT = result.FILE_CONTENT.Replace("&nbsp;", "\x20").Replace("<br />", "\n");
                }
                return result;
            });
        }

        /// <summary>
        /// 修订/废除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullRevisionUpdate")]
        public JsonActionResult<bool> FullRevisionUpdate([FromBody] T_SC_STANDARD_CREATE entity)
        {
            return SafeExecute(() =>
            {
                //var oldEntity = this.GetEntity<T_SC_STANDARD_CREATE>(entity.ID.ToString());
                //if (oldEntity != null)
                //{
                //    if (oldEntity.STATUS != SCSystemEditStatus.已归档)
                //        this.ThrowError("040003");
                //}
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndScrap"))
                {
                    if (entity.STATUS != SCSystemEditStatus.已归档 && entity.STATUS != SCSystemEditStatus.已驳回)
                        this.ThrowError("040009");
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.STATUS != SCSystemEditStatus.已归档 && entity.STATUS != SCSystemEditStatus.已驳回)
                        this.ThrowError("040008");
                }
                var files = entity.Nav_Files;
                entity.ID = Guid.NewGuid();
                entity.STATUS = SCSystemEditStatus.草稿;
                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;
                entity.VERSION = entity.VERSION + 1;
                entity.IMPORT_TYPE = DisableStatusEnum.否;
                if (files != null && files.Any())
                {
                    files.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.STANDARD_CREATE_ID = entity.ID;
                    });
                }
                T_SC_STANDARD_CREATE oldEntity = null;
                //废除
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndScrap"))
                {
                    //entity.STATUS = SCSystemEditStatus.已废除;
                    //entity.FILE_STATUS = SCSystemFileStatus.失效;
                    //oldEntity = this.GetEntity<T_SC_STANDARD_CREATE>(t => t.ID != entity.ID && t.CODE == entity.CODE && t.FILE_STATUS == SCSystemFileStatus.有效);
                    //if (oldEntity != null)
                    //    oldEntity.FILE_STATUS = SCSystemFileStatus.失效;
                    entity.FILE_STATUS = SCSystemFileStatus.废除中;
                    entity.STATUS = SCSystemEditStatus.审核中;
                    entity.Nav_Files = 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(SCDepartmentType), entity.DEPARTMENT_TYPE);
                    MFlowPermitService.InsertApprove(serialCode[0], "SC052", param, entity.ID, "SC052_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null)
                            this.UpdateEntityNoCommit(entity);
                        if (files != null && files.Any())
                            this.BantchSaveEntityNoCommit(files);
                    }, null, null, null, null, null, "SC052_SHOWPRINT", null, entity.NAME + "废除");
                    return true;
                }
                //修订
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    //var formCode = "SC052";
                    //switch (entity.TYPE)
                    //{
                    //    case SCType.制度:
                    //        formCode = "SC052";
                    //        break;
                    //    case SCType.安全生产责任制:
                    //        formCode = "SC052";
                    //        break;
                    //    case SCType.岗位安全操作规程和指导书:
                    //        break;
                    //    case SCType.应急预案修订记录:
                    //        break;
                    //    default: formCode = "SC052";
                    //        break;
                    //}
                    entity.FILE_STATUS = SCSystemFileStatus.修订中;
                    entity.STATUS = SCSystemEditStatus.审核中;
                    entity.Nav_Files = null;
                    if (!string.IsNullOrEmpty(entity.FILE_CONTENT))
                    {
                        entity.FILE_CONTENT = entity.FILE_CONTENT.Replace("\x20", "&nbsp;").Replace("\x0A", "<br />&nbsp;&nbsp;&nbsp;&nbsp;");
                    }
                    //取审批流水码
                    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(SCDepartmentType), entity.DEPARTMENT_TYPE);
                    MFlowPermitService.InsertApprove(serialCode[0], "SC052", param, entity.ID, "SC052_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null)
                            this.UpdateEntityNoCommit(entity);
                        if (files != null && files.Any())
                            this.BantchSaveEntityNoCommit(files);
                    }, null, null, null, null, null, "SC052_SHOWPRINT", null, entity.NAME + "修订");
                    return true;
                }
                entity.Nav_Files = null;
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (oldEntity != null)
                        this.UpdateEntityNoCommit(oldEntity);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                });
                return true;
            });
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("SC/SCStandardCreate/BackUpdate", id);
            });
        }
        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult<bool> RejectUpdate([FromBody] T_PF_APPROVE model)
        {
            return SafeExecute(() =>
            {
                //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                string Msg = string.Empty;
                bool ResultGetInfo = ApproveCallBackService.GetApproject(model, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败！");

                if (modelApp == null || listAppDetail == null)
                    throw new Exception("获取驳回信息失败！");
                var entity = this.GetEntity<T_SC_STANDARD_CREATE>(model.DATA_ID, new string[] { "Nav_User" });
                entity.STATUS = SCSystemEditStatus.已驳回;
                T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                if (entity != null && entity.USER_ID != null)
                {
                    string formCode = "SC046";
                    if (entity.FILE_STATUS == SCSystemFileStatus.废除中 || entity.FILE_STATUS == SCSystemFileStatus.废除中)
                    {
                        formCode = "SC052";
                        if (entity.TYPE == SCType.安全生产责任制)
                        {
                            formCode = "SC054";
                        }
                        if (entity.TYPE == SCType.岗位安全操作规程和指导书)
                        {
                            formCode = "SC056";
                        }
                        if (entity.TYPE == SCType.应急预案)
                        {
                            formCode = "SC068";
                        }
                    }
                    else
                    {
                        if (entity.TYPE == SCType.安全生产责任制)
                        {
                            formCode = "SC048";
                        }
                        if (entity.TYPE == SCType.岗位安全操作规程和指导书)
                        {
                            formCode = "SC050";
                        }
                        if (entity.TYPE == SCType.应急预案)
                        {
                            formCode = "SC067";
                        }
                    }
                    //驳回给创建人
                    notice = NotificationTaskService.InsertUserNoticeTaskModel(entity.NAME+"已被驳回", entity.ID, entity.ORG_ID, (Guid)entity.USER_ID, entity.Nav_User.NAME, DateTime.Now,
                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, formCode);
                }
                else
                {
                    throw new Exception("驳回失败，请联系管理员排查");
                }
                    UnifiedCommit(() =>
                    {
                        if (entity != null)
                            this.UpdateEntityNoCommit(entity);
                        if (notice != null)
                            this.UpdateEntityNoCommit(notice);
                        if (modelApp != null)
                            UpdateEntityNoCommit(modelApp);
                        if (listAppDetail != null && listAppDetail.Count > 0)
                            BantchUpdateEntityNoCommit(listAppDetail);
                        if (taskFinish != null)
                            UpdateEntityNoCommit(taskFinish);
                    });
                return true;
                //return ApproveCallBackService.CallReject("HM/HMLicenseAnalysis/RejectUpdate", id);
            });
        }
        /// <summary>
        /// 自动生成CODE
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("GetFileCode")]
        public JsonActionResult<string> GetFileCode([FromBody] KeywordFilter filter)
        {
            return SafeExecute<string>(() =>
            {
                var fileCode = "";
                var nextCodeInfo = this.GetEntities<T_SC_STANDARD_CREATE>(t => !t.IS_DELETED && (int)t.TYPE == int.Parse(filter.Keyword), new BaseFilter(filter.OrgId)).OrderByDescending(t => t.CREATE_TIME).FirstOrDefault();
                var year = DateTime.Now.Year;
                var month = DateTime.Now.Month.PadLeft(2, '0');
                var day = DateTime.Now.Day.PadLeft(2, '0');
                var prefix = "ZD";
                if (filter.Keyword == "1")
                    prefix = "ZRZ";
                if (filter.Keyword == "2")
                    prefix = "GWGC";
                if (filter.Keyword == "3")
                    prefix = "YJYA";
                if (nextCodeInfo == null)
                {
                    fileCode = prefix + year + month + day + "00001";
                }
                else
                {
                    if (nextCodeInfo.CODE.Length <= 5)
                    {
                        fileCode = prefix + year + month + day + "00001";
                    }
                    //取最后五位序列号
                    var serial = nextCodeInfo.CODE.Substring(nextCodeInfo.CODE.Length - 5);
                    //序列号+1，不足五位补0
                    var num = (int.Parse(serial) + 1).ToString().PadLeft(5, '0');
                    fileCode = prefix + year + month + day + num;
                }
                return fileCode;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_SC_STANDARD_CREATE> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_SC_STANDARD_CREATE>();
            var id = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
            if (string.IsNullOrEmpty(id))
                this.ThrowError("030017");
            var entity = this.GetEntity<T_SC_STANDARD_CREATE>(id);
            FilterRule rule = new FilterRule();
            rule.Field = "CODE";
            rule.Value = entity.CODE;
            FilterRule ruleOrg = new FilterRule();
            ruleOrg.Field = "ORG_ID";
            ruleOrg.Value = entity.ORG_ID;
            FilterRule ruleType = new FilterRule();
            ruleType.Field = "TYPE";
            ruleType.Value = entity.TYPE;
            pageFilter = new KeywordPageFilter();
            pageFilter.FilterGroup.Rules.Add(rule);
            pageFilter.FilterGroup.Rules.Add(ruleOrg);
            pageFilter.Sort = "CREATE_TIME";
            pageFilter.Order = 0;
            pageFilter.Include.Add("Nav_User");
            pageFilter.Include.Add("Nav_Department");
            pageFilter.SelectField.Clear();
            result = this.GetOrderPageEntities<T_SC_STANDARD_CREATE>(null, pageFilter);
            if (result.Data != null && result.Data.Any())
            {
                result.Data.ForEach(t =>
                {
                    if (string.IsNullOrEmpty(t.REASON))
                        t.REASON = "/";
                    if (string.IsNullOrEmpty(t.PROFILE))
                        t.PROFILE = "/";
                    t.VERSION_NAME = t.VERSION == null ? 0.ToString("#0.0") : t.VERSION.Value.ToString("#0.0");
                    if (!string.IsNullOrEmpty(t.FILE_CONTENT))
                    {
                        t.FILE_CONTENT = t.FILE_CONTENT.Replace("&nbsp;", "\x20").Replace("<br />", "\n");
                    }
                });
            }
            return result;
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedNew")]
        public PagedActionResult<T_SC_STANDARD_CREATE> OrderPagedNew([FromBody] KeywordPageFilter pageFilter)
        {
            pageFilter.Include.Add("Nav_Department");
            pageFilter.Include.Add("Nav_Files.Nav_ImgFile");
            pageFilter.SelectField.Clear();
            var result = this.GetOrderPageEntities<T_SC_STANDARD_CREATE>(null, pageFilter);
            if (result.Data != null && result.Data.Any())
            {
                result.Data = result.Data.GroupBy(t => t.CODE).Select(y => y.OrderByDescending(x => x.CREATE_TIME).FirstOrDefault()).ToList();
                result.Data.ForEach(t =>
                {
                    if (string.IsNullOrEmpty(t.REASON))
                        t.REASON = "/";
                    if (string.IsNullOrEmpty(t.PROFILE))
                        t.PROFILE = "/";
                    t.VERSION_NAME = t.VERSION == null ? 0.ToString("#0.0") : t.VERSION.Value.ToString("#0.0");
                    if (!string.IsNullOrEmpty(t.FILE_CONTENT))
                    {
                        t.FILE_CONTENT = t.FILE_CONTENT.Replace("&nbsp;", "\x20").Replace("<br />", "\n");
                    }
                });
                //result.TotalCount = result.Data.Count();
            }
            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> { "NAME" };
            var standLaws = this.GetEntities<T_SC_STANDARD_CREATE>(t => !t.IS_DELETED, newFilter);
            List<T_SC_STANDARD_CREATE> laws = new List<T_SC_STANDARD_CREATE>();
            var lawTypess = GetEntities<T_SC_POST>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            var departments = GetEntities<T_FM_DEPARTMENT>(t => t.IS_DELETED == false, new BaseFilter(orgId));
            DateTime dtNow = DateTime.Now;
            KeywordFilter filter = new KeywordFilter();
            filter.OrgId = orgId;
            filter.Keyword = "0";
            if (dtSource.Rows.Count == 1)
            {
                throw new Exception("导入必须两条以上，一条请直接新增");
            }
            if (dtSource.Rows[1][0].ToString().Trim() != "制度" && dtSource.Rows[1][0].ToString().Trim() != "安全生产责任制" && dtSource.Rows[1][0].ToString().Trim() != "岗位安全操作规程和指导书" && dtSource.Rows[1][0].ToString().Trim() != "应急预案")
            {
                if(string.IsNullOrEmpty(Msg))
                    Msg = "第一行第一列:体系类型未按规定填写(制度,安全生产责任制，岗位安全操作规程和指导书，应急预案)";
                else
                    Msg = Msg+ "\n" + "第一行第一列:体系类型未按规定填写(制度,安全生产责任制，岗位安全操作规程和指导书，应急预案)";
                //throw new Exception("体系类型未按规定填写(制度,安全生产责任制，岗位安全操作规程和指导书，应急预案)");
            }
            else
            {
                switch (dtSource.Rows[1][0].ToString().Trim())
                {
                    case "制度":
                        filter.Keyword = "0";
                        break;
                    case "安全生产责任制":
                        filter.Keyword = "1";
                        break;
                    case "岗位安全操作规程和指导书":
                        filter.Keyword = "2";
                        break;
                    case "应急预案":
                        filter.Keyword = "3";
                        break;
                    default:
                        filter.Keyword = "0";
                        break;
                }
            }
            var code = GetFileCode(filter).Data;
            int j = 1;
            for (int i = 0; i < rowAll; i++)
            {
                T_SC_STANDARD_CREATE law = new T_SC_STANDARD_CREATE();
                law.ID = Guid.NewGuid();
                law.VERSION = 1;
                law.USER_ID = (Guid)userId;
                law.STATUS = SCSystemEditStatus.草稿;
                law.FILE_STATUS = SCSystemFileStatus.失效;
                law.IMPORT_TYPE = DisableStatusEnum.是;
                // 取最后五位序列号
                var serial = code.Substring(code.Length - 5);
                //序列号+1，不足五位补0
                var num = (int.Parse(serial) + i).ToString().PadLeft(5, '0');
                var temp = code.Substring(0, code.Length - 5);
                law.CODE = temp + num;
                if (dtSource.Rows[i][0].ToString().Trim() == "制度")
                {
                    law.TYPE = 0;
                }
                else if (dtSource.Rows[i][0].ToString().Trim() == "安全生产责任制")
                {
                    law.TYPE = (SCType)1;
                    if (string.IsNullOrEmpty(dtSource.Rows[i][7].ToString().Trim()))
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第"+i+ "行第8列:责任制必须填写责任制岗位";
                        else
                            Msg = Msg + "\n" + "第" + i + "行第8列:责任制必须填写责任制岗位";
                        //throw new Exception("责任制导入，必须填写责任制岗位");
                    } 
                    else
                    {
                        var post = lawTypess.FirstOrDefault(t => t.NAME == dtSource.Rows[i][7].ToString().Trim());
                        if (post != null)
                        {
                            law.POST_ID = post.ID;
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(Msg))
                                Msg = "第" + i + "行第8列:责任制岗位:" + dtSource.Rows[i][7].ToString().Trim() + "未找到";
                            else
                                Msg = Msg + "\n" + "第" + i + "行第8列:责任制岗位:" + dtSource.Rows[i][7].ToString().Trim() + "未找到";
                            //throw new Exception("责任制岗位:" + dtSource.Rows[i][7].ToString().Trim() + "未找到");
                        }
                    }
                    //if (string.IsNullOrEmpty(dtSource.Rows[i][8].ToString().Trim()))
                    //{
                    //    if (string.IsNullOrEmpty(Msg))
                    //        Msg = "第" + i + "行第9列:责任制必须填写责任制说明";
                    //    else
                    //        Msg = "\r\n" + "第" + i + "行第9列:责任制必须填写责任制说明";
                    //    //throw new Exception("责任制导入，必须填写责任制说明");
                    //}
                    //else
                    {
                        law.NOTE = dtSource.Rows[i][8].ToString().Trim();
                    }
                    if (string.IsNullOrEmpty(dtSource.Rows[i][9].ToString().Trim()))
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + i + "行第10列:责任制必须填写文件名称";
                        else
                            Msg = Msg + "\n" + "第" + i + "行第10列:责任制必须填写文件名称";
                        //throw new Exception("责任制导入，必须填写文件名称");
                    }
                    else
                    {
                        law.FILE_NAME = dtSource.Rows[i][9].ToString().Trim();
                    }
                    if (string.IsNullOrEmpty(dtSource.Rows[i][10].ToString().Trim()))
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + i + "行第11列:责任制必须填写文件内容";
                        else
                            Msg = Msg + "\n" + "第" + i + "行第11列:责任制必须填写文件内容";
                        //throw new Exception("责任制导入，必须填写文件内容");
                    }
                    else
                    {
                        law.FILE_CONTENT = dtSource.Rows[i][10].ToString().Trim().Replace("\x20", "&nbsp;").Replace("\x0A", "<br />&nbsp;&nbsp;&nbsp;&nbsp;");
                    }
                }
                else if (dtSource.Rows[i][0].ToString().Trim() == "岗位安全操作规程和指导书")
                {
                    law.TYPE = (SCType)2;
                }
                else if (dtSource.Rows[i][0].ToString().Trim() == "应急预案")
                {
                    law.TYPE = (SCType)3;
                }
                else
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + i + "行第1列:体系类型未按规定填写(制度，安全生产责任制，岗位安全操作规程和指导书，应急预案)";
                    else
                        Msg = Msg + "\n" + "第" + i + "行第1列:体系类型未按规定填写(制度，安全生产责任制，岗位安全操作规程和指导书，应急预案)";
                    //throw new Exception("体系类型未按规定填写(制度，安全生产责任制，岗位安全操作规程和指导书，应急预案)");
                }
                if (dtSource.Rows[i][1].ToString().Trim() != "全公司" && dtSource.Rows[i][1].ToString().Trim() != "选矿厂" && dtSource.Rows[i][1].ToString().Trim() != "尾矿库" && dtSource.Rows[i][1].ToString().Trim() != "露天矿")
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + i + "行第2列:生产单元未按规定填写(全公司，露天矿，选矿厂，尾矿库)";
                    else
                        Msg = Msg + "\n" + "第" + i + "行第2列:生产单元未按规定填写(全公司，露天矿，选矿厂，尾矿库)";
                    //throw new Exception("生产单元未按规定填写(全公司，露天矿，选矿厂，尾矿库)");
                }
                else
                {
                    switch (dtSource.Rows[i][1].ToString().Trim())
                    {
                        case "全公司":
                            law.MineType = 0;
                            break;
                        case "露天矿":
                            law.MineType = (FMProductionUnit)30;
                            break;
                        case "选矿厂":
                            law.MineType = (FMProductionUnit)10;
                            break;
                        case "尾矿库":
                            law.MineType = (FMProductionUnit)20;
                            break;
                        default:
                            law.MineType = 0;
                            break;
                    }
                    //law.MineType = (FMProductionUnit)int.Parse(dtSource.Rows[i][1].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][2].ToString().Trim()))
                {
                    var standLaw = standLaws.FirstOrDefault(t => t.NAME == dtSource.Rows[i][2].ToString().Trim() && t.MineType == (FMProductionUnit)law.MineType);
                    if (standLaw == null)
                        law.NAME = dtSource.Rows[i][2].ToString().Trim();
                    else
                    {
                        if (string.IsNullOrEmpty(Msg))
                            Msg = "第" + i + "行第3列:当前生产单元制度名称" + dtSource.Rows[i][2].ToString().Trim() + "已存在，不能重复导入";
                        else
                            Msg = Msg + "\n" + "第" + i + "行第3列:当前生产单元制度名称" + dtSource.Rows[i][2].ToString().Trim() + "已存在，不能重复导入";
                        //throw new Exception("当前生产单元制度名称" + dtSource.Rows[i][2].ToString().Trim() + "已存在，不能重复导入");
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + i + "行第3列:制度名称必须填写";
                    else
                        Msg = Msg + "\n" + "第" + i + "行第3列:制度名称必须填写";
                    //throw new Exception("制度名称必须填写");
                }

                if (departments.FirstOrDefault(t => t.NAME == dtSource.Rows[i][3].ToString().Trim()) != null)
                {
                    law.DEPARTMENT_ID = departments.FirstOrDefault(t => t.NAME == dtSource.Rows[i][3].ToString().Trim()).ID;
                    law.UNIT = dtSource.Rows[i][3].ToString().Trim();
                }
                else
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + i + "行第4列:编制单位:" + dtSource.Rows[i][3].ToString().Trim() + "未找到";
                    else
                        Msg = Msg + "\n" + "第" + i + "行第4列:编制单位:" + dtSource.Rows[i][3].ToString().Trim() + "未找到";
                    //throw new Exception("编制单位:" + dtSource.Rows[i][3].ToString().Trim() + "未找到");
                }
                   
                if (dtSource.Rows[i][4].ToString().Trim() != "部门级" && dtSource.Rows[i][4].ToString().Trim() != "车间级" && dtSource.Rows[i][4].ToString().Trim() != "班组级" && dtSource.Rows[i][4].ToString().Trim() != "公司级")
                {
                    if (string.IsNullOrEmpty(Msg))
                        Msg = "第" + i + "行第5列:部门类型未按规定填写(公司级,部门级，车间级，班组级)";
                    else
                        Msg = Msg + "\n" + "第" + i + "行第5列:部门类型未按规定填写(公司级,部门级，车间级，班组级)";
                    //throw new Exception("部门类型未按规定填写(公司级,部门级，车间级，班组级)");
                }
                else
                {
                    switch (dtSource.Rows[i][4].ToString().Trim())
                    {
                        case "公司级":
                            law.DEPARTMENT_TYPE = (SCDepartmentType)3;
                            break;
                        case "部门级":
                            law.DEPARTMENT_TYPE = (SCDepartmentType)0;
                            break;
                        case "车间级":
                            law.DEPARTMENT_TYPE = (SCDepartmentType)1;
                            break;
                        case "班组级":
                            law.DEPARTMENT_TYPE = (SCDepartmentType)2;
                            break;
                        default:
                            law.DEPARTMENT_TYPE = (SCDepartmentType)3;
                            break;
                    }
                    //law.DEPARTMENT_TYPE = (SCDepartmentType)int.Parse(dtSource.Rows[i][4].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][5].ToString().Trim()))
                {
                    law.COMPILE_TIME = DateTime.Parse(dtSource.Rows[i][5].ToString().Trim());
                }
                if (!string.IsNullOrEmpty(dtSource.Rows[i][6].ToString().Trim()))
                {
                    law.PUBLISH_TIME = DateTime.Parse(dtSource.Rows[i][6].ToString().Trim());
                }
                law.ORG_ID = orgId;
                laws.Add(law);

            }
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            else
            {
                UnifiedCommit(() =>
                {
                    if (laws != null && laws.Any())
                        BantchAddEntityNoCommit(laws);
                });
                Msg = "导入成功！";
            }
            return true;
        }
    }
}
