web_cubit.dart 25.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:appframe/config/constant.dart';
import 'package:appframe/config/locator.dart';
import 'package:appframe/config/routes.dart';
import 'package:appframe/data/models/message/h5_message.dart';
import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/services/local_server_service.dart';
import 'package:appframe/utils/audio_util.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:fluwx/fluwx.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

class WebState extends Equatable {
  final bool loaded;
  final String title;
  final bool beBack;

  final String? ip;
  final String? sessionCode;
  final String? userCode;
  final String? classCode;
  final int? userType;
  final String? stuId;

  /// 录音
  final bool recorderIsInit;
  final int recordState;
  final String recordPath;

  /// 播放
  final bool playerIsInit;
  final int playState;
  final String playId;

  /// getOrientationCmd
  final bool orientationCmdFlag;
  final String orientationCmdMessage;

  /// getWindowInfoCmd
  final bool windowInfoCmdFlag;
  final String windowInfoCmdMessage;

  /// chooseImageCmd
  final bool chooseImageCmdFlag;
  final String chooseImageCmdMessage;

  /// chooseVideoCmd
  final bool chooseVideoCmdFlag;
  final String chooseVideoCmdMessage;

  const WebState({
    this.loaded = false,
    this.title = '界面加载中...',
    this.beBack = false,
    this.ip,
    this.sessionCode,
    this.userCode,
    this.classCode,
    this.userType,
    this.stuId,
    this.recorderIsInit = false,
    this.recordState = 0,
    this.recordPath = '',
    this.playerIsInit = false,
    this.playState = 0,
    this.playId = '',
    this.orientationCmdFlag = false,
    this.orientationCmdMessage = '',
    this.windowInfoCmdFlag = false,
    this.windowInfoCmdMessage = '',
    this.chooseImageCmdFlag = false,
    this.chooseImageCmdMessage = '',
    this.chooseVideoCmdFlag = false,
    this.chooseVideoCmdMessage = '',
  });

  WebState copyWith({
    bool? loaded,
    String? title,
    bool? beBack,
    String? ip,
    String? sessionCode,
    String? userCode,
    String? classCode,
    int? userType,
    String? stuId,
    bool? recorderIsInit,
    int? recordState,
    String? recordPath,
    bool? playerIsInit,
    int? playState,
    String? playId,
    bool? orientationCmdFlag,
    String? orientationCmdMessage,
    bool? windowInfoCmdFlag,
    String? windowInfoCmdMessage,
    bool? chooseImageCmdFlag,
    String? chooseImageCmdMessage,
    bool? chooseVideoCmdFlag,
    String? chooseVideoCmdMessage,
  }) {
    return WebState(
      loaded: loaded ?? this.loaded,
      title: title ?? this.title,
      beBack: beBack ?? this.beBack,
      ip: ip ?? this.ip,
      sessionCode: sessionCode ?? this.sessionCode,
      userCode: userCode ?? this.userCode,
      classCode: classCode ?? this.classCode,
      userType: userType ?? this.userType,
      stuId: stuId ?? this.stuId,
      recorderIsInit: recorderIsInit ?? this.recorderIsInit,
      recordState: recordState ?? this.recordState,
      recordPath: recordPath ?? this.recordPath,
      playerIsInit: playerIsInit ?? this.playerIsInit,
      playState: playState ?? this.playState,
      playId: playId ?? this.playId,
      orientationCmdFlag: orientationCmdFlag ?? this.orientationCmdFlag,
      orientationCmdMessage: orientationCmdMessage ?? this.orientationCmdMessage,
      windowInfoCmdFlag: windowInfoCmdFlag ?? this.windowInfoCmdFlag,
      windowInfoCmdMessage: windowInfoCmdMessage ?? this.windowInfoCmdMessage,
      chooseImageCmdFlag: chooseImageCmdFlag ?? this.chooseImageCmdFlag,
      chooseImageCmdMessage: chooseImageCmdMessage ?? this.chooseImageCmdMessage,
      chooseVideoCmdFlag: chooseVideoCmdFlag ?? this.chooseVideoCmdFlag,
      chooseVideoCmdMessage: chooseVideoCmdMessage ?? this.chooseVideoCmdMessage,
    );
  }

