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.PT;
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.SC;
using APT.BaseData.Domain.ApiModel.FM;
namespace APT.SC.WebApi.Controllers.Api.SCController
{
    /// 
    ///  标准化创建
    /// 
    [Route("api/SC/SCStandardCreate")]
    public partial class StandardCreateController : AuthorizeApiController
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// 
        /// 
        /// 
        /// 
        public StandardCreateController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// 
        /// 导入
        /// 
        /// 
        /// 
        [HttpPost, Route("FullImport")]
        public JsonActionResult 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 stas = new List();
                List files = new List();
                //List posts = new List();
                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", " ").Replace("\x0A", "
    ");
                        }
                        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;
            });
        }
        /// 
        /// 新增/编辑
        /// 
        /// 
        /// 
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult 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;
                entity.USER_ID = loginUserId;
                entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                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", " ").Replace("\x0A", "
    ");
                }
                var userInfo = this.GetEntity(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 (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);
                            MFlowPermitService.InsertApprove(serialCode[0], "SC046", param, entity.ID, "SC046_SHOWPRINT", entity.TaskID, true, () =>
                            {
                                if (entity != null)
                                    this.UpdateEntityNoCommit(entity);
                                if (files != null && files.Any())
                                    this.BantchSaveEntityNoCommit(files);
                            }, 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.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "SC046_SHOWPRINT";
                    }
                }
                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;
            });
        }
        /// 
        /// 获取
        /// 
        /// 
        /// 
        [HttpPost, Route("GetEdit")]
        public JsonActionResult 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(id, new string[] { "Nav_User", "Nav_User.Nav_Department",
                    "Nav_Files","Nav_Files.Nav_ImgFile","Nav_Files.Nav_ImgFile.Nav_File","Nav_Post"
                });
                if (result != null && !string.IsNullOrEmpty(result.FILE_CONTENT))
                {
                    result.FILE_CONTENT = result.FILE_CONTENT.Replace(" ", "\x20").Replace("
", "\n");
                }
                return result;
            });
        }
      
        /// 
        /// 修订/废除
        /// 
        /// 
        /// 
        [HttpPost, Route("FullRevisionUpdate")]
        public JsonActionResult FullRevisionUpdate([FromBody] T_SC_STANDARD_CREATE entity)
        {
            return SafeExecute(() =>
            {
                //var oldEntity = this.GetEntity(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.已归档)
                        this.ThrowError("040009");
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (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;
                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 => 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", " ").Replace("\x0A", "
    ");
                    }
                    //取审批流水码
                    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;
            });
        }
        
        /// 
        /// 回调函数
        /// 
        /// 
        /// 
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("SC/SCStandardCreate/BackUpdate", id);
            });
        }
        /// 
        /// 自动生成CODE
        /// 
        /// 
        [HttpPost, Route("GetFileCode")]
        public JsonActionResult GetFileCode([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var fileCode = "";
                var nextCodeInfo = this.GetEntities(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;
            });
        }
        /// 
        /// 排序分页查询数据
        /// 
        /// 分页过滤实体
        /// 
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult();
            var id = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
            if (string.IsNullOrEmpty(id))
                this.ThrowError("030017");
            var entity = this.GetEntity(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();
            ruleOrg.Field = "TYPE";
            ruleOrg.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(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");
                });
            }
            return result;
        }
        /// 
        /// 排序分页查询数据
        /// 
        /// 分页过滤实体
        /// 
        [HttpPost, Route("OrderPagedNew")]
        public PagedActionResult OrderPagedNew([FromBody] KeywordPageFilter pageFilter)
        {
            pageFilter.Include.Add("Nav_Department");
            pageFilter.Include.Add("Nav_Files.Nav_ImgFile.Nav_File");
            pageFilter.SelectField.Clear();
            var result = this.GetOrderPageEntities(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.FILE_CONTENT))
                    {
                        t.FILE_CONTENT = t.FILE_CONTENT.Replace(" ", "\x20").Replace("
", "\n");
                    }
                });
                //result.TotalCount = result.TotalCount;
            }
            return result;
        }
        /// 
        /// 获取导入数据  
        /// 参考         [Route("api/PF/Import")]
        /// 
        /// 
        [HttpPost, Route("GetImportData")]
        public JsonActionResult GetImportData()
        {
            return SafeExecute(() =>
            {
                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 startRowIndexs = new Dictionary();
                    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 { Msg };
                }
                return result;
            });
        }
        /// 
        /// 数据插入
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        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 { "NAME" };
            var standLaws = this.GetEntities(t => !t.IS_DELETED, newFilter);
            List laws = new List();
            var lawTypess = GetEntities(t => t.IS_DELETED == false, new BaseFilter(orgId));
            var departments = GetEntities(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[1][0].ToString().Trim() != "制度" && dtSource.Rows[1][0].ToString().Trim() != "安全生产责任制" && dtSource.Rows[1][0].ToString().Trim() != "岗位安全操作规程和指导书" && dtSource.Rows[1][0].ToString().Trim() != "应急预案")
            {
                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()))
                        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
                            throw new Exception("责任制岗位:" + dtSource.Rows[i][7].ToString().Trim() + "未找到");
                    }
                    if (string.IsNullOrEmpty(dtSource.Rows[i][8].ToString().Trim()))
                        throw new Exception("责任制导入,必须填写责任制说明");
                    else
                    {
                        law.NOTE = dtSource.Rows[i][8].ToString().Trim();
                    }
                    if (string.IsNullOrEmpty(dtSource.Rows[i][9].ToString().Trim()))
                        throw new Exception("责任制导入,必须填写文件名称");
                    else
                    {
                        law.FILE_NAME = dtSource.Rows[i][9].ToString().Trim();
                    }
                    if (string.IsNullOrEmpty(dtSource.Rows[i][10].ToString().Trim()))
                        throw new Exception("责任制导入,必须填写文件内容");
                    else
                    {
                        law.FILE_CONTENT = dtSource.Rows[i][10].ToString().Trim().Replace("\x20", " ").Replace("\x0A", "
    ");
                    }
                }
                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
                {
                    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() != "露天矿")
                {
                    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
                        throw new Exception("当前生产单元制度名称" + dtSource.Rows[i][2].ToString().Trim() + "已存在,不能重复导入");
                }
                else
                    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
                    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() != "公司级")
                {
                    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);
            }
            UnifiedCommit(() =>
            {
                if (laws != null && laws.Any())
                    BantchAddEntityNoCommit(laws);
            });
            Msg = "导入成功!";
            return true;
        }
    }
}