using Fantasy;
using Fantasy.Async;
using Fantasy.Network.Interface;

namespace NB.Chat;

public class C2S_SendMailRequestHandler : RouteRPC<SocialUnit, C2S_SendMailRequest, S2C_SendMailResponse>
{
    protected override async FTask Run(SocialUnit entity, C2S_SendMailRequest request, S2C_SendMailResponse response,
        Action reply)
    {
        if (request.Target < 1)
        {
            response.ErrorCode = ErrorCode.ErrArgs;
            return;
        }

        var mailManageComponent = entity.Scene.GetComponent<MailManageComponent>();
        if (mailManageComponent == null)
        {
            Log.Error("组件不存在 MailManageComponent");
            response.ErrorCode = ErrorCode.ErrServer;
            return;
        }

        var chatUnitManage = entity.Scene.GetComponent<SocialUnitManageComponent>();
        if (chatUnitManage == null)
        {
            Log.Error("组件不存在 SocialUnitManageComponent");
            response.ErrorCode = ErrorCode.ErrServer;
            return;
        }

        var conversation = await mailManageComponent.GetConversation(entity.Id, request.Target);
        if (conversation == null)
        {
            response.ErrorCode = ErrorCode.ErrArgs;
            return;
        }
        //检查是否可以发消息，如果会话只有一句，则不允许再发
        if (!conversation.CanSend(entity.Id))
        {
            response.ErrorCode = ErrorCode.MailNotReply;
            return;
        }

        var mail = MailFactory.Create(entity.Scene, request.Content);
        mail.Sender = entity.Id;
        mail.OwnerId = request.Target;
        await conversation.Add(mail);

        var res = new S2C_HaveMail()
        {
            Mail = mail.ToMailInfo(),
            Key = conversation.Key
        };
        //同步客户端
        entity.Scene.NetworkMessagingComponent.SendInnerRoute(entity.GateRouteId, res);

        var chatUnit = chatUnitManage.Get(request.Target);

        if (chatUnit != null)
        {
            //对方在线
            entity.Scene.NetworkMessagingComponent.SendInnerRoute(chatUnit.GateRouteId, res);
        }
    }
}