using DocumentFormat.OpenXml.Wordprocessing;
using SqlSugar;

namespace OpenAuth.App.workflow;

/// <summary>
/// 业务编号生成器
/// 格式：YYYYMM + 4位序列号 (如：2024120001)
/// </summary>
public class BusinessNoGenerator
{
    private readonly ISqlSugarClient _sqlSugar;
    private static readonly object _lockObject = new object();

    public BusinessNoGenerator(ISqlSugarClient sqlSugar)
    {
        _sqlSugar = sqlSugar;
    }

    /// <summary>
    /// 生成业务编号
    /// </summary>
    /// <param name="prefix">业务前缀（可选）</param>
    /// <returns>业务编号</returns>
    public string GenerateBusinessNo(string prefix = "")
    {
        lock (_lockObject)
        {
            var currentDate = DateTime.Now;
            var yearMonth = currentDate.ToString("yyyyMM");

            // 查询当天最大序列号
            var todayPrefix = $"{prefix}{yearMonth}";
            var maxSequence = _sqlSugar.Queryable<BusinessNoSequence>()
                .Where(s => s.DatePrefix == todayPrefix)
                .OrderByDescending(s => s.SequenceNumber)
                .Select(s => s.SequenceNumber)
                .First();
            // 计算新的序列号
            var newSequence = maxSequence + 1;

            // 更新序列号记录
            var sequenceRecord = new BusinessNoSequence
            {
                DatePrefix = todayPrefix,
                SequenceNumber = newSequence,
                LastUpdateTime = DateTime.Now
            };

            // 如果记录不存在则插入，否则更新
            var existingRecord = _sqlSugar.Queryable<BusinessNoSequence>()
                .Where(s => s.DatePrefix == todayPrefix)
                .First();

            if (existingRecord == null)
            {
                _sqlSugar.Insertable(sequenceRecord).ExecuteCommand();
            }
            else
            {
                _sqlSugar.Updateable<BusinessNoSequence>()
                    .SetColumns(s => new BusinessNoSequence
                    {
                        SequenceNumber = newSequence,
                        LastUpdateTime = DateTime.Now
                    })
                    .Where(s => s.DatePrefix == todayPrefix)
                    .ExecuteCommand();
            }

            // 格式化返回业务编号
            return $"{todayPrefix}{newSequence:D4}";
        }
    }


    /// <summary>
    /// 批量生成业务编号
    /// </summary>
    /// <param name="count">生成数量</param>
    /// <param name="prefix">业务前缀</param>
    /// <returns>业务编号列表</returns>
    public List<string> GenerateBatchBusinessNo(int count, string prefix = "")
    {
        var businessNos = new List<string>();

        lock (_lockObject)
        {
            for (int i = 0; i < count; i++)
            {
                businessNos.Add(GenerateBusinessNo(prefix));
            }
        }

        return businessNos;
    }
}

/// <summary>
/// 业务编号序列记录表
/// </summary>
[SugarTable("zy_business_no_sequence")]
public class BusinessNoSequence
{
    /// <summary>
    /// 日期前缀 (YYYYMM格式)
    /// </summary>
    [SugarColumn(ColumnName = "dateprefix")]
    public string DatePrefix { get; set; }

    /// <summary>
    /// 当前序列号
    /// </summary>
    [SugarColumn(ColumnName = "sequencenumber")]

    public int SequenceNumber { get; set; }

    /// <summary>
    /// 最后更新时间
    /// </summary>
    [SugarColumn(ColumnName = "lastupdatetime")]
    public DateTime LastUpdateTime { get; set; }
}