controller.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:electronic_assistant/base/base_controller.dart';
  4. import 'package:electronic_assistant/data/repositories/task_repository.dart';
  5. import 'package:electronic_assistant/module/chat/view.dart';
  6. import 'package:electronic_assistant/module/home/controller.dart';
  7. import 'package:electronic_assistant/module/talk/summary/view.dart';
  8. import 'package:electronic_assistant/module/talk/todo/controller.dart';
  9. import 'package:electronic_assistant/module/talk/todo/view.dart';
  10. import 'package:electronic_assistant/resource/assets.gen.dart';
  11. import 'package:electronic_assistant/resource/colors.gen.dart';
  12. import 'package:electronic_assistant/resource/string.gen.dart';
  13. import 'package:electronic_assistant/utils/error_handler.dart';
  14. import 'package:electronic_assistant/utils/expand.dart';
  15. import 'package:electronic_assistant/utils/mmkv_util.dart';
  16. import 'package:flutter/cupertino.dart';
  17. import 'package:flutter/material.dart';
  18. import 'package:flutter_screenutil/flutter_screenutil.dart';
  19. import 'package:get/get.dart';
  20. import 'package:connectivity_plus/connectivity_plus.dart';
  21. import '../../data/api/request/agenda_update_bean.dart';
  22. import '../../data/bean/agenda.dart';
  23. import '../../data/bean/agenda_list_all_bean.dart';
  24. import '../../data/bean/talks.dart';
  25. import '../../data/repositories/agenda_repository.dart';
  26. import '../../data/repositories/talk_repository.dart';
  27. import '../../dialog/add_agenda_dialog.dart';
  28. import '../../dialog/alert_dialog.dart';
  29. import '../../router/app_pages.dart';
  30. import '../../utils/event_bus.dart';
  31. import '../../utils/toast_util.dart';
  32. import '../record/controller.dart';
  33. import 'original/view.dart';
  34. import 'package:just_audio/just_audio.dart';
  35. class TalkController extends BaseController {
  36. final String uploadNoPrompts = "UPLOAD_NO_PROMPTS";
  37. final Rxn<TalkBean> talkBean = Rxn();
  38. final isShowElectricLow = false.obs;
  39. bool isAudioLoading = false;
  40. final double sliderMax = 1;
  41. bool? audioFileIsExist;
  42. bool? isUploadedFile;
  43. Rxn<bool> isUploading = Rxn();
  44. final isAudioPlaying = false.obs;
  45. final audioProgressValue = 0.0.obs;
  46. final audioDuration = Duration.zero.obs;
  47. final agendaOriginalAllList = <AgendaListAllBean>[];
  48. final agendaAllList = <AgendaListAllBean>[].obs;
  49. final _isEditModel = false.obs;
  50. final TextEditingController editTalkNameController = TextEditingController();
  51. final tabIndex = 0.obs;
  52. final List<String> tabBeans = [
  53. StringName.talkTabSummary.tr,
  54. StringName.talkTabMyTask.tr,
  55. StringName.talkTabOriginal.tr
  56. ];
  57. bool get isEditModel => _isEditModel.value;
  58. RxBool get isEditModelRx => _isEditModel;
  59. final _audioPlayer = AudioPlayer();
  60. StreamSubscription? _talkBeanListener;
  61. final pages = [const SummaryView(), const TodoView(), const OriginalView()];
  62. TextEditingController? _agendaContentController;
  63. TextEditingController? _agendaNameController;
  64. TextEditingController get agendaContentController {
  65. _agendaContentController ??= TextEditingController();
  66. return _agendaContentController!;
  67. }
  68. TextEditingController get agendaNameController {
  69. _agendaNameController ??= TextEditingController();
  70. return _agendaNameController!;
  71. }
  72. @override
  73. void onReady() {
  74. super.onReady();
  75. _initAudioPlayer();
  76. _initListener();
  77. _getArguments();
  78. }
  79. void _initAudioPlayer() {
  80. _audioPlayer.playerStateStream.listen((playerState) {
  81. if (playerState.processingState == ProcessingState.loading ||
  82. playerState.processingState == ProcessingState.buffering) {
  83. isAudioLoading = true;
  84. debugPrint('音频load = true');
  85. } else {
  86. debugPrint('音频load = false');
  87. isAudioLoading = false;
  88. if (playerState.processingState == ProcessingState.completed) {
  89. _audioPlayer.stop();
  90. _audioPlayer.seek(Duration.zero);
  91. isAudioPlaying.value = false;
  92. debugPrint('音频 播放结束了');
  93. }
  94. }
  95. isAudioPlaying.value = playerState.playing;
  96. }, onError: (Object e, StackTrace stackTrace) {
  97. debugPrint('音频加载异常 == $e');
  98. });
  99. _audioPlayer.durationStream.listen((duration) {
  100. if (duration != null) {
  101. debugPrint('音频总播放时长 == ${duration.inMilliseconds}');
  102. audioDuration.value = duration;
  103. }
  104. });
  105. _audioPlayer.positionStream.listen((position) {
  106. if (audioDuration.value.inMilliseconds > 0) {
  107. audioProgressValue.value =
  108. (position.inMilliseconds / audioDuration.value.inMilliseconds)
  109. .clamp(0.0, sliderMax);
  110. }
  111. });
  112. }
  113. void _initListener() {
  114. _talkBeanListener = talkBean.listen((bean) {
  115. _dealTalkUpdate(bean);
  116. });
  117. }
  118. void _dealTalkUpdate(TalkBean? bean) async {
  119. String? id = talkBean.value?.id;
  120. if (id == null) {
  121. return;
  122. }
  123. if (talkRepository.isUploadingTalk(id) &&
  124. talkBean.value?.status.value == TalkStatus.notAnalysis) {
  125. isUploading.value = true;
  126. } else {
  127. isUploading.value = false;
  128. }
  129. try {
  130. Uri? uri;
  131. if (bean?.isExample == true && bean?.audioUrl != null) {
  132. uri = Uri.parse(bean!.audioUrl!);
  133. } else {
  134. File? file = await getFileByTalk(id, bean?.uploadType);
  135. if (file?.existsSync() == true) {
  136. uri = file?.uri;
  137. }
  138. }
  139. if (uri == null) {
  140. throw '音频文件不存在';
  141. }
  142. await _audioPlayer.setAudioSource(AudioSource.uri(uri));
  143. audioFileIsExist = true;
  144. } catch (e) {
  145. audioFileIsExist = false;
  146. debugPrint('音频设置异常 == $e');
  147. }
  148. }
  149. void _getArguments() {
  150. if (Get.arguments is TalkBean) {
  151. talkBean.value = Get.arguments as TalkBean;
  152. }
  153. }
  154. void updateProgress(double value) {
  155. final newPosition = Duration(
  156. milliseconds: (value * audioDuration.value.inMilliseconds).toInt());
  157. _audioPlayer.seek(newPosition);
  158. }
  159. void clickPlayAudio() {
  160. if (audioFileIsExist != true) {
  161. ToastUtil.showToast(StringName.talkFileNotFind.tr);
  162. return;
  163. }
  164. if (isAudioLoading) {
  165. ToastUtil.showToast(StringName.talkAudioLoading.tr);
  166. return;
  167. }
  168. if (_audioPlayer.playing) {
  169. _audioPlayer.pause();
  170. isAudioPlaying.value = false;
  171. } else {
  172. _audioPlayer.play();
  173. isAudioPlaying.value = true;
  174. }
  175. }
  176. void _checkFileSizeAndNet() async {
  177. String? id = talkBean.value?.id;
  178. if (id == null) {
  179. return;
  180. }
  181. File? file =
  182. await getFileByTalk(talkBean.value?.id, talkBean.value?.uploadType);
  183. if (file == null || !file.existsSync()) {
  184. ToastUtil.showToast(StringName.talkUploadFileNotExist.tr);
  185. return;
  186. }
  187. bool isCheckRemind = KVUtil.getBool(uploadNoPrompts, false);
  188. if (isCheckRemind) {
  189. _requestAnalyze(file);
  190. return;
  191. }
  192. //如果文件大小低于250MB 不弹窗提醒
  193. if (file.lengthSync() < 250 * 1024 * 1024) {
  194. _requestAnalyze(file);
  195. return;
  196. }
  197. final List<ConnectivityResult> connectivityResult =
  198. await (Connectivity().checkConnectivity());
  199. if (connectivityResult.contains(ConnectivityResult.wifi)) {
  200. _requestAnalyze(file);
  201. } else {
  202. _showTrafficRemindDialog(file.lengthSync().toReadableSize(),
  203. confirmOnTap: (isCheckRemind) {
  204. if (isCheckRemind) {
  205. KVUtil.putBool(uploadNoPrompts, true);
  206. }
  207. _requestAnalyze(file);
  208. });
  209. }
  210. }
  211. void _showTrafficRemindDialog(String holderTxt,
  212. {void Function(bool isCheckRemind)? confirmOnTap}) {
  213. final remindTrafficConsume = false.obs;
  214. Widget getSelectIcon() {
  215. return Obx(() {
  216. return remindTrafficConsume.value
  217. ? Assets.images.iconSelectTrue.image()
  218. : Assets.images.iconSelectFalse.image();
  219. });
  220. }
  221. Assets.images.iconSelectTrue.image();
  222. EAAlertDialog.show(
  223. contentWidget: Column(
  224. children: [
  225. Text(
  226. StringName.talkTrafficRemindTitle.tr
  227. .replacePlaceholders([holderTxt]),
  228. style:
  229. TextStyle(fontSize: 15.sp, color: ColorName.primaryTextColor),
  230. ),
  231. SizedBox(height: 8.h),
  232. GestureDetector(
  233. onTap: () {
  234. remindTrafficConsume.value = !remindTrafficConsume.value;
  235. },
  236. child: IntrinsicWidth(
  237. child: Row(
  238. children: [
  239. SizedBox(width: 20.w, height: 20.w, child: getSelectIcon()),
  240. SizedBox(width: 5.w),
  241. Text(
  242. StringName.talkTrafficRemindTips.tr,
  243. style: TextStyle(
  244. fontSize: 15.sp, color: ColorName.tertiaryTextColor),
  245. )
  246. ],
  247. ),
  248. ),
  249. )
  250. ],
  251. ),
  252. cancelText: StringName.cancel.tr,
  253. confirmText: StringName.sure.tr,
  254. confirmOnTap: () {
  255. confirmOnTap?.call(remindTrafficConsume.value);
  256. });
  257. }
  258. void checkCanAnalyze() {
  259. String? id = talkBean.value?.id;
  260. double? duration = talkBean.value?.duration;
  261. if (id == null || duration == null) {
  262. return;
  263. }
  264. talkRepository.checkElectric(duration).then((data) {
  265. if (data.enough) {
  266. //检查网络以及文件大小
  267. _checkFileSizeAndNet();
  268. } else {
  269. ToastUtil.showToast(StringName.talkAnalyseLowToast.tr);
  270. isShowElectricLow.value = true;
  271. }
  272. }).catchError((error) {
  273. ToastUtil.showToast(error);
  274. });
  275. }
  276. void _requestAnalyze(File file) {
  277. String? talkId = talkBean.value?.id;
  278. double? duration = talkBean.value?.duration;
  279. if (talkId == null || duration == null || isUploadedFile == true) {
  280. return;
  281. }
  282. isUploading.value = true;
  283. talkRepository.uploadTalkFile(talkId, duration, file).then((taskId) {
  284. isUploadedFile = true;
  285. taskRepository.addTask(taskId);
  286. }).catchError((error) {
  287. isUploading.value = false;
  288. ErrorHandler.toastError(error);
  289. });
  290. }
  291. void refreshAgendaAllData({bool isForceRefresh = false}) {
  292. String? id = talkBean.value?.id;
  293. if (id == null || (!isForceRefresh && agendaAllList.isNotEmpty)) {
  294. return;
  295. }
  296. agendaRepository.agendaListAll(id).then((agenda) {
  297. agendaAllList.clear();
  298. agendaOriginalAllList.clear();
  299. if (agenda.list != null) {
  300. agendaOriginalAllList.addAll(
  301. agenda.list!.map((item) => AgendaListAllBean.from(item)).toList());
  302. agendaAllList.addAll(agenda.list!);
  303. }
  304. });
  305. }
  306. void clickAIAnalysis() {
  307. if (talkBean.value != null) {
  308. ChatPage.startByTalk(talkBean.value!);
  309. }
  310. }
  311. void onGoElectricStore() {
  312. Get.toNamed(RoutePath.store);
  313. Future.delayed(const Duration(milliseconds: 250), () {
  314. isShowElectricLow.value = false;
  315. });
  316. }
  317. void onEditModelClick() {
  318. _isEditModel.value = true;
  319. if (_audioPlayer.playing) {
  320. _audioPlayer.pause();
  321. isAudioPlaying.value = false;
  322. }
  323. editTalkNameController.text = talkBean.value?.title.value ?? '';
  324. }
  325. void updateTabIndex(int index) {
  326. tabIndex.value = index;
  327. }
  328. void onEditCancel() {
  329. _isEditModel.value = false;
  330. agendaAllList.assignAll(agendaOriginalAllList
  331. .map((item) => AgendaListAllBean.from(item))
  332. .toList());
  333. }
  334. void onEditDoneClick() {
  335. if (talkBean.value == null) {
  336. return;
  337. }
  338. List<AgendaUpdateBean> list = [];
  339. for (AgendaListAllBean item in agendaAllList) {
  340. if (item.list != null) {
  341. for (Agenda agenda in item.list!) {
  342. list.add(AgendaUpdateBean(agenda.id, agenda.name, agenda.content));
  343. }
  344. }
  345. }
  346. agendaRepository.agendaUpdate(talkBean.value!.id, list).then((data) {
  347. refreshAgendaAllData(isForceRefresh: true);
  348. eventBus.emit(TodoController.refreshTalkMineTask);
  349. isEditModelRx.value = false;
  350. }).catchError((error) {
  351. ErrorHandler.toastError(error);
  352. });
  353. if (tabIndex.value == 0) {
  354. String updateName = editTalkNameController.text;
  355. talkRepository.talkRename(talkBean.value!.id, updateName).then((data) {
  356. talkBean.value?.title.value = updateName;
  357. }).catchError((error) {
  358. ErrorHandler.toastError(error);
  359. });
  360. }
  361. }
  362. void removeTalkAgenda(List<Agenda>? list, Agenda agenda) {
  363. list?.remove(agenda);
  364. agendaAllList.refresh();
  365. }
  366. void showSingleAddAgendaDialog(BuildContext context) {
  367. showAddAgendaDialog(context, agendaContentController, agendaNameController,
  368. list: agendaAllList.map((e) => e.name ?? "").toList(), callback: () {
  369. if (agendaContentController.text.isEmpty) {
  370. ToastUtil.showToast(StringName.talkAddAgendaContentHint.tr);
  371. return;
  372. }
  373. if (agendaNameController.text.isEmpty) {
  374. ToastUtil.showToast(StringName.talkAddAgendaNameHint.tr);
  375. return;
  376. }
  377. Get.back();
  378. _dealAddProcedureList();
  379. });
  380. }
  381. void _dealAddProcedureList() {
  382. String name = agendaNameController.text;
  383. final addItem = Agenda(
  384. id: "",
  385. talkId: "",
  386. name: name,
  387. );
  388. addItem.content = agendaContentController.text;
  389. for (AgendaListAllBean item in agendaAllList) {
  390. if (item.name == name) {
  391. List<Agenda> list = item.list ?? [];
  392. list.add(addItem);
  393. item.list = list;
  394. agendaAllList.refresh();
  395. agendaContentController.clear();
  396. agendaNameController.clear();
  397. return;
  398. }
  399. }
  400. agendaAllList.add(AgendaListAllBean(name: name, list: [addItem]));
  401. agendaContentController.clear();
  402. agendaNameController.clear();
  403. }
  404. @override
  405. void onClose() {
  406. super.onClose();
  407. _talkBeanListener?.cancel();
  408. _audioPlayer.dispose();
  409. _agendaContentController?.dispose();
  410. _agendaNameController?.dispose();
  411. }
  412. }
  413. Future<File?> getFileByTalk(String? talkId, int? uploadType) async {
  414. if (talkId == null) {
  415. return null;
  416. }
  417. if (uploadType == TalkUploadType.localUpload) {
  418. return await getChoiceUploadFile(talkId);
  419. } else {
  420. return await RecordController.getRecordFile(talkId);
  421. }
  422. }