43 lines
4.0 KiB
TypeScript
43 lines
4.0 KiB
TypeScript
'use client';
|
|
import { FormEvent, useEffect, useRef, useState } from 'react';
|
|
const unavailable = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
|
|
const token = () => { try { return localStorage.getItem('accessToken') || ''; } catch { return ''; } };
|
|
export default function SupportChat() {
|
|
const [open,setOpen]=useState(false), [message,setMessage]=useState(''), [scope,setScope]=useState('public'), [busy,setBusy]=useState(false);
|
|
const [rows,setRows]=useState<{question:string,answer:string}[]>([]);
|
|
const identity=useRef(''), pending=useRef<AbortController|null>(null);
|
|
useEffect(()=>{
|
|
identity.current=token();
|
|
const check=()=>{ if(identity.current!==token()){identity.current=token();pending.current?.abort();setRows([]);setMessage('');setScope('public');setBusy(false);} };
|
|
window.addEventListener('focus',check);window.addEventListener('storage',check);
|
|
const interval=window.setInterval(check,500);
|
|
return ()=>{window.removeEventListener('focus',check);window.removeEventListener('storage',check);clearInterval(interval);pending.current?.abort();};
|
|
},[]);
|
|
async function send(event:FormEvent) {
|
|
event.preventDefault();if(busy||!message.trim())return;
|
|
const current=token(); if(current!==identity.current){setRows([]);identity.current=current;}
|
|
const question=message.trim();setMessage('');setBusy(true);
|
|
const controller=new AbortController();pending.current=controller;
|
|
let answer=unavailable;
|
|
try {
|
|
const response=await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/ask`,{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest',...(current?{Authorization:`Bearer ${current}`}:{})},credentials:'include',body:JSON.stringify({message:question,scope}),signal:AbortSignal.any([controller.signal,AbortSignal.timeout(50000)])});
|
|
if(response.status===401)answer='لطفاً دوباره وارد حساب کاربری شوید.';
|
|
else if(response.ok){const data=await response.json();if(typeof data.answer==='string')answer=data.answer;}
|
|
} catch {}
|
|
if(!controller.signal.aborted&&token()===current)setRows(r=>[...r.slice(-9),{question,answer}]);
|
|
if(pending.current===controller)setBusy(false);
|
|
}
|
|
return <aside dir="rtl" className="fixed bottom-24 left-4 z-[1000] max-w-[calc(100vw-2rem)]">
|
|
<button type="button" onClick={()=>setOpen(!open)} aria-expanded={open} className="rounded-full bg-sky-700 p-3 text-white shadow-lg">{open?'بستن گفتگو':'گفتگو با پشتیبان'}</button>
|
|
{open&&<section aria-label="پشتیبان کنینا" className="mt-2 w-80 rounded-xl border bg-white p-4 shadow-xl">
|
|
<p className="text-sm">پشتیبان هوشمند کنینا · هر پیام مستقل است. اطلاعات پزشکی جایگزین دامپزشک نیست.</p>
|
|
<div aria-live="polite" className="my-3 max-h-64 overflow-y-auto whitespace-pre-wrap text-sm">{rows.map((r,i)=><div key={i} className="my-3"><p className="font-bold">{r.question}</p><p>{r.answer}</p></div>)}{busy&&<p>در حال بررسی…</p>}</div>
|
|
<form onSubmit={send}>
|
|
<label className="text-sm">موضوع<select aria-label="موضوع گفتگو" value={scope} onChange={e=>setScope(e.target.value)} className="block w-full border p-2"><option value="public">محصولات و اطلاعات عمومی</option><option value="orders">سفارشهای من</option><option value="wallet">کیف پول من</option></select></label>
|
|
<label className="text-sm">پیام شما<textarea aria-label="پیام شما" value={message} maxLength={1500} onChange={e=>setMessage(e.target.value)} className="mt-2 w-full border p-2" /></label>
|
|
<button disabled={busy||!message.trim()} className="rounded bg-sky-700 px-4 py-2 text-white disabled:opacity-50">ارسال</button>
|
|
</form><a href="/dashboard?tab=tickets" className="mt-2 block text-sm text-sky-700">ثبت تیکت پشتیبانی</a>
|
|
</section>}
|
|
</aside>;
|
|
}
|