namespace Tiobon.Core.Services;

/// <summary>
/// 培训机构 (服务)
/// </summary>
public class Ghre_SchoolServices : BaseServices<Ghre_School, Ghre_SchoolDto, InsertGhre_SchoolInput, EditGhre_SchoolInput>, IGhre_SchoolServices
{
    private readonly IBaseRepository<Ghre_School> _dal;
    private IGhre_AttachmentServices _ghre_AttachmentServices;
    private IGhre_SchoolAttachmentServices _ghre_SchoolAttachmentServices;
    public Ghre_SchoolServices(ICaching caching,
        IGhre_AttachmentServices ghre_AttachmentServices,
        IGhre_SchoolAttachmentServices ghre_SchoolAttachmentServices,
        IBaseRepository<Ghre_School> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
        _ghre_AttachmentServices = ghre_AttachmentServices;
        _ghre_SchoolAttachmentServices = ghre_SchoolAttachmentServices;
    }

    public override async Task<ServicePageResult<Ghre_SchoolDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {
        string schoolNo1 = string.Empty;
        if (filter.jsonParam != null)
            foreach (JProperty jProperty in filter.jsonParam.Properties())
            {
                var name = jProperty.Name;
                var value = jProperty.Value.ToString();
                if (name == "SchoolNo1")
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);
                    schoolNo1 = jsonParam?.columnValue?.ToString();
                }
            }
        if (!string.IsNullOrWhiteSpace(schoolNo1))
            if (condition.IsNull())
                condition = $"(SchoolNo LIKE '%{schoolNo1}%' OR SchoolName LIKE '%{schoolNo1}%')";
            else condition = $" AND (SchoolNo LIKE '%{schoolNo1}%' OR SchoolName LIKE '%{schoolNo1}%')";

        var data = await base.QueryFilterPage(filter, condition);
        data.result.DT_TableDataT1.ForEach(x =>
        {
            if (x.ExpirationDate != null)
                x.ExpirationDate1 = x.ExpirationDate.Value.ToString("yyyy-MM-dd");

            if (x.EffectiveDate != null)
                x.EffectiveDate1 = x.EffectiveDate.Value.ToString("yyyy-MM-dd");
        });

        return data;
    }

    public override async Task<ServiceFormResult<Ghre_SchoolDto>> QueryForm(QueryForm body)
    {
        var data = await base.QueryForm(body);
        var entitys = data.result.DT_TableDataT1;
        var ids = entitys.Select(x => x.Id).ToList();
        var schoolAttachments = await _ghre_SchoolAttachmentServices.QueryDto(x => ids.Contains(x.SchoolId.Value));
        var ids1 = schoolAttachments.Select(x => x.Id.ToString()).ToList();
        var attachments = await _ghre_AttachmentServices.QueryDto(x => ids1.Contains(x.TableName));

        schoolAttachments.ForEach(x =>
        {
            x.Attachments = attachments.Where(o => o.TableName == x.Id.ToString()).ToList();
        });
        entitys.ForEach(x =>
        {
            x.SchoolAttachments = schoolAttachments.Where(o => o.SchoolId == x.Id).ToList();
        });

        data.result.DT_TableDataT1 = entitys;
        return data;
    }

    public override async Task<long> Add(InsertGhre_SchoolInput entity)
    {
        var id = await base.Add(entity);

        if (entity.SchoolAttachments != null && entity.SchoolAttachments.Any())
        {
            for (int i = 0; i < entity.SchoolAttachments.Count; i++)
            {
                var insert = entity.SchoolAttachments[i];
                insert.SchoolId = id;
                var schoolAttachmentId = await _ghre_SchoolAttachmentServices.Add(insert);
                if (insert.Attachments != null && insert.Attachments.Any())
                    for (int j = 0; j < insert.Attachments.Count; j++)
                    {
                        await Db.Updateable<Ghre_Attachment>()
                              .SetColumns(it => new Ghre_Attachment() { TableName = schoolAttachmentId.ToString(), UpdateTime = DateTime.Now })
                              .Where(it => it.RelativePath == insert.Attachments[j].RelativePath)
                              .ExecuteCommandAsync();
                    }
            }
        }

        return id;
    }

    public override async Task<bool> Update(long Id, EditGhre_SchoolInput editModel)
    {
        var result = await base.Update(Id, editModel);
        await _ghre_SchoolAttachmentServices.Delete(x => x.SchoolId == Id);
        if (editModel.SchoolAttachments != null && editModel.SchoolAttachments.Any())
        {
            for (int i = 0; i < editModel.SchoolAttachments.Count; i++)
            {
                var insert = editModel.SchoolAttachments[i];
                insert.SchoolId = Id;
                var schoolAttachmentId = await _ghre_SchoolAttachmentServices.Add(Mapper.Map(insert).ToANew<InsertGhre_SchoolAttachmentInput>());
                if (insert.Attachments != null && insert.Attachments.Any())
                    for (int j = 0; j < insert.Attachments.Count; j++)
                    {
                        await Db.Updateable<Ghre_Attachment>()
                              .SetColumns(it => new Ghre_Attachment() { TableName = schoolAttachmentId.ToString(), UpdateTime = DateTime.Now })
                              .Where(it => it.RelativePath == insert.Attachments[j].RelativePath)
                              .ExecuteCommandAsync();
                    }
            }
        }

        return result;
    }
}