using OASystem.Domain.Entities.PersonnelModule;
using OASystem.Infrastructure.Repositories.PersonnelModule;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace OASystem.API.OAMethodLib.Quartz.Business
{
    /// <summary>
    /// 任务指派
    /// 定时任务
    /// </summary>
    public static class TaskAssignment
    {
        private readonly static TaskAllocationRepository _taskAllocationRep = AutofacIocManager.Instance.GetService<TaskAllocationRepository>();
        //private readonly static SqlSugarClient _sqlSugar = AutofacIocManager.Instance.GetService<SqlSugarClient>();
        private readonly static ILogger _logger;
        /// <summary>
        /// 定时任务更改状态
        /// 每天下午六点定时更新
        /// </summary>
        public static async void PostTaskUpdateStatus()
        {
            //_taskAllocationRep.ChangeDataBase(DBEnum.OA2023DB);
            var newDB = _taskAllocationRep._sqlSugar.CopyNew();
            var data = newDB.Queryable<Pm_TaskAllocation>()
                            .Where(it => it.IsDel == 0 &&
                                        !string.IsNullOrEmpty(it.PredictEndTime) &&
                                        Convert.ToDateTime(it.PredictEndTime) >= DateTime.Now
                                )
                            .ToList();
            if (data.Count > 0)
            {
                //处理要变更状态的员工
                List<int> primaryIds = new List<int>();
                primaryIds = data.Select(it => it.Id).ToList();
                var subData = newDB.Queryable<Pm_TaskRelevanceUser>()
                                    .Where(it =>
                                                    it.IsDel == 0 &&
                                                    primaryIds.Contains(it.TAId) &&
                                                    it.TaskStatus <= TaskerEnum.UnderWay
                                            )
                                    .ToList();

                if (subData.Count > 0)
                {
                    foreach (var item in subData)
                    {
                        item.OverTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        item.TaskStatus = TaskerEnum.UnFinished;
                        item.Cause = string.Format(@"任务没有提交完成或者超时,由系统设置任务未完成");
                    }

                    var updateStatus = newDB.Updateable(subData)
                                            .WhereColumns(it => it.Id)
                                            .ExecuteCommand();
                    //_taskAllocationRep._sqlSugar.Close();
                }
            }
        }
    }
}