controller.dart 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. if (fromType == ChatFromType.fromMain) {
  119. EventHandler.report(EventId.event_102001, params: {
  120. EventId.id: EventId.id_001,
  121. });
  122. } else if (fromType == ChatFromType.fromTalkDetail) {
  123. EventHandler.report(EventId.event_102001, params: {
  124. EventId.id: EventId.id_002,
  125. });
  126. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  127. EventHandler.report(EventId.event_102001, params: {
  128. EventId.id: EventId.id_003,
  129. });
  130. }
  131. Get.bottomSheet(const ChatStartPage(),
  132. isScrollControlled: true,
  133. barrierColor: ColorName.black55,
  134. backgroundColor: ColorName.transparent)
  135. .then((result) {
  136. if (accountRepository.userInfo.value?.profession == null ||
  137. accountRepository.userInfo.value?.post == null) {
  138. Get.back();
  139. }
  140. });
  141. }
  142. void _sendMessage(String chatContent) {
  143. chatItems.insert(0, createUserChatItem(chatContent));
  144. ProgressingChatItem progressingChatItem = ProgressingChatItem(
  145. id: const Uuid().v4(),
  146. conversationId: chatItems.last.conversationId,
  147. role: "assistant",
  148. content: "",
  149. createTime: DateTime.now().toString(),
  150. );
  151. chatItems.insert(0, progressingChatItem);
  152. _scrollToBottom();
  153. if (talkInfo.value == null) {
  154. EventHandler.report(EventId.event_102003, params: {
  155. EventId.id: EventId.id_002,
  156. });
  157. } else {
  158. EventHandler.report(EventId.event_102003, params: {
  159. EventId.id: EventId.id_001,
  160. });
  161. }
  162. chatRepository
  163. .streamChat(chatContent,
  164. talkId: talkInfo.value?.id, agendaId: agenda.value?.id)
  165. .then((stream) {
  166. stream.listen((event) {
  167. try {
  168. Map<String, dynamic> json = jsonDecode(event.data);
  169. if (json.isEmpty) {
  170. return;
  171. }
  172. StreamChatOriginData data = StreamChatOriginData.fromJson(json);
  173. if (data.choices == null || data.choices!.isEmpty) {
  174. return;
  175. }
  176. Delta? delta = data.choices![0].delta;
  177. if (delta == null) {
  178. return;
  179. }
  180. isConsumeElectric = true;
  181. progressingChatItem.append(delta.content ?? "");
  182. } catch (ignore) {}
  183. }, onDone: () {
  184. progressingChatItem.content = progressingChatItem.streamContent.value;
  185. progressingChatItem.isFinished.value = true;
  186. }, onError: (error) {
  187. progressingChatItem.isFailed.value = true;
  188. progressingChatItem.error.value = "网络错误,请检查网络连接";
  189. debugPrint("error: $error");
  190. debugPrintStack();
  191. });
  192. }).catchError((error) {
  193. progressingChatItem.isFailed.value = true;
  194. if (error is ServerErrorException) {
  195. progressingChatItem.error.value = error.message ?? "服务出错,请稍后再试";
  196. if (error.code == ErrorCode.errorCodeNoLogin) {
  197. Get.toNamed(RoutePath.login)?.then((loginSuccess) async {
  198. if (loginSuccess != null && loginSuccess) {
  199. _clearChat();
  200. await loadMoreHistory();
  201. _sendMessage(chatContent);
  202. }
  203. });
  204. } else if (error.code == ErrorCode.errorCodeNoProfession) {
  205. showStartSheet();
  206. }
  207. } else {
  208. progressingChatItem.error.value = "网络错误,请检查网络连接";
  209. debugPrint("error: $error");
  210. debugPrintStack();
  211. }
  212. });
  213. }
  214. void _clearChat() async {
  215. return chatItems.clear();
  216. }
  217. void _scrollToBottom() {
  218. Future.delayed(const Duration(milliseconds: 300), () {
  219. listScrollController.animateTo(
  220. 0,
  221. duration: const Duration(milliseconds: 300),
  222. curve: Curves.easeOut,
  223. );
  224. });
  225. }
  226. createUserChatItem(String chatContent) {
  227. final id = const Uuid().v4();
  228. final conversationId =
  229. chatItems.isEmpty ? "" : chatItems.last.conversationId;
  230. const role = "user";
  231. final content = chatContent;
  232. final createTime = DateTime.now().toString();
  233. final talkInfo = this.talkInfo.value;
  234. return talkInfo == null
  235. ? ChatItem(
  236. id: id,
  237. conversationId: conversationId,
  238. role: role,
  239. content: chatContent,
  240. createTime: createTime)
  241. : ReferenceChatItem(
  242. talkInfo: talkInfo,
  243. id: id,
  244. conversationId: conversationId,
  245. role: role,
  246. content: content,
  247. createTime: createTime);
  248. }
  249. onDeleteReference() {
  250. talkInfo.value = null;
  251. agenda.value = null;
  252. }
  253. void initReport() {
  254. if (fromType == ChatFromType.fromMain) {
  255. EventHandler.report(EventId.event_102002, params: {
  256. EventId.id: EventId.id_001,
  257. });
  258. } else if (fromType == ChatFromType.fromTalkDetail) {
  259. EventHandler.report(EventId.event_102002, params: {
  260. EventId.id: EventId.id_002,
  261. });
  262. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  263. EventHandler.report(EventId.event_102002, params: {
  264. EventId.id: EventId.id_003,
  265. });
  266. }
  267. }
  268. @override
  269. void onClose() {
  270. super.onClose();
  271. if (isConsumeElectric) {
  272. accountRepository.refreshUserInfo();
  273. }
  274. }
  275. }