@page "/AIChat/{CompanyID:int}"
@using Common.Dtos
@inject ConversationService conversationService
@inject ILocalStorageService localStorageService
@inject AuthService authService
@inject BaseController baseController
@inject ToastService toastService
@inject IJSRuntime JS
@layout UserPanelLayout
@using Common.Dtos.Company
@using HushianWebApp.Service
@using HushianWebApp.Services
@using Microsoft.AspNetCore.Components.Web
@inject CompanyService companyService
@inject ToastService toastService
گفتگو با دستیار هوشمند @CompanyInfo.FullName
@if (isReady)
{
@if (messages is not null)
{
@foreach (var msg in messages)
{
}
}
}
else
{
@if (isError)
{
@msgError
}
else
{
در حال بارگذاری ...
}
}
@code {
ReadANDUpdate_CompanyDto? CompanyInfo = new();
[Parameter] public int CompanyID { get; set; }
List messages = new();
string inputText = string.Empty;
bool isReady = false;
bool isError= false;
string msgError= "";
public string aikeyUser { get; set; } = "";
protected override async Task OnInitializedAsync()
{
await EnsureAuth();
CompanyInfo = await companyService.GetCompany(CompanyID);
if (CompanyInfo != null && CompanyInfo.allowBot)
{
await LoadMessages();
isReady = true;
}
else
{
isError = true;
msgError = "دستیار هوشمند یافت نشد";
}
}
private async Task EnsureAuth()
{
aikeyUser = await localStorageService.GetItem("aikeyUser");
if (string.IsNullOrEmpty(aikeyUser))
{
aikeyUser = Guid.NewGuid().ToString();
await localStorageService.SetItem("aikeyUser", aikeyUser);
}
}
private async Task LoadMessages()
{
messages = await conversationService.GetAiCurrentResponses(CompanyID, aikeyUser);
StateHasChanged();
await JS.InvokeVoidAsync("scrollToBottom", "ai-chat");
}
bool disSend = false;
private async Task Send()
{
if (string.IsNullOrWhiteSpace(inputText)) return;
disSend = true;
var dto = new aiNewResponseDto { companyId = CompanyID, aiKeyUser = aikeyUser, requestText = inputText };
var okmodel = await conversationService.AiNewResponse(dto);
if (okmodel != null)
{
messages.Add(okmodel);
inputText = string.Empty;
StateHasChanged();
await JS.InvokeVoidAsync("scrollToBottom", "ai-chat");
}
else
{
toastService.Notify(new ToastMessage(ToastType.Danger, "ارسال ناموفق بود"));
}
disSend = false;
}
private async Task HandleKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Enter") await Send();
}
private async Task Logout()
{
await localStorageService.RemoveItem("aiKeyUser");
}
}