ImportService.cs 7.48 KB
using Hh.Mes.Service.WebService.Planned;
using HHECS.Application.Service.ImportBase;
using HHECS.Dal;
using HHECS.Infrastructure;
using HHECS.Infrastructure.Json;
using HHECS.Infrastructure.LogHelper;
using HHECS.Model.Entities;
using HHECS.Model.ViewEntity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using static HHECS.Infrastructure.NpoiExcelImportHelper;

namespace HHECS.Application.Service
{
    /// <summary>
    /// 导入Excel 公共方法  这里使用了反射,字典 动态执行注册方法
    /// 1:ImportOhter  定义模板名称 和【Excel文件名导入名一致】 前端JavaScript有判断文件要一致
    /// 2:ImportOhter  定义表名
    /// 3: ImportMethod 实体类 写对应的导入方法
    /// </summary>
    public class ImportService : BaseService
    {
        #region 属性
        /// <summary>
        /// 方法 需要加上特性
        /// </summary>
        private Dictionary<string, MethodInfo> sysDicMethod { get; set; }

        /// <summary>
        /// 导入Excel文件数据源 key 是文件名,value 是数据源
        /// ps:【keys】 保存数据的时候只取后缀包含 string tableSuffix = "_source"的中间过程可能存在加工
        /// </summary>
        private Dictionary<string, DtAllCls> sysDicDtSource { get; set; }

        private string materialDtKey { get; set; }

        private Dictionary<string, Action<DateTime>> ImportInSaveDataSuccess { get; set; }

        private DateTime sysNowTime { get; set; }
        #endregion

        #region 构造函数 初始化
        public ImportService()
        {
            Init();
            RegisterDicMethod();
        }

        private void Init()
        {
            sysDicDtSource = new Dictionary<string, DtAllCls>();

            sysNowTime = DateTime.Now;
            ImportInSaveDataSuccess = new Dictionary<string, Action<DateTime>>
            {
                { ExcelName.equipmenttype.ToString(), (sysNowTime) =>  {  new ImportMethod().SaveSuccessAfterEquipmenttype(sysNowTime);  }  },
                { ExcelName.equipmentmaintainruledetail.ToString(),(sysNowTime) =>{ new ImportMethod().SaveSuccessAfterEquipmentmaintainruledetail(sysNowTime); } }
            };
        }

        private void RegisterDicMethod()
        {
            sysDicMethod = ActionAttribute.GetMethods(typeof(ImportMethod));
        }
        #endregion

        #region 读取excel 文件数据 保存到 sysDicDtSource
        /// <summary>
        /// 导入
        /// </summary>
        public dynamic ImportIn(IFormFileCollection excelfile, IHostingEnvironment hostingEnvironment, User user)
        {
            var response = new Response();
            return ExceptionsHelp.Instance.ExecuteT<string>(() =>
            {
                #region Excel 读取 保存到dt
                foreach (var file in excelfile)
                {
                    var fileSuffix = Path.GetExtension(file.FileName);
                    var key = Path.GetFileNameWithoutExtension(file.FileName);
                    var dic = NpoiExcelImportHelper._.ExcelToDataTable(file.OpenReadStream(), fileSuffix, out var result, out var resultMsg);
                    foreach (var item in dic)
                    {
                        sysDicDtSource.Add(item.Key, item.Value);
                    }

                    if (result) continue;
                    response.Code = 500;
                    response.Message = resultMsg;
                    return response.ToJson();
                }
                #endregion

                #region 调用导入处理方法 key: dict[key]
                var objImportMethod = new ImportMethod();
                var isExtMethod = false;
                for (int i = 0; i < sysDicDtSource.Count; i++)
                {
                    (string key, DtAllCls value) = sysDicDtSource.ElementAt(i);

                    if (sysDicMethod.ContainsKey(key))
                    {
                        isExtMethod = true;
                        response = sysDicMethod[key].Invoke(objImportMethod, new object[] { sysDicDtSource, user.UserCode, sysNowTime }) as Response;
                        if (response == null) throw new Exception(SystemVariable.dataActionError + "--ImportIn");
                        if (response.Code == 200) continue;
                        return response.ToJson();
                    }
                }
                if (!isExtMethod)
                {
                    sysDicDtSource = null;
                    sysDicMethod = null;
                    response.Code = 500;
                    response.Message = "【ImportMethod】未实现导入方法,或者Excel文件 sheet页签名称和ExcelName不一致,请核实!";
                    return response.ToJson();
                }
                #endregion

                #region 导入数据判断

                #endregion

                //保存数据源
                return ImportInSaveData(response);
            });
        }
        #endregion

        #region 保存
        /// <summary>
        /// 写入数据源之前判断
        /// </summary>
        public Response ImportInSaveDataBefore(Response response)
        {
            //公共物料编码dt判断
            if (sysDicDtSource[materialDtKey].dtData.Rows.Count > 0)
            {
                /*  dicDtSource[materialDtKey] = dicDtSource[materialDtKey].Distinct("MaterialCode");
                  var materialdt = dicDtSource[materialDtKey];
                  for (int i = materialdt.Rows.Count - 1; i >= 0; i--)
                  {
                      var index = i;
                      if (Context.Queryable<base_material>().Where(u => u.MaterialCode == materialdt.Rows[index]["MaterialCode"].ToString()).Any())
                      {
                          materialdt.Rows.Remove(materialdt.Rows[i]);
                      }
                  }*/
            }

            return response;
        }

        /// <summary>
        /// 保存数据 只保存key 后缀包含TableName.tableSuffix
        /// </summary>
        public string ImportInSaveData(Response response)
        {
            //Dictionary<string, object> tempData = new Dictionary<string, object>();
            var tempSource = new Dictionary<string, DataTable>();
            foreach (var item in sysDicDtSource)
            {
                tempSource.Add(item.Key, item.Value.dtData);
            }
            var result = SqlHelper.SqlBulkCopyByDataTable(tempSource);
            if (result.Item1)
            {
                ImportInSaveDataSuccessAfter();
                sysDicDtSource = null;
                sysDicMethod = null;
                response.Code = 200;
                response.Message = SystemVariable.excelDataOk;
                return response.ToJson();
            }
            sysDicDtSource = null;
            sysDicMethod = null;
            response.Code = 500;
            response.Message = result.Item2;
            return response.ToJson();

        }


        public void ImportInSaveDataSuccessAfter()
        {
            for (int i = 0; i < sysDicDtSource.Count; i++)
            {
                (string key, DtAllCls value) = sysDicDtSource.ElementAt(i);

                if (ImportInSaveDataSuccess.ContainsKey(key))
                {
                    ImportInSaveDataSuccess[key].Invoke(sysNowTime);
                }
            }
        }
        #endregion

    }
}