using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.ApiModel.Platform;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.BD;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;

namespace APT.PF.WebApiControllers.Api.PF
{
    [Route("api/PF/Import")]
    public class ImportController : APTApiController<T_PF_FILE>
    {


        /// <summary>
        /// 获取导入数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportData()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                return Import(false);
            });
        }

        [HttpPost, Route("DownLoadFile")]
        public JsonActionResult<dynamic> DownLoadFile([FromBody] dynamic config)
        {
            return SafeExecute<dynamic>(() =>
            {
                var importService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IFMImportService>();

                var importData = importService.DownLoadFile(config);
                return importData;
            });
        }
        private ImportDataModel Import(bool isUpdate)
        {
            var httpRequest = this.HttpContext.Request;
            string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织
            string importConfigCode = httpRequest.Form["ImportConfigCode"];//导入配置代码
            var delFlag = false;
            if (!string.IsNullOrEmpty(httpRequest.Form["delFlag"]))
            {
                delFlag = bool.Parse(httpRequest.Form["delFlag"]);
            }
            Guid? orgId = null;
            if (!string.IsNullOrEmpty(orgIdStr))
                orgId = new Guid(orgIdStr);
            else
                return null;
            ImportDataModel result = null;
            var importService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IFMImportService>();

            foreach (var key in httpRequest.Form.Files)  // 文件键
            {
                var postedFile = key;    // 获取文件键对应的文件对象
                var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                if (!Directory.Exists(dic))
                    Directory.CreateDirectory(dic);
                string fileName = 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(fileName, FileMode.CreateNew))
                {
                    fs.Write(fileData, 0, fileData.Length);
                    fs.Flush();
                    fs.Close();
                }

                result = importService.GetImortData(orgId.Value, importConfigCode, fileName, isUpdate, delFlag);

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

            }
            return result;
        }

        [HttpPost, Route("ImportAndUpdate")]
        public JsonActionResult<ImportDataModel> ImportAndUpdate()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                return Import(true);
            });
        }

        [HttpPost, Route("ImportUpdateTest")]
        public JsonActionResult<bool> ImportUpdateTest(IFormCollection files)
        {
            return SafeExecute<bool>(() =>
            {
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];
                string fileName = string.Empty;//文件名称
                #region 文件先保存
                foreach (var key in httpRequest.Form.Files)  // 文件键
                {
                    var postedFile = key;    // 获取文件键对应的文件对象
                    var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                    if (!Directory.Exists(dic))
                        Directory.CreateDirectory(dic);
                    fileName = 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(fileName, FileMode.CreateNew))
                    {
                        fs.Write(fileData, 0, fileData.Length);
                        fs.Flush();
                        fs.Close();
                    }
                }
                #endregion
                ////List<T_ED_PROD_RECORD> prodRecodes = new List<T_ED_PROD_RECORD>();//产品生产记录表
                //List<T_ED_PROD_RECORD> addRecords = new List<T_ED_PROD_RECORD>();
                //List<T_ED_PROD_RECORD> updateRecords = new List<T_ED_PROD_RECORD>();
                //#region excel读取
                //var importTempDatas = FileUtils.ReadExcelByImport(fileName.Contains(".xlsx") ? fileName : fileName + ".xlsx");
                //#endregion
                //DateTime date = Convert.ToDateTime(importTempDatas[0].START_TIME);
                //var timeMin = new DateTime(date.Year, date.Month, 1);//月份第一天
                //var timeEnd = timeMin.AddMonths(1).AddDays(-1);//月份最后一天

                //#region 获取生产单元信息
                //var baseFilter = new BaseFilter(new Guid(orgIdStr));
                //baseFilter.SelectField = new string[] { "ID", "NAME" };
                //var nodes = this.GetEntities<T_BD_METER_NODE>(t => t.IS_PLAN, baseFilter);
                //#endregion
                //#region 获取产品生产记录表旧数据
                //var baseFilterold = new BaseFilter();
                //baseFilterold.SelectField = new string[] { "ID", "QTY", "METER_NODE_ID", "START_TIME" };
                //var oldRecords = this.GetEntities<T_ED_PROD_RECORD>(t => t.START_TIME >= timeMin && t.START_TIME <= timeEnd, baseFilterold, true).ToList();

                //#endregion
                //#region 生产ID 
                //var baseFilterPud = new BaseFilter();
                //baseFilterPud.SelectField = new string[] { "ID" };
                //var product = this.GetEntity<T_FM_PRODUCT>(i => i.ORG_ID == new Guid(orgIdStr), baseFilterPud);
                //#endregion
                //foreach (var item in importTempDatas)
                //{
                //    item.METER_NODE_ID = nodes.Single(x => x.NAME == item.Name).ID;
                //    if (oldRecords.Any(x => x.METER_NODE_ID == item.METER_NODE_ID && x.START_TIME == Convert.ToDateTime(item.START_TIME)))//旧表已存在数据
                //    {
                //        var nodeRecords = oldRecords.Where(x => x.METER_NODE_ID == item.METER_NODE_ID
                //           && x.START_TIME >= Convert.ToDateTime(item.START_TIME) && x.START_TIME < Convert.ToDateTime(item.START_TIME).AddDays(1));
                //        var dbQty = nodeRecords.Sum(i => i.QTY);
                //        if (dbQty < Convert.ToDecimal(item.QTY))//新修改的数据值大
                //        {
                //            var record = nodeRecords.FirstOrDefault();
                //            record.QTY += (Convert.ToDecimal(item.QTY) - dbQty);
                //            updateRecords.Add(record);
                //        }
                //        else if (dbQty > Convert.ToDecimal(item.QTY))//新修改的值变小
                //        {
                //            var deQty = dbQty - Convert.ToDecimal(item.QTY);
                //            foreach (var x in nodeRecords)
                //            {
                //                var minQty = Math.Min(x.QTY, deQty);
                //                x.QTY -= minQty;
                //                updateRecords.Add(x);
                //                deQty -= minQty;
                //                if (deQty <= 0)
                //                    break;
                //            }
                //        }
                //    }
                //    else//不存在
                //    {
                //        var record = new T_ED_PROD_RECORD()
                //        {
                //            ID = Guid.NewGuid(),
                //            PRODUCT_ID = product.ID,
                //            QTY = Convert.ToDecimal(item.QTY),
                //            START_TIME = Convert.ToDateTime(item.START_TIME),
                //            END_TIME = Convert.ToDateTime(item.START_TIME).AddDays(1),
                //            METER_NODE_ID = item.METER_NODE_ID,
                //            ORG_ID = new Guid(orgIdStr)
                //        };
                //        addRecords.Add(record);
                //    }
                //}
                //#region 更新数据        
                //this.UnifiedCommit(() =>
                //{
                //    this.BantchUpdateEntityNoCommit(updateRecords, new string[] { "QTY" });
                //    this.BantchAddEntityNoCommit(addRecords);
                //});
                //#endregion
                return true;
            });
        }

        //#region 导入历史数据
        ///// <summary>
        ///// 导入历史用量数据
        ///// </summary>
        ///// <param name="files">导入的Excel</param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportHistData")]
        //public JsonActionResult<dynamic> ImportHistData(IFormCollection files)
        //{
        //    return SafeExecute<dynamic>(() =>
        //    {
        //        dynamic result = new ExpandoObject();
        //        var httpRequest = this.HttpContext.Request;
        //        string orgIdStr = httpRequest.Form["OrgId"];
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "histImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        List<T_EM_HIST_ENERGY_DOSAGE_MONTH> addDosage = new List<T_EM_HIST_ENERGY_DOSAGE_MONTH>();
        //        List<T_EM_HIST_ENERGY_DOSAGE_MONTH> updateDosage = new List<T_EM_HIST_ENERGY_DOSAGE_MONTH>();
        //        #region excel读取
        //        var importHistDatas = FileUtils.ReadExcelByImportHistData(fileName);
        //        if (importHistDatas.Count == 0)
        //            return null;
        //        var stime = importHistDatas.Min(x => x.Time);
        //        var etime = importHistDatas.Max(x => x.Time);
        //        #endregion

        //        #region 获取器具信息和节点信息
        //        var baseFilter = new BaseFilter(new Guid(orgIdStr))
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] {
        //                "NAME", "Nav_ApplianceAttrs", "ENERGY_CLASS_ID", "APPLIANCE_GRADE",
        //                "Nav_EnergyClass.Nav_EnergyType.Nav_UnitEnumItem.POINTNUM",
        //                "Nav_EnergyClass.Nav_EnergyType.Nav_UnitEnumItem.NAME" }
        //        };
        //        var apps = this.GetEntities<T_BD_APPLIANCE>(x => x.ENABLE_STATUS == (int)FMEnableStatusEnum.启用, baseFilter)?.ToList();
        //        baseFilter.SelectField = new string[]
        //             {
        //                "PARENT_ID", "APPLIANCE_ID", "NAME", "Nav_Appliance.NAME", "Nav_Appliance.APPLIANCE_GRADE"
        //             };
        //        var node = GetEntities<T_BD_METER_NODE>(x => x.Nav_Appliance != null, baseFilter);
        //        #endregion

        //        #region 获取历史用量表数据
        //        baseFilter.SelectField = new string[] {
        //            "APPLIANCE_ID", "TIME", "DOSAGE", "ORG_ID"
        //            };
        //        updateDosage = GetEntities<T_EM_HIST_ENERGY_DOSAGE_MONTH>(x => x.TIME >= stime && x.TIME <= etime, baseFilter)?.ToList();
        //        #endregion

        //        var head = new List<TableHeadModel>
        //        {
        //            new TableHeadModel { Title = $"器具", DataIndex = "app" },
        //            new TableHeadModel { Title = "节点名称", DataIndex = "node" },
        //            new TableHeadModel { Title = "器具等级", DataIndex = "grade" },
        //            new TableHeadModel { Title = "单位", DataIndex = "unit" }
        //        };

        //        var startTime = new DateTime(stime.Year, 1, 1);
        //        var endTime = stime.AddYears(1);
        //        while (startTime < endTime)
        //        {
        //            head.Add(new TableHeadModel { Title = startTime.ToString("yyyy-MM"), DataIndex = startTime.ToString("yyyy-MM") });
        //            startTime = startTime.AddMonths(1);
        //        }
        //        var dataList = new List<Dictionary<string, object>>();
        //        if (importHistDatas.Any())
        //        {
        //            var appArry = importHistDatas.Select(x => x.Name);
        //            var app = new List<string>();
        //            foreach (var item in appArry)
        //            {
        //                var appName = apps.Where(x => x.NAME.Contains(item)).FirstOrDefault();
        //                if (appName != null && !app.Contains(appName.NAME))
        //                {
        //                    app.Add(appName.NAME);
        //                }
        //            }
        //            foreach (var item in app)
        //            {
        //                var meterNode = node.FirstOrDefault(x => x.Nav_Appliance?.NAME == item);
        //                var read = apps.FirstOrDefault(x => x.NAME == item);
        //                var dicData = new Dictionary<string, object>
        //                    {
        //                        { "app", item },
        //                        { "node", meterNode?.NAME },
        //                        { "grade", Enum.GetName(typeof(FMApplianceGrade), read.APPLIANCE_GRADE) },
        //                        { "unit", read.Nav_EnergyClass.Nav_EnergyType.Nav_UnitEnumItem.NAME }
        //                    };
        //                dataList.Add(dicData);
        //            }
        //            foreach (var item in importHistDatas)
        //            {
        //                var appAttr = apps.Where(x => x.NAME.Contains(item.Name)).FirstOrDefault();
        //                if (appAttr != null)
        //                {
        //                    var pointNum = appAttr.Nav_EnergyClass.Nav_EnergyType.Nav_UnitEnumItem.POINTNUM;
        //                    var month = updateDosage.FirstOrDefault(x => x.APPLIANCE_ID == appAttr.ID && x.TIME.ToIMonth() == item.Time.ToIMonth());
        //                    if (month == null)
        //                    {
        //                        var energyDosage = new T_EM_HIST_ENERGY_DOSAGE_MONTH()
        //                        {
        //                            ID = new Guid(),
        //                            DOSAGE = item.Data,
        //                            APPLIANCE_ID = appAttr.ID,
        //                            TIME = item.Time,
        //                            ORG_ID = new Guid(orgIdStr),
        //                        };
        //                        addDosage.Add(energyDosage);
        //                    }
        //                    else
        //                    {
        //                        month.DOSAGE = item.Data;
        //                    }
        //                    foreach (var dic in dataList)
        //                    {
        //                        if (dic.First().Value.ToString() == appAttr.NAME)
        //                        {
        //                            dic[item.Time.ToString("yyyy-MM")] = item.Data.ChangeDoubleToNum(pointNum);
        //                        }
        //                    }

        //                }
        //            }
        //        }
        //        result.Head = head;
        //        result.DataSource = dataList;

        //        #region 更新数据  

        //        this.UnifiedCommit(() =>
        //        {
        //            this.BantchUpdateEntityNoCommit(updateDosage);
        //            this.BantchAddEntityNoCommit(addDosage);
        //        });
        //        #endregion
        //        result.message = true;
        //        return result;
        //    });
        //}

        ///// <summary>
        ///// 导入历史用量数据
        ///// </summary>
        ///// <param name="files">导入的Excel</param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportHistValData")]
        //public JsonActionResult<dynamic> ImportHistValData(IFormCollection files)
        //{
        //    return SafeExecute<dynamic>(() =>
        //    {
        //        dynamic result = new ExpandoObject();
        //        var httpRequest = this.HttpContext.Request;
        //        string orgIdStr = httpRequest.Form["OrgId"];
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "histImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        List<T_EM_HIST_ENERGY_VAL_MONTH> addVal = new List<T_EM_HIST_ENERGY_VAL_MONTH>();
        //        List<T_EM_HIST_ENERGY_VAL_MONTH> updateVal = new List<T_EM_HIST_ENERGY_VAL_MONTH>();
        //        #region excel读取
        //        var importHistDatas = FileUtils.ReadExcelByImportHistData(fileName);
        //        if (importHistDatas.Count == 0)
        //            return null;
        //        var stime = importHistDatas.Min(x => x.Time);
        //        var etime = importHistDatas.Max(x => x.Time);
        //        #endregion

        //        #region 获取器具信息和节点信息
        //        var baseFilter = new BaseFilter(new Guid(orgIdStr))
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] {
        //                "NAME", "Nav_ApplianceAttrs", "ENERGY_CLASS_ID", "APPLIANCE_GRADE",
        //                "Nav_EnergyClass.Nav_EnergyType.Nav_UnitEnumItem.POINTNUM",
        //                "Nav_EnergyClass.Nav_EnergyType.Nav_UnitEnumItem.NAME" }
        //        };
        //        var apps = this.GetEntities<T_BD_APPLIANCE>(x => x.ENABLE_STATUS == (int)FMEnableStatusEnum.启用, baseFilter)?.ToList();
        //        baseFilter.SelectField = new string[]
        //             {
        //                "PARENT_ID", "APPLIANCE_ID", "NAME", "Nav_Appliance.NAME", "Nav_Appliance.APPLIANCE_GRADE"
        //             };
        //        var node = GetEntities<T_BD_METER_NODE>(x => x.Nav_Appliance != null, baseFilter);
        //        #endregion

        //        #region 获取历史用量表数据
        //        baseFilter.SelectField = new string[] {
        //            "APPLIANCE_ID", "TIME", "VAL", "ORG_ID"
        //            };
        //        updateVal = GetEntities<T_EM_HIST_ENERGY_VAL_MONTH>(x => x.TIME >= stime && x.TIME <= etime, baseFilter)?.ToList();
        //        #endregion

        //        var head = new List<TableHeadModel>
        //        {
        //            new TableHeadModel { Title = $"器具", DataIndex = "app" },
        //            new TableHeadModel { Title = "节点名称", DataIndex = "node" },
        //            new TableHeadModel { Title = "器具等级", DataIndex = "grade" },
        //            new TableHeadModel { Title = "单位", DataIndex = "unit" }
        //        };

        //        var startTime = new DateTime(stime.Year, 1, 1);
        //        var endTime = stime.AddYears(1);
        //        while (startTime < endTime)
        //        {
        //            head.Add(new TableHeadModel { Title = startTime.ToString("yyyy-MM"), DataIndex = startTime.ToString("yyyy-MM") });
        //            startTime = startTime.AddMonths(1);
        //        }
        //        var dataList = new List<Dictionary<string, object>>();
        //        if (importHistDatas.Any())
        //        {
        //            var appArry = importHistDatas.Select(x => x.Name);
        //            var app = new List<string>();
        //            foreach (var item in appArry)
        //            {
        //                var appName = apps.Where(x => x.NAME.Contains(item)).FirstOrDefault();
        //                if (appName != null && !app.Contains(appName.NAME))
        //                {
        //                    app.Add(appName.NAME);
        //                }
        //            }
        //            foreach (var item in app)
        //            {
        //                var meterNode = node.FirstOrDefault(x => x.Nav_Appliance?.NAME == item);
        //                var read = apps.FirstOrDefault(x => x.NAME == item);
        //                var dicData = new Dictionary<string, object>
        //                    {
        //                        { "app", item },
        //                        { "node", meterNode?.NAME },
        //                        { "grade", Enum.GetName(typeof(FMApplianceGrade), read.APPLIANCE_GRADE) },
        //                        { "unit", read.Nav_EnergyClass.Nav_EnergyType.Nav_UnitEnumItem.NAME }
        //                    };
        //                dataList.Add(dicData);
        //            }
        //            foreach (var item in importHistDatas)
        //            {
        //                var appAttr = apps.Where(x => x.NAME.Contains(item.Name)).FirstOrDefault();
        //                if (appAttr != null)
        //                {
        //                    var pointNum = appAttr.Nav_EnergyClass.Nav_EnergyType.Nav_UnitEnumItem.POINTNUM;
        //                    var month = updateVal.FirstOrDefault(x => x.APPLIANCE_ID == appAttr.ID && x.TIME.ToIMonth() == item.Time.ToIMonth());
        //                    if (month == null)
        //                    {
        //                        var energyVal = new T_EM_HIST_ENERGY_VAL_MONTH()
        //                        {
        //                            ID = new Guid(),
        //                            VAL = item.Data,
        //                            APPLIANCE_ID = appAttr.ID,
        //                            TIME = item.Time,
        //                            ORG_ID = new Guid(orgIdStr),
        //                        };
        //                        addVal.Add(energyVal);
        //                    }
        //                    else
        //                    {
        //                        month.VAL = item.Data;
        //                    }
        //                    foreach (var dic in dataList)
        //                    {
        //                        if (dic.First().Value.ToString() == appAttr.NAME)
        //                        {
        //                            dic[item.Time.ToString("yyyy-MM")] = item.Data.ChangeDoubleToNum(pointNum);
        //                        }
        //                    }

        //                }
        //            }
        //        }
        //        result.Head = head;
        //        result.DataSource = dataList;

        //        #region 更新数据  

        //        this.UnifiedCommit(() =>
        //        {
        //            this.BantchUpdateEntityNoCommit(updateVal);
        //            this.BantchAddEntityNoCommit(addVal);
        //        });
        //        #endregion
        //        result.message = true;
        //        return result;
        //    });
        //}

        //#endregion

        //#region 导入抄表卡数据
        ///// <summary>
        ///// 导入年抄表卡数据
        ///// </summary>
        ///// <param name="files"></param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportYearMeterReadData")]
        //public JsonActionResult<dynamic> ImportYearMeterReadData(IFormCollection files)
        //{
        //    return SafeExecute<dynamic>(() =>
        //    {
        //        dynamic result = new ExpandoObject();
        //        var httpRequest = this.HttpContext.Request;
        //        string orgIdStr = httpRequest.Form["OrgId"];
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "meterImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        List<T_EM_METER_READING_YEAR> addMeterRead = new List<T_EM_METER_READING_YEAR>();
        //        List<T_EM_METER_READING_YEAR> updateMeterRead = new List<T_EM_METER_READING_YEAR>();
        //        #region excel读取
        //        var importMeterReadDatas = FileUtils.ReadExcelByImportYearMeterReadData(fileName);
        //        var sTime = importMeterReadDatas.Min(x => x.Time);
        //        var eTime = importMeterReadDatas.Max(x => x.Time);
        //        #endregion

        //        #region 获取器具信息
        //        var baseFilter = new BaseFilter(new Guid(orgIdStr))
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "NAME", "Nav_ApplianceAttrs" }
        //        };
        //        var apps = this.GetEntities<T_BD_APPLIANCE>(x => x.ENABLE_STATUS == (int)FMEnableStatusEnum.启用, baseFilter);
        //        #endregion

        //        #region 获取历史数据
        //        baseFilter.SelectField = new string[] {
        //            "APPLIANCE_ID", "TIME", "SRC_DATA", "ORG_ID"
        //            };
        //        updateMeterRead = GetEntities<T_EM_METER_READING_YEAR>(x => x.TIME >= sTime && x.TIME <= eTime, baseFilter)?.ToList();
        //        #endregion
        //        //var head = new List<TableHeadModel>();
        //        //head.Add(new TableHeadModel { Title = "器具", DataIndex = "app" });
        //        //head.Add(new TableHeadModel { Title = "时间", DataIndex = "time" });
        //        //head.Add(new TableHeadModel { Title = "用量", DataIndex = "dosage" });
        //        //var dataList = new List<Dictionary<string, object>>();
        //        if (importMeterReadDatas.Any())
        //        {
        //            foreach (var item in importMeterReadDatas)
        //            {
        //                var appAttr = apps.Where(x => x.NAME.Contains(item.Name)).FirstOrDefault();
        //                if (appAttr != null)
        //                {
        //                    var histRead = updateMeterRead.
        //                        FirstOrDefault(x => x.APPLIANCE_ID == appAttr.ID && x.TIME.ToIMonth() == item.Time.ToIMonth());
        //                    if (histRead == null)
        //                    {
        //                        var meterRead = new T_EM_METER_READING_YEAR()
        //                        {
        //                            ID = new Guid(),
        //                            SRC_DATA = item.Data,
        //                            APPLIANCE_ID = appAttr.ID,
        //                            TIME = item.Time,
        //                            ORG_ID = new Guid(orgIdStr),
        //                        };
        //                        addMeterRead.Add(meterRead);
        //                    }
        //                    else
        //                        histRead.SRC_DATA = item.Data;
        //                }
        //            }
        //        }

        //        #region 更新数据  

        //        this.UnifiedCommit(() =>
        //        {
        //            this.BantchUpdateEntityNoCommit(updateMeterRead);
        //            this.BantchAddEntityNoCommit(addMeterRead);
        //        });
        //        #endregion
        //        result.message = true;
        //        //result.Head = head;
        //        //result.DataSource = dataList;
        //        return result;
        //    });
        //}

        ///// <summary>
        ///// 导入月抄表卡数据
        ///// </summary>
        ///// <param name="files"></param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportMonthMeterReadData")]
        //public JsonActionResult<dynamic> ImportMonthMeterReadData(IFormCollection files)
        //{
        //    return SafeExecute<dynamic>(() =>
        //    {
        //        dynamic result = new ExpandoObject();
        //        var httpRequest = this.HttpContext.Request;
        //        string orgIdStr = httpRequest.Form["OrgId"];
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "meterImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        List<T_EM_METER_READING_MONTH> addMeterRead = new List<T_EM_METER_READING_MONTH>();
        //        List<T_EM_METER_READING_MONTH> updateMeterRead = new List<T_EM_METER_READING_MONTH>();
        //        #region excel读取
        //        var importMeterReadDatas = FileUtils.ReadExcelByImportMonthMeterReadData(fileName);
        //        var sTime = importMeterReadDatas.Min(x => x.Time);
        //        var eTime = importMeterReadDatas.Max(x => x.Time);
        //        #endregion

        //        #region 获取器具信息
        //        var baseFilter = new BaseFilter(new Guid(orgIdStr))
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "NAME", "Nav_ApplianceAttrs" }
        //        };
        //        var apps = this.GetEntities<T_BD_APPLIANCE>(x => x.ENABLE_STATUS == (int)FMEnableStatusEnum.启用, baseFilter);
        //        #endregion

        //        #region 获取历史数据
        //        baseFilter.SelectField = new string[] {
        //            "APPLIANCE_ID", "TIME", "SRC_DATA", "ORG_ID"
        //            };
        //        updateMeterRead = GetEntities<T_EM_METER_READING_MONTH>(x => x.TIME >= sTime && x.TIME <= eTime, baseFilter)?.ToList();
        //        #endregion
        //        //var head = new List<TableHeadModel>();
        //        //head.Add(new TableHeadModel { Title = "器具", DataIndex = "app" });
        //        //head.Add(new TableHeadModel { Title = "时间", DataIndex = "time" });
        //        //head.Add(new TableHeadModel { Title = "用量", DataIndex = "dosage" });
        //        //var dataList = new List<Dictionary<string, object>>();
        //        if (importMeterReadDatas.Any())
        //        {
        //            foreach (var item in importMeterReadDatas)
        //            {
        //                var appAttr = apps.Where(x => x.NAME.Contains(item.Name)).FirstOrDefault();
        //                if (appAttr != null)
        //                {
        //                    var histRead = updateMeterRead.
        //                        FirstOrDefault(x => x.APPLIANCE_ID == appAttr.ID && x.TIME.ToIMonth() == item.Time.ToIMonth());
        //                    if (histRead == null)
        //                    {
        //                        var meterRead = new T_EM_METER_READING_MONTH()
        //                        {
        //                            ID = new Guid(),
        //                            SRC_DATA = item.Data,
        //                            APPLIANCE_ID = appAttr.ID,
        //                            TIME = item.Time,
        //                            ORG_ID = new Guid(orgIdStr),
        //                        };
        //                        addMeterRead.Add(meterRead);
        //                    }
        //                    else
        //                        histRead.SRC_DATA = item.Data;
        //                }
        //            }
        //        }

        //        #region 更新数据  

        //        this.UnifiedCommit(() =>
        //        {
        //            this.BantchUpdateEntityNoCommit(updateMeterRead);
        //            this.BantchAddEntityNoCommit(addMeterRead);
        //        });
        //        #endregion
        //        result.message = true;
        //        //result.Head = head;
        //        //result.DataSource = dataList;
        //        return result;
        //    });
        //}



        ///// <summary>
        ///// 导入日抄表卡数据
        ///// </summary>
        ///// <param name="files"></param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportDayMeterReadData")]
        //public JsonActionResult<dynamic> ImportDayMeterReadData(IFormCollection files)
        //{
        //    return SafeExecute<dynamic>(() =>
        //    {
        //        dynamic result = new ExpandoObject();
        //        var httpRequest = this.HttpContext.Request;
        //        string orgIdStr = httpRequest.Form["OrgId"];
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "meterImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        List<T_EM_METER_READING_DAY> addMeterRead = new List<T_EM_METER_READING_DAY>();
        //        List<T_EM_METER_READING_DAY> updateMeterRead = new List<T_EM_METER_READING_DAY>();
        //        #region excel读取
        //        var importMeterReadDatas = FileUtils.ReadExcelByImportDayMeterReadData(fileName);
        //        var sTime = importMeterReadDatas.Min(x => x.Time);
        //        var eTime = importMeterReadDatas.Max(x => x.Time);
        //        #endregion

        //        #region 获取器具信息
        //        var baseFilter = new BaseFilter(new Guid(orgIdStr))
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "NAME", "Nav_ApplianceAttrs" }
        //        };
        //        var apps = this.GetEntities<T_BD_APPLIANCE>(x => x.ENABLE_STATUS == (int)FMEnableStatusEnum.启用, baseFilter);
        //        #endregion

        //        #region 获取历史数据
        //        baseFilter.SelectField = new string[] {
        //            "APPLIANCE_ID", "TIME", "SRC_DATA", "ORG_ID"
        //            };
        //        updateMeterRead = GetEntities<T_EM_METER_READING_DAY>(x => x.TIME >= sTime && x.TIME <= eTime, baseFilter)?.ToList();
        //        #endregion
        //        //var head = new List<TableHeadModel>();
        //        //head.Add(new TableHeadModel { Title = "器具", DataIndex = "app" });
        //        //head.Add(new TableHeadModel { Title = "时间", DataIndex = "time" });
        //        //head.Add(new TableHeadModel { Title = "用量", DataIndex = "dosage" });
        //        //var dataList = new List<Dictionary<string, object>>();
        //        if (importMeterReadDatas.Any())
        //        {
        //            foreach (var item in importMeterReadDatas)
        //            {
        //                var appAttr = apps.Where(x => x.NAME.Contains(item.Name)).FirstOrDefault();
        //                if (appAttr != null)
        //                {
        //                    var histRead = updateMeterRead.
        //                        FirstOrDefault(x => x.APPLIANCE_ID == appAttr.ID && x.TIME.ToIMonth() == item.Time.ToIMonth());
        //                    if (histRead == null)
        //                    {
        //                        var meterRead = new T_EM_METER_READING_DAY()
        //                        {
        //                            ID = new Guid(),
        //                            SRC_DATA = item.Data,
        //                            APPLIANCE_ID = appAttr.ID,
        //                            TIME = item.Time,
        //                            ORG_ID = new Guid(orgIdStr),
        //                        };
        //                        addMeterRead.Add(meterRead);
        //                    }
        //                    else
        //                        histRead.SRC_DATA = item.Data;
        //                }
        //            }
        //        }

        //        #region 更新数据  

        //        this.UnifiedCommit(() =>
        //        {
        //            this.BantchUpdateEntityNoCommit(updateMeterRead);
        //            this.BantchAddEntityNoCommit(addMeterRead);
        //        });
        //        #endregion
        //        result.message = true;
        //        //result.Head = head;
        //        //result.DataSource = dataList;
        //        return result;
        //    });
        //}
        //#endregion

        //#region 导入生产记录信息
        ///// <summary>
        ///// 导入生产记录数据
        ///// </summary>
        ///// <param name="files">导入的Excel</param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportProductRecordData")]
        //public JsonActionResult<dynamic> ImportProductRecordData(IFormCollection files)
        //{
        //    return SafeExecute<dynamic>(() =>
        //    {
        //        dynamic result = new ExpandoObject();
        //        var httpRequest = this.HttpContext.Request;
        //        string orgIdStr = httpRequest.Form["OrgId"];
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "histImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        List<T_ED_PROD_RECORD> addRecord = new List<T_ED_PROD_RECORD>();
        //        #region excel读取
        //        var importHistDatas = FileUtils.ReadExcelByImportProductRecordData(fileName);
        //        #endregion

        //        #region 获取获取产品，生产记录，班组，班别信息
        //        var baseFilter = new BaseFilter(new Guid(orgIdStr))
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "CODE", "NAME" }
        //        };
        //        var product = this.GetEntities<T_FM_PRODUCT>(null, baseFilter)?.ToList();
        //        baseFilter.SelectField = new string[] { "NAME" };
        //        var node = this.GetEntities<T_BD_METER_NODE>(null, baseFilter)?.ToList();
        //        var team = this.GetEntities<T_FM_TEAM>(null, baseFilter)?.ToList();
        //        var clas = this.GetEntities<T_FM_CLASS>(null, baseFilter)?.ToList();
        //        #endregion
        //        var dataList = new List<Dictionary<string, object>>();
        //        if (importHistDatas.Any())
        //        {

        //            foreach (var item in importHistDatas)
        //            {
        //                var products = product.FirstOrDefault(x => x.CODE == item.Product_Code);
        //                var nodes = node.FirstOrDefault(x => x.NAME.Contains(item.MeterNode_Name));
        //                var teams = team.FirstOrDefault(x => x.NAME.Contains(item.Team_Name));
        //                var cla = clas.FirstOrDefault(x => x.NAME.Contains(item.Class_Name));
        //                var status = (int)Enum.Parse(typeof(FMOrderStatusEnum), item.Order_Status);
        //                if (products != null)
        //                {
        //                    var proRecord = new T_ED_PROD_RECORD()
        //                    {
        //                        ORG_ID = new Guid(orgIdStr),
        //                        PRODUCT_ID = products.ID,
        //                        METER_NODE_ID = (Guid)(nodes?.ID),
        //                        TEAM_ID = teams?.ID,
        //                        CLASS_ID = cla?.ID,
        //                        QTY = item.Qty,
        //                        START_TIME = item.Start_Time,
        //                        END_TIME = item.End_Time,
        //                        MODIFY_TIME = DateTime.Now,
        //                        ORDER_STATUS = status,
        //                        REMARK = item.Remark,
        //                    };
        //                    addRecord.Add(proRecord);
        //                }
        //            }
        //        }

        //        #region 更新数据  
        //        this.UnifiedCommit(() =>
        //        {
        //            this.BantchAddEntityNoCommit(addRecord);
        //        });
        //        #endregion
        //        result.message = true;
        //        return result;
        //    });
        //}
        //#endregion


        //#region 导入能源采购记录
        ///// <summary>
        ///// 导入能源采购记录
        ///// </summary>
        ///// <param name="files">导入的Excel</param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportEnergyPurchaseData")]
        //public JsonActionResult<bool> ImportEnergyPurchaseData(IFormCollection files)
        //{
        //    return SafeExecute<bool>(() =>
        //    {
        //        dynamic result = new ExpandoObject();
        //        var httpRequest = this.HttpContext.Request;
        //        string orgIdStr = httpRequest.Form["OrgId"];
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "histImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        List<T_ED_ENERGY_PURCHASE> addPurchase = new List<T_ED_ENERGY_PURCHASE>();
        //        #region excel读取
        //        var importEnergyPurchaseDatas = FileUtils.ReadExcelByImportEnergyPurchaseData(fileName);
        //        #endregion

        //        #region 获取能源分类分项数据和能源库存
        //        var baseFilter = new BaseFilter()
        //        {
        //            OrgId = new Guid(orgIdStr),
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "NAME" },
        //        };
        //        var energy = GetEntities<T_BD_ENERGY_CLASS>(null, baseFilter);
        //        baseFilter.SelectField = new string[]
        //        {
        //            "ENGERY_ID", "QTY", "RESERVE_QTY", "AVAILA_QTY"
        //        };
        //        var energyStore = GetEntities<T_ED_ENGERY_STORE>(null, baseFilter);
        //        #endregion
        //        if (importEnergyPurchaseDatas.Any())
        //        {
        //            foreach (var item in importEnergyPurchaseDatas)
        //            {
        //                var energys = energy.FirstOrDefault(x => x.NAME.Contains(item.Energy_Name));
        //                var store = energyStore.FirstOrDefault(x => x.ENGERY_ID == energys.ID);
        //                var energyPurchase = new T_ED_ENERGY_PURCHASE()
        //                {
        //                    ORG_ID = new Guid(orgIdStr),
        //                    ENGERY_ID = energys.ID,
        //                    QTY = item.Qty,
        //                    PLAN_DATE = item.Plan_Date,
        //                    BATCH = item.Batch,
        //                };
        //                if (store != null)
        //                {
        //                    energyPurchase.CURRENT_QTY = store.QTY;
        //                    energyPurchase.AVAILA_QTY = store.AVAILA_QTY;
        //                    energyPurchase.RESERVE_QTY = store.RESERVE_QTY;
        //                }
        //                addPurchase.Add(energyPurchase);
        //            }
        //        }

        //        #region 更新数据  
        //        this.UnifiedCommit(() =>
        //        {
        //            this.BantchAddEntityNoCommit(addPurchase);
        //        });
        //        #endregion
        //        return true;
        //    });
        //}

        //#endregion

        //#region 导入生产记录

        ///// <summary>
        ///// 导入生产记录(表单ED052)
        ///// </summary>
        ///// <param name="files"></param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportProductionRecords")]
        //public JsonActionResult<bool> ImportProductionRecords(IFormCollection files)
        //{
        //    return SafeExecute<bool>(() =>
        //    {
        //        var httpRequest = this.HttpContext.Request;
        //        var orgId = new Guid(httpRequest.Form["OrgId"]);
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "histImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        var datas = FileUtils.ReadExcelByImportProductionRecords(fileName);
        //        var productFilter = new BaseFilter(orgId)
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "ID", "CODE" }
        //        };
        //        var products = this.GetEntities<T_FM_PRODUCT>(null, productFilter);
        //        var baseFilter = new BaseFilter(orgId)
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "ID", "NAME" }
        //        };
        //        var nodes = this.GetEntities<T_BD_METER_NODE>(null, baseFilter);
        //        var teams = this.GetEntities<T_FM_TEAM>(null, baseFilter);
        //        var classList = this.GetEntities<T_FM_CLASS>(null, baseFilter);
        //        var list = new List<T_ED_PROD_RECORD>();
        //        foreach (var item in datas)
        //        {
        //            var model = new T_ED_PROD_RECORD
        //            {
        //                ORG_ID = orgId,
        //                START_TIME = item.Start_Time,
        //                END_TIME = item.End_Time,
        //                WORKHOUR = item.WorkHour,
        //                QTY = item.Qty
        //            };
        //            var node = nodes.FirstOrDefault(x => x.NAME == item.MeterNode_Name);
        //            if (node == null)
        //                throw new Exception("导入的生产单元不存在！");
        //            model.METER_NODE_ID = node.ID;

        //            var classItem = classList.FirstOrDefault(x => x.NAME == item.Class_Name);
        //            if (classItem == null && item.Class_Name != "全天")
        //                throw new Exception("导入的班别不存在！");
        //            model.CLASS_ID = classItem?.ID;

        //            var team = teams.FirstOrDefault(x => x.NAME == item.Team_Name);
        //            if (team == null && !string.IsNullOrEmpty(item.Team_Name))
        //                throw new Exception("导入的班组不存在！");
        //            model.TEAM_ID = team?.ID;

        //            var product = products.FirstOrDefault(x => x.CODE == item.Product_Name);
        //            if (product == null && item.Product_Name != "产品")
        //                throw new Exception("导入的产品不存在！");
        //            model.PRODUCT_ID = product?.ID;

        //            list.Add(model);
        //        }

        //        if (list.Any())
        //        {
        //            var model = list.First();
        //            var time = model.START_TIME.ToIMonth().FromIMonth();
        //            this.UnifiedCommit(() =>
        //            {
        //                this.DeleteEntityNoCommit<T_ED_PROD_RECORD>(x=>x.METER_NODE_ID==model.METER_NODE_ID && x.START_TIME>=time && x.START_TIME<time.AddMonths(1));
        //                this.BantchAddEntityNoCommit(list);
        //            });
        //        }

        //        return true;
        //    });
        //}
        ///// <summary>
        ///// 导入产量按部门
        ///// </summary>
        ///// <param name="files"></param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportProductionRecordsByDept")]
        //public JsonActionResult<bool> ImportProductionRecordsByDept(IFormCollection files)
        //{
        //    return SafeExecute<bool>(() =>
        //    {
        //        var httpRequest = this.HttpContext.Request;
        //        var orgId = new Guid(httpRequest.Form["OrgId"]);
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "histImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        var datas = FileUtils.ReadExcelByImportDeptRecords(fileName);                
        //        var baseFilter = new BaseFilter(orgId)
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "ID", "NAME" }
        //        };
        //        var nodes = this.GetEntities<T_FM_DEPARTMENT>(null, baseFilter);
        //        var equips = this.GetEntities<T_BD_EQUIPMENT>(null, baseFilter);           
        //        var list = new List<T_ED_DEPT_RECORD>();
        //        foreach (var item in datas)
        //        {
        //            var model = new T_ED_DEPT_RECORD
        //            {
        //                ORG_ID = orgId,
        //                TIME = item.Time,
        //                QTY = item.Qty
        //            };
        //            var node = nodes.FirstOrDefault(x => x.NAME == item.Dept_Name);
        //            if (node == null)
        //                throw new Exception("导入的部门不存在！");
        //            model.DEPARTMENT_ID = node.ID;                                  
        //            var equip = equips.FirstOrDefault(x => x.NAME == item.Equip_Name);
        //            if (equip == null)
        //                throw new Exception("导入的设备不存在！");
        //            model.EQUIPMENT_ID = equip.ID;
        //            list.Add(model);
        //        }

        //        if (list.Any())
        //        {
        //            var model = list.First();                 
        //            this.UnifiedCommit(() =>
        //            {
        //                this.DeleteEntityNoCommit<T_ED_DEPT_RECORD>(x => x.DEPARTMENT_ID == model.DEPARTMENT_ID && x.TIME.Year == model.TIME.Year);
        //                this.BantchAddEntityNoCommit(list);
        //            });
        //        }

        //        return true;
        //    });
        //}


        //#endregion


        //#region 导入生产计划

        ///// <summary>
        ///// 导入生产记录(表单PM038)
        ///// </summary>
        ///// <param name="files"></param>
        ///// <returns></returns>
        //[HttpPost, Route("ImportProductionPlan")]
        //public JsonActionResult<bool> ImportProductionPlan(IFormCollection files)
        //{
        //    return SafeExecute<bool>(() =>
        //    {
        //        var httpRequest = this.HttpContext.Request;
        //        var orgId = new Guid(httpRequest.Form["OrgId"]);
        //        string fileName = string.Empty;//文件名称
        //        #region 文件先保存
        //        foreach (var key in httpRequest.Form.Files)  // 文件键
        //        {
        //            var postedFile = key;    // 获取文件键对应的文件对象
        //            var dic = Path.Combine(System.AppContext.BaseDirectory, "histImportFiles");
        //            if (!Directory.Exists(dic))
        //                Directory.CreateDirectory(dic);
        //            fileName = 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(fileName, FileMode.CreateNew))
        //            {
        //                fs.Write(fileData, 0, fileData.Length);
        //                fs.Flush();
        //                fs.Close();
        //            }
        //        }
        //        #endregion
        //        var datas = FileUtils.ReadExcelByImportProductionPlans(fileName);
        //        var productFilter = new BaseFilter(orgId)
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "ID", "CODE" }
        //        };
        //        var products = this.GetEntities<T_FM_PRODUCT>(null, productFilter);
        //        var baseFilter = new BaseFilter(orgId)
        //        {
        //            IgnoreDataRule = true,
        //            SelectField = new string[] { "ID", "NAME" }
        //        };
        //        var nodes = this.GetEntities<T_BD_METER_NODE>(null, baseFilter);             
        //        var list = new List<T_PM_PRODUCT_PLAN>();
        //        foreach (var item in datas)
        //        {
        //            var model = new T_PM_PRODUCT_PLAN
        //            {
        //                ORG_ID = orgId,
        //                START_TIME = item.Start_Time,
        //                END_TIME = item.End_Time,                    
        //                QTY = item.Qty,
        //                AVG_QTY = item.Qty
        //            };
        //            var node = nodes.FirstOrDefault(x => x.NAME == item.MeterNode_Name);
        //            if (node == null)
        //                throw new Exception("导入的生产单元不存在！");
        //            model.NODE_ID = node.ID;                

        //            var product = products.FirstOrDefault(x => x.CODE == item.Product_Name);
        //            if (product == null && item.Product_Name != "产品")
        //                throw new Exception("导入的产品不存在！");
        //            model.PRODUCT_ID = product?.ID;

        //            list.Add(model);
        //        }

        //        var creat = new List<T_PM_PRODUCT_PLAN>();
        //        var update = new List<T_PM_PRODUCT_PLAN>();
        //        if (list.Any())
        //        {
        //            var codeRuleService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFCodeRuleService>();
        //            SystemCodeFilter filter = new SystemCodeFilter();
        //            filter.CodeType = (int)PFCodeRuleType.计划单号;
        //            filter.Count = 1;
        //            filter.OrgId = orgId;
        //            //var code = codeRuleService.NewGenSerial(filter);

        //            var nodeId = list.First().NODE_ID;
        //            var records = this.GetEntities<T_PM_PRODUCT_PLAN>(x => x.NODE_ID == nodeId, new BaseFilter(orgId));
        //            foreach (var item in list)
        //            {
        //                var record = records.FirstOrDefault(x =>
        //                    x.PRODUCT_ID == item.PRODUCT_ID && x.START_TIME == item.START_TIME &&
        //                    x.END_TIME == item.END_TIME);

        //                if (record != null)
        //                {
        //                    record.CODE = codeRuleService.NewGenSerial(filter);
        //                    record.QTY = item.QTY;
        //                    record.AVG_QTY = item.QTY;
        //                    update.Add(record);
        //                }
        //                else
        //                {
        //                    item.CODE = codeRuleService.NewGenSerial(filter);
        //                    creat.Add(item);
        //                }
        //            }
        //        }

        //        this.UnifiedCommit(() =>
        //        {
        //            if (creat.Any())
        //                this.BantchAddEntityNoCommit(creat);
        //            if (update.Any())
        //                this.BantchUpdateEntityNoCommit(update);
        //        });

        //        return true;
        //    });
        //}

        //#endregion
    }
}
