namespace BPA.MES.Base.Application.Services
{
    /// <summary>
    /// 名    称 ：工单服务  
    /// 创 建 人 ：yangxiao  
    /// 创建时间 ：2023/7/20 14:39:41 
    /// 描    述 ：  
    /// </summary>
    [ApiDescriptionSettings("工单批次服务", Order = 0, Tag = "工单服务", Name = "WorkBatch", KeepName = true, SplitCamelCase = true, KeepVerb = true)]
    public class WorkBatchService : IWorkBatchService, ITransient, IDynamicApiController
    {
        private readonly ISqlSugarClient _dbContext;
        private readonly IMQTTService _MQTTService;
        private readonly IWorkInfoService _workInfoService;
        public WorkBatchService(ISqlSugarClient db,  IMQTTService MQTTService, IWorkInfoService WorkInfoService)
        {
            _dbContext = db;
            _MQTTService = MQTTService;
            _workInfoService = WorkInfoService;
        }
        public async Task<bool> Add(WorkBatchAddInput input)
        {
            WorkBatchEntity entity = input.Adapt<WorkBatchEntity>();
            entity.Status = WorkOrderStatusEnum.Draft;
            return await _dbContext.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandIdentityIntoEntityAsync();
        }

        public async Task<bool> Del(WorkBatchDelInput input)
        {
            var res = false;
            try
            {
                _dbContext.Ado.BeginTran();
                await _dbContext.Deleteable<WorkBatchEntity>().Where(x => x.Id == input.Id).ExecuteCommandHasChangeAsync();
                await _dbContext.Deleteable<Pztj_WorkInfoEntity>().Where(x => x.BatchId == input.Id).ExecuteCommandAsync();
                _dbContext.Ado.CommitTran();
                res = true;
            }
            catch (Exception)
            {
                _dbContext.Ado.RollbackTran();
            }
            return res;
        }

        public async Task<List<WorkBatchOutput>> List(WorkBatchQueryInput input)
        {
            var entity = await _dbContext.Queryable<WorkBatchEntity>().ToListAsync();
            List<WorkBatchOutput> output = entity.Adapt<List<WorkBatchOutput>>();
            return output;
        }

        public async Task<SqlSugarPagedList<WorkBatchOutput>> PagedList(WorkBatchQueryPageInput input)
        {
            var entity = await _dbContext.Queryable<WorkBatchEntity>()
              .WhereIF(!string.IsNullOrEmpty(input.Id),x=>x.Id.Contains(input.Id))
               .WhereIF(input.StartTime != null, x => input.StartTime <= Convert.ToDateTime(x.CreateTime))
               .WhereIF(input.EndTime != null, x => input.EndTime.Value.AddHours(23).AddMinutes(59).AddSeconds(59) >= Convert.ToDateTime(x.CreateTime))
              .OrderByDescending(x => x.CreateTime)
              .Select((x)=>new WorkBatchOutput
              {
                  Id = x.Id.SelectAll(),
                  Count = SqlFunc.Subqueryable<Pztj_WorkInfoEntity>().Where(d=>d.BatchId==x.Id).Count()
              })
              .ToPagedListAsync(input.PageIndex, input.PageSize);
            foreach (var item in entity.Items)
            {
                item.WorkList = await _workInfoService.List(new WorkInfoQueryInput { BatchId = item.Id });
            }
            return entity;
        }

        public async Task<bool> Update(WorkBatchUpdateInput input)
        {
            var entity = await _dbContext.Queryable<WorkBatchEntity>().Where(x => x.Id == input.Id).FirstAsync();
            entity = input.Adapt<WorkBatchEntity>();
            var res = await _dbContext.Updateable(entity).IgnoreColumns(true).ExecuteCommandHasChangeAsync();
            return res;
        }
    }
}
