@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
@if (isReady)
{
@if (isLogin)
{
@if (messages is not null)
{
@foreach (var msg in messages)
{
}
}
}
else
{
}
}
else
{
}
@code {
ReadANDUpdate_CompanyDto? CompanyInfo = new();
[Parameter] public int CompanyID { get; set; }
List messages = new();
string inputText = string.Empty;
bool isLogin = false;
bool isReady = false;
public string aikeyUser { get; set; }
protected override async Task OnInitializedAsync()
{
await EnsureAuth();
if (isLogin)
{
CompanyInfo = await companyService.GetCompany(CompanyID);
if (CompanyInfo != null)
await LoadMessages();
else
{
toastService.Notify(new ToastMessage(ToastType.Danger, "شناسه شرکت صحیح نمی باشد"));
}
}
}
private async Task EnsureAuth()
{
aikeyUser = await localStorageService.GetItem("aikeyUser");
if (string.IsNullOrEmpty(aikeyUser))
{
aikeyUser = Guid.NewGuid().ToString();
await localStorageService.SetItem("aikeyUser", aikeyUser);
}
isLogin = true;
isReady = true;
}
private async Task LoadMessages()
{
messages = await conversationService.GetAiCurrentResponses(CompanyID,aikeyUser);
StateHasChanged();
await JS.InvokeVoidAsync("scrollToBottom", "ai-chat");
}
private async Task Send()
{
if (string.IsNullOrWhiteSpace(inputText)) return;
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, "ارسال ناموفق بود"));
}
}
private async Task HandleKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Enter") await Send();
}
private async Task Logout()
{
await localStorageService.RemoveItem("aiKeyUser");
isLogin = false;
}
}