//==============================================================
//  版权所有：深圳杰文科技
//  文件名：SysNumberService.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace Framework.DomainBase
{
	public static class SysNumberService
	{
		private static object _Locker = new object();

		public static string Generate(string type)
		{
			return Generate(type, DateTime.Now.Year, DateTime.Now.Month, 0, "", 4);
		}

		public static string Generate(string type, string prefix)
		{
			return Generate(type, DateTime.Now.Year, DateTime.Now.Month, 0, prefix, 4);
		}

		public static string Generate(string type, int year, int length)
		{
			int number = GetAndUpdate(type, year, 0, 0);
			string s = year.ToString() + number.ToString().PadLeft(length, '0');
			return s;
		}

		public static string Generate(string type, int year, int month, int day, string prefix, int length)
		{
			int number = GetAndUpdate(type, year, month, day);
			string s = year.ToString().Substring(2, 2) + month.ToString().PadLeft(2, '0') + day.ToString().PadLeft(2, '0');
			s = prefix + s + number.ToString().PadLeft(length, '0');
			return s;
		}

		public static string Generate(string type, DateTime d, string prefix, int length)
		{
			int year = d.Year;
			int month = d.Month;
			int day = d.Day;
			int number = GetAndUpdate(type, year, month, day);
			string s = prefix + number.ToString().PadLeft(length, '0');
			return s;
		}

		public static int GetAndUpdate(string type, int year, int month, int day)
		{
			lock (_Locker)
			{
				using (BaseDB db = new BaseDB())
				{
					SysNumber sysNumber = db.SysNumber.FirstOrDefault(a => a.Type == type && a.Year == year && a.Month == month && a.Day == day);
					if (sysNumber == null)
					{
						sysNumber = new SysNumber()
						{
							NumberId = Guid.NewGuid(),
							Type = type,
							Year = year,
							Month = month,
							Day = day,
							Number = 1,
						};
						db.SysNumber.Add(sysNumber);
					}
					else
					{
						sysNumber.Number++;
					}

					db.Save();

					return sysNumber.Number;
				}
			}
		}
	}
}