  @override
  List<Object?> get props => [
        loaded,
        title,
        beBack,
        ip,
        sessionCode,
        userCode,
        classCode,
        userType,
        stuId,
        recorderIsInit,
        recordState,
        recordPath,
        playerIsInit,
        playState,
        playId,
        orientationCmdFlag,
        orientationCmdMessage,
        windowInfoCmdFlag,
        windowInfoCmdMessage,
        chooseImageCmdFlag,
        chooseImageCmdMessage,
        chooseVideoCmdFlag,
        chooseVideoCmdMessage,
      ];
}

class WebCubit extends Cubit<WebState> {
  late final MessageDispatcher _dispatcher;
  late final WebViewController _controller;
  late final HttpServer _server;
  late final Fluwx _fluwx;
  FlutterSoundRecorder? _recorder;
  FlutterSoundPlayer? _player;

  WebViewController get controller => _controller;

  FlutterSoundRecorder? get recorder => _recorder;

  FlutterSoundPlayer? get player => _player;

  WebCubit(super.initialState) {
    // 消息处理器
    _dispatcher = MessageDispatcher();

    // WebView控制器
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onUrlChange: (UrlChange url) {},
          onPageStarted: (String url) async {
            // 进行新页面加载时,关闭录音器和播放器,(如果有打开过)
            // closeLocalRecorder();
            // closeLocalPlayer();
          },
          onPageFinished: (String url) async {
            print('onPageFinished--------------------------------->');
            print(url);

            if (url == '${Constant.localServerTestFileUrl}/login.html') {
              return;
            }

            // 页面加载完成时,清空录音和音频(如果有打开过)
            await clearRecording();
            await clearAudio();

            _controller.runJavaScript(
              'document.querySelector("meta[name=viewport]").setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")',
            );
            finishLoading();
          },
        ),
      )
      ..addJavaScriptChannel("xeJsBridge", onMessageReceived: _onMessageReceived);

    // 启动本地服务器,并加载HTML
    _startLocalServerAndLoadHtml();

    _fluwx = getIt.get<Fluwx>();
  }

  _startLocalServerAndLoadHtml() async {
    // 启动本地服务器
    _server = await LocalServerService().startLocalServer();

    final String serverUrl;
    if (state.sessionCode == null || state.sessionCode == '') {
      serverUrl = '${Constant.localServerUrl}/index.html';
      // serverUrl = '${Constant.localServerTestFileUrl}/login.html';
      // serverUrl = '${Constant.localServerTestFileUrl}/test2.html';
    } else {
      // serverUrl =
      //     'http://${state.ip}:${_server.port}/index.html#/h5/login/pages/applogin?sessionCode=${state.sessionCode}&userCode=${state.userCode}&classCode=${state.classCode}&userType=${state.userType}&stuId=${state.stuId}';
      serverUrl =
          '${Constant.localServerUrl}/index.html#/h5/login/pages/applogin?sessionCode=${state.sessionCode}&userCode=${state.userCode}&classCode=${state.classCode}&userType=${state.userType}&stuId=${state.stuId}';
    }

    _controller.loadRequest(Uri.parse(serverUrl));
  }

  _onMessageReceived(JavaScriptMessage message) async {
    try {
      _dispatcher.dispatch(message.message, (response) {
        _sendResponse(response);
      }, webCubit: this);
    } catch (e) {
      print('消息解析错误: $e');
    }
  }

  // 向H5发送响应
  void _sendResponse(Map<String, dynamic> response) {
    String jsonString = jsonEncode(response);
    String escapedJson = jsonString.replaceAll('"', '\\"');
    final String script = 'xeJsBridgeCallback("$escapedJson");';
    _controller.runJavaScript(script);
  }

  void finishLoading() {
    emit(state.copyWith(loaded: true, title: '班小二测试', beBack: true));
  }

  // 测试
  void resetLoading() {
    emit(state.copyWith(loaded: false, title: '界面加载中...'));
  }

  //测试
  void goWechatAuth() {
    router.go('/wechatAuth');
  }

  void goLogin() {
    router.go('/loginMain');
  }

  void goMqtt(){
    router.go('/mqtt');
  }

  //测试
  void goAuth() {
    // String serverUrl = 'http://${state.ip}:${_server.port}/index.html';
    String serverUrl = '${Constant.localServerUrl}/index.html';
    // String serverUrl = 'http://localdev.banxiaoer.net';
    _controller.loadRequest(Uri.parse(serverUrl));
  }

  void goMiniProgram() {
    _fluwx
      // ..addSubscriber(_responseListener)
      ..open(
        target: MiniProgram(
          username: 'gh_9a8d84445828',
          path: '/pages/index/index?classCode=needswitch',
          miniProgramType: WXMiniProgramType.preview,
        ),
      );
  }

  // void _responseListener(response) {
  //   if (response is WeChatLaunchMiniProgramResponse) {
  //     print("小程序跳转 1 --------------------------------");
  //     print(response);
  //   }
  // }

  Future<String?> goScanCode() async {
    var result = await router.push('/scanCode');
    return result as String?;
  }

  Future<void> handleBack() async {
    // navigateBack指令
    var resp = {'unique': '', 'cmd': 'navigateBack', 'data': '', 'errMsg': ''};
    _sendResponse(resp);
  }

  bool setTitle(String title, bool beBack) {
    emit(state.copyWith(title: title, beBack: beBack));
    return true;
  }

  Future<void> refresh() async {
    clearRecording();
    clearAudio();
    _controller.reload();
  }

  Future<void> clearStorage() async {
    await getIt.get<SharedPreferences>().clear();
  }

  void setChooseImageCmdFlag(bool chooseImageCmdFlag, String chooseImageCmdMessage) {
    emit(state.copyWith(chooseImageCmdFlag: chooseImageCmdFlag, chooseImageCmdMessage: chooseImageCmdMessage));
  }

  void chooseImage(BuildContext context) async {
    final Map<String, dynamic> data = json.decode(state.chooseImageCmdMessage);
    H5Message h5Message = H5Message.fromJson(data);

    setChooseImageCmdFlag(false, '');

    final params = h5Message.params;
    if (params is! Map<String, dynamic>) {
      throw Exception('参数错误');
    }
    var sourceType = params['sourceType'] as String;
    if (sourceType != 'album' && sourceType != 'camera') {
      sourceType = 'album';
    }
    // 暂时忽略 sizeType 参数

    int count = 9;
    if (params.containsKey('count')) {
      count = params['count'] as int;
      if (count < 1 || count > 9) {
        count = 9;
      }
    }

    // 相册
    if (sourceType == 'album') {
      _chooseImageFromAlbum(context, count, h5Message.unique, h5Message.cmd);
    }
    // 拍照
    else {
      _chooseImageFromCamera(context, h5Message.unique, h5Message.cmd);
    }
  }

  void _chooseImageFromAlbum(BuildContext context, int count, String unique, String cmd) async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: count,
        requestType: RequestType.image,
        gridThumbnailSize: const ThumbnailSize.square(80),
        previewThumbnailSize: const ThumbnailSize.square(150),
      ),
    );

    if (result == null || result.isEmpty) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
      _sendResponse(resp);
      return;
    }

    // 获取临时目录
    final Directory tempDir = await getTemporaryDirectory();

    final List<Map<String, dynamic>> resultList = [];
    for (var asset in result) {
      resultList.add(await _handleSingleImage(asset, tempDir));
    }
    var resp = {
      'unique': unique,
      'cmd': cmd,
      'data': {'tempFiles': resultList},
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  void _chooseImageFromCamera(BuildContext context, String unique, String cmd) async {
    AssetEntity? asset = await CameraPicker.pickFromCamera(context, pickerConfig: const CameraPickerConfig());

    if (asset == null) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
      _sendResponse(resp);
      return;
    }

    final Directory tempDir = await getTemporaryDirectory();
    final Map<String, dynamic> result = await _handleSingleImage(asset, tempDir);
    var resp = {
      'unique': unique,
      'cmd': cmd,
      'data': {
        'tempFiles': [result],
      },
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  Future<Map<String, dynamic>> _handleSingleImage(AssetEntity asset, Directory tempDir) async {
    final file = await asset.file;

    // 生成缩略图
    final data = await asset.thumbnailData;
    final thumbnailFile = await File(
      '${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.png',
    ).writeAsBytes(data!);

    return {
      "tempFilePath": '${Constant.localServerTempFileUrl}${file!.path}',
      "size": file.lengthSync(),
      "width": asset.width,
      "height": asset.height,
      "thumbTempFilePath": '${Constant.localServerTempFileUrl}${thumbnailFile.path}',
      "fileType": file.path.split('/').last.split('.').last,
    };
  }

  void setChooseVideoCmdFlag(bool chooseVideoCmdFlag, String chooseVideoCmdMessage) {
    emit(state.copyWith(chooseVideoCmdFlag: chooseVideoCmdFlag, chooseVideoCmdMessage: chooseVideoCmdMessage));
  }

  void chooseVideo(BuildContext context) async {
    final Map<String, dynamic> data = json.decode(state.chooseVideoCmdMessage);
    H5Message h5Message = H5Message.fromJson(data);

    setChooseVideoCmdFlag(false, '');
    final params = h5Message.params;
    if (params is! Map<String, dynamic>) {
      throw Exception('参数错误');
    }
    var sourceType = params['sourceType'] as String;
    if (sourceType != 'album' && sourceType != 'camera') {
      sourceType = 'album';
    }
    // 暂时忽略 sizeType 参数

    int count = 1;
    if (params.containsKey('count')) {
      count = params['count'] as int;
      if (count < 1 || count > 9) {
        count = 9;
      }
    }

    int maxDuration = 60;
    if (params.containsKey('maxDuration')) {
      maxDuration = params['maxDuration'] as int;
      if (maxDuration < 1 || maxDuration > 600) {
        maxDuration = 60;
      }
    }

    // 相册选择
    if (sourceType == 'album') {
      _chooseVideoFromAlbum(context, count, h5Message.unique, h5Message.cmd);
    }
    // 拍摄
    else {
      _chooseVideoFromCamera(context, maxDuration, h5Message.unique, h5Message.cmd);
    }
  }

  void _chooseVideoFromAlbum(BuildContext context, int count, String unique, String cmd) async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(maxAssets: count, requestType: RequestType.video),
    );

    if (result == null || result.isEmpty) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
      _sendResponse(resp);
      return;
    }

    // 获取临时目录
    final Directory tempDir = await getTemporaryDirectory();

    final List<Map<String, dynamic>> resultList = [];
    for (var asset in result) {
      resultList.add(await _handleSingleVideo(asset, tempDir));
    }
    var resp = {
      'unique': unique,
      'cmd': cmd,
      'data': {'tempFiles': resultList},
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  void _chooseVideoFromCamera(BuildContext context, int maxDuration, String unique, String cmd) async {
    AssetEntity? asset = await CameraPicker.pickFromCamera(
      context,
      pickerConfig: CameraPickerConfig(
        enableRecording: true,
        onlyEnableRecording: true,
        // enableTapRecording: true,
        maximumRecordingDuration: Duration(seconds: maxDuration),
      ),
    );

    if (asset == null) {
      var resp = {'unique': unique, 'cmd': cmd, 'data': null, 'errMsg': 'cancel'};
      _sendResponse(resp);
      return;
    }

    final Directory tempDir = await getTemporaryDirectory();
    final Map<String, dynamic> result = await _handleSingleVideo(asset, tempDir);
    var resp = {
      'unique': unique,
      'cmd': cmd,
      'data': {
        'tempFiles': [result],
      },
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  Future<Map<String, dynamic>> _handleSingleVideo(AssetEntity asset, Directory tempDir) async {
    final file = await asset.file;

    // 获取缩略图
    final data = await asset.thumbnailData;
    final thumbnailFile = await File(
      '${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}.png',
    ).writeAsBytes(data!);

    return {
      "tempFilePath": '${Constant.localServerTempFileUrl}${file!.path}',
      "size": file.lengthSync(),
      "width": asset.width,
      "height": asset.height,
      "thumbTempFilePath": '${Constant.localServerTempFileUrl}${thumbnailFile.path}',
      "fileType": file.path.split('/').last.split('.').last,
    };
  }

  void setOrientationCmdFlag(bool orientationCmdFlag, String orientationCmdMessage) {
    emit(state.copyWith(orientationCmdFlag: orientationCmdFlag, orientationCmdMessage: orientationCmdMessage));
  }

  void getOrientation(BuildContext context) async {
    final Map<String, dynamic> data = json.decode(state.orientationCmdMessage);
    H5Message h5Message = H5Message.fromJson(data);

    setOrientationCmdFlag(false, '');

    final orientation = MediaQuery.of(context).orientation;

    var resp = {
      'unique': h5Message.unique,
      'cmd': h5Message.cmd,
      'data': {'orientation': orientation == Orientation.portrait ? "portrait" : "landscape"},
      'errMsg': '',
    };
    _sendResponse(resp);
  }

  void setWindowInfoCmdFlag(bool windowInfoCmdFlag, String windowInfoCmdMessage) {
    emit(state.copyWith(windowInfoCmdFlag: windowInfoCmdFlag, windowInfoCmdMessage: windowInfoCmdMessage));
  }

  void getWindowInfo(BuildContext context) async {
    final Map<String, dynamic> data = json.decode(state.windowInfoCmdMessage);
    H5Message h5Message = H5Message.fromJson(data);

    setWindowInfoCmdFlag(false, '');

    final mediaQuery = MediaQuery.of(context);
    final viewPadding = mediaQuery.viewPadding;
    final size = mediaQuery.size;
    final safeArea = mediaQuery.padding;
    final devicePixelRatio = mediaQuery.devicePixelRatio;

    // 计算安全区域坐标
    final safeAreaLeft = safeArea.left;
    final safeAreaRight = size.width - safeArea.right;
    final safeAreaTop = safeArea.top;
    final safeAreaBottom = size.height - safeArea.bottom;
    final safeAreaWidth = size.width - safeArea.horizontal;
    final safeAreaHeight = size.height - safeArea.vertical;

    final windowInfo = {
      'pixelRatio': devicePixelRatio,
      'screenWidth': size.width * devicePixelRatio,
      'screenHeight': size.height * devicePixelRatio,
      'windowWidth': size.width,
      'windowHeight': size.height,
      'statusBarHeight': viewPadding.top,
      'screenTop': 0, // Flutter中通常不使用此值,设为0
      'safeArea': {
        'left': safeAreaLeft,
        'right': safeAreaRight,
        'top': safeAreaTop,
        'bottom': safeAreaBottom,
        'width': safeAreaWidth,
        'height': safeAreaHeight,
      },
    };

    var resp = {'unique': h5Message.unique, 'cmd': h5Message.cmd, 'data': windowInfo, 'errMsg': ''};
    _sendResponse(resp);
  }

  /// 录音初始化
  Future<bool> _initRecorder() async {
    // 请求麦克风权限
    var status = await Permission.microphone.request();
    if (status != PermissionStatus.granted) {
      throw RecordingPermissionException('no auth');
    }

    if (state.recordState != 0) {
      return false;
    }

    final directory = await getTemporaryDirectory();
    // String recordPath = '${directory.path}/${Uuid().v5(Namespace.url.value, 'www.banxiaoer.com')}_record.aac';
    // String recordPath = '${directory.path}/${Uuid().v4()}_record.aac';
    String recordPath = '${directory.path}/${Uuid().v4()}_record.m4a';

    // 打开录音器
    try {
      final recorder = FlutterSoundRecorder();
      _recorder = (await recorder.openRecorder())!;

      emit(state.copyWith(recorderIsInit: true, recordPath: recordPath));
      return true;
    } catch (e) {
      throw Exception('打开录音器失败!');
    }
  }

  /// 开始录音
  Future<bool> startRecording() async {
    if (state.recorderIsInit) {
      return false;
    }

    if (state.recordState != 0) {
      return false;
    }

    final initResult = await _initRecorder();
    if (!initResult) {
      return false;
    }

    await _recorder!.startRecorder(toFile: state.recordPath, codec: Codec.aacMP4);
    emit(state.copyWith(recordState: 1));
    return true;
  }

  /// 暂停录音
  Future<bool> pauseRecording() async {
    if (!state.recorderIsInit) {
      return false;
    }

    if (state.recordState != 1) {
      return false;
    }

    await _recorder!.pauseRecorder();
    emit(state.copyWith(recordState: 2));
    return true;
  }

  /// 恢复录音
  Future<bool> resumeRecording() async {
    if (!state.recorderIsInit) {
      return false;
    }

    if (state.recordState != 2) {
      return false;
    }

    await _recorder!.resumeRecorder();
    emit(state.copyWith(recordState: 1));
    return true;
  }

  /// 停止录音
  Future<Map<String, dynamic>> stopRecording() async {
    if (!state.recorderIsInit) {
      throw Exception("录音器未初始化");
    }

    if (state.recordState != 1 && state.recordState != 2) {
      throw Exception("录音器状态错误");
    }

    var url = await _recorder!.stopRecorder();
    await _recorder!.closeRecorder();
    emit(state.copyWith(recorderIsInit: false, recordState: 0, recordPath: ''));

    if (url == null || url.isEmpty) {
      throw Exception("录音失败");
    }

    var tempDir = await getTemporaryDirectory();
    String fileName = path.basenameWithoutExtension(url);
    String mp3Path = '${tempDir.path}/$fileName.mp3';

    // var convertResult = await compute(AudioUtil.convertAacToMp3, {'accPath': url, 'mp3Path': mp3Path});
    var convertResult = await AudioUtil.convertAacToMp3({'accPath': url, 'mp3Path': mp3Path});
    if (!convertResult) {
      throw Exception("录音转码失败");
    }

    // 时长
    // var duration = await AudioUtil.getAudioDuration(mp3Path);
    var duration = await AudioUtil.getAudioDuration(url);

    return {'tempFilePath': '${Constant.localServerTempFileUrl}$mp3Path', 'duration': duration.inSeconds};
  }

  /// 清空录音
  Future<bool> clearRecording() async {
    // await _recorder!.stopRecorder();
    try {
      await _recorder?.closeRecorder();
    } catch (e) {
      print(e);
    }
    emit(state.copyWith(recorderIsInit: false, recordState: 0, recordPath: ''));
    return true;
  }

  /// 播放初始化
  Future<bool> _initPlayer() async {
    // 打开播放器
    try {
      final player = FlutterSoundPlayer();
      _player = (await player.openPlayer())!;

      emit(state.copyWith(playerIsInit: true));
      return true;
    } catch (e) {
      throw Exception('打开播放器失败!');
    }
  }

  /// 播放音频
  Future<bool> playAudio(String url) async {
    if (!state.playerIsInit) {
      final initResult = await _initPlayer();
      if (!initResult) {
        return false;
      }
    }

    await _player!.startPlayer(
      fromURI: url,
      whenFinished: () async {
        await _player!.stopPlayer();
        emit(state.copyWith(playState: 0));
      },
    );
    emit(state.copyWith(playState: 1));
    return true;
  }

  /// 暂停播放
  Future<bool> pauseAudio() async {
    if (!state.playerIsInit) {
      throw Exception("播放器未初始化");
    }

    if (state.playState != 1) {
      throw Exception("播放器状态错误");
    }

    await _player!.pausePlayer();
    emit(state.copyWith(playState: 2));
    return true;
  }

  /// 恢复播放
  Future<bool> resumeAudio() async {
    if (!state.playerIsInit) {
      throw Exception("播放器未初始化");
    }

    if (state.playState != 2) {
      throw Exception("播放器状态错误");
    }

    await _player!.resumePlayer();
    emit(state.copyWith(playState: 1));
    return true;
  }

  /// 跳转播放
  Future<bool> seekAudio(int seek) async {
    if (!state.playerIsInit) {
      throw Exception("播放器未初始化");
    }

    await _player!.seekToPlayer(Duration(seconds: seek));
    emit(state.copyWith(playState: 1));
    return true;
  }

  /// 停止播放
  Future<bool> stopAudio() async {
    if (!state.playerIsInit) {
      throw Exception("播放器未初始化");
    }

    if (state.playState != 1 && state.playState != 2) {
      throw Exception("播放器状态错误");
    }

    await _player!.stopPlayer();
    emit(state.copyWith(playState: 0));
    return true;
  }

  /// 清空播放
  Future<bool> clearAudio() async {
    try {
      await _player?.closePlayer();
    } catch (e) {
      print(e);
    }
    emit(state.copyWith(playerIsInit: false, playState: 0, playId: ''));
    return true;
  }

  @override
  Future<void> close() async {
    _server.close();
    // _fluwx.removeSubscriber(_responseListener);
    // closeLocalRecorder();
    // closeLocalPlayer();

    try {
      await _recorder?.closeRecorder();
    } catch (e) {
      print(e);
    }

    try {
      await _player?.closePlayer();
    } catch (e) {
      print(e);
    }

    return super.close();
  }
}