357 lines
11 KiB
Dart
357 lines
11 KiB
Dart
import 'package:dash_chat_2/dash_chat_2.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:nhance_app_pwa/pages/postEnrollment/service/api_service.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import 'package:url_launcher/url_launcher.dart';
|
|
import '../../customAppBar/customAppBar.dart';
|
|
import '../../customAppBar/customAppBarChatbot.dart';
|
|
import 'data.dart';
|
|
|
|
class chatbot extends StatefulWidget {
|
|
@override
|
|
_chatbotState createState() => _chatbotState();
|
|
}
|
|
|
|
class _chatbotState extends State<chatbot> {
|
|
late ApiService apiService;
|
|
List<ChatMessage> messages = <ChatMessage>[];
|
|
Map<String, String> firstApiOptions = {};
|
|
dynamic isOptionStatus;
|
|
dynamic requestStatus;
|
|
dynamic returnMessage;
|
|
dynamic mobileNo;
|
|
dynamic policyID;
|
|
dynamic empCode;
|
|
dynamic empClientBranchId;
|
|
dynamic client_id;
|
|
dynamic navigation_type;
|
|
dynamic navigation;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
apiService = ApiService(context); // Initialize ApiService here
|
|
quickReplyOptions();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
super.dispose();
|
|
}
|
|
|
|
void quickReplyOptions() async {
|
|
final SharedPreferences prefs = await SharedPreferences.getInstance();
|
|
empCode = prefs.getString('empCode');
|
|
empClientBranchId = prefs.getString('empClientBranchId');
|
|
client_id = prefs.getString('client_id');
|
|
Map<String, dynamic> chatBotDataApi = {
|
|
'request_for': 'Start',
|
|
'is_option': '1',
|
|
'option': '0',
|
|
'mobile_no': '',
|
|
'policy_id': '',
|
|
'emp_code': empCode,
|
|
'client_id': client_id,
|
|
'client_branch_id': empClientBranchId
|
|
};
|
|
chatBotDataApi =
|
|
chatBotDataApi.map((key, value) => MapEntry(key, value.toString()));
|
|
// final url;
|
|
// if (is_option != '0') {
|
|
// url = Uri.parse(
|
|
// '${Environment.apiUrl}getChatResponse?request_for=$requestFor&is_option=$is_option&option=$option&mobile_no=$mobileNo&policy_id=$policyID');
|
|
// } else {
|
|
// url = Uri.parse(
|
|
// '${Environment.apiUrl}getChatResponse?request_for=$requestFor&is_option=$is_option&text=$returnMessage&value=$option&mobile_no=$mobileNo&policy_id=$policyID');
|
|
// }
|
|
final response = await apiService.getBotDetails(chatBotDataApi);
|
|
print(response);
|
|
if (response['status'] == 'success') {
|
|
print('check 2');
|
|
dynamic data = response['data'];
|
|
print('data: $data');
|
|
dynamic optionsData = data['options'];
|
|
print('optionsData: $optionsData');
|
|
isOptionStatus = data['is_option'];
|
|
print('isOptionStatus: $isOptionStatus');
|
|
requestStatus = data['request_for'];
|
|
print('requestStatus: $requestStatus');
|
|
navigation = data['navigation'];
|
|
navigation_type = data['navigation_type'];
|
|
|
|
setState(() {
|
|
firstApiOptions = Map<String, String>.from(optionsData);
|
|
print('firstApiOptions: $firstApiOptions');
|
|
addInitialMessage();
|
|
});
|
|
} else {
|
|
// Handle the error accordingly
|
|
print('Failed to load quick reply options');
|
|
}
|
|
}
|
|
|
|
void addInitialMessage() {
|
|
List<QuickReply> quickReplies = firstApiOptions.entries
|
|
.map((entry) => QuickReply(title: entry.value, value: entry.key))
|
|
.toList();
|
|
|
|
final ChatMessage initialMessage = ChatMessage(
|
|
text: 'Welcome to our service. How can we assist you today?',
|
|
user: user4,
|
|
createdAt: DateTime.now(),
|
|
quickReplies: quickReplies,
|
|
);
|
|
|
|
setState(() {
|
|
messages.add(initialMessage);
|
|
});
|
|
}
|
|
|
|
void handleQuickReply(QuickReply quickReply) async {
|
|
print('QuickReply value: ${quickReply.value}');
|
|
print('QuickReply title: ${quickReply.title}');
|
|
|
|
final ChatMessage replyMessage = ChatMessage(
|
|
user: user,
|
|
text: quickReply.title,
|
|
createdAt: DateTime.now(),
|
|
);
|
|
|
|
setState(() {
|
|
messages.insert(0, replyMessage);
|
|
});
|
|
|
|
await processMessage(quickReply.value ?? quickReply.title);
|
|
}
|
|
|
|
Future<void> processMessage(String messageText) async {
|
|
print('Processing message: $messageText');
|
|
|
|
// Add a placeholder loading message with an animated loader
|
|
final ChatMessage loadingMessage = ChatMessage(
|
|
user: user4,
|
|
text: 'Loading...',
|
|
createdAt: DateTime.now(),
|
|
customProperties: {
|
|
'isLoading': true,
|
|
},
|
|
);
|
|
|
|
setState(() {
|
|
messages.insert(0, loadingMessage);
|
|
});
|
|
|
|
Map<String, dynamic> chatBotDataApi;
|
|
if (isOptionStatus != '0') {
|
|
chatBotDataApi = {
|
|
'request_for': requestStatus,
|
|
'is_option': isOptionStatus,
|
|
'option': messageText,
|
|
'mobile_no': '',
|
|
'policy_id': '',
|
|
'emp_code': empCode,
|
|
'client_id': client_id,
|
|
'client_branch_id': empClientBranchId
|
|
};
|
|
} else {
|
|
chatBotDataApi = {
|
|
'request_for': requestStatus,
|
|
'is_option': isOptionStatus,
|
|
'text': returnMessage,
|
|
'value': messageText,
|
|
'mobile_no': mobileNo,
|
|
'policy_id': policyID,
|
|
'emp_code': empCode,
|
|
'client_id': client_id,
|
|
'client_branch_id': empClientBranchId
|
|
};
|
|
}
|
|
|
|
chatBotDataApi =
|
|
chatBotDataApi.map((key, value) => MapEntry(key, value.toString()));
|
|
|
|
// Simulate API call with a delay of 2 seconds
|
|
await Future.delayed(Duration(seconds: 2));
|
|
// final response = await apiService.getBotDetails(requestStatus,
|
|
// isOptionStatus, messageText, returnMessage, mobileNo, policyID);
|
|
// Future<Map<String, dynamic>> getBotDetails(String requestFor, is_option,
|
|
// option, returnMessage, mobileNo, policyID)
|
|
// final url;
|
|
// if (is_option != '0') {
|
|
// url = Uri.parse(
|
|
// '${Environment.apiUrl}getChatResponse?request_for=$requestFor&is_option=$is_option&option=$option&mobile_no=$mobileNo&policy_id=$policyID');
|
|
// } else {
|
|
// url = Uri.parse(
|
|
// '${Environment.apiUrl}getChatResponse?request_for=$requestFor&is_option=$is_option&text=$returnMessage&value=$option&mobile_no=$mobileNo&policy_id=$policyID');
|
|
// }
|
|
|
|
final response = await apiService.getBotDetails(chatBotDataApi);
|
|
|
|
if (response['status'] == 'success') {
|
|
dynamic chatApiData = response['data'];
|
|
print('chatApiData : $chatApiData');
|
|
dynamic optionsData = chatApiData['options'];
|
|
returnMessage = chatApiData['text'];
|
|
isOptionStatus = chatApiData['is_option'];
|
|
requestStatus = chatApiData['request_for'];
|
|
navigation = chatApiData['navigation'];
|
|
navigation_type = chatApiData['navigation_type'];
|
|
|
|
if (chatApiData.containsKey('mobile_no')) {
|
|
mobileNo = chatApiData['mobile_no'];
|
|
}
|
|
if (chatApiData.containsKey('policy_id')) {
|
|
policyID = chatApiData['policy_id'];
|
|
}
|
|
|
|
setState(() {
|
|
print(returnMessage);
|
|
// Split and format the returnMessage
|
|
String formattedMessage = '';
|
|
if (returnMessage != null) {
|
|
if (navigation == '1') {
|
|
if (navigation_type == 'form') {
|
|
if (returnMessage == 'open_service_form' ||
|
|
returnMessage == 'open_sales_form' ||
|
|
returnMessage == 'open_gmc_form' ||
|
|
returnMessage == 'open_gpa_form') {
|
|
var details = {'claimsDetails': '', 'fromClaimPage': 1};
|
|
Navigator.pushNamed(context, 'planclaimsform',
|
|
arguments: details);
|
|
}
|
|
} else if (navigation_type == 'dialpad') {
|
|
print(returnMessage);
|
|
_openDialPad(returnMessage);
|
|
} else if (navigation_type == 'mail') {
|
|
print(returnMessage);
|
|
_openEmail(returnMessage);
|
|
}
|
|
} else {
|
|
if (returnMessage.contains('%')) {
|
|
try {
|
|
List<String> messageParts = returnMessage
|
|
.split('%')
|
|
.map((part) => part.trim())
|
|
.cast<String>()
|
|
.toList();
|
|
formattedMessage = messageParts
|
|
.asMap()
|
|
.map(
|
|
(index, part) => MapEntry(index, '${index + 1}. $part'))
|
|
.values
|
|
.join('\n');
|
|
} catch (e) {
|
|
print('Error splitting returnMessage: $e');
|
|
formattedMessage =
|
|
returnMessage; // Fallback to original message
|
|
}
|
|
} else {
|
|
formattedMessage = returnMessage;
|
|
}
|
|
}
|
|
} else {
|
|
print('returnMessage is null');
|
|
}
|
|
print('formattedMessage: $formattedMessage');
|
|
|
|
firstApiOptions =
|
|
optionsData != null ? Map<String, String>.from(optionsData) : {};
|
|
|
|
final ChatMessage apiResponseMessage = ChatMessage(
|
|
user: user4,
|
|
text: formattedMessage ?? '',
|
|
createdAt: DateTime.now(),
|
|
customProperties: {
|
|
'isLoading': false,
|
|
},
|
|
quickReplies: firstApiOptions.entries
|
|
.map((entry) => QuickReply(title: entry.value, value: entry.key))
|
|
.toList(),
|
|
);
|
|
|
|
// Remove the loading message and add the actual response
|
|
messages.removeAt(0);
|
|
messages.insert(0, apiResponseMessage);
|
|
});
|
|
} else {
|
|
setState(() {
|
|
// Remove the loading message and add an error message
|
|
messages.removeAt(0);
|
|
messages.insert(
|
|
0,
|
|
ChatMessage(
|
|
user: user4,
|
|
text: 'Failed to load data from API',
|
|
createdAt: DateTime.now(),
|
|
customProperties: {
|
|
'isLoading': false,
|
|
},
|
|
),
|
|
);
|
|
});
|
|
}
|
|
}
|
|
|
|
void _openDialPad(String phoneNumber) async {
|
|
final url = 'tel:$phoneNumber';
|
|
if (await canLaunch(url)) {
|
|
await launch(url);
|
|
} else {
|
|
throw 'Could not open dial pad for $phoneNumber';
|
|
}
|
|
}
|
|
|
|
void _openEmail(String email) async {
|
|
final Uri params = Uri(
|
|
scheme: 'mailto',
|
|
path: email,
|
|
query:
|
|
'subject=Your Subject&body=Hello', // Add default subject and body here
|
|
);
|
|
var url = params.toString();
|
|
if (await canLaunch(url)) {
|
|
await launch(url);
|
|
} else {
|
|
throw 'Could not open email client for $email';
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: CustomAppBarChatbot(),
|
|
body: DashChat(
|
|
currentUser: user,
|
|
onSend: (ChatMessage m) {
|
|
setState(() {
|
|
messages.insert(0, m);
|
|
});
|
|
processMessage(m.text);
|
|
},
|
|
quickReplyOptions: QuickReplyOptions(onTapQuickReply: handleQuickReply),
|
|
messages: messages,
|
|
),
|
|
);
|
|
}
|
|
|
|
// late WebViewController _controller;
|
|
//
|
|
// @override
|
|
// void initState() {
|
|
// super.initState();
|
|
// _controller = WebViewController()
|
|
// ..setJavaScriptMode(JavaScriptMode.unrestricted)
|
|
// ..loadRequest(Uri.parse(
|
|
// 'https://mediafiles.botpress.cloud/0439df41-8f0c-4bfd-ad85-340462deebc0/webchat/bot.html'));
|
|
// }
|
|
|
|
// @override
|
|
// Widget build(BuildContext context) {
|
|
// return Scaffold(
|
|
// backgroundColor: Colors.white,
|
|
// appBar: CustomAppBar(),
|
|
// body: WebViewWidget(controller: _controller),
|
|
// );
|
|
// }
|
|
}
|