using IWareCC.ORM;
|
using IWareCommon.Enum.Common;
|
using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace IWareCC.Extend
|
{
|
public static class NumberHelp
|
{
|
/// <summary>
|
/// 生成随机设备任务号
|
/// </summary>
|
/// <param name="deviceId"></param>
|
/// <returns></returns>
|
public static string GenerateRandomCode()
|
{
|
//1、第一层校验-跟当前内存数据对比
|
if (IWareCC.Service.existTaskCodeList.Count > 100)
|
{
|
var removeList = IWareCC.Service.existTaskCodeList.Take(10).OrderBy(x => x.createTime).ToList();
|
foreach (var item in removeList)
|
{
|
IWareCC.Service.existTaskCodeList.Remove(item);
|
}
|
}
|
int tryCount = 0;
|
var taskCode = _GenerateRandomCode(ref tryCount);
|
|
//2、第二次校验,跟当前数据库对比
|
bool result = ValidateIsExistNoFinishedTaskSameTaskCode(taskCode);
|
if (result == false)
|
{
|
tryCount = 0;
|
taskCode = _GenerateRandomCode(ref tryCount);
|
result = ValidateIsExistNoFinishedTaskSameTaskCode(taskCode);
|
if (result == false)
|
{
|
throw new Exception("第二次生成任务号,还是跟数据库中的任务号重复!");
|
}
|
}
|
|
//成功后保留到内存
|
IWareCC.Service.existTaskCodeList.Add(new ExistTaskCodeListModel()
|
{
|
createTime = DateTime.Now,
|
taskCode = taskCode
|
});
|
return taskCode;
|
}
|
|
public static string GenerateRandomCodeForMainTask()
|
{
|
var result = new StringBuilder();
|
for (var i = 0; i < 4; i++)
|
{
|
var r = new Random(Guid.NewGuid().GetHashCode());
|
result.Append(r.Next(1, 9));
|
}
|
var taskCode = result.ToString();
|
return taskCode;
|
}
|
|
private static string _GenerateRandomCode(ref int tryCount)
|
{
|
if (tryCount >= 3)
|
{
|
throw new Exception("已经重试生成三次了,还是会生成同一个任务号!");
|
}
|
tryCount++;
|
var result = new StringBuilder();
|
for (var i = 0; i < 4; i++)
|
{
|
var r = new Random(Guid.NewGuid().GetHashCode());
|
result.Append(r.Next(1, 9));
|
}
|
var taskCode = result.ToString();
|
//判断是否已经存在
|
if (IWareCC.Service.existTaskCodeList.Exists(x => x.taskCode == taskCode))
|
{
|
//说明这里面已经存在了
|
_GenerateRandomCode(ref tryCount);
|
}
|
return taskCode;
|
}
|
|
/// <summary>
|
/// 是否存在未结束的任务,相同任务号,相同设备
|
/// </summary>
|
/// <param name="deviceId"></param>
|
/// <param name="taskCode"></param>
|
/// <returns></returns>
|
private static bool ValidateIsExistNoFinishedTaskSameTaskCode(string taskCode)
|
{
|
using (var dbModel = new DbModel())
|
{
|
var task = dbModel.PartTasks.OrderBy(x => x.finishtimes).FirstOrDefault(x => x.isfinished == (int)EYesOrNo.否 && x.taskcode == taskCode);
|
if (task != null && task.id > 0)
|
{
|
return false;
|
}
|
}
|
return true;
|
}
|
}
|
}
|