controller.dart 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import 'dart:convert';
  2. import 'package:electronic_assistant/base/base_controller.dart';
  3. import 'package:electronic_assistant/data/bean/agenda.dart';
  4. import 'package:electronic_assistant/data/bean/chat_item.dart';
  5. import 'package:electronic_assistant/data/bean/file_chat_item.dart';
  6. import 'package:electronic_assistant/data/bean/progressing_chat_item.dart';
  7. import 'package:electronic_assistant/data/bean/reference_chat_item.dart';
  8. import 'package:electronic_assistant/data/consts/event_report_id.dart';
  9. import 'package:electronic_assistant/data/repositories/account_repository.dart';
  10. import 'package:electronic_assistant/data/repositories/chat_repository.dart';
  11. import 'package:electronic_assistant/data/repositories/talk_repository.dart';
  12. import 'package:electronic_assistant/handler/event_handler.dart';
  13. import 'package:electronic_assistant/module/chat/start/view.dart';
  14. import 'package:electronic_assistant/module/chat/view.dart';
  15. import 'package:electronic_assistant/resource/colors.gen.dart';
  16. import 'package:flutter/material.dart';
  17. import 'package:get/get.dart';
  18. import 'package:pull_to_refresh/pull_to_refresh.dart';
  19. import 'package:uuid/uuid.dart';
  20. import '../../data/bean/stream_chat_origin_data.dart';
  21. import '../../data/bean/talks.dart';
  22. import '../../data/consts/error_code.dart';
  23. import '../../router/app_pages.dart';
  24. import '../../utils/http_handler.dart';
  25. class ChatController extends BaseController {
  26. final RefreshController refreshController =
  27. RefreshController(initialLoadStatus: LoadStatus.loading);
  28. final ScrollController listScrollController = ScrollController();
  29. final TextEditingController inputController = TextEditingController();
  30. final RxList chatItems = [].obs;
  31. final Rxn<TalkBean> talkInfo = Rxn<TalkBean>();
  32. final Rxn<Agenda> agenda = Rxn<Agenda>();
  33. ChatFromType? fromType;
  34. bool isConsumeElectric = false;
  35. @override
  36. void onInit() {
  37. super.onInit();
  38. loadMoreHistory();
  39. checkArguments();
  40. initReport();
  41. }
  42. @override
  43. void onReady() {
  44. super.onReady();
  45. if (accountRepository.userInfo.value?.profession == null ||
  46. accountRepository.userInfo.value?.post == null) {
  47. showStartSheet();
  48. }
  49. }
  50. void checkArguments() {
  51. List<dynamic> arguments = Get.arguments ?? [];
  52. if (arguments.isEmpty) {
  53. return;
  54. }
  55. if (arguments[0] is ChatFromType) {
  56. fromType = arguments[0];
  57. }
  58. if (arguments.length > 2 && arguments[2] is Agenda) {
  59. agenda.value = arguments[2];
  60. }
  61. if (arguments.length > 1 && arguments[1] is TalkBean) {
  62. talkInfo.value = arguments[1];
  63. sendInitialMessage();
  64. } else if (arguments.length > 1 && arguments[1] is String) {
  65. talkRepository
  66. .talkInfo(arguments[1])
  67. .then((response) => talkInfo.value = response.talkInfo)
  68. .then((_) => sendInitialMessage());
  69. }
  70. }
  71. void sendInitialMessage() {
  72. final talkInfo = this.talkInfo.value;
  73. if (talkInfo == null) {
  74. return;
  75. }
  76. chatItems.insert(
  77. 0,
  78. FileChatItem(talkInfo,
  79. id: const Uuid().v4(),
  80. conversationId: "",
  81. role: "user",
  82. content: "",
  83. createTime: DateTime.now().toString()));
  84. if (agenda.value != null) {
  85. _sendMessage("以这份谈话为背景,你为我执行“${agenda.value?.content}”这一事项");
  86. }
  87. }
  88. onSendClick() {
  89. if (inputController.text.isEmpty) {
  90. return;
  91. }
  92. String chatContent = inputController.text;
  93. inputController.clear();
  94. _sendMessage(chatContent);
  95. }
  96. void onAddFileClick() {
  97. Get.toNamed(RoutePath.fileSearch)?.then((talkInfo) {
  98. if (talkInfo is TalkBean) {
  99. this.talkInfo.value = talkInfo;
  100. agenda.value = null;
  101. sendInitialMessage();
  102. }
  103. });
  104. }
  105. Future<void> loadMoreHistory() {
  106. bool isEmpty = chatItems.isEmpty;
  107. return chatRepository
  108. .chatHistory(chatItems.isEmpty ? null : chatItems.last.id)
  109. .then((value) => chatItems.addAll(value))
  110. .whenComplete(() => refreshController.loadComplete())
  111. .whenComplete(() {
  112. if (isEmpty) {
  113. _scrollToBottom();
  114. }
  115. });
  116. }
  117. void showStartSheet() {
  118. WidgetsBinding.instance.addPostFrameCallback((_) {
  119. if (fromType == ChatFromType.fromMain) {
  120. EventHandler.report(EventId.event_102001, params: {
  121. EventId.id: EventId.id_001,
  122. });
  123. } else if (fromType == ChatFromType.fromTalkDetail) {
  124. EventHandler.report(EventId.event_102001, params: {
  125. EventId.id: EventId.id_002,
  126. });
  127. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  128. EventHandler.report(EventId.event_102001, params: {
  129. EventId.id: EventId.id_003,
  130. });
  131. }
  132. showModalBottomSheet(
  133. context: Get.context!,
  134. isScrollControlled: true,
  135. barrierColor: ColorName.black55,
  136. backgroundColor: ColorName.transparent,
  137. builder: (BuildContext context) {
  138. return const ChatStartPage();
  139. },
  140. ).then((result) {
  141. if (accountRepository.userInfo.value?.profession == null ||
  142. accountRepository.userInfo.value?.post == null) {
  143. Get.back();
  144. }
  145. });
  146. });
  147. }
  148. void _sendMessage(String chatContent) {
  149. chatItems.insert(0, createUserChatItem(chatContent));
  150. ProgressingChatItem progressingChatItem = ProgressingChatItem(
  151. id: const Uuid().v4(),
  152. conversationId: chatItems.last.conversationId,
  153. role: "assistant",
  154. content: "",
  155. createTime: DateTime.now().toString(),
  156. );
  157. chatItems.insert(0, progressingChatItem);
  158. _scrollToBottom();
  159. if (talkInfo.value == null) {
  160. EventHandler.report(EventId.event_102003, params: {
  161. EventId.id: EventId.id_002,
  162. });
  163. } else {
  164. EventHandler.report(EventId.event_102003, params: {
  165. EventId.id: EventId.id_001,
  166. });
  167. }
  168. chatRepository
  169. .streamChat(chatContent,
  170. talkId: talkInfo.value?.id, agendaId: agenda.value?.id)
  171. .then((stream) {
  172. stream.listen((event) {
  173. try {
  174. Map<String, dynamic> json = jsonDecode(event.data);
  175. if (json.isEmpty) {
  176. return;
  177. }
  178. StreamChatOriginData data = StreamChatOriginData.fromJson(json);
  179. if (data.choices == null || data.choices!.isEmpty) {
  180. return;
  181. }
  182. Delta? delta = data.choices![0].delta;
  183. if (delta == null) {
  184. return;
  185. }
  186. isConsumeElectric = true;
  187. progressingChatItem.append(delta.content ?? "");
  188. } catch (ignore) {}
  189. }, onDone: () {
  190. progressingChatItem.content = progressingChatItem.streamContent.value;
  191. progressingChatItem.isFinished.value = true;
  192. }, onError: (error) {
  193. progressingChatItem.isFailed.value = true;
  194. progressingChatItem.error.value = "网络错误,请检查网络连接";
  195. debugPrint("error: $error");
  196. debugPrintStack();
  197. });
  198. }).catchError((error) {
  199. progressingChatItem.isFailed.value = true;
  200. if (error is ServerErrorException) {
  201. progressingChatItem.error.value = error.message ?? "服务出错,请稍后再试";
  202. if (error.code == ErrorCode.errorCodeNoLogin) {
  203. Get.toNamed(RoutePath.login)?.then((loginSuccess) async {
  204. if (loginSuccess != null && loginSuccess) {
  205. _clearChat();
  206. await loadMoreHistory();
  207. _sendMessage(chatContent);
  208. }
  209. });
  210. } else if (error.code == ErrorCode.errorCodeNoProfession) {
  211. showStartSheet();
  212. }
  213. } else {
  214. progressingChatItem.error.value = "网络错误,请检查网络连接";
  215. debugPrint("error: $error");
  216. debugPrintStack();
  217. }
  218. });
  219. }
  220. void _clearChat() async {
  221. return chatItems.clear();
  222. }
  223. void _scrollToBottom() {
  224. Future.delayed(const Duration(milliseconds: 300), () {
  225. listScrollController.animateTo(
  226. 0,
  227. duration: const Duration(milliseconds: 300),
  228. curve: Curves.easeOut,
  229. );
  230. });
  231. }
  232. createUserChatItem(String chatContent) {
  233. final id = const Uuid().v4();
  234. final conversationId =
  235. chatItems.isEmpty ? "" : chatItems.last.conversationId;
  236. const role = "user";
  237. final content = chatContent;
  238. final createTime = DateTime.now().toString();
  239. final talkInfo = this.talkInfo.value;
  240. return talkInfo == null
  241. ? ChatItem(
  242. id: id,
  243. conversationId: conversationId,
  244. role: role,
  245. content: chatContent,
  246. createTime: createTime)
  247. : ReferenceChatItem(
  248. talkInfo: talkInfo,
  249. id: id,
  250. conversationId: conversationId,
  251. role: role,
  252. content: content,
  253. createTime: createTime);
  254. }
  255. onDeleteReference() {
  256. talkInfo.value = null;
  257. agenda.value = null;
  258. }
  259. void initReport() {
  260. if (fromType == ChatFromType.fromMain) {
  261. EventHandler.report(EventId.event_102002, params: {
  262. EventId.id: EventId.id_001,
  263. });
  264. } else if (fromType == ChatFromType.fromTalkDetail) {
  265. EventHandler.report(EventId.event_102002, params: {
  266. EventId.id: EventId.id_002,
  267. });
  268. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  269. EventHandler.report(EventId.event_102002, params: {
  270. EventId.id: EventId.id_003,
  271. });
  272. }
  273. }
  274. @override
  275. void onClose() {
  276. super.onClose();
  277. if (isConsumeElectric) {
  278. accountRepository.refreshUserInfo();
  279. }
  280. }
  281. }