Files
zszq-trs/YLErpDAL/Modules/UnderlyingModule/VarietyPFEDeductService.cs
T
2024-05-09 14:06:26 +08:00

318 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using BaseOUDAL;
using System.Data;
using System.Globalization;
using System.Text.RegularExpressions;
using YLErp.Model;
namespace YLErp.Modules.ClientCashModule
{
/// <summary>
///
/// </summary>
public class VarietyPFEDeductService : YLBaseService
{
public VarietyPFEDeductService(OptUserInfo userInfo) : base(userInfo)
{
}
public variety_pfe_deduct SaveVarietyPFEConfig(variety_pfe_deduct req)
{
if (req is null)
{
throw new ArgumentNullException(nameof(req));
}
if (DbContext.variety_pfe_deduct.Any(x => x.id != req.id && x.VarietyIds == req.VarietyIds))
{
throw new Exception("同一品种对不支持多条配置记录");
}
var varietyPFEDeduct = DbContext.variety_pfe_deduct.Find(req.id);
if (varietyPFEDeduct == null)
{
varietyPFEDeduct = new variety_pfe_deduct();
DbContext.variety_pfe_deduct.Add(varietyPFEDeduct);
}
UpdateChanges(varietyPFEDeduct, req);
varietyPFEDeduct.OptDate = DateTime.Now;
varietyPFEDeduct.OptId = UserId;
varietyPFEDeduct.OptName = UserName;
DbContext.SaveChanges();
return varietyPFEDeduct;
}
/// <summary>
/// 导入PFE抵扣品种系数配置
/// </summary>
/// <param name="streamIn"></param>
/// <param name="totalNum">当前文件中的目标期权总条数</param>
/// <param name="successNum">成功入库的数量</param>
public void ImportVarietyPFEDeductFromExcel(Stream streamIn, out int totalNum, out int successNum)
{
totalNum = 0;
successNum = 0;
var rowIndex = 0;
try
{
var ds = Office.ExcelHelper.ReadExcelAsDataSet(streamIn, new[] { 0 }, 0);
if (ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 2)
{
throw new ServiceException("读取导入数据失败:数据为空") { Tag = "111" };
}
var table = ds.Tables[0];
var reader = new DataRowReader(table);
rowIndex = 1;
totalNum = table.Rows.Count - rowIndex;
using (var trans = BeginTransaction())
{
foreach (var row in table.Rows.Cast<DataRow>().Skip(1))
{
rowIndex++;
if (row.ItemArray.All(n => string.IsNullOrWhiteSpace(n?.ToString())))
{
totalNum--;
continue;
}
reader.SetDataRow(row);
var varietyCodes = reader.GetString("品种");
var varietyCodeList = varietyCodes.Split(',', '').ToList();
List<Variety> varietys = new List<Variety>();
varietyCodeList.ForEach(x =>
{
var variety = DataCacheProvider.GetVarietyDataSource().GetData(x);
if (variety == null)
{
throw new ServiceException($"品种{x}不存在");
}
else
{
varietys.Add(variety);
}
});
var varietyIds = string.Join(",", varietys.Select(x => x.id));
if (DbContext.variety_pfe_deduct.Any(x => x.VarietyIds == varietyIds))
{
throw new ServiceException($"品种{varietyCodes}的配置已存在");
}
var variety_pfe_deduct = new variety_pfe_deduct()
{
VarietyIds = varietyIds,
Rate = reader.GetPercent("抵扣系数", true) ?? 1,
OptId = UserId,
OptName = UserName,
OptDate = DateTime.Now
};
DbContext.variety_pfe_deduct.Add(variety_pfe_deduct);
DbContext.SaveChanges();
successNum++;
}
trans.Commit();
}
}
catch (ServiceException se)
{
if (se.Tag != null)
{
throw;
}
throw new ServiceException($"第{rowIndex}行,{se.Message}");
}
catch (Exception ex)
{
LogFactory.GetLogger("导入PFE抵扣品种系数配置").Error(ex);
throw new ServiceException($"第{rowIndex}行,发生错误:{ex.Message}", ex);
}
}
/// <summary>
/// trade_swap_flow
/// </summary>
public SearchListResult<variety_pfe_deduct> SearchVarietyPFEDeductList(VarietyMappingDeductReq req)
{
var query = from source in DbContext.variety_pfe_deduct select source;
if (string.IsNullOrEmpty(req.sidx))
{
req.sidx = "id";
req.sord = "desc";
}
var retListResult = query.ToSearchList(req);
foreach (var item in retListResult.rows)
{
var varietyIds = item.VarietyIds.Split(',');
var varietys = DbContext.variety.Where(x => varietyIds.Contains(x.id.ToString()));
item.VarietyCodes = string.Join(",", varietys.Select(x => x.VarietyCode));
}
return retListResult;
}
#region---内部业务类----
class DataRowReader
{
DataRow _row;
readonly Dictionary<string, int> _colMap;
public DataRowReader(DataTable table)
{
var colCount = table.Columns.Count;
_colMap = new Dictionary<string, int>(colCount, StringComparer.OrdinalIgnoreCase);
var row1 = table.Rows[0];
var preCol1 = string.Empty;
for (var index = 0; index < colCount; index++)
{
var col1 = row1[index]?.ToString()?.Trim();
if (!string.IsNullOrWhiteSpace(col1))
{
preCol1 = col1;
}
_colMap[preCol1] = index;
}
}
/// <summary>
/// 设置datarow
/// </summary>
public void SetDataRow(DataRow row)
{
_row = row;
}
public string GetString(string fieldName, bool required = false)
{
var str = _colMap.TryGetValue(fieldName, out var colIndex) ? _row[colIndex]?.ToString()?.Trim() : null;
if (required && string.IsNullOrWhiteSpace(str))
{
throw new ServiceException($"{fieldName} 必须填写");
}
return str;
}
public double? GetDoubleOrPercent(string fieldName, bool required, bool percent)
{
var str = GetString(fieldName, required);
if (!required && string.IsNullOrWhiteSpace(str))
{
return null;
}
if (percent && (percent = str.EndsWith("%")))
{
str = str.TrimEnd('%');
}
return double.TryParse(str, out var num) ? (percent ? num / 100 : num) : throw new ServiceException($"{fieldName} 填写错误:{str}");
}
public double? GetDouble(string fieldName, bool required = false)
{
var str = GetString(fieldName, required);
if (!required && string.IsNullOrWhiteSpace(str))
{
return null;
}
return double.TryParse(str, out var num) ? num : throw new ServiceException($"{fieldName} 填写错误:{str}");
}
//为了兼容模板修改导致的字段名称改变问题
public double? GetDouble(string fieldName, string fieldName2, bool required = false)
{
var str = GetString(fieldName, false) ?? GetString(fieldName2, false);
if (string.IsNullOrWhiteSpace(str))
{
return required ? throw new ServiceException($"{fieldName} 必须填写") : (double?)null;
}
return double.TryParse(str, out var num) ? num : throw new ServiceException($"{fieldName} 填写错误:{str}");
}
public double? GetPercent(string fieldName, bool required = false)
{
var str = GetString(fieldName, required);
if (!required && string.IsNullOrWhiteSpace(str))
{
return null;
}
var percent = str.EndsWith("%");
if (percent)
{
str = str.TrimEnd('%');
}
return double.TryParse(str, out var num) ? (percent ? num / 100 : num) : throw new ServiceException($"{fieldName} 填写错误:{str}");
}
/// <summary>
/// 获取日期(不包括时间)
/// </summary>
public DateTime? GetDate(string fieldName, bool required = false)
{
var str = GetString(fieldName, required);
if (!required && string.IsNullOrWhiteSpace(str))
{
return null;
}
if (str.Length == 8 && Regex.IsMatch(str, @"^\d+$"))
{
return DateTime.TryParseExact(str, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt2) ? dt2 : throw new ServiceException($"{fieldName} 填写错误:{str}");
}
return DateTime.TryParse(str, out var dt) ? dt.Date : throw new ServiceException($"{fieldName} 填写错误:{str}");
}
/// <summary>
///
/// </summary>
public int? GetInt32(string fieldName, bool required = false)
{
var str = GetString(fieldName, required);
if (!required && string.IsNullOrWhiteSpace(str))
{
return null;
}
return int.TryParse(str, out var num) ? num : throw new ServiceException($"{fieldName} 填写错误:{str}");
}
}
#endregion
}
}